⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 aac_qc.c

📁 jpeg and mpeg 编解码技术源代码
💻 C
📖 第 1 页 / 共 3 页
字号:

 
#include "common.h" 
#include "bitstream.h"
#include "tf_main.h"
#include "aac_qc.h"
#include "aac_se_enc.h"
#include <math.h>

#ifdef OLDHUFF
#include "hufftab.h"
#else
#include "hufftab5.h"
#endif


#define QUANT_TYPE double

QUANT_TYPE pow_quant[9000];
int g_Count;


void tf_init_encode_spectrum_aac( int quality )
{
	unsigned int j;

	g_Count = quality;

	for (j=0;j<9000;j++){
		pow_quant[j]=pow(j, ((double)4.0/(double)3.0));
	}
}

int tf_encode_spectrum_aac(
			   double      *p_spectrum[MAX_TIME_CHANNELS],
			   double      *PsySigMaskRatio[MAX_TIME_CHANNELS],
			   double      allowed_dist[MAX_TIME_CHANNELS][MAX_SCFAC_BANDS],
			   double      energy[MAX_TIME_CHANNELS][MAX_SCFAC_BANDS],
			   enum WINDOW_TYPE block_type[MAX_TIME_CHANNELS],
			   int         sfb_width_table[MAX_TIME_CHANNELS][MAX_SCFAC_BANDS],
			   int         nr_of_sfb[MAX_TIME_CHANNELS],
			   int         average_block_bits,
			   int         available_bitreservoir_bits,
			   int         padding_limit,
			   BsBitStream *fixed_stream,
			   BsBitStream *var_stream,
			   int         nr_of_chan,
			   double      *p_reconstructed_spectrum[MAX_TIME_CHANNELS],
			   int         useShortWindows,
			   /* Window_shape     window_shape,*/      /* offers the possibility to select different window functions */
			   int aacAllowScalefacs,
			   AACQuantInfo* quantInfo,      /* AAC quantization information */ 
			   Ch_Info* ch_info,
			   int varBitRate,
			   int bitRate)
{
	int quant[CHANNEL][NUM_COEFF];
	int i=0;
	int j=0;
	int k,sfb;
	int ch=0;
	QUANT_TYPE max_dct_line = 0;
	int global_gain;
	/*  int common_scalefac; */           /* Now in AACQuantInfo */
	/*  int scale_factor[SFB_NUM_MAX]; */ /* Now in AACQuantInfo structure */
	int store_common_scalefac;
	QUANT_TYPE error_energy/*[SFB_NUM_MAX]*/;
	QUANT_TYPE pow_spectrum[NUM_COEFF];
	int sfb_amplify_check[SFB_NUM_MAX];
	QUANT_TYPE requant[CHANNEL][NUM_COEFF];
	QUANT_TYPE ftmp;
	int largest_sb, sb;
	QUANT_TYPE largest_ratio;
	QUANT_TYPE ratio/*[SFB_NUM_MAX]*/;
	/* int data[5*NUM_COEFF];  */  /* for each pair of spec values 5 bitstream elemets are requiered: 1*(esc)+2*(sign)+2*(esc value)=5 */  /* Now in AACQuantInfo structure */
	/* int len[5*NUM_COEFF];   */ /* Now in AACQuantInfo structure */
	int max_quant/*,tmp*/;
	/* int sfb_offset[250];  */ /* Now in AACQuantInfo structure */
	int sf_bits;
	int extra_bits;
	int book_bits;
	int spectral_bits;
	int max_bits;
	/* int book_vector[SFB_NUM_MAX]; */ /* Now in AACQuantInfo structure */
	/* int num_window_groups; */ /* Now in AACQuantInfo structure */
	int bits_written=0;
	int output_book_vector[SFB_NUM_MAX*2];
	int all_amplified;
	int maxRatio;
	/* change these values to test the different GROUPING possibilities */
	/* int window_group_length[8] = {1,0,0,0,0}; */  /* Now in AACQuantInfo structure */
	int start_com_sf;
	QUANT_TYPE SigMaskRatio[SFB_NUM_MAX];
	int  calc_sf[SFB_NUM_MAX];
	/* num_window_groups = 1; */ /* Now in AACQuantInfo structure */
	IS_Info *is_info;
	int *ptr_book_vector;

	/* Set up local pointers to quantInfo elements for convenience */
	int* sfb_offset = quantInfo -> sfb_offset;
	int* scale_factor = quantInfo -> scale_factor;
	int* common_scalefac = &(quantInfo -> common_scalefac);

	int count = g_Count;
	int check;

	start_com_sf = 40;

	/* Set block type in quantization info */
	quantInfo -> block_type = block_type[MONO_CHAN];

	/** create the sfb_offset tables **/
	if (quantInfo -> block_type == ONLY_SHORT_WINDOW) {

		/* Now compute interleaved sf bands and spectrum */
		sort_for_grouping(
			quantInfo,                       /* ptr to quantization information */
			/* sfb_offset, */                /* Now in AACQuantInfo structure */
			sfb_width_table[MONO_CHAN],      /* Widths of single window */
			p_spectrum,                      /* Spectral values, noninterleaved */
			/* num_window_groups, */         /* Now in AACQuantInfo structure */
			/* window_group_length, */       /* Now in AACQuantInfo structure */
			/* &nr_of_sfb[MONO_CHAN], */     /* Now in AACQuantInfo structure */
			SigMaskRatio,
			PsySigMaskRatio[MONO_CHAN]
			);

		extra_bits = 51;
	} else{
		/* For long windows, band are not actually interleaved */
		if ((quantInfo -> block_type == ONLY_LONG_WINDOW) ||  
			(quantInfo -> block_type == LONG_SHORT_WINDOW) || 
			(quantInfo -> block_type == SHORT_LONG_WINDOW)) {
			quantInfo->nr_of_sfb = quantInfo->max_sfb;

			sfb_offset[0] = 0;
			k=0;
			for( i=0; i< quantInfo -> nr_of_sfb; i++ ){
				sfb_offset[i] = k;
				k +=sfb_width_table[MONO_CHAN][i];
				SigMaskRatio[i]=PsySigMaskRatio[MONO_CHAN][i];
			}
			sfb_offset[i] = k;
			extra_bits = 100; /* header bits and more ... */

		} 
	}

	extra_bits += 1;

    /* Take into account bits for TNS data */
    extra_bits += WriteTNSData(quantInfo,fixed_stream,0);    /* Count but don't write */

    /* for short windows, compute interleaved energy here */
    if (quantInfo->block_type==ONLY_SHORT_WINDOW) {
		int numWindowGroups = quantInfo->num_window_groups;
		int maxBand = quantInfo->max_sfb;
		int windowOffset=0;
		int sfb_index=0;
		int g;
		for (g=0;g<numWindowGroups;g++) {
			int numWindowsThisGroup = quantInfo->window_group_length[g];
			int b;
			for (b=0;b<maxBand;b++) {
				QUANT_TYPE sum=0.0;
				int w;
				for (w=0;w<numWindowsThisGroup;w++) {
					int bandNum = (w+windowOffset)*maxBand + b;
					sum += energy[MONO_CHAN][bandNum];
				}
				energy[MONO_CHAN][sfb_index++]=sum;
			}
			windowOffset += numWindowsThisGroup;
		}
    } 

	/* Compute allowed distortion */
#if 1
	/* Always set to 0.0 since version 0.2.                        *
	 * Since version 0.4 the SMR values aren't calculated anymore, *
	 * hence the speed.                                            */
	for( sfb=0; sfb< quantInfo -> nr_of_sfb; sfb++ ) {
		allowed_dist[MONO_CHAN][sfb] = 0.0;
	}
#else
	for( sfb=0; sfb< quantInfo -> nr_of_sfb; sfb++ ) {
		if ((10*log10(energy[MONO_CHAN][sfb]+1e-15))>70 ) {    /* ? */
			allowed_dist[MONO_CHAN][sfb] = energy[MONO_CHAN][sfb] * SigMaskRatio[sfb];
		} else {
			allowed_dist[MONO_CHAN][sfb] = energy[MONO_CHAN][sfb] * 1.1;
		}
	}
#endif

	/** find the maximum spectral coefficient **/
	/* Bug fix, 3/10/98 CL */
	/* for(i=0; i<NUM_COEFF; i++){ */
	for(i=0; i<sfb_offset[quantInfo -> nr_of_sfb]; i++){ 
		pow_spectrum[i]=(pow(ABS(p_spectrum[ch][i]), 0.75));
		if ((p_spectrum[ch][i]) > max_dct_line){
			max_dct_line = p_spectrum[ch][i];
		}
	}

	if (max_dct_line!=0.0) {
		*common_scalefac = start_com_sf + (int)(16/3 * (log(ABS(pow(max_dct_line,0.75)/MAX_QUANT)/log(2.0))));
	} else {
		*common_scalefac = 20;
	}
	if ((*common_scalefac>200) || (*common_scalefac<0) )
		*common_scalefac = 20;
	*common_scalefac -= 10;

	/* Very simple VBR implementation. Doesn't work really well,
	   but extremely fast encoding. */
	if (varBitRate)
		*common_scalefac += 2*count;

	/* initialize the scale_factors that aren't intensity stereo bands */
	is_info=&(ch_info->is_info);
	for(k=0; k< quantInfo -> nr_of_sfb ;k++) {
		sfb_amplify_check[k] = 0;
		calc_sf[k]=1;
		scale_factor[k]=((is_info->is_present)&&(is_info->is_used[k])) ? scale_factor[k] : 0;
	}
	ratio = 0.0;

	/* Mark IS bands by setting book_vector to INTENSITY_HCB */
	ptr_book_vector=quantInfo->book_vector;
	for (k=0;k<quantInfo->nr_of_sfb;k++) {
		if ((is_info->is_present)&&(is_info->is_used[k])) {
			ptr_book_vector[k] = (is_info->sign[k]) ? INTENSITY_HCB2 : INTENSITY_HCB;
		} else {
			ptr_book_vector[k] = 0;
		}
	}

	maxRatio=1;
	largest_sb = 0;
	do {  /* rate loop */

		do {  /* distortion loop */

			max_quant = 0;
			largest_ratio = 0;
			store_common_scalefac=*common_scalefac;
			for (sb=0; sb<quantInfo -> nr_of_sfb;sb++) {
				if (calc_sf[sb]) {
					register QUANT_TYPE quantFac;
					register QUANT_TYPE invQuantFac;

					quantFac = pow(2.0, 0.1875*(scale_factor[sb] - *common_scalefac ));
					invQuantFac = pow(2.0,-0.25 * (scale_factor[sb] - *common_scalefac ));

					error_energy = 0.0;

					ftmp=0;
					for (i=sfb_offset[sb]; i<sfb_offset[sb+1]; i++){
						register int tmp_quant;
						register QUANT_TYPE tmp_requant, tmp_linediff, tmp_p_spectrum;
						tmp_quant = (int)(pow_spectrum[i] * quantFac + MAGIC_NUMBER);
						if (tmp_quant > MAX_QUANT) {
							//CommonExit(1,"Error in quantization module");
							return MBERROR;
						}
						tmp_requant =  pow_quant[tmp_quant]  * invQuantFac; 
						tmp_p_spectrum = p_spectrum[ch][i];
						quant[ch][i] = sgn(tmp_p_spectrum) * tmp_quant;  /* restore the original sign */
						requant[ch][i] = tmp_requant;

						/* measure the distortion in each scalefactor band */
						/* 	  error_energy[sb] += pow((p_spectrum[ch][i] - requant), 2.0); */
						tmp_linediff = (ABS(tmp_p_spectrum) - tmp_requant);
						error_energy += tmp_linediff*tmp_linediff;
					} /* --- for (i=sfb_offset[sb] --- */
					if ( ( allowed_dist[ch][sb] != 0) && (energy[MONO_CHAN][sb] > allowed_dist[ch][sb]) ){
						ratio = error_energy / allowed_dist[ch][sb];
					} else {
						ratio = 1e-15;
						sfb_amplify_check[sb] = 1;
					}

					/* find the scalefactor band with the largest error ratio */
					if ((ratio > maxRatio) && (scale_factor[sb]<60) && aacAllowScalefacs){
						scale_factor[sb]++;
						sfb_amplify_check[sb] = 1;
						calc_sf[sb]=1;
					} else {
						calc_sf[sb]=0;
					}
					if ( (ratio > largest_ratio)&& (scale_factor[sb]<60) ){
						largest_ratio = ratio;
					}
				} /* ---  for (sb=0; --- */
			}
			/* amplify the scalefactor of the worst scalefactor band */
			/* check to see if all the sfb's have been amplified.*/
			/* if they have been all amplified, then all_amplified remains at 1 and we're done iterating */
			all_amplified = 1;
			for(j=0; j<quantInfo->nr_of_sfb;j++){
				if (sfb_amplify_check[j] == 0   )
					all_amplified = 0;
			}

		} while ((largest_ratio > maxRatio) && (all_amplified == 0)  ); 

		/* find a good method to section the scalefactor bands into huffman codebook sections */
		bit_search(quant,              /* Quantized spectral values */
			/* book_vector, */  /* Now in quantInfo. */
//			huff,               /* Huffman codebooks */
			quantInfo);         /* Quantization information */

		/* calculate the amount of bits needed for encoding the huffman codebook numbers */
		book_bits = sort_book_numbers(quantInfo,             /* Quantization information */
			/* book_vector,*/      /* Now in quantInfo. */
			output_book_vector,    /* Output codebook vector, formatted for bitstream */
			fixed_stream,          /* Bitstream */
			0);                    /* Write flag: 0 count, 1 write */

		/* calculate the amount of bits needed for the spectral values */
		quantInfo -> spectralCount = 0;
		spectral_bits = 0;
		for(k=0;k< quantInfo -> nr_of_sfb;k++) {  
			calc_sf[k]=1;
			spectral_bits += output_bits(/* block_type,*/     /* Now in quantInfo */    
				quantInfo,
//				huff,     
				quantInfo->book_vector[k],
				quant,
				quantInfo->sfb_offset[k], 
				quantInfo->sfb_offset[k+1]-quantInfo->sfb_offset[k], 
				0);
		}

		/* the number of bits for the scalefactors */
		sf_bits = write_scalefactor_bitstream(/* nr_of_sfb[MONO_CHAN],*//* Now in quantInfo */
			fixed_stream,             /* Bitstream */  
			0,                        /* Write flag */
			quantInfo
			);               
		max_bits = spectral_bits + sf_bits + book_bits + extra_bits;

		if (all_amplified){ 
			maxRatio = maxRatio*2;
			*common_scalefac += 1;      
		}

		*common_scalefac += 1;
		if ( *common_scalefac > 200 ) {
			//CommonExit(-1,"Error in loops: common_scalefac");
			return MBERROR;
		}

		if (varBitRate) {
			check = 0; //(count-- > 0) ? 1 : 0;
		} else {
			check = (max_bits > average_block_bits) ? 1 : 0;
		}

	} while( check );
//	} while( max_bits > average_block_bits);


	*common_scalefac = store_common_scalefac;

	/* offset the differenec of common_scalefac and scalefactors by SF_OFFSET  */
	for (i=0; i<quantInfo->nr_of_sfb; i++){
		if ((ptr_book_vector[i]!=INTENSITY_HCB)&&(ptr_book_vector[i]!=INTENSITY_HCB2)) {
			scale_factor[i] = *common_scalefac - scale_factor[i] + SF_OFFSET;
		}
	}
	*common_scalefac = global_gain = scale_factor[0];

	/* place the codewords and their respective lengths in arrays data[] and len[] respectively */
	/* there are 'counter' elements in each array, and these are variable length arrays depending on the input */

	quantInfo -> spectralCount = 0;
	for(k=0;k< quantInfo -> nr_of_sfb; k++) {  
		spectral_bits += output_bits(
			quantInfo,
			quantInfo->book_vector[k],
			quant,
			quantInfo->sfb_offset[k],
			quantInfo->sfb_offset[k+1]-quantInfo->sfb_offset[k], 
			1);
	}

#if 0 /* No prediction anyway. */
	/* write the reconstructed spectrum to the output for use with prediction */
	{
		int ch, i;
		for( ch=0; ch<nr_of_chan; ch++ ) {
			for (sb=0; sb<quantInfo -> nr_of_sfb; sb++){
				if ((ptr_book_vector[sb]==INTENSITY_HCB)||(ptr_book_vector[sb]==INTENSITY_HCB2)){
					for (i=sfb_offset[sb]; i<sfb_offset[sb+1]; i++){
						p_reconstructed_spectrum[ch][i]=673;
					}
				} else {
					for (i=sfb_offset[sb]; i<sfb_offset[sb+1]; i++){
						p_reconstructed_spectrum[ch][i] = sgn(quant[ch][i]) * requant[ch][i]; 
					}
				}
			}
		}
	}
#endif

	return MBNO_ERROR;
}

int sort_for_grouping(AACQuantInfo* quantInfo,        /* ptr to quantization information */
		      int sfb_width_table[],          /* Widths of single window */
		      double *p_spectrum[],           /* Spectral values, noninterleaved */
		      double *SigMaskRatio,
		      double *PsySigMaskRatio)
{
	int i,j,ii;
	int index = 0;
	QUANT_TYPE tmp[1024];
	int book=1;
	int group_offset=0;
	int k=0;
	int windowOffset = 0;

	/* set up local variables for used quantInfo elements */
	int* sfb_offset = quantInfo -> sfb_offset;
	int* nr_of_sfb = &(quantInfo -> nr_of_sfb);
	int* window_group_length;
	int num_window_groups;
	*nr_of_sfb = quantInfo->max_sfb;              /* Init to max_sfb */
	window_group_length = quantInfo -> window_group_length;
	num_window_groups = quantInfo -> num_window_groups;
	
	/* calc org sfb_offset just for shortblock */
	sfb_offset[k]=0;
	for (k=1 ; k <*nr_of_sfb+1; k++) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -