qc_main.c revision 956c553ab0ce72f8074ad0fda2ffd66a0305700c
1/*
2 ** Copyright 2003-2010, VisualOn, Inc.
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 **     http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16/*******************************************************************************
17	File:		qc_main.c
18
19	Content:	Quantizing & coding functions
20
21*******************************************************************************/
22
23#include "basic_op.h"
24#include "oper_32b.h"
25#include "qc_main.h"
26#include "quantize.h"
27#include "interface.h"
28#include "adj_thr.h"
29#include "sf_estim.h"
30#include "stat_bits.h"
31#include "bit_cnt.h"
32#include "dyn_bits.h"
33#include "channel_map.h"
34#include "memalign.h"
35
36
37typedef enum{
38  FRAME_LEN_BYTES_MODULO =  1,
39  FRAME_LEN_BYTES_INT    =  2
40}FRAME_LEN_RESULT_MODE;
41
42static const Word16 maxFillElemBits = 7 + 270*8;
43
44/* forward declarations */
45
46static Word16 calcMaxValueInSfb(Word16 sfbCnt,
47                                Word16 maxSfbPerGroup,
48                                Word16 sfbPerGroup,
49                                Word16 sfbOffset[MAX_GROUPED_SFB],
50                                Word16 quantSpectrum[FRAME_LEN_LONG],
51                                UWord16 maxValue[MAX_GROUPED_SFB]);
52
53
54/*****************************************************************************
55*
56* function name: calcFrameLen
57* description: estimate the frame length according the bitrates
58*
59*****************************************************************************/
60static Word16 calcFrameLen(Word32 bitRate,
61                           Word32 sampleRate,
62                           FRAME_LEN_RESULT_MODE mode)
63{
64
65  Word32 result;
66  Word32 quot;
67
68  result = (FRAME_LEN_LONG >> 3) * bitRate;
69  quot = result / sampleRate;
70
71
72  if (mode == FRAME_LEN_BYTES_MODULO) {
73    result -= quot * sampleRate;
74  }
75  else { /* FRAME_LEN_BYTES_INT */
76    result = quot;
77  }
78
79  return result;
80}
81
82/*****************************************************************************
83*
84*  function name:framePadding
85*  description: Calculates if padding is needed for actual frame
86*  returns: paddingOn or not
87*
88*****************************************************************************/
89static Word16 framePadding(Word32 bitRate,
90                           Word32 sampleRate,
91                           Word32 *paddingRest)
92{
93  Word16 paddingOn;
94  Word16 difference;
95
96  paddingOn = 0;
97
98  difference = calcFrameLen( bitRate,
99                             sampleRate,
100                             FRAME_LEN_BYTES_MODULO );
101  *paddingRest = *paddingRest - difference;
102
103
104  if (*paddingRest <= 0 ) {
105    paddingOn = 1;
106    *paddingRest = *paddingRest + sampleRate;
107  }
108
109  return paddingOn;
110}
111
112
113/*********************************************************************************
114*
115* function name: QCOutNew
116* description: init qcout parameter
117* returns:     0 if success
118*
119**********************************************************************************/
120
121Word16 QCOutNew(QC_OUT *hQC, Word16 nChannels, VO_MEM_OPERATOR *pMemOP)
122{
123  Word32 i;
124  Word16 *quantSpec;
125  Word16 *scf;
126  UWord16 *maxValueInSfb;
127
128  quantSpec = (Word16 *)mem_malloc(pMemOP, nChannels * FRAME_LEN_LONG * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
129  if(NULL == quantSpec)
130	  return 1;
131  scf = (Word16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
132  if(NULL == scf)
133  {
134	  return 1;
135  }
136  maxValueInSfb = (UWord16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(UWord16), 32, VO_INDEX_ENC_AAC);
137  if(NULL == maxValueInSfb)
138  {
139	  return 1;
140  }
141
142  for (i=0; i<nChannels; i++) {
143    hQC->qcChannel[i].quantSpec = quantSpec + i*FRAME_LEN_LONG;
144
145    hQC->qcChannel[i].maxValueInSfb = maxValueInSfb + i*MAX_GROUPED_SFB;
146
147    hQC->qcChannel[i].scf = scf + i*MAX_GROUPED_SFB;
148  }
149
150  return 0;
151}
152
153
154/*********************************************************************************
155*
156* function name: QCOutDelete
157* description: unint qcout parameter
158* returns:      0 if success
159*
160**********************************************************************************/
161void QCOutDelete(QC_OUT* hQC, VO_MEM_OPERATOR *pMemOP)
162{
163   Word32 i;
164   if(hQC)
165   {
166      if(hQC->qcChannel[0].quantSpec);
167		 mem_free(pMemOP, hQC->qcChannel[0].quantSpec, VO_INDEX_ENC_AAC);
168
169      if(hQC->qcChannel[0].maxValueInSfb)
170		  mem_free(pMemOP, hQC->qcChannel[0].maxValueInSfb, VO_INDEX_ENC_AAC);
171
172	  if(hQC->qcChannel[0].scf)
173		  mem_free(pMemOP, hQC->qcChannel[0].scf, VO_INDEX_ENC_AAC);
174
175	  for (i=0; i<MAX_CHANNELS; i++) {
176		  hQC->qcChannel[i].quantSpec = NULL;
177
178		  hQC->qcChannel[i].maxValueInSfb = NULL;
179
180		  hQC->qcChannel[i].scf = NULL;
181	  }
182   }
183}
184
185/*********************************************************************************
186*
187* function name: QCNew
188* description: set QC to zero
189* returns:     0 if success
190*
191**********************************************************************************/
192Word16 QCNew(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
193{
194  pMemOP->Set(VO_INDEX_ENC_AAC, hQC,0,sizeof(QC_STATE));
195
196  return (0);
197}
198
199/*********************************************************************************
200*
201* function name: QCDelete
202* description: unint qcout parameter
203*
204**********************************************************************************/
205void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
206{
207
208  /*
209     nothing to do
210  */
211  hQC=NULL;
212}
213
214/*********************************************************************************
215*
216* function name: QCInit
217* description: init QD parameter
218* returns:     0 if success
219*
220**********************************************************************************/
221Word16 QCInit(QC_STATE *hQC,
222              struct QC_INIT *init)
223{
224  hQC->nChannels       = init->elInfo->nChannelsInEl;
225  hQC->maxBitsTot      = init->maxBits;
226  hQC->bitResTot       = sub(init->bitRes, init->averageBits);
227  hQC->averageBitsTot  = init->averageBits;
228  hQC->maxBitFac       = init->maxBitFac;
229
230  hQC->padding.paddingRest = init->padding.paddingRest;
231
232  hQC->globStatBits    = 3;                          /* for ID_END */
233
234  /* channel elements init */
235  InitElementBits(&hQC->elementBits,
236                  *init->elInfo,
237                  init->bitrate,
238                  init->averageBits,
239                  hQC->globStatBits);
240
241  /* threshold parameter init */
242  AdjThrInit(&hQC->adjThr,
243             init->meanPe,
244             hQC->elementBits.chBitrate);
245
246  return 0;
247}
248
249
250/*********************************************************************************
251*
252* function name: QCMain
253* description:  quantization and coding the spectrum
254* returns:      0 if success
255*
256**********************************************************************************/
257Word16 QCMain(QC_STATE* hQC,
258              ELEMENT_BITS* elBits,
259              ATS_ELEMENT* adjThrStateElement,
260              PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],  /* may be modified in-place */
261              PSY_OUT_ELEMENT* psyOutElement,
262              QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],    /* out                      */
263              QC_OUT_ELEMENT* qcOutElement,
264              Word16 nChannels,
265			  Word16 ancillaryDataBytes)
266{
267  Word16 maxChDynBits[MAX_CHANNELS];
268  Word16 chBitDistribution[MAX_CHANNELS];
269  Word32 ch;
270
271  if (elBits->bitResLevel < 0) {
272    return -1;
273  }
274
275  if (elBits->bitResLevel > elBits->maxBitResBits) {
276    return -1;
277  }
278
279  qcOutElement->staticBitsUsed = countStaticBitdemand(psyOutChannel,
280                                                      psyOutElement,
281                                                      nChannels,
282													  qcOutElement->adtsUsed);
283
284
285  if (ancillaryDataBytes) {
286    qcOutElement->ancBitsUsed = 7 + (ancillaryDataBytes << 3);
287
288    if (ancillaryDataBytes >= 15)
289      qcOutElement->ancBitsUsed = qcOutElement->ancBitsUsed + 8;
290  }
291  else {
292    qcOutElement->ancBitsUsed = 0;
293  }
294
295  CalcFormFactor(hQC->logSfbFormFactor, hQC->sfbNRelevantLines, hQC->logSfbEnergy, psyOutChannel, nChannels);
296
297  /*adjust thresholds for the desired bitrate */
298  AdjustThresholds(&hQC->adjThr,
299                   adjThrStateElement,
300                   psyOutChannel,
301                   psyOutElement,
302                   chBitDistribution,
303                   hQC->logSfbEnergy,
304                   hQC->sfbNRelevantLines,
305                   qcOutElement,
306				   elBits,
307				   nChannels,
308				   hQC->maxBitFac);
309
310  /*estimate scale factors */
311  EstimateScaleFactors(psyOutChannel,
312                       qcOutChannel,
313                       hQC->logSfbEnergy,
314                       hQC->logSfbFormFactor,
315                       hQC->sfbNRelevantLines,
316                       nChannels);
317
318  /* condition to prevent empty bitreservoir */
319  for (ch = 0; ch < nChannels; ch++) {
320    Word32 maxDynBits;
321    maxDynBits = elBits->averageBits + elBits->bitResLevel - 7; /* -7 bec. of align bits */
322    maxDynBits = maxDynBits - qcOutElement->staticBitsUsed + qcOutElement->ancBitsUsed;
323    maxChDynBits[ch] = extract_l(chBitDistribution[ch] * maxDynBits / 1000);
324  }
325
326  qcOutElement->dynBitsUsed = 0;
327  for (ch = 0; ch < nChannels; ch++) {
328    Word32 chDynBits;
329    Flag   constraintsFulfilled;
330    Word32 iter;
331    iter = 0;
332    do {
333      constraintsFulfilled = 1;
334
335      QuantizeSpectrum(psyOutChannel[ch].sfbCnt,
336                       psyOutChannel[ch].maxSfbPerGroup,
337                       psyOutChannel[ch].sfbPerGroup,
338                       psyOutChannel[ch].sfbOffsets,
339                       psyOutChannel[ch].mdctSpectrum,
340                       qcOutChannel[ch].globalGain,
341                       qcOutChannel[ch].scf,
342                       qcOutChannel[ch].quantSpec);
343
344      if (calcMaxValueInSfb(psyOutChannel[ch].sfbCnt,
345                            psyOutChannel[ch].maxSfbPerGroup,
346                            psyOutChannel[ch].sfbPerGroup,
347                            psyOutChannel[ch].sfbOffsets,
348                            qcOutChannel[ch].quantSpec,
349                            qcOutChannel[ch].maxValueInSfb) > MAX_QUANT) {
350        constraintsFulfilled = 0;
351      }
352
353      chDynBits = dynBitCount(qcOutChannel[ch].quantSpec,
354                              qcOutChannel[ch].maxValueInSfb,
355                              qcOutChannel[ch].scf,
356                              psyOutChannel[ch].windowSequence,
357                              psyOutChannel[ch].sfbCnt,
358                              psyOutChannel[ch].maxSfbPerGroup,
359                              psyOutChannel[ch].sfbPerGroup,
360                              psyOutChannel[ch].sfbOffsets,
361                              &qcOutChannel[ch].sectionData);
362
363      if (chDynBits >= maxChDynBits[ch]) {
364        constraintsFulfilled = 0;
365      }
366
367      if (!constraintsFulfilled) {
368        qcOutChannel[ch].globalGain = qcOutChannel[ch].globalGain + 1;
369      }
370
371      iter = iter + 1;
372
373    } while(!constraintsFulfilled);
374
375    qcOutElement->dynBitsUsed = qcOutElement->dynBitsUsed + chDynBits;
376
377    qcOutChannel[ch].mdctScale    = psyOutChannel[ch].mdctScale;
378    qcOutChannel[ch].groupingMask = psyOutChannel[ch].groupingMask;
379    qcOutChannel[ch].windowShape  = psyOutChannel[ch].windowShape;
380  }
381
382  /* save dynBitsUsed for correction of bits2pe relation */
383  AdjThrUpdate(adjThrStateElement, qcOutElement->dynBitsUsed);
384
385  {
386    Word16 bitResSpace = elBits->maxBitResBits - elBits->bitResLevel;
387    Word16 deltaBitRes = elBits->averageBits -
388                        (qcOutElement->staticBitsUsed +
389                         qcOutElement->dynBitsUsed + qcOutElement->ancBitsUsed);
390
391    qcOutElement->fillBits = max(0, (deltaBitRes - bitResSpace));
392  }
393
394  return 0; /* OK */
395}
396
397
398/*********************************************************************************
399*
400* function name: calcMaxValueInSfb
401* description:  search the max Spectrum in one sfb
402*
403**********************************************************************************/
404static Word16 calcMaxValueInSfb(Word16 sfbCnt,
405                                Word16 maxSfbPerGroup,
406                                Word16 sfbPerGroup,
407                                Word16 sfbOffset[MAX_GROUPED_SFB],
408                                Word16 quantSpectrum[FRAME_LEN_LONG],
409                                UWord16 maxValue[MAX_GROUPED_SFB])
410{
411  Word16 sfbOffs, sfb;
412  Word16 maxValueAll;
413
414  maxValueAll = 0;
415
416  for(sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup) {
417    for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
418      Word16 line;
419      Word16 maxThisSfb;
420      maxThisSfb = 0;
421
422      for (line = sfbOffset[sfbOffs+sfb]; line < sfbOffset[sfbOffs+sfb+1]; line++) {
423        Word16 absVal;
424        absVal = abs_s(quantSpectrum[line]);
425        maxThisSfb = max(maxThisSfb, absVal);
426      }
427
428      maxValue[sfbOffs+sfb] = maxThisSfb;
429      maxValueAll = max(maxValueAll, maxThisSfb);
430    }
431  }
432  return maxValueAll;
433}
434
435
436/*********************************************************************************
437*
438* function name: updateBitres
439* description: update bitreservoir
440*
441**********************************************************************************/
442void updateBitres(QC_STATE* qcKernel,
443                  QC_OUT*   qcOut)
444
445{
446  ELEMENT_BITS *elBits;
447
448  qcKernel->bitResTot = 0;
449
450  elBits = &qcKernel->elementBits;
451
452
453  if (elBits->averageBits > 0) {
454    /* constant bitrate */
455    Word16 bitsUsed;
456    bitsUsed = (qcOut->qcElement.staticBitsUsed + qcOut->qcElement.dynBitsUsed) +
457                   (qcOut->qcElement.ancBitsUsed + qcOut->qcElement.fillBits);
458    elBits->bitResLevel = elBits->bitResLevel + (elBits->averageBits - bitsUsed);
459    qcKernel->bitResTot = qcKernel->bitResTot + elBits->bitResLevel;
460  }
461  else {
462    /* variable bitrate */
463    elBits->bitResLevel = elBits->maxBits;
464    qcKernel->bitResTot = qcKernel->maxBitsTot;
465  }
466}
467
468/*********************************************************************************
469*
470* function name: FinalizeBitConsumption
471* description: count bits used
472*
473**********************************************************************************/
474Word16 FinalizeBitConsumption(QC_STATE *qcKernel,
475                              QC_OUT* qcOut)
476{
477  Word32 nFullFillElem;
478  Word32 totFillBits;
479  Word16 diffBits;
480  Word16 bitsUsed;
481
482  totFillBits = 0;
483
484  qcOut->totStaticBitsUsed = qcKernel->globStatBits;
485  qcOut->totStaticBitsUsed += qcOut->qcElement.staticBitsUsed;
486  qcOut->totDynBitsUsed    = qcOut->qcElement.dynBitsUsed;
487  qcOut->totAncBitsUsed    = qcOut->qcElement.ancBitsUsed;
488  qcOut->totFillBits       = qcOut->qcElement.fillBits;
489
490  if (qcOut->qcElement.fillBits) {
491    totFillBits += qcOut->qcElement.fillBits;
492  }
493
494  nFullFillElem = (max((qcOut->totFillBits - 1), 0) / maxFillElemBits) * maxFillElemBits;
495
496  qcOut->totFillBits = qcOut->totFillBits - nFullFillElem;
497
498  /* check fill elements */
499
500  if (qcOut->totFillBits > 0) {
501    /* minimum Fillelement contains 7 (TAG + byte cnt) bits */
502    qcOut->totFillBits = max(7, qcOut->totFillBits);
503    /* fill element size equals n*8 + 7 */
504    qcOut->totFillBits = qcOut->totFillBits + ((8 - ((qcOut->totFillBits - 7) & 0x0007)) & 0x0007);
505  }
506
507  qcOut->totFillBits = qcOut->totFillBits + nFullFillElem;
508
509  /* now distribute extra fillbits and alignbits over channel elements */
510  qcOut->alignBits = 7 - ((qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed +
511                           qcOut->totAncBitsUsed + qcOut->totFillBits - 1) & 0x0007);
512
513
514  if ( (qcOut->alignBits + qcOut->totFillBits - totFillBits == 8) &&
515       (qcOut->totFillBits > 8))
516    qcOut->totFillBits = qcOut->totFillBits - 8;
517
518
519  diffBits = qcOut->alignBits + qcOut->totFillBits - totFillBits;
520
521  if(diffBits>=0) {
522    qcOut->qcElement.fillBits += diffBits;
523  }
524
525  bitsUsed = qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed + qcOut->totAncBitsUsed;
526  bitsUsed = bitsUsed + qcOut->totFillBits + qcOut->alignBits;
527
528  if (bitsUsed > qcKernel->maxBitsTot) {
529    return -1;
530  }
531  return bitsUsed;
532}
533
534
535/*********************************************************************************
536*
537* function name: AdjustBitrate
538* description:  adjusts framelength via padding on a frame to frame basis,
539*               to achieve a bitrate that demands a non byte aligned
540*               framelength
541* return:       errorcode
542*
543**********************************************************************************/
544Word16 AdjustBitrate(QC_STATE        *hQC,
545                     Word32           bitRate,    /* total bitrate */
546                     Word32           sampleRate) /* output sampling rate */
547{
548  Word16 paddingOn;
549  Word16 frameLen;
550  Word16 codeBits;
551  Word16 codeBitsLast;
552
553  /* Do we need a extra padding byte? */
554  paddingOn = framePadding(bitRate,
555                           sampleRate,
556                           &hQC->padding.paddingRest);
557
558  /* frame length */
559  frameLen = paddingOn + calcFrameLen(bitRate,
560                                      sampleRate,
561                                      FRAME_LEN_BYTES_INT);
562
563  frameLen = frameLen << 3;
564  codeBitsLast = hQC->averageBitsTot - hQC->globStatBits;
565  codeBits     = frameLen - hQC->globStatBits;
566
567  /* calculate bits for every channel element */
568  if (codeBits != codeBitsLast) {
569    Word16 totalBits = 0;
570
571    hQC->elementBits.averageBits = (hQC->elementBits.relativeBits * codeBits) >> 16; /* relativeBits was scaled down by 2 */
572    totalBits += hQC->elementBits.averageBits;
573
574    hQC->elementBits.averageBits = hQC->elementBits.averageBits + (codeBits - totalBits);
575  }
576
577  hQC->averageBitsTot = frameLen;
578
579  return 0;
580}
581