UINT8* encodeMcu( UINT32 imageFormat, UINT8 *outputBuffer ) { levelShift(Y1); dct(Y1); quantization(Y1, ILqt); outputBuffer = huffman(1, outputBuffer); #if 0 if (imageFormat != GRAY) { levelShift(CB); dct(CB); quantization(CB, ICqt); outputBuffer = huffman(2, outputBuffer); levelShift(CR); dct(CR); quantization(CR, ICqt); outputBuffer = huffman(3, outputBuffer); } #endif //0 return outputBuffer; }
void blockEncoder( bool init, bool color_mode, int sampling, unsigned short imagewidth, unsigned short imageheight, unsigned char Standard_Luminance_Quantization_Table[64] , unsigned char Standard_Chromiance_Quantization_Table0[64] , unsigned char Standard_Chromiance_Quantization_Table1[64] , const unsigned char buffer[MAX_ROWBUF_WIDTH*3*8], pixel_queue_t& queue,bool flush ) { yuv_t yQ[64]; yuv_t uQ[64]; yuv_t vQ[64]; freq_t yfrqQ[64]; freq_t ufrqQ[64]; freq_t vfrqQ[64]; freq_t yquantQ[64]; freq_t uquantQ[64]; freq_t vquantQ[64]; bits_t yBitQ[MAX_HUFF]; bits_t uBitQ[MAX_HUFF]; bits_t vBitQ[MAX_HUFF]; bits_t emptyBitQ[1]; bitlen_t yBitLenQ[MAX_HUFF]; bitlen_t uBitLenQ[MAX_HUFF]; bitlen_t vBitLenQ[MAX_HUFF]; bitlen_t emptyBitLenQ[1]; unsigned char yLen, uLen, vLen, emptyLen; emptyLen=1; bool ydcten, udcten, vdcten, yqen, vqen, uqen, yhen, uhen, vhen; colorBuffer( color_mode, sampling, imagewidth, buffer, yQ, uQ, vQ, ydcten, udcten, vdcten); dct(ydcten, yQ,yfrqQ, yqen); dct(udcten, uQ,ufrqQ, vqen); dct(vdcten, vQ,vfrqQ, uqen); quant_y(yqen, Standard_Luminance_Quantization_Table, yfrqQ, yquantQ , yhen); quant_u(vqen, Standard_Chromiance_Quantization_Table0, ufrqQ, uquantQ, uhen); quant_v(uqen, Standard_Chromiance_Quantization_Table1, vfrqQ, vquantQ, vhen); huffman_Y (yhen, yquantQ, yBitQ, yBitLenQ, yLen); huffman_UV(uhen, uquantQ, uBitQ, uBitLenQ,U_DATA,uLen); huffman_UV(vhen, vquantQ, vBitQ, vBitLenQ,V_DATA,vLen); bitWriter(yBitQ, yBitLenQ,yLen,false, queue); bitWriter(uBitQ, uBitLenQ,uLen,false, queue); bitWriter(vBitQ, vBitLenQ,vLen,false, queue); bitWriter(emptyBitQ, emptyBitLenQ,emptyLen,false, queue); }
int main(void) { printf("DCT II (the DCT)\n"); dct( FFTW_REDFT10, 2); dct( FFTW_REDFT10, 4); printf("DCT III (Inverse DCT)\n"); dct( FFTW_REDFT01, 2); dct( FFTW_REDFT01, 4); return 0; }
static void uncompress(void) { int x2,y2,x,y,a,b; int i1,u1,v1; int ci[64]; int cu[64]; int cv[64]; dct(cu,in[4],q2,0); dct(cv,in[5],q3,0); for(y=0;y<16;y++) for(x=0;x<16;x++) { u1=cu[(x>>1)+(y>>1)*8]; v1=cv[(x>>1)+(y>>1)*8]; rgb[x+y*16][0]=( 291*v1 ) >> 8; rgb[x+y*16][1]=( -101*u1-148*v1 ) >> 8; rgb[x+y*16][2]=( 564*u1 ) >> 8; } for(y2=0;y2<=8;y2+=8) for(x2=0;x2<=8;x2+=8) { dct(ci,in[(x2/8)+(y2/8)*2],q1,1); for(y=0;y<8;y++) for(x=0;x<8;x++) { i1=ci[x+y*8]; rgb[(x+x2)+(y+y2)*16][0]+=i1+128; rgb[(x+x2)+(y+y2)*16][1]+=i1+128; rgb[(x+x2)+(y+y2)*16][2]+=i1+128; } } // convert to short for(y=0;y<16;y++) for(x=0;x<16;x++) { b=1; a=rgb[x+y*16][0]; a=(a>>3); if(a<0) a=0; if(a>31) a=31; b+=(a<<11); a=rgb[x+y*16][1]; a=(a>>3); if(a<0) a=0; if(a>31) a=31; b+=(a<<6); a=rgb[x+y*16][2]; a=(a>>3); if(a<0) a=0; if(a>31) a=31; b+=(a<<1); out[x+y*16]=b; } }
int main_encoder(int argc, FRAMECHAR *CurrentFrame) { int compression,sample; unsigned int col, cols, row, rows, framenumber,row2, col2; framenumber = CurrentFrame->position; openBMPJPG(framenumber); rows = CurrentFrame->height/MACRO_BLOCK_SIZE; cols = CurrentFrame->width/MACRO_BLOCK_SIZE; dct_init_start(); zzq_encode_init_start(compression); vlc_init_start(); for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { for(row2 = 0;row2<MACRO_BLOCK_SIZE;row2++) { for(col2 = 0;col2<MACRO_BLOCK_SIZE*3;col2++) { pixelmatrix[row2][col2] = CurrentFrame->framebits[row*MACRO_BLOCK_SIZE+row2][col*MACRO_BLOCK_SIZE*3+col2]-128; } } for(sample=0;sample<5;sample++) { if(sample<4) { RGB2YCrCb(pixelmatrix,YMatrix,CrMatrix,CbMatrix,sample); dct(YMatrix,0); } else { dct(CrMatrix,1); dct(CbMatrix,2); } } } } dct_stop_done(); zzq_encode_stop_done(); vlc_stop_done(); closeBMPJPG(); return 0; }
Qt::Alignment alsyms2qtalignment(RPP::Array alsyms) { if (alsyms.isNil()) return Qt::Alignment(0); // for convenience Qt::Alignment al; VALUE *v = alsyms.ptr(); RPP::Dictionary dct(mQt.cv("@@alignmentflags"), RPP::VERYUNSAFE); if (!dct.isHash()) { mQt.cv_set("@@alignmentflags", dct = RPP::Dictionary()); #define ENTRY_DO(sym, enumval) dct[#sym] = RPP::Fixnum(Qt::Align##enumval) ENTRY_DO(left, Left); ENTRY_DO(right, Right); ENTRY_DO(center, HCenter); ENTRY_DO(hcenter, HCenter); ENTRY_DO(vcenter, HCenter); ENTRY_DO(top, Top); ENTRY_DO(bottom, Bottom); ENTRY_DO(absolute, Absolute); ENTRY_DO(leading, Leading); // == left ENTRY_DO(trailing, Trailing); // == right #undef ENTRY_DO } for (long i = 0, l = alsyms.len(); i < l; i++, v++) al |= Qt::AlignmentFlag(RPP::Fixnum(dct[*v]).to_i()); return al; }
int main(int argc, char** argv) { try { if(argc < 2) { std::cout << full_help; return 1; } else if(argc > 4) { if(argv[1][0] == '-' && argv[1][1] == 'h') { return huffile(argc, argv); } else if(argv[1][0] == '-' && argv[1][1] == 'd') { return dct(argc, argv); } else if(argv[1][0] == '-' && argv[1][1] == 'p') { return diff_pic(argc, argv); } } else { std::cout << full_help; return 1; } } catch(const std::exception &e) { std::cout << std::endl; std::cerr << e.what() << std::endl; return 1; } catch(...) { std::cout << std::endl; std::cerr << "Unknown Exception found ..." << std::endl; return 1; } return 0; }
int main() { dct_data_t a[FF * N], b[FF * N]; int retval = 0, i, j; FILE *fp; // double start, finish, elapsed_time; for (i = 0; i < FF; i++) { fp = fopen("../in.dat", "r"); for (j = 0; j < N; j++) { int tmp; fscanf(fp, "%d", &tmp); a[i * N + j] = tmp; } fclose(fp); } // start = dtime(); rapl_power_start(); dct(a, b); rapl_power_stop(); // finish = dtime(); // elapsed_time = finish - start; // printf("%.3fms\n", elapsed_time); return retval; }
MFCC MelFilter_to_MFCC (MelFilter me, long numberOfCoefficients) { try { long nf = my ny; double fmax_mel = my y1 + (nf - 1) * my dy; Melder_assert (numberOfCoefficients > 0); autoNUMmatrix<double> dct (NUMcosinesTable (1, numberOfCoefficients, nf), 1, 1); autoMFCC thee = MFCC_create (my xmin, my xmax, my nx, my dx, my x1, numberOfCoefficients, my y1, fmax_mel); for (long frame = 1; frame <= my nx; frame++) { CC_Frame cf = (CC_Frame) & thy frame[frame]; CC_Frame_init (cf, numberOfCoefficients); for (long i = 1; i <= numberOfCoefficients; i++) { double p = 0; for (long j = 1; j <= nf; j++) { p += my z[j][frame] * dct[i][j]; } cf -> c[i] = p; } // c0 equals the average of the filterbank outputs. double p = 0; for (long j = 1; j <= nf; j++) { p += my z[j][frame]; } cf -> c0 = p / nf; } return thee.transfer(); } catch (MelderError) { Melder_throw (me, ": no MFCC created."); } }
int main() { tga_image tga; double dct_buf[8][8]; int i, j, k, l; load_tga(&tga, "in.tga"); k = 0; l = (tga.height / 8) * (tga.width / 8); for (j=0; j<tga.height/8; j++) for (i=0; i<tga.width/8; i++) { dct(&tga, dct_buf, i*8, j*8); quantize(dct_buf); idct(&tga, dct_buf, i*8, j*8); printf("processed %d/%d blocks.\r", ++k,l); fflush(stdout); } printf("\n"); DONTFAIL( tga_write_mono("out.tga", tga.image_data, tga.width, tga.height) ); tga_free_buffers(&tga); return EXIT_SUCCESS; }
void Initializator::createTypesNodes() { spCreatorNode simple (new CreatorNode()); spCreatorNode account (new TypeAccount()); spCreatorNode language (new TypeLanguage()); spCreatorNode partOfSpeech (new TypePartOfSpeech()); spCreatorNode dct (new TypeDct()); spCreatorNode llForDctLK (new TypeLLForDctLK()); spCreatorNode word (new TypeWord()); idtnRoot_ = base_->registerTypeNode(simple); idtnAccounts_ = base_->registerTypeNode(simple); idtnLanguages_ = base_->registerTypeNode(simple); idtnParts_OfSpeech_ = base_->registerTypeNode(simple); idtnRefLK_ = base_->registerTypeNode(simple); idtnRefLL_ = base_->registerTypeNode(simple); idtnRefPS_ = base_->registerTypeNode(simple); idtnAccount_ = base_->registerTypeNode(account); idtnLanguage_ = base_->registerTypeNode(language); idtnPart_OfSpeech_ = base_->registerTypeNode(partOfSpeech); idtnDct_ = base_->registerTypeNode(dct); idtnLLForDctLK_ = base_->registerTypeNode(llForDctLK); idtnWord_ = base_->registerTypeNode(word); }
void Dct::doDCT(Matrix<short> *originMatrix, long (*resultMatrix)[MATRIX_SIZE+4], long dctRadius){ this->originMatrix = originMatrix; this->resultMatrix = resultMatrix; dct(); lpf(dctRadius); idct(); }
MelFilter MFCC_to_MelFilter2 (MFCC me, long first_cc, long last_cc, double f1_mel, double df_mel) { try { int use_c0 = 0; long nf = ((my fmax - my fmin) / df_mel + 0.5); double fmin = MAX (f1_mel - df_mel, 0), fmax = f1_mel + (nf + 1) * df_mel; if (nf < 1) { Melder_throw ("MFCC_to_MelFilter: the position of the first filter, the distance between the filters, " "and, the maximum do not result in a positive number of filters."); } // Default values if (first_cc == 0) { first_cc = 1; use_c0 = 1; } if (last_cc == 0) { last_cc = my maximumNumberOfCoefficients; } // Be strict if (last_cc < first_cc || first_cc < 1 || last_cc > my maximumNumberOfCoefficients) { Melder_throw ("MFCC_to_MelFilter: coefficients must be in interval [1,", my maximumNumberOfCoefficients, "]."); } autoNUMmatrix<double> dct (NUMcosinesTable (first_cc, last_cc, nf), first_cc, 1); // TODO ?? //if ((dct = NUMcosinesTable (first_cc, last_cc, nf)) == NULL) return NULL; autoMelFilter thee = MelFilter_create (my xmin, my xmax, my nx, my dx, my x1, fmin, fmax, nf, df_mel, f1_mel); for (long frame = 1; frame <= my nx; frame++) { CC_Frame cf = (CC_Frame) & my frame[frame]; long ie = MIN (last_cc, cf -> numberOfCoefficients); for (long j = 1; j <= nf; j++) { double t = 0; for (long i = first_cc; i <= ie; i++) { t += cf -> c[i] * dct[i][j]; } // The inverse CT has a factor 1/N t /= nf; if (use_c0) { t += cf -> c0; } thy z[j][frame] = t; } } return thee.transfer(); } catch (MelderError) { Melder_throw (me, ": no MelFilter created."); } }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { DOUBLE *sig,*wcp,*tmp; mxArray *temp; unsigned int m,n; int nr,nc,nn,J; /* Check for proper number of arguments */ if (nrhs != 1) { mexErrMsgTxt("dct_ii requires one input argument."); } else if (nlhs != 1) { mexErrMsgTxt("dct_ii requires one output argument."); } /* Check the dimensions of signal. signal can be n X 1 or 1 X n. */ /* future enhancement -- vectorize, do each column of matrix */ m = mxGetM(Sig_IN); n = mxGetN(Sig_IN); if(m == 1){ nr = (int) n; nc = 1; } else { nr = (int) m; nc = (int) n; } J = 0; for( nn = 1; nn < nr; nn *= 2 ) J ++; if( nn != nr){ mexErrMsgTxt("dct_ii requires dyadic length"); } /* Create a matrix for the return argument */ DCT_OUT = mxCreateDoubleMatrix(m, n, mxREAL); temp = mxCreateDoubleMatrix(4*n,1,mxREAL); /* Assign pointers to the various parameters */ wcp = mxGetPr(DCT_OUT); sig = mxGetPr(Sig_IN); tmp = mxGetPr(temp); copydouble(sig,tmp,nr); /* Do the actual computations in a subroutine */ dct(&tmp[0],&tmp[nr],J,&tmp[2*nr]); copydouble(tmp,wcp,nr); mxDestroyArray(temp); }
/** compute image DCT */ void computeImgDCT(image img, image output, s_args args){ float *data = malloc(sizeof(float)*BLOCK_SIZE*BLOCK_SIZE); int i=0,j=0; for (i = 0; i < img.h; i += BLOCK_SIZE) { for (j = 0; j < img.w; j+= BLOCK_SIZE) { dct(&img, data, i, j); putDCTValues(&output, data, i, j); } } free(data); writePgm(args.outFilename, &output); }
/** quantify image */ void quantifyImg(image img, image output, s_args args){ int *quantizeData = malloc(sizeof(int)*BLOCK_SIZE*BLOCK_SIZE); float *dctData = malloc(sizeof(float)*BLOCK_SIZE*BLOCK_SIZE); for (int i = 0; i < img.h; i += BLOCK_SIZE) { for (int j = 0; j < img.w; j+= BLOCK_SIZE) { dct(&img, dctData, i, j); quantize(dctData, quantizeData); putQUANTIZEValues(&output, quantizeData, i, j); } } free(quantizeData); free(dctData); writePgm(args.outFilename, &output); }
void grayDctDenoisingInvoker::operator() (const Range &range) const { for (int i = range.start; i <= range.end - 1; ++i) { int y = i / (src.cols - psize); int x = i % (src.cols - psize); Rect patchNum( x, y, psize, psize ); Mat patch(psize, psize, CV_32FC1); src(patchNum).copyTo( patch ); dct(patch, patch); float *data = (float *) patch.data; for (int k = 0; k < psize*psize; ++k) data[k] *= fabs(data[k]) > thresh; idct(patch, patches[i]); } }
//////////// 感知哈希算法 //////////// //pHash算法 string Filter::PHashValue(Mat &src) { Mat clone = src.clone(); Mat img, dst; if (clone.channels() == 3) { cvtColor(clone, clone, CV_BGR2GRAY); img = Mat_<double>(clone); } else { img = Mat_<double>(clone); } /* 第一步,缩放尺寸,可以为Size(32,32)或Size(8,8),也可以更高,主要是为了提高计算效率*/ resize(img, img, Size(32,32)); // 顺时针旋转图像90度 transpose(img, dst); flip(dst, img, 1); /* 第二步,离散余弦变换,DCT系数求取*/ dct(img, dst); /* 第三步,求取DCT系数均值(左上角8*8区块的DCT系数,频率最低的部分,即图像信息的大部分)*/ double dIdex[64]; double mean = 0.0; int k = 0; for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { dIdex[k] = dst.at<double>(i, j); mean += dst.at<double>(i, j)/64; ++k; } } /* 第四步,计算哈希值。*/ string rst(64,' '); for (int i = 0; i < 64; ++i) { if (dIdex[i] >= mean) { rst[i] = '1'; } else { rst[i] = '0'; } } return rst; }
void dct_2(float **x, int n1, int n2, float **c1, float **c2, int type) /***************************************************************************** in place 2D-DCT ****************************************************************************** x array[][] of the signal before and after transform n1 length of the signal along the 1st dimension n2 length of the signal along the 2nd dimension c1 table for the 1st dimension c2 table for the 2nd dimension type 0 for forward and 1 for inverse transform *****************************************************************************/ { int i; /* first along the faster dimension */ for(i=0; i<n2; i++) dct(x[i], n1, c1, type); /* then along the slower dimension */ dct_row(x, n1, n2, c2, type); }
int main(){ double out[8][8]; double out2[8][8]; double out3[8][8]; double in[8][8]; double in2[8][8]; for(int y=0;y<N;y++) for(int x=0;x<N;x++){ mzero(in); in[y][x]=1; idct(in,out); for(int iy=0;iy<N;iy++) for(int ix=0;ix<N;ix++){ if(out[iy][ix]>=0) in2[iy][ix]=255; else in2[iy][ix]=0; } dct(in2,out2); if(x==0&&y==0) out3[y][x]=out2[0][0]; else out3[y][x]=mmax(out2); } // mmap(out3,(1.0/4)*); mmap(out3,round); mprint(out3); return true; }
std::pair<std::vector<int>, int> JpegCodec::encode(const Bitmap &bmp) { if (!bmp.isValid()) return std::pair<std::vector<int>, int>(); const int size = bmp.width() * bmp.height(); char y[size]; char cb[size]; char cr[size]; const Pixel *data = bmp.data(); for (int i = 0; i < size; ++i) { const Pixel &p = data[i]; y[i] = 0.299 * p.red() + 0.587 * p.green() + 0.114 * p.blue() - 128; cb[i] = -0.1687 * p.red() - 0.3313 * p.green() + 0.5 * p.blue() + 128 - 128; cr[i] = 0.5 * p.red() - 0.4187 * p.green() - 0.0813 * p.blue() + 128 - 128; } BitDataBuilder builder; dct(y, bmp.width(), bmp.height(), builder); return builder.data(); }
/** compress Image */ void compressImg(image img, image output, s_args args){ int *quantizeData = malloc(sizeof(int)*BLOCK_SIZE*BLOCK_SIZE); int *vectorizeData = malloc(sizeof(int)*BLOCK_SIZE*BLOCK_SIZE); float *dctData = malloc(sizeof(float)*BLOCK_SIZE*BLOCK_SIZE); int offset = 0; for (int i = 0; i < img.h; i += BLOCK_SIZE){ for (int j = 0; j < img.w; j+= BLOCK_SIZE) { dct(&img, dctData, j, i); quantize(dctData, quantizeData); vectorize(quantizeData, vectorizeData); putCompressedValues(&output, vectorizeData, &offset); } } writeCompressed(args.outFilename, &output); free(quantizeData); free(vectorizeData); free(dctData); }
int main() { short pixels[8][8] = { { 0x0000, 0x008c, 0x00bd, 0x00ee, 0x011f, 0x0150, 0x0181, 0x01b2 }, { 0x001b, 0x004c, 0x0133, 0x0164, 0x0195, 0x01c6, 0x01f7, 0x0228 }, { 0x0036, 0x00c2, 0x0098, 0x01da, 0x020b, 0x023c, 0x026d, 0x029e }, { 0x0051, 0x0082, 0x010e, 0x00e4, 0x0281, 0x02b2, 0x02e3, 0x0314 }, { 0x006c, 0x00f8, 0x0184, 0x015a, 0x0130, 0x0328, 0x0359, 0x038a }, { 0x0087, 0x00b8, 0x00e9, 0x01d0, 0x01a6, 0x017c, 0x03cf, 0x0400 }, { 0x00a2, 0x012e, 0x015f, 0x0246, 0x021c, 0x01f2, 0x01c8, 0x0476 }, { 0x00bd, 0x00ee, 0x01d5, 0x0150, 0x0292, 0x0268, 0x023e, 0x0214 } }; short data[8][8]; dct(pixels, data); for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) output << data[row][col] << " "; output << "\n"; } // CHECK: 0x00000d27 0xfffff97a 0xfffffff9 0xffffff15 0x00000021 0xffffffb3 0x0000000e 0x00000007 // CHECK: 0xfffffdde 0x0000006b 0xffffff86 0x0000007a 0xffffffa1 0x00000033 0xffffffde 0xffffffe0 // CHECK: 0xfffffeaf 0x000001a6 0xffffff3b 0xffffffce 0x00000063 0xffffffae 0x00000023 0x0000002b // CHECK: 0xffffffca 0xffffff9c 0x0000011f 0xffffff13 0x00000003 0x0000007b 0xffffffbc 0xffffffaf // CHECK: 0xffffffb0 0x0000004a 0xffffffc8 0x000000e1 0xfffffee3 0xffffffd3 0x00000085 0x0000006f // CHECK: 0xffffffff 0xffffffe8 0x00000019 0xffffffc3 0x000000e3 0xffffff4a 0xffffffe1 0xffffffd2 // CHECK: 0xffffffba 0xfffffff6 0x0000000c 0x00000055 0xffffffe3 0x00000079 0xffffff2b 0x00000034 // CHECK: 0x00000040 0x00000039 0x00000006 0xffffffc2 0xffffffe7 0xffffffd0 0x0000004c 0xffffff14 return 0; }
int main() { unsigned int iter; int dctin[64]; int dctout[64]; int quantizeout[64]; int zigzagout[64]; // preallocate memory for global variable unsigned char ScanBuffer[IMG_HEIGHT_MDU*8][IMG_WIDTH_MDU*8]; ReadBmp(ScanBuffer); for (iter = 0; iter < IMG_BLOCKS; iter++) { readblock(ScanBuffer, dctin); dct(dctin, dctout); quantize(dctout,quantizeout); zigzag(quantizeout, zigzagout); huffencode(zigzagout); } return 0; }
//----------------------------------------------------------------------------- // Name: displayFunc( ) // Desc: callback function invoked to draw the client area //----------------------------------------------------------------------------- void displayFunc( ) { static const int LP = 4; static long int count = 0; static char str[1024]; static unsigned int wf = 0; static SAMPLE buffer[LPC_BUFFER_SIZE], residue[LPC_BUFFER_SIZE], coefs[1024], coefs_dct[1024], noise[LPC_BUFFER_SIZE]; float pitch, power, fval; int i; // clear the color and depth buffers glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glPushMatrix( ); // rotate the sphere about y axis glRotatef( g_angle_y += g_inc, 0.0f, 1.0f, 0.0f ); // color waveform glColor3f( 0.4f, 0.4f, 1.0f ); // wait for data while( !g_ready ) #if !defined(__OS_WINDOWS__) usleep( 0 ); #else Sleep( 0 ); #endif // g_mutex.lock(); // get the window //memcpy( buffer, g_audio_buffer, g_buffer_size * sizeof(SAMPLE) ); //memset( g_another_buffer, 0, g_buffer_size * sizeof(SAMPLE) ); // g_mutex.unlock(); sf_readf_float( g_fin, buffer, LPC_BUFFER_SIZE ); memcpy( g_another_buffer, buffer, LPC_BUFFER_SIZE * sizeof(SAMPLE) ); //apply_window( (float*)buffer, g_window, g_buffer_size ); lpc_analyze( g_lpc, buffer, g_buffer_size, coefs, 40, &power, &pitch, residue ); if( !g_ctf ) { lpc_synthesize( g_lpc, g_another_buffer, g_buffer_size, coefs, 40, power, 0 ); } else { // inverse window // dct dct( residue, LPC_BUFFER_SIZE ); lpc_analyze( g_lpc_freq, residue, g_buffer_size, coefs_dct, 10, &power, &pitch, NULL ); for( i = 0; i < LPC_BUFFER_SIZE; i++ ) { noise[i] = 2.0f * (float)rand() / RAND_MAX - 1.0f; noise[i] *= power * 32.0f; } // dct dct( noise, LPC_BUFFER_SIZE ); lpc_synthesize( g_lpc_freq, residue, g_buffer_size, coefs_dct, 10, power, pitch, noise ); // idct idct( residue, LPC_BUFFER_SIZE ); // window? //apply_window( (float *)residue, g_window, g_buffer_size ); lpc_synthesize( g_lpc, g_another_buffer, g_buffer_size, coefs, 40, power, pitch, residue ); memset(residue,0,LPC_BUFFER_SIZE*sizeof(SAMPLE)); } g_ready = FALSE; // apply the window GLfloat x = -1.8f, inc = 3.6f / g_buffer_size, y = 1.0f; // draw the time domain waveform glBegin( GL_LINE_STRIP ); GLint ii = ( g_buffer_size - (g_buffer_size/g_time_view) ) / 2; for( i = ii; i < ii + g_buffer_size / g_time_view; i++ ) { glVertex3f( x, g_gain * g_time_scale * .75f * buffer[i] + y, 0.0f ); x += inc * g_time_view; } glEnd(); // apply the window x = -1.8f, inc = 3.6f / g_buffer_size, y = .5f; glColor3f( 0.4f, 0.8f, 1.0f ); // draw the prediction glBegin( GL_LINE_STRIP ); for( i = ii; i < ii + g_buffer_size / g_time_view; i++ ) { glVertex3f( x, g_gain * g_time_scale * .75f * (buffer[i]-residue[i]) + y, 0.0f ); x += inc * g_time_view; } glEnd(); // apply the window x = -1.8f, inc = 3.6f / g_buffer_size, y = .0f; // draw the residue glColor3f( 0.8f, 0.8f, 0.4f ); glBegin( GL_LINE_STRIP ); for( i = ii; i < ii + g_buffer_size / g_time_view; i++ ) { glVertex3f( x, g_gain * g_time_scale * 5.0f * residue[i] + y, 0.0f ); x += inc * g_time_view; } glEnd(); // apply the window x = -1.8f, inc = 0.3f/g_order, y = -0.5f; // draw the coefficients if( pitch == 0 ) glColor3f( 1.0f, .4f, .4f ); else glColor3f( 1.0f, 1.2f - pitch/g_buffer_size*4.0f, .4f ); glBegin( GL_LINE_STRIP ); for( i = 0; i < g_order; i++ ) { glVertex3f( x, coefs[i] + y, 0.0f ); x += inc * g_time_view; } glEnd(); // fft memcpy( residue, g_another_buffer, LPC_BUFFER_SIZE * sizeof(SAMPLE) ); rfft( (float *)residue, g_buffer_size/2, FFT_FORWARD ); memcpy( buffer, residue, LPC_BUFFER_SIZE * sizeof(SAMPLE) ); x = -1.8f; y = -1.2f; inc = 3.6f / g_buffer_size; complex * cbuf = (complex *)buffer; // color the spectrum glColor3f( 0.4f, 1.0f, 0.4f ); // draw the frequency domain representation glBegin( GL_LINE_STRIP ); for( i = 0; i < g_buffer_size/g_freq_view; i++ ) { g_spectrums[wf][i].x = x; if( !g_usedb ) g_spectrums[wf][i].y = g_gain * g_freq_scale * .7f * ::pow( 25 * cmp_abs( cbuf[i] ), .5 ) + y; else g_spectrums[wf][i].y = g_gain * g_freq_scale * .8f * ( 20.0f * log10( cmp_abs(cbuf[i])/8.0 ) + 80.0f ) / 80.0f + y + .73f; x += inc * g_freq_view; } glEnd(); g_draw[wf] = true; for( i = 0; i < g_depth; i++ ) { if( g_draw[(wf+i)%g_depth] ) { Pt2D * pt = g_spectrums[(wf+i)%g_depth]; fval = (g_depth-i)/(float)g_depth; glColor3f( .4f * fval, 1.0f * fval, .4f * fval ); x = -1.8f; glBegin( GL_LINE_STRIP ); for( int j = 0; j < g_buffer_size/g_freq_view; j++, pt++ ) glVertex3f( x + j*(inc*g_freq_view), pt->y, -i * g_space + g_z ); glEnd(); } } if( !g_wutrfall ) g_draw[wf] = false; wf--; wf %= g_depth; /* for( int i = 0; i < 9; i++ ) fprintf( stderr, "%.4f ", coefs[i] ); fprintf( stderr, "power: %.8f pitch: %.4f\n", power, pitch ); for( int i = 0; i < 9; i++ ) fprintf( stderr, "%.4f ", lpc(i) ); fprintf( stderr, "power: %.8f pitch: %.4f\n", lpc(10), lpc(9) ); fprintf( stderr, "\n" ); */ draw_string( 0.4f, 0.8f, 0.0f, "original", .5f ); draw_string( 0.4f, 0.3f, 0.0f, "predicted", .5f ); draw_string( 0.4f, -.2f, 0.0f, "residue (error)", .5f ); draw_string( -1.8f, -.7f, 0.0f, "coefficients", .5f ); sprintf( str, "pitch factor: %.4f", g_speed ); glColor3f( 0.8f, .4f, .4f ); draw_string( 1.2f, -.25f, 0.0f, str, .35f ); sprintf( str, "LPC order: %i", g_order ); draw_string( 1.2f, -.35f, 0.0f, str, .35f ); SAMPLE sum = 0.0f; for( i = 0; i < g_buffer_size; i++ ) sum += fabs(buffer[i]); glPushMatrix(); if( pitch == 0 ) { glColor3f( 1.0f, .4f, .4f ); glTranslatef( 1.28f, -.45f, 0.0f ); } else { glColor3f( 1.0f, 1.2f - pitch/g_buffer_size*4.0f, .4f ); glTranslatef( 1.55f, -.45f, 0.0f ); } glutSolidSphere( .001f + sum/g_buffer_size * 120.0f, 10, 10 ); glPopMatrix(); draw_string( 1.2f, -.55f, 0.0f, "non-pitch | pitched", .35f ); draw_string( 1.2f, -.65f, 0.0f, g_ctf ? "both" : "time-only", .35f ); glPopMatrix( ); // swap the buffers glFlush( ); glutSwapBuffers( ); g_buffer_count_b++; }
/* recv_packet processes a received audio packet. The packet has sequence number seqno, and consists of len bytes of data. In this case, it's just PCM, encoded in 16-bit linear format. The "strategy" parameter determines which of several possible loss concealment techniques to apply */ void recv_packet(int seqno, int len, char *data, FILE *ofile, int strategy) { static int prev_seqno = -1; static int16_t* prev_packet_samples = 0; int16_t *samples = (int16_t*)data; /* we receive a bunch of bytes from the (simulated) net, but we know they're really 16 bit sample values. In real life we'd convert them from network byte order to host byte order, but no need to do that here */ int num_samples = len/2; /* two bytes to a 16 bit integer */ printf("recv_packet: seqno=%d\n", seqno); if (prev_seqno != -1 && (prev_seqno+1 != seqno)) { /* there was missing data - we need to replace it */ int missing_seqno; switch(strategy) { case SILENCE: { /* create as many packet containing silence as we need to fill the gap */ missing_seqno = prev_seqno + 1; while (missing_seqno < seqno) { write_silence(ofile, num_samples); missing_seqno++; } break; } case REPEAT_PREV: { /* repeat the previous packet once to fill the gap. If the gap is longer than one packet, fill the remainder with silence */ fwrite(prev_packet_samples, 2, num_samples, ofile); missing_seqno = prev_seqno + 2; while (missing_seqno < seqno) { write_silence(ofile, num_samples); missing_seqno++; } break; } case REPEAT_NEXT: { /* play the next packet (twice) to fill the gap. If the gap is longer than one packet, first insert silence, then insert the next packet */ missing_seqno = prev_seqno + 1; while (missing_seqno < seqno) { if (missing_seqno == seqno-1) { /* only repeat back once */ /* write the current packet instead of the missing one */ fwrite(data, 2, num_samples, ofile); } else { write_silence(ofile, num_samples); } missing_seqno++; } break; } case REPEAT_BOTH: { /* we'll fill the gap with data from both before and after the gap. If the gap is one packet long, repeat the last half of the previous packet and the first half of the next packet. If the gap is two packets long, repeat the whole previous packet, then the whole next packet. If the gap is three of more packets long, fill the remainder with silence. */ missing_seqno = prev_seqno + 1; if (missing_seqno == seqno-1) { /* the gap is only one packet long */ /* fill with last half of prev packet, first half of current packet */ /* uncomment the next line to enable smoothing*/ #define SMOOTH #ifdef SMOOTH int16_t prev = ((prev_packet_samples[num_samples-1] * 0.66) + (samples[0] * 0.33)); int16_t prev2 = ((prev_packet_samples[num_samples-2] * 0.5) + (prev * 0.5)); int16_t next = ((prev_packet_samples[num_samples-1] * 0.33) + (samples[0] * 0.66)); int16_t next2 = ((next * 0.5) + (samples[1] * 0.5)); fwrite(prev_packet_samples+num_samples/2, 2, (num_samples/2) - 2, ofile); fwrite(&prev2, 2, 1, ofile); fwrite(&prev, 2, 1, ofile); fwrite(&next, 2, 1, ofile); fwrite(&next2, 2, 1, ofile); fwrite(samples + 2, 2, (num_samples/2) - 2, ofile); #else fwrite(prev_packet_samples+num_samples/2, 2, num_samples/2, ofile); fwrite(samples, 2, num_samples/2, ofile); #endif } else { /* the gap is two or more packets long */ /* first write the prev packet a second time */ fwrite(prev_packet_samples, 2, num_samples, ofile); missing_seqno++; while (missing_seqno < seqno) { if (missing_seqno == seqno-1) { /* write the current packet instead of the missing one */ fwrite(samples, 2, num_samples, ofile); } else { write_silence(ofile, num_samples); } missing_seqno++; } } break; } case INTERPOLATE: { /* We're going to interpolate a whole new packet (or several packets) in the frequency domain. */ if (seqno < (prev_seqno + 5)) { int *prev_coeff = dct(prev_packet_samples, num_samples); int *next_coeff = dct(samples, num_samples); missing_seqno = prev_seqno + 1; while (missing_seqno < seqno) { double next_weight = (double)(missing_seqno - prev_seqno)/(seqno - prev_seqno); double prev_weight = (double)(seqno - missing_seqno)/(seqno - prev_seqno); int new_coeff[num_samples]; int i; for (i = 0; i < num_samples; i++) { new_coeff[i] = (prev_weight * prev_coeff[i]) + (next_weight * next_coeff[i]); } fwrite(idct(new_coeff, num_samples), 2, num_samples, ofile); missing_seqno++; } } else { missing_seqno = prev_seqno + 1; while (missing_seqno < seqno) { write_silence(ofile, num_samples); missing_seqno++; } } break; } } } /* finally, don't forget to write out the packet that arrived after the gap */ fwrite(samples, 2, num_samples, ofile); /* hold onto the last received packet - we may need it */ if (prev_packet_samples != 0) free(prev_packet_samples); prev_packet_samples = samples; prev_seqno = seqno; };
/************************************************************************************************************************************ void update_yuv(unsigned char** Y, unsigned char** U, unsigned char** V, int height, int width) { FILE* fp; int outer_r, inner_r, outer_c, inner_c; if((fp = fopen("Down_Sampled_YUV","rb")) == NULL) { printf("\n In update_yuv() Error opening DCT_output file !"); exit(0); } for(outer_r =0; outer_r < height; outer_r += 8) { for(outer_c = 0; outer_c < width; outer_c += 8) { for(inner_r = outer_r; inner_r < outer_r+8; inner_r++) { for(inner_c = outer_c; inner_c < outer_c+8; inner_c++) { fscanf(fp,"%d\t",Y[inner_r][inner_c]); } } } } for(outer_r =0; outer_r < height; outer_r += 8) { for(outer_c = 0; outer_c < width; outer_c += 8) { for(inner_r = outer_r; inner_r < outer_r+8; inner_r++) { for(inner_c = outer_c; inner_c < outer_c+8; inner_c++) { fscanf(fp,"%d\t",U[inner_r][inner_c]); } } } } for(outer_r =0; outer_r < height; outer_r += 8) { for(outer_c = 0; outer_c < width; outer_c += 8) { for(inner_r = outer_r; inner_r < outer_r+8; inner_r++) { for(inner_c = outer_c; inner_c < outer_c+8; inner_c++) { fscanf(fp,"%d\t",V[inner_r][inner_c]); } } } } } ***************************************************************************************************************************************/ int main(int argc, char const *argv[]) { FILE*fp, *image_rgb, *image_yuv, *down_sampled, *DCT, *image; unsigned char** red, **green, **blue, **Y, **U, **V, *image_contents_rgb, *image_contents_yuv, *image_contents_rgbt; int i,ERROR; Header1 header1; Header2 header2; if((image_rgb = fopen("Image_Contents_RGB","wb")) == NULL) /*For storing RGB contents*/ { printf("\n Error creating Image_Contents_RGB file !!"); return -1; } if((image_yuv = fopen("Image_Contents_YUV","wb")) == NULL) /* For storing YUV contents*/ { printf("\n Error creating Image_Contents_YUV file !!"); return -1; } if((down_sampled = fopen("Down_Sampled_YUV","wb")) == NULL) /* For storing down sampled YUV contents*/ { printf("\n Error creating Down_Sampled_YUV file !!"); return -1; } if((DCT = fopen("DCT_Output","wb")) == NULL) /* For storing DCT contents*/ { printf("\n Error creating Down_Sampled_YUV file !!"); return -1; } if(argc!= 2) /* syntax error check*/ { printf("\n The format is ./quantizer [file-name]"); return -1; } if((fp = fopen(argv[1],"rb"))== NULL) /* open the .bmp file for reading*/ { printf("\n Error opening the file specified. Please check if the file exists !!\n"); fclose(fp); return -1; } if(fread(&header1,sizeof(header1),1,fp)!=1) /* Read the primary header from the bmp file */ { printf("\n Error reading header1 \n"); fclose(fp); return -1; } if(header1.type!= 19778) /* check if its a valid bmp file*/ { printf("\n Not a bmp file. Exiting !! \n"); fclose(fp); return -1; } if(fread(&header2,sizeof(header2),1,fp)!=1 ) { printf("\n Error reading header 2"); fclose(fp); return -1; } image_contents_rgb = (unsigned char*)malloc(sizeof(char) * header2.imagesize); image_contents_rgbt = (unsigned char*)malloc(sizeof(char) * header2.imagesize); /*allocate memory to store image data*/ image_contents_yuv = (unsigned char*)malloc(sizeof(char) * header2.imagesize); fseek(fp,header1.offset,SEEK_SET); /* To assign file pointer to start of image byte*/ if((ERROR = fread(image_contents_rgb,header2.imagesize,1,fp))!=1) { printf("\nError reading contents\n"); free(image_contents_rgb); fclose(fp); return -1; } fclose(fp); red = (unsigned char**)malloc(sizeof(char*) * header2.height); green = (unsigned char**)malloc(sizeof(char*) * header2.height); blue = (unsigned char**)malloc(sizeof(char*) * header2.height); Y = (unsigned char**)malloc(sizeof(char*) * header2.height); U = (unsigned char**)malloc(sizeof(char*) * header2.height); V = (unsigned char**)malloc(sizeof(char*) * header2.height); for(i=0 ; i<header2.height ;i++) { red[i] = (unsigned char*)malloc( sizeof(char) * header2.width); green[i]= (unsigned char*)malloc( sizeof(char) * header2.width); blue[i]= (unsigned char*)malloc( sizeof(char) * header2.width); Y[i] = (unsigned char*)malloc( sizeof(char) * header2.width); U[i] = (unsigned char*)malloc( sizeof(char) * header2.width); V[i] = (unsigned char*)malloc( sizeof(char) * header2.width); } vector2matrix(red, green, blue, image_contents_rgb, header2.height, header2.width); /* Store image contents as matrix */ FileWrite(red, green, blue, image_rgb, header2.height, header2.width); /* Optional step*/ rgb2yuv(red,green,blue,Y,U,V,header2.height,header2.width); /* RGB to YUV conversion*/ FileWrite(Y, U, V, image_yuv, header2.height, header2.width); /* Writing YUV into file*/ downsampling(Y, U, V, header2.height, header2.width); /* 4:2:0 Downsampling and update YUV */ FileWrite(Y, U, V, down_sampled, header2.height, header2.width); /* Write downsampled YUV into file*/ dct(DCT, header2.height, header2.width); /* Perform dct and store the result into a file*/ printf("\n"); yuv2rgb(red,green,blue,Y,U,V,header2.height,header2.width); /* Optional step*/ matrix2vector_rgb(red,green,blue,image_contents_rgbt,header2.height,header2.width); /* convert back from matrix to vector*/ matrix2vector_yuv(Y,U,V,image_contents_yuv,header2.height,header2.width); if((image = fopen("Output_image","wb")) == NULL) { printf("\n ERROR opening the file to write quantized image !!\n"); fclose(image); return -1; } if(fwrite(&header1,sizeof(header1),1,image)!= 1) { printf("\n ERROR writing header 1 into destination file !!\n"); fclose(image); return -1; } if(fwrite(&header2,sizeof(header2),1,image)!= 1) { printf("\n ERROR writing header 2 into destination file !! \n"); fclose(image); return -1; } fseek(image, header1.offset, SEEK_SET); if(fwrite(image_contents_rgbt,header2.imagesize,1,image)!=1) /* Change the vector to write into the bmp file here*/ { printf("\n ERROR writing image contents into destination file \n"); fclose(image); return -1; } free(red); free(green); free(blue); free(Y); free(U); free(V); fclose(image); return 0; }
int main(int argc, char *argv[]) { FILE *fp; char *s, *infile = NULL, c; FILE *getfp(); Boolean dftmode = DFTMODE; Boolean compmode = COMPMODE; double *x, *y, *pReal2, *pImag2, *dgetmem(); int size2; if ((cmnd = strrchr(argv[0], '/')) == NULL) cmnd = argv[0]; else cmnd++; while (--argc) { if (*(s = *++argv) == '-') { c = *++s; if ((c == 'l') && (*++s == '\0')) { s = *++argv; --argc; } switch (c) { case 'l': size = atoi(s); break; case 'I': out = c; compmode = 1 - compmode; break; case 'd': dftmode = 1 - dftmode; break; case 'h': default: usage(); } } else infile = s; } if (infile) fp = getfp(infile, "rb"); else fp = stdin; x = dgetmem(size2 = size + size); pReal2 = dgetmem(size2 = size + size); y = x + size; pImag2 = pReal2 + size; while (!feof(fp)) { fillz(x, size2, sizeof(double)); fillz(y, size, sizeof(double)); if (freadf(x, sizeof(*x), size, fp) == 0) break; if (out == 'I') { if (freadf(y, sizeof(*y), size, fp) == 0) break; } dct(x, pReal2, size, size, dftmode, compmode); fwritef(pReal2, sizeof(*pReal2), size, stdout); if (out == 'I') fwritef(pImag2, sizeof(*pReal2), size, stdout); } if (infile) fclose(fp); return (0); }
int DCTCoder::encode(YuvFrame& frame, BitStream& bs, uint quantization) { int err; int block[SIZE] = {0}; float dctC[SIZE] = {.0f}; int qBlock[SIZE] = {0}; int yRowBlocks = (frame.getYRows() + H - 1)/H; // ceil() int yColBlocks = (frame.getYCols() + W - 1)/W; int uRowBlocks = (frame.getURows() + H - 1)/H; int uColBlocks = (frame.getUCols() + W - 1)/W; int vRowBlocks = (frame.getVRows() + H - 1)/H; int vColBlocks = (frame.getVCols() + W - 1)/W; //Y for (int i = 0; i < yRowBlocks; i++){ for (int j = 0; j < yColBlocks; j++){ for (int k = 0; k < H; k++){ for (int l = 0; l < W; l++){ block[k*W+l] = frame.getYPixel(i*H+k,j*W+l); } } shift(block, -128); dct(block, dctC); quantize(dctC, quantization, LUMINANCE, qBlock); for (int c = 0; c < SIZE; c++){ if ((err = Golomb::encode(M, qBlock[c], bs)) != 0){ return err; } } } } //U for (int i = 0; i < uRowBlocks; i++){ for (int j = 0; j < uColBlocks; j++){ for (int k = 0; k < H; k++){ for (int l = 0; l < W; l++){ block[k*W+l] = frame.getUPixel(i*H+k,j*W+l); } } shift(block, -128); dct(block, dctC); quantize(dctC, quantization, CROMINANCE, qBlock); for (int c = 0; c < SIZE; c++){ if ((err = Golomb::encode(M, qBlock[c], bs)) != 0){ return err; } } } } //V for (int i = 0; i < vRowBlocks; i++){ for (int j = 0; j < vColBlocks; j++){ for (int k = 0; k < H; k++){ for (int l = 0; l < W; l++){ block[k*W+l] = frame.getVPixel(i*H+k,j*W+l); } } shift(block, -128); dct(block, dctC); quantize(dctC, quantization, CROMINANCE, qBlock); for (int c = 0; c < SIZE; c++){ if ((err = Golomb::encode(M, qBlock[c], bs)) != 0){ return err; } } } } return 0; }
void chebctor(double (*fun)(double), double a, double b, int *M, double *coeffs, int *flag){ // compute variables int sz = 17; int ii, jj, N = pow(2,sz)+1, stride; double *x,*temp, maxnum, tol = 2.2204e-16; double pt; // allocate memory temp = (double*)malloc(sizeof(double)*N); x = (double*)malloc(sizeof(double)*N); // initialize *flag = 1; // compute shifted chebyshev pts for(ii=0; ii < N; ii++){ pt = cos((long double)(ii)*PI/(long double)(N-1)); x[ii] = ((b-a)*pt+(b+a))/2.0; } // compute y = f(x) and maxnum maxnum = 0.0; for(ii=0; ii < N; ii++){ x[ii] = (*fun)(x[ii]); if(fabs(x[ii]) > maxnum){ maxnum = fabs(x[ii]); } } // exit if overflow if(maxnum == INFINITY){ printf("Function causes overflow!\n"); *flag = 2; return; } tol = tol*maxnum; // compute coefficients adaptively for(ii=3; ii<sz+1; ii++){ // set current degree *M = pow(2,ii)+1; // set stride stride = pow(2,sz-ii); // fill temp for(jj=0;jj<*M;jj++){ temp[jj] = x[jj*stride]; } // compute coeffs dct(*M, temp, coeffs); // check for convergence for(jj=0;jj<*M;jj++){ if(fabs(coeffs[*M-1-jj]) >= tol){ if(jj > 7){ *M = *M-1-jj; *flag = 0; // store coeffs in correct order for(jj=0;jj<*M+1;jj++){ temp[jj] = coeffs[*M-jj]; } for(jj=0;jj<*M+1;jj++){ coeffs[jj] = temp[jj]; } for(jj=*M+1;jj<N;jj++){ coeffs[jj] = 0.0f; } // free memory free(temp); free(x); return; } break; } } } // free memory free(temp); free(x); }