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