• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2018 Fraunhofer-Gesellschaft zur Förderung der angewandten
5 Forschung e.V. All rights reserved.
6 
7  1.    INTRODUCTION
8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
11 a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
14 general perceptual audio codecs. AAC-ELD is considered the best-performing
15 full-bandwidth communications codec by independent studies and is widely
16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
17 specifications.
18 
19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
20 those of Fraunhofer) may be obtained through Via Licensing
21 (www.vialicensing.com) or through the respective patent owners individually for
22 the purpose of encoding or decoding bit streams in products that are compliant
23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
24 Android devices already license these patent claims through Via Licensing or
25 directly from the patent owners, and therefore FDK AAC Codec software may
26 already be covered under those patent licenses when it is used for those
27 licensed purposes only.
28 
29 Commercially-licensed AAC software libraries, including floating-point versions
30 with enhanced sound quality, are also available from Fraunhofer. Users are
31 encouraged to check the Fraunhofer website for additional applications
32 information and documentation.
33 
34 2.    COPYRIGHT LICENSE
35 
36 Redistribution and use in source and binary forms, with or without modification,
37 are permitted without payment of copyright license fees provided that you
38 satisfy the following conditions:
39 
40 You must retain the complete text of this software license in redistributions of
41 the FDK AAC Codec or your modifications thereto in source code form.
42 
43 You must retain the complete text of this software license in the documentation
44 and/or other materials provided with redistributions of the FDK AAC Codec or
45 your modifications thereto in binary form. You must make available free of
46 charge copies of the complete source code of the FDK AAC Codec and your
47 modifications thereto to recipients of copies in binary form.
48 
49 The name of Fraunhofer may not be used to endorse or promote products derived
50 from this library without prior written permission.
51 
52 You may not charge copyright license fees for anyone to use, copy or distribute
53 the FDK AAC Codec software or your modifications thereto.
54 
55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
56 that you changed the software and the date of any change. For modified versions
57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
59 AAC Codec Library for Android."
60 
61 3.    NO PATENT LICENSE
62 
63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
65 Fraunhofer provides no warranty of patent non-infringement with respect to this
66 software.
67 
68 You may use this FDK AAC Codec software or modifications thereto only for
69 purposes that are authorized by appropriate patent licenses.
70 
71 4.    DISCLAIMER
72 
73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
75 including but not limited to the implied warranties of merchantability and
76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
78 or consequential damages, including but not limited to procurement of substitute
79 goods or services; loss of use, data, or profits, or business interruption,
80 however caused and on any theory of liability, whether in contract, strict
81 liability, or tort (including negligence), arising in any way out of the use of
82 this software, even if advised of the possibility of such damage.
83 
84 5.    CONTACT INFORMATION
85 
86 Fraunhofer Institute for Integrated Circuits IIS
87 Attention: Audio and Multimedia Departments - FDK AAC LL
88 Am Wolfsmantel 33
89 91058 Erlangen, Germany
90 
91 www.iis.fraunhofer.de/amm
92 amm-info@iis.fraunhofer.de
93 ----------------------------------------------------------------------------- */
94 
95 /*********************** MPEG surround decoder library *************************
96 
97    Author(s):
98 
99    Description: SAC Dec bitstream decoder
100 
101 *******************************************************************************/
102 
103 #include "sac_bitdec.h"
104 
105 #include "sac_dec_errorcodes.h"
106 #include "nlc_dec.h"
107 #include "sac_rom.h"
108 #include "FDK_matrixCalloc.h"
109 #include "sac_tsd.h"
110 
111 enum {
112   ottVsTotInactiv = 0,
113   ottVsTotDb1Activ = 1,
114   ottVsTotDb2Activ = 2,
115   ottVsTotDb1Db2Activ = 3
116 };
117 
SpatialDecDecodeHelperInfo(SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,UPMIXTYPE upmixType)118 static SACDEC_ERROR SpatialDecDecodeHelperInfo(
119     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, UPMIXTYPE upmixType) {
120   int i;
121   UINT syntaxFlags;
122 
123   /* Determine bit stream syntax */
124   syntaxFlags = 0;
125   switch (pSpatialSpecificConfig->coreCodec) {
126     case AOT_ER_AAC_ELD:
127     case AOT_ER_AAC_LD:
128       syntaxFlags |= SACDEC_SYNTAX_LD;
129       break;
130     case AOT_USAC:
131       syntaxFlags |= SACDEC_SYNTAX_USAC;
132       break;
133     case AOT_NONE:
134     default:
135       return MPS_UNSUPPORTED_FORMAT;
136   }
137 
138   pSpatialSpecificConfig->syntaxFlags = syntaxFlags;
139 
140   switch (pSpatialSpecificConfig->treeConfig) {
141     case TREE_212: {
142       pSpatialSpecificConfig->ottCLDdefault[0] = 0;
143     } break;
144     default:
145       return MPS_INVALID_TREECONFIG;
146   }
147 
148   if (syntaxFlags & SACDEC_SYNTAX_USAC) {
149     if (pSpatialSpecificConfig->bsOttBandsPhasePresent) {
150       pSpatialSpecificConfig->numOttBandsIPD =
151           pSpatialSpecificConfig->bsOttBandsPhase;
152     } else {
153       int numParameterBands;
154 
155       numParameterBands = pSpatialSpecificConfig->freqRes;
156       switch (numParameterBands) {
157         case 4:
158         case 5:
159           pSpatialSpecificConfig->numOttBandsIPD = 2;
160           break;
161         case 7:
162           pSpatialSpecificConfig->numOttBandsIPD = 3;
163           break;
164         case 10:
165           pSpatialSpecificConfig->numOttBandsIPD = 5;
166           break;
167         case 14:
168           pSpatialSpecificConfig->numOttBandsIPD = 7;
169           break;
170         case 20:
171         case 28:
172           pSpatialSpecificConfig->numOttBandsIPD = 10;
173           break;
174         default:
175           return MPS_INVALID_PARAMETERBANDS;
176       }
177     }
178   } else {
179     pSpatialSpecificConfig->numOttBandsIPD = 0;
180   }
181   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
182     {
183       pSpatialSpecificConfig->bitstreamOttBands[i] =
184           pSpatialSpecificConfig->freqRes;
185     }
186     {
187       pSpatialSpecificConfig->numOttBands[i] =
188           pSpatialSpecificConfig->bitstreamOttBands[i];
189       if (syntaxFlags & SACDEC_SYNTAX_USAC &&
190           !pSpatialSpecificConfig->bsOttBandsPhasePresent) {
191         if (pSpatialSpecificConfig->bResidualCoding &&
192             pSpatialSpecificConfig->ResidualConfig[i].bResidualPresent &&
193             (pSpatialSpecificConfig->numOttBandsIPD <
194              pSpatialSpecificConfig->ResidualConfig[i].nResidualBands)) {
195           pSpatialSpecificConfig->numOttBandsIPD =
196               pSpatialSpecificConfig->ResidualConfig[i].nResidualBands;
197         }
198       }
199     }
200   } /* i */
201 
202   return MPS_OK;
203 }
204 
205 /*******************************************************************************
206  Functionname: SpatialDecParseExtensionConfig
207  *******************************************************************************
208 
209  Description:
210 
211  Arguments:
212 
213  Return:
214 
215 *******************************************************************************/
216 
SpatialDecParseExtensionConfig(HANDLE_FDK_BITSTREAM bitstream,SPATIAL_SPECIFIC_CONFIG * config,int numOttBoxes,int numTttBoxes,int numOutChan,int bitsAvailable)217 static SACDEC_ERROR SpatialDecParseExtensionConfig(
218     HANDLE_FDK_BITSTREAM bitstream, SPATIAL_SPECIFIC_CONFIG *config,
219     int numOttBoxes, int numTttBoxes, int numOutChan, int bitsAvailable) {
220   SACDEC_ERROR err = MPS_OK;
221   INT ba = bitsAvailable;
222 
223   config->sacExtCnt = 0;
224   config->bResidualCoding = 0;
225 
226   ba = fMin((int)FDKgetValidBits(bitstream), ba);
227 
228   while ((ba >= 8) && (config->sacExtCnt < MAX_NUM_EXT_TYPES)) {
229     int bitsRead, nFillBits;
230     INT tmp;
231     UINT sacExtLen;
232 
233     config->sacExtType[config->sacExtCnt] = FDKreadBits(bitstream, 4);
234     ba -= 4;
235 
236     sacExtLen = FDKreadBits(bitstream, 4);
237     ba -= 4;
238 
239     if (sacExtLen == 15) {
240       sacExtLen += FDKreadBits(bitstream, 8);
241       ba -= 8;
242       if (sacExtLen == 15 + 255) {
243         sacExtLen += FDKreadBits(bitstream, 16);
244         ba -= 16;
245       }
246     }
247 
248     tmp = (INT)FDKgetValidBits(
249         bitstream); /* Extension config payload start anchor. */
250     if ((tmp <= 0) || (tmp < (INT)sacExtLen * 8) || (ba < (INT)sacExtLen * 8)) {
251       err = MPS_PARSE_ERROR;
252       goto bail;
253     }
254 
255     switch (config->sacExtType[config->sacExtCnt]) {
256       default:; /* unknown extension data => do nothing */
257     }
258 
259     /* skip remaining extension data */
260     bitsRead = tmp - FDKgetValidBits(bitstream);
261     nFillBits = 8 * sacExtLen - bitsRead;
262 
263     if (nFillBits < 0) {
264       err = MPS_PARSE_ERROR;
265       goto bail;
266     } else {
267       /* Skip fill bits or an unkown extension. */
268       FDKpushFor(bitstream, nFillBits);
269     }
270 
271     ba -= 8 * sacExtLen;
272     config->sacExtCnt++;
273   }
274 
275 bail:
276   return err;
277 }
278 
SpatialDecParseSpecificConfigHeader(HANDLE_FDK_BITSTREAM bitstream,SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,AUDIO_OBJECT_TYPE coreCodec,SPATIAL_DEC_UPMIX_TYPE upmixType)279 SACDEC_ERROR SpatialDecParseSpecificConfigHeader(
280     HANDLE_FDK_BITSTREAM bitstream,
281     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig,
282     AUDIO_OBJECT_TYPE coreCodec, SPATIAL_DEC_UPMIX_TYPE upmixType) {
283   SACDEC_ERROR err = MPS_OK;
284   INT numFillBits;
285   int sacHeaderLen = 0;
286   int sacTimeAlignFlag = 0;
287 
288   sacTimeAlignFlag = FDKreadBits(bitstream, 1);
289   sacHeaderLen = FDKreadBits(bitstream, 7);
290 
291   if (sacHeaderLen == 127) {
292     sacHeaderLen += FDKreadBits(bitstream, 16);
293   }
294   numFillBits = (INT)FDKgetValidBits(bitstream);
295 
296   err = SpatialDecParseSpecificConfig(bitstream, pSpatialSpecificConfig,
297                                       sacHeaderLen, coreCodec);
298 
299   numFillBits -=
300       (INT)FDKgetValidBits(bitstream); /* the number of read bits (tmpBits) */
301   numFillBits = (8 * sacHeaderLen) - numFillBits;
302   if (numFillBits < 0) {
303     /* Parsing went wrong */
304     err = MPS_PARSE_ERROR;
305   }
306   /* Move to the very end of the SSC */
307   FDKpushBiDirectional(bitstream, numFillBits);
308 
309   if ((err == MPS_OK) && sacTimeAlignFlag) {
310     /* not supported */
311     FDKreadBits(bitstream, 16);
312     err = MPS_UNSUPPORTED_CONFIG;
313   }
314 
315   /* Derive additional helper variables */
316   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, (UPMIXTYPE)upmixType);
317 
318   return err;
319 }
320 
SpatialDecParseMps212Config(HANDLE_FDK_BITSTREAM bitstream,SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,int samplingRate,AUDIO_OBJECT_TYPE coreCodec,INT stereoConfigIndex,INT coreSbrFrameLengthIndex)321 SACDEC_ERROR SpatialDecParseMps212Config(
322     HANDLE_FDK_BITSTREAM bitstream,
323     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, int samplingRate,
324     AUDIO_OBJECT_TYPE coreCodec, INT stereoConfigIndex,
325     INT coreSbrFrameLengthIndex) {
326   int i;
327 
328   FDKmemclear(pSpatialSpecificConfig, sizeof(SPATIAL_SPECIFIC_CONFIG));
329 
330   pSpatialSpecificConfig->stereoConfigIndex = stereoConfigIndex;
331   pSpatialSpecificConfig->coreSbrFrameLengthIndex = coreSbrFrameLengthIndex;
332   pSpatialSpecificConfig->freqRes =
333       (SPATIALDEC_FREQ_RES)freqResTable[FDKreadBits(bitstream, 3)];
334   if (pSpatialSpecificConfig->freqRes == 0) {
335     return MPS_PARSE_ERROR; /* reserved value */
336   }
337 
338   switch (coreCodec) {
339     case AOT_DRM_USAC:
340       pSpatialSpecificConfig->bsFixedGainDMX =
341           (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
342       /* tempShapeConfig = (bsTempShapeConfigDrm == 1) ? 3 : 0 */
343       pSpatialSpecificConfig->tempShapeConfig =
344           (SPATIALDEC_TS_CONF)(FDKreadBits(bitstream, 1) * 3);
345       pSpatialSpecificConfig->decorrConfig = (SPATIALDEC_DECORR_CONF)0;
346       pSpatialSpecificConfig->bsDecorrType = 0;
347       break;
348     case AOT_USAC:
349       pSpatialSpecificConfig->bsFixedGainDMX =
350           (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
351       pSpatialSpecificConfig->tempShapeConfig =
352           (SPATIALDEC_TS_CONF)FDKreadBits(bitstream, 2);
353       pSpatialSpecificConfig->decorrConfig =
354           (SPATIALDEC_DECORR_CONF)FDKreadBits(bitstream, 2);
355       if (pSpatialSpecificConfig->decorrConfig > 2) {
356         return MPS_PARSE_ERROR; /* reserved value */
357       }
358       pSpatialSpecificConfig->bsDecorrType = 0;
359       break;
360     default:
361       return MPS_UNSUPPORTED_FORMAT;
362   }
363   pSpatialSpecificConfig->nTimeSlots = (coreSbrFrameLengthIndex == 4) ? 64 : 32;
364   pSpatialSpecificConfig->bsHighRateMode = (UCHAR)FDKreadBits(bitstream, 1);
365 
366   {
367     pSpatialSpecificConfig->bsPhaseCoding = (UCHAR)FDKreadBits(bitstream, 1);
368     pSpatialSpecificConfig->bsOttBandsPhasePresent =
369         (UCHAR)FDKreadBits(bitstream, 1);
370     if (pSpatialSpecificConfig->bsOttBandsPhasePresent) {
371       if (MAX_PARAMETER_BANDS < (pSpatialSpecificConfig->bsOttBandsPhase =
372                                      FDKreadBits(bitstream, 5))) {
373         return MPS_PARSE_ERROR;
374       }
375     } else {
376       pSpatialSpecificConfig->bsOttBandsPhase = 0;
377     }
378   }
379 
380   if (stereoConfigIndex > 1) { /* do residual coding */
381     pSpatialSpecificConfig->bResidualCoding = 1;
382     pSpatialSpecificConfig->ResidualConfig->bResidualPresent = 1;
383     if (pSpatialSpecificConfig->freqRes <
384         (pSpatialSpecificConfig->ResidualConfig->nResidualBands =
385              FDKreadBits(bitstream, 5))) {
386       return MPS_PARSE_ERROR;
387     }
388     pSpatialSpecificConfig->bsOttBandsPhase =
389         fMax(pSpatialSpecificConfig->bsOttBandsPhase,
390              pSpatialSpecificConfig->ResidualConfig->nResidualBands);
391     pSpatialSpecificConfig->bsPseudoLr = (UCHAR)FDKreadBits(bitstream, 1);
392 
393     if (pSpatialSpecificConfig->bsPhaseCoding) {
394       pSpatialSpecificConfig->bsPhaseCoding = 3;
395     }
396   } else {
397     pSpatialSpecificConfig->bResidualCoding = 0;
398     pSpatialSpecificConfig->ResidualConfig->bResidualPresent = 0;
399   }
400 
401   if (pSpatialSpecificConfig->tempShapeConfig == 2) {
402     switch (coreCodec) {
403       case AOT_USAC:
404         pSpatialSpecificConfig->envQuantMode = FDKreadBits(bitstream, 1);
405         break;
406       default: /* added to avoid compiler warning */
407         break; /* added to avoid compiler warning */
408     }
409   }
410 
411   /* Static parameters */
412 
413   pSpatialSpecificConfig->samplingFreq =
414       samplingRate; /* wrong for stereoConfigIndex == 3 but value is unused */
415   pSpatialSpecificConfig->treeConfig = SPATIALDEC_MODE_RSVD7;
416   pSpatialSpecificConfig->nOttBoxes =
417       treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
418   pSpatialSpecificConfig->nInputChannels =
419       treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
420   pSpatialSpecificConfig->nOutputChannels =
421       treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
422 
423   pSpatialSpecificConfig->bArbitraryDownmix = 0;
424 
425   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
426     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
427   }
428 
429   if (coreCodec == AOT_DRM_USAC) {
430     /* MPS payload is MPEG conform -> no need for pseudo DRM AOT */
431     coreCodec = AOT_USAC;
432   }
433   pSpatialSpecificConfig->coreCodec = coreCodec;
434 
435   /* Derive additional helper variables */
436   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
437 
438   return MPS_OK;
439 }
440 
SpatialDecParseSpecificConfig(HANDLE_FDK_BITSTREAM bitstream,SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,int sacHeaderLen,AUDIO_OBJECT_TYPE coreCodec)441 SACDEC_ERROR SpatialDecParseSpecificConfig(
442     HANDLE_FDK_BITSTREAM bitstream,
443     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, int sacHeaderLen,
444     AUDIO_OBJECT_TYPE coreCodec) {
445   SACDEC_ERROR err = MPS_OK;
446   int i;
447   int bsSamplingFreqIndex;
448   int bsFreqRes, b3DaudioMode = 0;
449   int numHeaderBits;
450   int cfgStartPos, bitsAvailable;
451 
452   FDKmemclear(pSpatialSpecificConfig, sizeof(SPATIAL_SPECIFIC_CONFIG));
453 
454   cfgStartPos = FDKgetValidBits(bitstream);
455   /* It might be that we do not know the SSC length beforehand. */
456   if (sacHeaderLen == 0) {
457     bitsAvailable = cfgStartPos;
458   } else {
459     bitsAvailable = 8 * sacHeaderLen;
460     if (bitsAvailable > cfgStartPos) {
461       err = MPS_PARSE_ERROR;
462       goto bail;
463     }
464   }
465 
466   bsSamplingFreqIndex = FDKreadBits(bitstream, 4);
467 
468   if (bsSamplingFreqIndex == 15) {
469     pSpatialSpecificConfig->samplingFreq = FDKreadBits(bitstream, 24);
470   } else {
471     pSpatialSpecificConfig->samplingFreq =
472         samplingFreqTable[bsSamplingFreqIndex];
473     if (pSpatialSpecificConfig->samplingFreq == 0) {
474       err = MPS_PARSE_ERROR;
475       goto bail;
476     }
477   }
478 
479   pSpatialSpecificConfig->nTimeSlots = FDKreadBits(bitstream, 5) + 1;
480   if ((pSpatialSpecificConfig->nTimeSlots < 1) ||
481       (pSpatialSpecificConfig->nTimeSlots > MAX_TIME_SLOTS)) {
482     err = MPS_PARSE_ERROR;
483     goto bail;
484   }
485 
486   bsFreqRes = FDKreadBits(bitstream, 3);
487 
488   pSpatialSpecificConfig->freqRes =
489       (SPATIALDEC_FREQ_RES)freqResTable_LD[bsFreqRes];
490 
491   pSpatialSpecificConfig->treeConfig =
492       (SPATIALDEC_TREE_CONFIG)FDKreadBits(bitstream, 4);
493 
494   if (pSpatialSpecificConfig->treeConfig != SPATIALDEC_MODE_RSVD7) {
495     err = MPS_UNSUPPORTED_CONFIG;
496     goto bail;
497   }
498 
499   {
500     pSpatialSpecificConfig->nOttBoxes =
501         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
502     pSpatialSpecificConfig->nTttBoxes =
503         treePropertyTable[pSpatialSpecificConfig->treeConfig].numTttBoxes;
504     pSpatialSpecificConfig->nInputChannels =
505         treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
506     pSpatialSpecificConfig->nOutputChannels =
507         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
508   }
509 
510   pSpatialSpecificConfig->quantMode =
511       (SPATIALDEC_QUANT_MODE)FDKreadBits(bitstream, 2);
512 
513   pSpatialSpecificConfig->bArbitraryDownmix = FDKreadBits(bitstream, 1);
514 
515   pSpatialSpecificConfig->bsFixedGainDMX =
516       (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
517 
518   pSpatialSpecificConfig->tempShapeConfig =
519       (SPATIALDEC_TS_CONF)FDKreadBits(bitstream, 2);
520   if (pSpatialSpecificConfig->tempShapeConfig > 2) {
521     return MPS_PARSE_ERROR; /* reserved value */
522   }
523 
524   pSpatialSpecificConfig->decorrConfig =
525       (SPATIALDEC_DECORR_CONF)FDKreadBits(bitstream, 2);
526   if (pSpatialSpecificConfig->decorrConfig > 2) {
527     return MPS_PARSE_ERROR; /* reserved value */
528   }
529 
530   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
531     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
532   }
533 
534   for (i = 0; i < pSpatialSpecificConfig->nTttBoxes; i++) {
535     int bTttDualMode = FDKreadBits(bitstream, 1);
536     FDKreadBits(bitstream, 3); /* not supported */
537 
538     if (bTttDualMode) {
539       FDKreadBits(bitstream, 8); /* not supported */
540     }
541   }
542 
543   if (pSpatialSpecificConfig->tempShapeConfig == 2) {
544     pSpatialSpecificConfig->envQuantMode = FDKreadBits(bitstream, 1);
545   }
546 
547   if (b3DaudioMode) {
548     if (FDKreadBits(bitstream, 2) == 0) { /* b3DaudioHRTFset ? */
549       int hc;
550       int HRTFnumBand;
551       int HRTFfreqRes = FDKreadBits(bitstream, 3);
552       int HRTFnumChan = FDKreadBits(bitstream, 4);
553       int HRTFasymmetric = FDKreadBits(bitstream, 1);
554 
555       HRTFnumBand = freqResTable_LD[HRTFfreqRes];
556 
557       for (hc = 0; hc < HRTFnumChan; hc++) {
558         FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFlevelLeft[hc][hb] */
559         if (HRTFasymmetric) {
560           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFlevelRight[hc][hb] */
561         }
562         if (FDKreadBits(bitstream, 1)) {          /* HRTFphase[hc] ? */
563           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFphaseLR[hc][hb] */
564         }
565         if (FDKreadBits(bitstream, 1)) {          /* HRTFicc[hc] ? */
566           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFiccLR[hc][hb] */
567         }
568       }
569     }
570   }
571 
572   FDKbyteAlign(bitstream,
573                cfgStartPos); /* ISO/IEC FDIS 23003-1: 5.2. ... byte alignment
574                                 with respect to the beginning of the syntactic
575                                 element in which ByteAlign() occurs. */
576 
577   numHeaderBits = cfgStartPos - (INT)FDKgetValidBits(bitstream);
578   bitsAvailable -= numHeaderBits;
579   if (bitsAvailable < 0) {
580     err = MPS_PARSE_ERROR;
581     goto bail;
582   }
583 
584   pSpatialSpecificConfig->sacExtCnt = 0;
585   pSpatialSpecificConfig->bResidualCoding = 0;
586 
587   err = SpatialDecParseExtensionConfig(
588       bitstream, pSpatialSpecificConfig, pSpatialSpecificConfig->nOttBoxes,
589       pSpatialSpecificConfig->nTttBoxes,
590       pSpatialSpecificConfig->nOutputChannels, bitsAvailable);
591 
592   FDKbyteAlign(
593       bitstream,
594       cfgStartPos); /* Same alignment anchor as above because
595                        SpatialExtensionConfig() always reads full bytes */
596 
597   pSpatialSpecificConfig->coreCodec = coreCodec;
598 
599   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
600 
601 bail:
602   if (sacHeaderLen > 0) {
603     /* If the config is of known length then assure that the
604        bitbuffer is exactly at its end when leaving the function. */
605     FDKpushBiDirectional(
606         bitstream,
607         (sacHeaderLen * 8) - (cfgStartPos - (INT)FDKgetValidBits(bitstream)));
608   }
609 
610   return err;
611 }
612 
SpatialDecDefaultSpecificConfig(SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,AUDIO_OBJECT_TYPE coreCodec,int samplingFreq,int nTimeSlots,int sacDecoderLevel,int isBlind,int numCoreChannels)613 int SpatialDecDefaultSpecificConfig(
614     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig,
615     AUDIO_OBJECT_TYPE coreCodec, int samplingFreq, int nTimeSlots,
616     int sacDecoderLevel, int isBlind, int numCoreChannels)
617 
618 {
619   int err = MPS_OK;
620   int i;
621 
622   FDK_ASSERT(coreCodec != AOT_NONE);
623   FDK_ASSERT(nTimeSlots > 0);
624   FDK_ASSERT(samplingFreq > 0);
625 
626   pSpatialSpecificConfig->coreCodec = coreCodec;
627   pSpatialSpecificConfig->samplingFreq = samplingFreq;
628   pSpatialSpecificConfig->nTimeSlots = nTimeSlots;
629   if ((pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_ELD) ||
630       (pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_LD))
631     pSpatialSpecificConfig->freqRes = SPATIALDEC_FREQ_RES_23;
632   else
633     pSpatialSpecificConfig->freqRes = SPATIALDEC_FREQ_RES_28;
634 
635   {
636     pSpatialSpecificConfig->treeConfig =
637         SPATIALDEC_MODE_RSVD7; /* 212  configuration */
638   }
639 
640   {
641     pSpatialSpecificConfig->nOttBoxes =
642         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
643     pSpatialSpecificConfig->nInputChannels =
644         treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
645     pSpatialSpecificConfig->nOutputChannels =
646         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
647   }
648 
649   pSpatialSpecificConfig->quantMode = SPATIALDEC_QUANT_FINE_DEF;
650   pSpatialSpecificConfig->bArbitraryDownmix = 0;
651   pSpatialSpecificConfig->bResidualCoding = 0;
652   if ((pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_ELD) ||
653       (pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_LD))
654     pSpatialSpecificConfig->bsFixedGainDMX = SPATIALDEC_GAIN_RSVD2;
655   else
656     pSpatialSpecificConfig->bsFixedGainDMX = SPATIALDEC_GAIN_MODE0;
657 
658   pSpatialSpecificConfig->tempShapeConfig = SPATIALDEC_TS_TPNOWHITE;
659   pSpatialSpecificConfig->decorrConfig = SPATIALDEC_DECORR_MODE0;
660 
661   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
662     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
663   }
664 
665   return err;
666 }
667 
668 /*******************************************************************************
669  Functionname: coarse2fine
670  *******************************************************************************
671 
672  Description:
673    Parameter index mapping from coarse to fine quantization
674 
675  Arguments:
676 
677 Input:
678 
679 Output:
680 
681 *******************************************************************************/
coarse2fine(SCHAR * data,DATA_TYPE dataType,int startBand,int numBands)682 static void coarse2fine(SCHAR *data, DATA_TYPE dataType, int startBand,
683                         int numBands) {
684   int i;
685 
686   for (i = startBand; i < startBand + numBands; i++) {
687     data[i] <<= 1;
688   }
689 
690   if (dataType == t_CLD) {
691     for (i = startBand; i < startBand + numBands; i++) {
692       if (data[i] == -14)
693         data[i] = -15;
694       else if (data[i] == 14)
695         data[i] = 15;
696     }
697   }
698 }
699 
700 /*******************************************************************************
701  Functionname: fine2coarse
702  *******************************************************************************
703 
704  Description:
705    Parameter index mapping from fine to coarse quantization
706 
707  Arguments:
708 
709 Input:
710 
711 Output:
712 
713 *******************************************************************************/
fine2coarse(SCHAR * data,DATA_TYPE dataType,int startBand,int numBands)714 static void fine2coarse(SCHAR *data, DATA_TYPE dataType, int startBand,
715                         int numBands) {
716   int i;
717 
718   for (i = startBand; i < startBand + numBands; i++) {
719     /* Note: the if cases below actually make a difference (negative values) */
720     if (dataType == t_CLD)
721       data[i] /= 2;
722     else
723       data[i] >>= 1;
724   }
725 }
726 
727 /*******************************************************************************
728  Functionname: getStrideMap
729  *******************************************************************************
730 
731  Description:
732    Index Mapping accroding to pbStrides
733 
734  Arguments:
735 
736 Input:
737 
738 Output:
739 
740 *******************************************************************************/
getStrideMap(int freqResStride,int startBand,int stopBand,int * aStrides)741 static int getStrideMap(int freqResStride, int startBand, int stopBand,
742                         int *aStrides) {
743   int i, pb, pbStride, dataBands, strOffset;
744 
745   pbStride = pbStrideTable[freqResStride];
746   dataBands = (stopBand - startBand - 1) / pbStride + 1;
747 
748   aStrides[0] = startBand;
749   for (pb = 1; pb <= dataBands; pb++) {
750     aStrides[pb] = aStrides[pb - 1] + pbStride;
751   }
752   strOffset = 0;
753   while (aStrides[dataBands] > stopBand) {
754     if (strOffset < dataBands) strOffset++;
755     for (i = strOffset; i <= dataBands; i++) {
756       aStrides[i]--;
757     }
758   }
759 
760   return dataBands;
761 }
762 
763 /*******************************************************************************
764  Functionname: ecDataDec
765  *******************************************************************************
766 
767  Description:
768    Do delta decoding and dequantization
769 
770  Arguments:
771 
772 Input:
773 
774 Output:
775 
776 
777 *******************************************************************************/
778 
ecDataDec(const SPATIAL_BS_FRAME * frame,UINT syntaxFlags,HANDLE_FDK_BITSTREAM bitstream,LOSSLESSDATA * const llData,SCHAR (* data)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],SCHAR ** lastdata,int datatype,int boxIdx,int startBand,int stopBand,SCHAR defaultValue)779 static SACDEC_ERROR ecDataDec(
780     const SPATIAL_BS_FRAME *frame, UINT syntaxFlags,
781     HANDLE_FDK_BITSTREAM bitstream, LOSSLESSDATA *const llData,
782     SCHAR (*data)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS], SCHAR **lastdata,
783     int datatype, int boxIdx, int startBand, int stopBand, SCHAR defaultValue) {
784   SACDEC_ERROR err = MPS_OK;
785   int i, j, pb, dataSets, setIdx, bsDataPair, dataBands, oldQuantCoarseXXX;
786   INT aStrides[MAX_PARAMETER_BANDS + 1] = {0};
787 
788   dataSets = 0;
789   for (i = 0; i < frame->numParameterSets; i++) {
790     llData->bsXXXDataMode[i] = (SCHAR)FDKreadBits(bitstream, 2);
791 
792     if ((frame->bsIndependencyFlag == 1) && (i == 0) &&
793         (llData->bsXXXDataMode[i] == 1 ||
794          llData->bsXXXDataMode[i] == 2)) { /* This check catches bitstreams
795                                               generated by older encoder that
796                                               cause trouble */
797       return MPS_PARSE_ERROR;
798     }
799     if ((i >= frame->numParameterSets - 1) &&
800         (llData->bsXXXDataMode[i] ==
801          2)) { /* The interpolation mode must not be active for the last
802                   parameter set */
803       return MPS_PARSE_ERROR;
804     }
805 
806     if (llData->bsXXXDataMode[i] == 3) {
807       dataSets++;
808     }
809   }
810 
811   setIdx = 0;
812   bsDataPair = 0;
813   oldQuantCoarseXXX = llData->state->bsQuantCoarseXXXprevParse;
814 
815   for (i = 0; i < frame->numParameterSets; i++) {
816     if (llData->bsXXXDataMode[i] == 0) {
817       for (pb = startBand; pb < stopBand; pb++) {
818         lastdata[boxIdx][pb] = defaultValue;
819       }
820 
821       oldQuantCoarseXXX = 0;
822     }
823 
824     if (llData->bsXXXDataMode[i] == 3) {
825       if (bsDataPair) {
826         bsDataPair = 0;
827       } else {
828         bsDataPair = FDKreadBits(bitstream, 1);
829         llData->bsQuantCoarseXXX[setIdx] = (UCHAR)FDKreadBits(bitstream, 1);
830         llData->bsFreqResStrideXXX[setIdx] = (UCHAR)FDKreadBits(bitstream, 2);
831 
832         if (llData->bsQuantCoarseXXX[setIdx] != oldQuantCoarseXXX) {
833           if (oldQuantCoarseXXX) {
834             coarse2fine(lastdata[boxIdx], (DATA_TYPE)datatype, startBand,
835                         stopBand - startBand);
836           } else {
837             fine2coarse(lastdata[boxIdx], (DATA_TYPE)datatype, startBand,
838                         stopBand - startBand);
839           }
840         }
841 
842         dataBands = getStrideMap(llData->bsFreqResStrideXXX[setIdx], startBand,
843                                  stopBand, aStrides);
844 
845         for (pb = 0; pb < dataBands; pb++) {
846           lastdata[boxIdx][startBand + pb] = lastdata[boxIdx][aStrides[pb]];
847         }
848 
849         if (boxIdx > MAX_NUM_OTT) return MPS_INVALID_BOXIDX;
850         if ((setIdx + bsDataPair) > MAX_PARAMETER_SETS)
851           return MPS_INVALID_SETIDX;
852 
853         /* DECODER_TYPE defined in FDK_tools */
854         DECODER_TYPE this_decoder_type = SAC_DECODER;
855         if (syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) {
856           this_decoder_type = USAC_DECODER;
857         } else if (syntaxFlags & SACDEC_SYNTAX_LD) {
858           this_decoder_type = SAOC_DECODER;
859         }
860 
861         err = (SACDEC_ERROR)EcDataPairDec(
862             this_decoder_type, bitstream, data[boxIdx][setIdx + 0],
863             data[boxIdx][setIdx + 1], lastdata[boxIdx], (DATA_TYPE)datatype,
864             startBand, dataBands, bsDataPair, llData->bsQuantCoarseXXX[setIdx],
865             !(frame->bsIndependencyFlag && (i == 0)) || (setIdx > 0));
866         if (err != MPS_OK) goto bail;
867 
868         if (datatype == t_IPD) {
869           const SCHAR mask = (llData->bsQuantCoarseXXX[setIdx]) ? 7 : 15;
870           for (pb = 0; pb < dataBands; pb++) {
871             for (j = aStrides[pb]; j < aStrides[pb + 1]; j++) {
872               lastdata[boxIdx][j] =
873                   data[boxIdx][setIdx + bsDataPair][startBand + pb] & mask;
874             }
875           }
876         } else {
877           for (pb = 0; pb < dataBands; pb++) {
878             for (j = aStrides[pb]; j < aStrides[pb + 1]; j++) {
879               lastdata[boxIdx][j] =
880                   data[boxIdx][setIdx + bsDataPair][startBand + pb];
881             }
882           }
883         }
884 
885         oldQuantCoarseXXX = llData->bsQuantCoarseXXX[setIdx];
886 
887         if (bsDataPair) {
888           llData->bsQuantCoarseXXX[setIdx + 1] =
889               llData->bsQuantCoarseXXX[setIdx];
890           llData->bsFreqResStrideXXX[setIdx + 1] =
891               llData->bsFreqResStrideXXX[setIdx];
892         }
893         setIdx += bsDataPair + 1;
894       } /* !bsDataPair */
895     }   /* llData->bsXXXDataMode[i] == 3 */
896   }
897 
898   llData->state->bsQuantCoarseXXXprevParse = oldQuantCoarseXXX;
899 
900 bail:
901   return err;
902 }
903 
904 /*******************************************************************************
905  Functionname: parseArbitraryDownmixData
906  *******************************************************************************
907 
908  Description:
909 
910  Arguments:
911 
912  Return:
913 
914 *******************************************************************************/
parseArbitraryDownmixData(spatialDec * self,const SPATIAL_SPECIFIC_CONFIG * pSSC,const UINT syntaxFlags,const SPATIAL_BS_FRAME * frame,HANDLE_FDK_BITSTREAM bitstream)915 static SACDEC_ERROR parseArbitraryDownmixData(
916     spatialDec *self, const SPATIAL_SPECIFIC_CONFIG *pSSC,
917     const UINT syntaxFlags, const SPATIAL_BS_FRAME *frame,
918     HANDLE_FDK_BITSTREAM bitstream) {
919   SACDEC_ERROR err = MPS_OK;
920   int ch;
921   int offset = pSSC->nOttBoxes;
922 
923   /* CLD (arbitrary down-mix gains) */
924   for (ch = 0; ch < pSSC->nInputChannels; ch++) {
925     err = ecDataDec(frame, syntaxFlags, bitstream,
926                     &frame->CLDLosslessData[offset + ch],
927                     frame->cmpArbdmxGainIdx, self->cmpArbdmxGainIdxPrev, t_CLD,
928                     ch, 0, pSSC->freqRes, arbdmxGainDefault);
929     if (err != MPS_OK) return err;
930   }
931 
932   return err;
933 
934 } /* parseArbitraryDownmixData */
935 
936 /*******************************************************************************
937  Functionname: SpatialDecParseFrame
938  *******************************************************************************
939 
940  Description:
941 
942  Arguments:
943 
944  Input:
945 
946  Output:
947 
948 *******************************************************************************/
949 
nBitsParamSlot(int i)950 static int nBitsParamSlot(int i) {
951   int bitsParamSlot;
952 
953   bitsParamSlot = fMax(0, DFRACT_BITS - 1 - fNormz((FIXP_DBL)i));
954   if ((1 << bitsParamSlot) < i) {
955     bitsParamSlot++;
956   }
957   FDK_ASSERT((bitsParamSlot >= 0) && (bitsParamSlot <= 32));
958 
959   return bitsParamSlot;
960 }
961 
SpatialDecParseFrameData(spatialDec_struct * self,SPATIAL_BS_FRAME * frame,HANDLE_FDK_BITSTREAM bitstream,const SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig,UPMIXTYPE upmixType,int fGlobalIndependencyFlag)962 SACDEC_ERROR SpatialDecParseFrameData(
963     spatialDec_struct *self, SPATIAL_BS_FRAME *frame,
964     HANDLE_FDK_BITSTREAM bitstream,
965     const SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, UPMIXTYPE upmixType,
966     int fGlobalIndependencyFlag) {
967   SACDEC_ERROR err = MPS_OK;
968   int bsFramingType, dataBands, ps, pg, i;
969   int pb;
970   int numTempShapeChan = 0;
971   int bsNumOutputChannels =
972       treePropertyTable[pSpatialSpecificConfig->treeConfig]
973           .numOutputChannels; /* CAUTION: Maybe different to
974                                  pSpatialSpecificConfig->treeConfig in some
975                                  modes! */
976   int paramSetErr = 0;
977   UINT alignAnchor = FDKgetValidBits(
978       bitstream); /* Anchor for ByteAlign() function. See comment below. */
979   UINT syntaxFlags;
980 
981   syntaxFlags = pSpatialSpecificConfig->syntaxFlags;
982 
983   if ((syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) &&
984       pSpatialSpecificConfig->bsHighRateMode == 0) {
985     bsFramingType = 0; /* fixed framing */
986     frame->numParameterSets = 1;
987   } else {
988     bsFramingType = FDKreadBits(bitstream, 1);
989     if (syntaxFlags & SACDEC_SYNTAX_LD)
990       frame->numParameterSets = FDKreadBits(bitstream, 1) + 1;
991     else
992       frame->numParameterSets = FDKreadBits(bitstream, 3) + 1;
993   }
994 
995   /* Any error after this line shall trigger parameter invalidation at bail
996    * label. */
997   paramSetErr = 1;
998 
999   if (frame->numParameterSets >= MAX_PARAMETER_SETS) {
1000     goto bail;
1001   }
1002 
1003   /* Basic config check. */
1004   if (pSpatialSpecificConfig->nInputChannels <= 0 ||
1005       pSpatialSpecificConfig->nOutputChannels <= 0) {
1006     err = MPS_UNSUPPORTED_CONFIG;
1007     goto bail;
1008   }
1009 
1010   if (bsFramingType) {
1011     int prevParamSlot = -1;
1012     int bitsParamSlot;
1013 
1014     {
1015       bitsParamSlot = nBitsParamSlot(pSpatialSpecificConfig->nTimeSlots);
1016 
1017       for (i = 0; i < frame->numParameterSets; i++) {
1018         frame->paramSlot[i] = FDKreadBits(bitstream, bitsParamSlot);
1019         /* Sanity check */
1020         if ((frame->paramSlot[i] <= prevParamSlot) ||
1021             (frame->paramSlot[i] >= pSpatialSpecificConfig->nTimeSlots)) {
1022           err = MPS_PARSE_ERROR;
1023           goto bail;
1024         }
1025         prevParamSlot = frame->paramSlot[i];
1026       }
1027     }
1028   } else {
1029     for (i = 0; i < frame->numParameterSets; i++) {
1030       frame->paramSlot[i] = ((pSpatialSpecificConfig->nTimeSlots * (i + 1)) /
1031                              frame->numParameterSets) -
1032                             1;
1033     }
1034   }
1035 
1036   if ((syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) &&
1037       fGlobalIndependencyFlag) {
1038     frame->bsIndependencyFlag = 1;
1039   } else {
1040     frame->bsIndependencyFlag = (UCHAR)FDKreadBits(bitstream, 1);
1041   }
1042 
1043   /*
1044    * OttData()
1045    */
1046   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
1047     err = ecDataDec(frame, syntaxFlags, bitstream, &frame->CLDLosslessData[i],
1048                     frame->cmpOttCLDidx, self->cmpOttCLDidxPrev, t_CLD, i, 0,
1049                     pSpatialSpecificConfig->bitstreamOttBands[i],
1050                     pSpatialSpecificConfig->ottCLDdefault[i]);
1051     if (err != MPS_OK) {
1052       goto bail;
1053     }
1054   } /* i < numOttBoxes */
1055 
1056   {
1057     for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
1058       err = ecDataDec(frame, syntaxFlags, bitstream, &frame->ICCLosslessData[i],
1059                       frame->cmpOttICCidx, self->cmpOttICCidxPrev, t_ICC, i, 0,
1060                       pSpatialSpecificConfig->bitstreamOttBands[i], ICCdefault);
1061       if (err != MPS_OK) {
1062         goto bail;
1063       }
1064     } /* i < numOttBoxes */
1065   }   /* !oneICC */
1066 
1067   if ((pSpatialSpecificConfig->treeConfig == SPATIALDEC_MODE_RSVD7) &&
1068       (pSpatialSpecificConfig->bsPhaseCoding)) {
1069     frame->phaseMode = FDKreadBits(bitstream, 1);
1070 
1071     if (frame->phaseMode == 0) {
1072       for (pb = 0; pb < pSpatialSpecificConfig->numOttBandsIPD; pb++) {
1073         self->cmpOttIPDidxPrev[0][pb] = 0;
1074         for (i = 0; i < frame->numParameterSets; i++) {
1075           frame->cmpOttIPDidx[0][i][pb] = 0;
1076           // frame->ottIPDidx[0][i][pb] = 0;
1077         }
1078         /* self->ottIPDidxPrev[0][pb] = 0; */
1079       }
1080       frame->OpdSmoothingMode = 0;
1081     } else {
1082       frame->OpdSmoothingMode = FDKreadBits(bitstream, 1);
1083       err = ecDataDec(frame, syntaxFlags, bitstream, &frame->IPDLosslessData[0],
1084                       frame->cmpOttIPDidx, self->cmpOttIPDidxPrev, t_IPD, 0, 0,
1085                       pSpatialSpecificConfig->numOttBandsIPD, IPDdefault);
1086       if (err != MPS_OK) {
1087         goto bail;
1088       }
1089     }
1090   }
1091 
1092   /*
1093    * SmgData()
1094    */
1095 
1096   {
1097     if (!pSpatialSpecificConfig->bsHighRateMode &&
1098         (syntaxFlags & SACDEC_SYNTAX_USAC)) {
1099       for (ps = 0; ps < frame->numParameterSets; ps++) {
1100         frame->bsSmoothMode[ps] = 0;
1101       }
1102     } else {
1103       for (ps = 0; ps < frame->numParameterSets; ps++) {
1104         frame->bsSmoothMode[ps] = (UCHAR)FDKreadBits(bitstream, 2);
1105         if (frame->bsSmoothMode[ps] >= 2) {
1106           frame->bsSmoothTime[ps] = (UCHAR)FDKreadBits(bitstream, 2);
1107         }
1108         if (frame->bsSmoothMode[ps] == 3) {
1109           frame->bsFreqResStrideSmg[ps] = (UCHAR)FDKreadBits(bitstream, 2);
1110           dataBands = (pSpatialSpecificConfig->freqRes - 1) /
1111                           pbStrideTable[frame->bsFreqResStrideSmg[ps]] +
1112                       1;
1113           for (pg = 0; pg < dataBands; pg++) {
1114             frame->bsSmgData[ps][pg] = (UCHAR)FDKreadBits(bitstream, 1);
1115           }
1116         }
1117       } /* ps < numParameterSets */
1118     }
1119   }
1120 
1121   /*
1122    * TempShapeData()
1123    */
1124   if ((pSpatialSpecificConfig->tempShapeConfig == 3) &&
1125       (syntaxFlags & SACDEC_SYNTAX_USAC)) {
1126     int TsdErr;
1127     TsdErr = TsdRead(bitstream, pSpatialSpecificConfig->nTimeSlots,
1128                      &frame->TsdData[0]);
1129     if (TsdErr) {
1130       err = MPS_PARSE_ERROR;
1131       goto bail;
1132     }
1133   } else {
1134     frame->TsdData[0].bsTsdEnable = 0;
1135   }
1136 
1137   for (i = 0; i < bsNumOutputChannels; i++) {
1138     frame->tempShapeEnableChannelSTP[i] = 0;
1139     frame->tempShapeEnableChannelGES[i] = 0;
1140   }
1141 
1142   if ((pSpatialSpecificConfig->tempShapeConfig == 1) ||
1143       (pSpatialSpecificConfig->tempShapeConfig == 2)) {
1144     int bsTempShapeEnable = FDKreadBits(bitstream, 1);
1145     if (bsTempShapeEnable) {
1146       numTempShapeChan =
1147           tempShapeChanTable[pSpatialSpecificConfig->tempShapeConfig - 1]
1148                             [pSpatialSpecificConfig->treeConfig];
1149       switch (pSpatialSpecificConfig->tempShapeConfig) {
1150         case 1: /* STP */
1151           for (i = 0; i < numTempShapeChan; i++) {
1152             int stpEnable = FDKreadBits(bitstream, 1);
1153             frame->tempShapeEnableChannelSTP[i] = stpEnable;
1154           }
1155           break;
1156         case 2: /* GES */
1157         {
1158           UCHAR gesChannelEnable[MAX_OUTPUT_CHANNELS];
1159 
1160           for (i = 0; i < numTempShapeChan; i++) {
1161             gesChannelEnable[i] = (UCHAR)FDKreadBits(bitstream, 1);
1162             frame->tempShapeEnableChannelGES[i] = gesChannelEnable[i];
1163           }
1164           for (i = 0; i < numTempShapeChan; i++) {
1165             if (gesChannelEnable[i]) {
1166               int envShapeData_tmp[MAX_TIME_SLOTS];
1167               if (huff_dec_reshape(bitstream, envShapeData_tmp,
1168                                    pSpatialSpecificConfig->nTimeSlots) != 0) {
1169                 err = MPS_PARSE_ERROR;
1170                 goto bail;
1171               }
1172               for (int ts = 0; ts < pSpatialSpecificConfig->nTimeSlots; ts++) {
1173                 if (!(envShapeData_tmp[ts] >= 0) &&
1174                     (envShapeData_tmp[ts] <= 4)) {
1175                   err = MPS_PARSE_ERROR;
1176                   goto bail;
1177                 }
1178                 frame->bsEnvShapeData[i][ts] = (UCHAR)envShapeData_tmp[ts];
1179               }
1180             }
1181           }
1182         } break;
1183         default:
1184           err = MPS_INVALID_TEMPSHAPE;
1185           goto bail;
1186       }
1187     } /* bsTempShapeEnable */
1188   }   /* pSpatialSpecificConfig->tempShapeConfig != 0 */
1189 
1190   if (pSpatialSpecificConfig->bArbitraryDownmix != 0) {
1191     err = parseArbitraryDownmixData(self, pSpatialSpecificConfig, syntaxFlags,
1192                                     frame, bitstream);
1193     if (err != MPS_OK) goto bail;
1194   }
1195 
1196   if (1 && (!(syntaxFlags & (SACDEC_SYNTAX_USAC)))) {
1197     FDKbyteAlign(bitstream,
1198                  alignAnchor); /* ISO/IEC FDIS 23003-1: 5.2. ... byte alignment
1199                                   with respect to the beginning of the syntactic
1200                                   element in which ByteAlign() occurs. */
1201   }
1202 
1203 bail:
1204   if (err != MPS_OK && paramSetErr != 0) {
1205     /* Since the parameter set data has already been written to the instance we
1206      * need to ... */
1207     frame->numParameterSets = 0; /* ... signal that it is corrupt ... */
1208   }
1209 
1210   return err;
1211 
1212 } /* SpatialDecParseFrame */
1213 
1214 /*******************************************************************************
1215  Functionname: createMapping
1216  *******************************************************************************
1217 
1218  Description:
1219 
1220  Arguments:
1221 
1222  Return:
1223 
1224 *******************************************************************************/
createMapping(int aMap[MAX_PARAMETER_BANDS+1],int startBand,int stopBand,int stride)1225 static void createMapping(int aMap[MAX_PARAMETER_BANDS + 1], int startBand,
1226                           int stopBand, int stride) {
1227   int inBands, outBands, bandsAchived, bandsDiff, incr, k, i;
1228   int vDk[MAX_PARAMETER_BANDS + 1];
1229   inBands = stopBand - startBand;
1230   outBands = (inBands - 1) / stride + 1;
1231 
1232   if (outBands < 1) {
1233     outBands = 1;
1234   }
1235 
1236   bandsAchived = outBands * stride;
1237   bandsDiff = inBands - bandsAchived;
1238   for (i = 0; i < outBands; i++) {
1239     vDk[i] = stride;
1240   }
1241 
1242   if (bandsDiff > 0) {
1243     incr = -1;
1244     k = outBands - 1;
1245   } else {
1246     incr = 1;
1247     k = 0;
1248   }
1249 
1250   while (bandsDiff != 0) {
1251     vDk[k] = vDk[k] - incr;
1252     k = k + incr;
1253     bandsDiff = bandsDiff + incr;
1254     if (k >= outBands) {
1255       if (bandsDiff > 0) {
1256         k = outBands - 1;
1257       } else if (bandsDiff < 0) {
1258         k = 0;
1259       }
1260     }
1261   }
1262   aMap[0] = startBand;
1263   for (i = 0; i < outBands; i++) {
1264     aMap[i + 1] = aMap[i] + vDk[i];
1265   }
1266 } /* createMapping */
1267 
1268 /*******************************************************************************
1269  Functionname: mapFrequency
1270  *******************************************************************************
1271 
1272  Description:
1273 
1274  Arguments:
1275 
1276  Return:
1277 
1278 *******************************************************************************/
mapFrequency(const SCHAR * pInput,SCHAR * pOutput,int * pMap,int dataBands)1279 static void mapFrequency(const SCHAR *pInput, /* Input */
1280                          SCHAR *pOutput,      /* Output */
1281                          int *pMap,           /* Mapping function */
1282                          int dataBands)       /* Number of data Bands */
1283 {
1284   int i, j;
1285   int startBand0 = pMap[0];
1286 
1287   for (i = 0; i < dataBands; i++) {
1288     int startBand, stopBand, value;
1289 
1290     value = pInput[i + startBand0];
1291 
1292     startBand = pMap[i];
1293     stopBand = pMap[i + 1];
1294     for (j = startBand; j < stopBand; j++) {
1295       pOutput[j] = value;
1296     }
1297   }
1298 }
1299 
1300 /*******************************************************************************
1301  Functionname: deq
1302  *******************************************************************************
1303 
1304  Description:
1305 
1306  Arguments:
1307 
1308  Return:
1309 
1310 *******************************************************************************/
deqIdx(int value,int paramType)1311 static int deqIdx(int value, int paramType) {
1312   int idx = -1;
1313 
1314   switch (paramType) {
1315     case t_CLD:
1316       if (((value + 15) >= 0) && ((value + 15) < 31)) {
1317         idx = (value + 15);
1318       }
1319       break;
1320 
1321     case t_ICC:
1322       if ((value >= 0) && (value < 8)) {
1323         idx = value;
1324       }
1325       break;
1326 
1327     case t_IPD:
1328       /* (+/-)15 * MAX_PARAMETER_BANDS for differential coding in frequency
1329        * domain (according to rbl) */
1330       if ((value >= -420) && (value <= 420)) {
1331         idx = (value & 0xf);
1332       }
1333       break;
1334 
1335     default:
1336       FDK_ASSERT(0);
1337   }
1338 
1339   return idx;
1340 }
1341 
1342   /*******************************************************************************
1343    Functionname: factorFunct
1344    *******************************************************************************
1345 
1346    Description:
1347 
1348    Arguments:
1349 
1350    Return:
1351 
1352   *******************************************************************************/
1353 
1354 #define SF_IDX (7)
1355 #define SF_FACTOR (3)
1356 #define SCALE_FACTOR (1 << SF_FACTOR)
1357 #define SCALE_CLD_C1C2 (1 << SF_CLD_C1C2)
1358 
factorFunct(FIXP_DBL ottVsTotDb,INT quantMode)1359 static FIXP_DBL factorFunct(FIXP_DBL ottVsTotDb, INT quantMode) {
1360   FIXP_DBL factor;
1361 
1362   if (ottVsTotDb > FL2FXCONST_DBL(0.0)) {
1363     ottVsTotDb = FL2FXCONST_DBL(0.0);
1364   }
1365 
1366   ottVsTotDb = -ottVsTotDb;
1367 
1368   switch (quantMode) {
1369     case 0:
1370       factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
1371       break;
1372     case 1:
1373       if (ottVsTotDb >= FL2FXCONST_DBL(21.0f / SCALE_CLD_C1C2))
1374         factor = FL2FXCONST_DBL(5.0f / SCALE_FACTOR);
1375       else if (ottVsTotDb <= FL2FXCONST_DBL(1.0f / SCALE_CLD_C1C2))
1376         factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
1377       else
1378         factor = (fMult(FL2FXCONST_DBL(0.2f), ottVsTotDb) +
1379                   FL2FXCONST_DBL(0.8f / SCALE_CLD_C1C2))
1380                  << (SF_CLD_C1C2 - SF_FACTOR);
1381       break;
1382     case 2:
1383       if (ottVsTotDb >= FL2FXCONST_DBL(25.0f / SCALE_CLD_C1C2)) {
1384         FDK_ASSERT(SF_FACTOR == 3);
1385         factor = (FIXP_DBL)
1386             MAXVAL_DBL; /* avoid warning: FL2FXCONST_DBL(8.0f/SCALE_FACTOR) */
1387       } else if (ottVsTotDb <= FL2FXCONST_DBL(1.0f / SCALE_CLD_C1C2))
1388         factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
1389       else
1390         factor = (fMult(FL2FXCONST_DBL(7.0f / 24.0f), ottVsTotDb) +
1391                   FL2FXCONST_DBL((17.0f / 24.0f) / SCALE_CLD_C1C2))
1392                  << (SF_CLD_C1C2 - SF_FACTOR);
1393       break;
1394     default:
1395       factor = FL2FXCONST_DBL(0.0f);
1396   }
1397 
1398   return (factor);
1399 }
1400 
1401 /*******************************************************************************
1402  Functionname: factorCLD
1403  *******************************************************************************
1404 
1405  Description:
1406 
1407  Arguments:
1408 
1409  Return:
1410 
1411 *******************************************************************************/
factorCLD(SCHAR * idx,FIXP_DBL ottVsTotDb,FIXP_DBL * ottVsTotDb1,FIXP_DBL * ottVsTotDb2,SCHAR ottVsTotDbMode,INT quantMode)1412 static void factorCLD(SCHAR *idx, FIXP_DBL ottVsTotDb, FIXP_DBL *ottVsTotDb1,
1413                       FIXP_DBL *ottVsTotDb2, SCHAR ottVsTotDbMode,
1414                       INT quantMode) {
1415   FIXP_DBL factor;
1416   FIXP_DBL cldIdxFract;
1417   INT cldIdx;
1418 
1419   factor = factorFunct(ottVsTotDb, quantMode);
1420 
1421   cldIdxFract =
1422       fMult((FIXP_DBL)((*idx) << ((DFRACT_BITS - 1) - SF_IDX)), factor);
1423   cldIdxFract += FL2FXCONST_DBL(15.5f / (1 << (SF_FACTOR + SF_IDX)));
1424   cldIdx = fixp_truncateToInt(cldIdxFract, SF_FACTOR + SF_IDX);
1425 
1426   cldIdx = fMin(cldIdx, 30);
1427   cldIdx = fMax(cldIdx, 0);
1428 
1429   *idx = cldIdx - 15;
1430 
1431   if (ottVsTotDbMode & ottVsTotDb1Activ)
1432     (*ottVsTotDb1) = ottVsTotDb + dequantCLD_c1[cldIdx];
1433 
1434   if (ottVsTotDbMode & ottVsTotDb2Activ)
1435     (*ottVsTotDb2) = ottVsTotDb + dequantCLD_c1[30 - cldIdx];
1436 }
1437 
1438 /*******************************************************************************
1439  Functionname: mapIndexData
1440  *******************************************************************************
1441 
1442  Description:
1443 
1444  Arguments:
1445 
1446  Return:
1447 
1448 *******************************************************************************/
mapIndexData(LOSSLESSDATA * llData,SCHAR *** outputDataIdx,SCHAR *** outputIdxData,const SCHAR (* cmpIdxData)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],SCHAR *** diffIdxData,SCHAR xttIdx,SCHAR ** idxPrev,int paramIdx,int paramType,int startBand,int stopBand,SCHAR defaultValue,int numParameterSets,const int * paramSlot,int extendFrame,int quantMode,SpatialDecConcealmentInfo * concealmentInfo,SCHAR ottVsTotDbMode,FIXP_DBL (* pOttVsTotDbIn)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],FIXP_DBL (* pOttVsTotDb1)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],FIXP_DBL (* pOttVsTotDb2)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS])1449 static SACDEC_ERROR mapIndexData(
1450     LOSSLESSDATA *llData, SCHAR ***outputDataIdx, SCHAR ***outputIdxData,
1451     const SCHAR (*cmpIdxData)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
1452     SCHAR ***diffIdxData, SCHAR xttIdx, SCHAR **idxPrev, int paramIdx,
1453     int paramType, int startBand, int stopBand, SCHAR defaultValue,
1454     int numParameterSets, const int *paramSlot, int extendFrame, int quantMode,
1455     SpatialDecConcealmentInfo *concealmentInfo, SCHAR ottVsTotDbMode,
1456     FIXP_DBL (*pOttVsTotDbIn)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
1457     FIXP_DBL (*pOttVsTotDb1)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
1458     FIXP_DBL (*pOttVsTotDb2)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS]) {
1459   int aParamSlots[MAX_PARAMETER_SETS];
1460   int aInterpolate[MAX_PARAMETER_SETS] = {0};
1461 
1462   int dataSets;
1463   int aMap[MAX_PARAMETER_BANDS + 1];
1464 
1465   int setIdx, i, band, parmSlot;
1466   int dataBands;
1467   int ps, pb;
1468   int i1;
1469 
1470   if (numParameterSets > MAX_PARAMETER_SETS) return MPS_WRONG_PARAMETERSETS;
1471 
1472   dataSets = 0;
1473   for (i = 0; i < numParameterSets; i++) {
1474     if (llData->bsXXXDataMode[i] == 3) {
1475       aParamSlots[dataSets] = i;
1476       dataSets++;
1477     }
1478   }
1479 
1480   setIdx = 0;
1481 
1482   /* Main concealment stage is here: */
1483   SpatialDecConcealment_Apply(
1484       concealmentInfo, cmpIdxData[xttIdx],
1485       (diffIdxData != NULL) ? diffIdxData[xttIdx] : NULL, idxPrev[xttIdx],
1486       llData->bsXXXDataMode, startBand, stopBand, defaultValue, paramType,
1487       numParameterSets);
1488 
1489   /* Prepare data */
1490   for (i = 0; i < numParameterSets; i++) {
1491     if (llData->bsXXXDataMode[i] == 0) {
1492       llData->nocmpQuantCoarseXXX[i] = 0;
1493       for (band = startBand; band < stopBand; band++) {
1494         outputIdxData[xttIdx][i][band] = defaultValue;
1495       }
1496       for (band = startBand; band < stopBand; band++) {
1497         idxPrev[xttIdx][band] = outputIdxData[xttIdx][i][band];
1498       }
1499       /* Because the idxPrev are also set to the defaultValue -> signalize fine
1500        */
1501       llData->state->bsQuantCoarseXXXprev = 0;
1502     }
1503 
1504     if (llData->bsXXXDataMode[i] == 1) {
1505       for (band = startBand; band < stopBand; band++) {
1506         outputIdxData[xttIdx][i][band] = idxPrev[xttIdx][band];
1507       }
1508       llData->nocmpQuantCoarseXXX[i] = llData->state->bsQuantCoarseXXXprev;
1509     }
1510 
1511     if (llData->bsXXXDataMode[i] == 2) {
1512       for (band = startBand; band < stopBand; band++) {
1513         outputIdxData[xttIdx][i][band] = idxPrev[xttIdx][band];
1514       }
1515       llData->nocmpQuantCoarseXXX[i] = llData->state->bsQuantCoarseXXXprev;
1516       aInterpolate[i] = 1;
1517     } else {
1518       aInterpolate[i] = 0;
1519     }
1520 
1521     if (llData->bsXXXDataMode[i] == 3) {
1522       int stride;
1523 
1524       parmSlot = aParamSlots[setIdx];
1525       stride = pbStrideTable[llData->bsFreqResStrideXXX[setIdx]];
1526       dataBands = (stopBand - startBand - 1) / stride + 1;
1527       createMapping(aMap, startBand, stopBand, stride);
1528       mapFrequency(&cmpIdxData[xttIdx][setIdx][0],
1529                    &outputIdxData[xttIdx][parmSlot][0], aMap, dataBands);
1530       for (band = startBand; band < stopBand; band++) {
1531         idxPrev[xttIdx][band] = outputIdxData[xttIdx][parmSlot][band];
1532       }
1533       llData->state->bsQuantCoarseXXXprev = llData->bsQuantCoarseXXX[setIdx];
1534       llData->nocmpQuantCoarseXXX[i] = llData->bsQuantCoarseXXX[setIdx];
1535 
1536       setIdx++;
1537     }
1538     if (diffIdxData != NULL) {
1539       for (band = startBand; band < stopBand; band++) {
1540         outputIdxData[xttIdx][i][band] += diffIdxData[xttIdx][i][band];
1541       }
1542     }
1543   } /* for( i = 0 ; i < numParameterSets; i++ ) */
1544 
1545   /* Map all coarse data to fine */
1546   for (i = 0; i < numParameterSets; i++) {
1547     if (llData->nocmpQuantCoarseXXX[i] == 1) {
1548       coarse2fine(outputIdxData[xttIdx][i], (DATA_TYPE)paramType, startBand,
1549                   stopBand - startBand);
1550       llData->nocmpQuantCoarseXXX[i] = 0;
1551     }
1552   }
1553 
1554   /* Interpolate */
1555   i1 = 0;
1556   for (i = 0; i < numParameterSets; i++) {
1557     int xi, i2, x1, x2;
1558 
1559     if (aInterpolate[i] != 1) {
1560       i1 = i;
1561     }
1562     i2 = i;
1563     while (aInterpolate[i2] == 1) {
1564       i2++;
1565       if (i2 >= MAX_PARAMETER_SETS) return MPS_WRONG_PARAMETERSETS;
1566     }
1567     x1 = paramSlot[i1];
1568     xi = paramSlot[i];
1569     x2 = paramSlot[i2];
1570 
1571     if (aInterpolate[i] == 1) {
1572       if (i2 >= numParameterSets) return MPS_WRONG_PARAMETERSETS;
1573       for (band = startBand; band < stopBand; band++) {
1574         int yi, y1, y2;
1575         y1 = outputIdxData[xttIdx][i1][band];
1576         y2 = outputIdxData[xttIdx][i2][band];
1577         if (x1 != x2) {
1578           yi = y1 + (xi - x1) * (y2 - y1) / (x2 - x1);
1579         } else {
1580           yi = y1 /*+ (xi-x1)*(y2-y1)/1e-12*/;
1581         }
1582         outputIdxData[xttIdx][i][band] = yi;
1583       }
1584     }
1585   } /* for( i = 0 ; i < numParameterSets; i++ ) */
1586 
1587   /* Dequantize data and apply factorCLD if necessary */
1588   for (ps = 0; ps < numParameterSets; ps++) {
1589     if (quantMode && (paramType == t_CLD)) {
1590       if (pOttVsTotDbIn == 0) return MPS_WRONG_OTT;
1591       if ((pOttVsTotDb1 == 0) && (ottVsTotDbMode == ottVsTotDb1Activ))
1592         return MPS_WRONG_OTT;
1593       if ((pOttVsTotDb2 == 0) && (ottVsTotDbMode == ottVsTotDb2Activ))
1594         return MPS_WRONG_OTT;
1595 
1596       for (pb = startBand; pb < stopBand; pb++) {
1597         factorCLD(&(outputIdxData[xttIdx][ps][pb]), (*pOttVsTotDbIn)[ps][pb],
1598                   (pOttVsTotDb1 != NULL) ? &((*pOttVsTotDb1)[ps][pb]) : NULL,
1599                   (pOttVsTotDb2 != NULL) ? &((*pOttVsTotDb2)[ps][pb]) : NULL,
1600                   ottVsTotDbMode, quantMode);
1601       }
1602     }
1603 
1604     /* Dequantize data */
1605     for (band = startBand; band < stopBand; band++) {
1606       outputDataIdx[xttIdx][ps][band] =
1607           deqIdx(outputIdxData[xttIdx][ps][band], paramType);
1608       if (outputDataIdx[xttIdx][ps][band] == -1) {
1609         outputDataIdx[xttIdx][ps][band] = defaultValue;
1610       }
1611     }
1612   } /* for( i = 0 ; i < numParameterSets; i++ ) */
1613 
1614   if (extendFrame) {
1615     for (band = startBand; band < stopBand; band++) {
1616       outputDataIdx[xttIdx][numParameterSets][band] =
1617           outputDataIdx[xttIdx][numParameterSets - 1][band];
1618     }
1619   }
1620 
1621   return MPS_OK;
1622 }
1623 
1624 /*******************************************************************************
1625  Functionname: decodeAndMapFrameOtt
1626  *******************************************************************************
1627 
1628  Description:
1629    Do delta decoding and dequantization
1630 
1631  Arguments:
1632 
1633 Input:
1634 
1635 Output:
1636 
1637 *******************************************************************************/
decodeAndMapFrameOtt(HANDLE_SPATIAL_DEC self,SPATIAL_BS_FRAME * pCurBs)1638 static SACDEC_ERROR decodeAndMapFrameOtt(HANDLE_SPATIAL_DEC self,
1639                                          SPATIAL_BS_FRAME *pCurBs) {
1640   int i, ottIdx;
1641   int numOttBoxes;
1642 
1643   SACDEC_ERROR err = MPS_OK;
1644 
1645   numOttBoxes = self->numOttBoxes;
1646 
1647   switch (self->treeConfig) {
1648     default: {
1649       if (self->quantMode != 0) {
1650         goto bail;
1651       }
1652     }
1653       for (i = 0; i < numOttBoxes; i++) {
1654         err = mapIndexData(
1655             &pCurBs->CLDLosslessData[i], /* LOSSLESSDATA *llData,*/
1656             self->ottCLD__FDK, self->outIdxData,
1657             pCurBs
1658                 ->cmpOttCLDidx, /* int
1659                                    cmpIdxData[MAX_NUM_OTT][MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
1660                                  */
1661             NULL,               /* no differential data */
1662             i, /*  int   xttIdx,  Which ott/ttt index to use for input and
1663                   output buffers */
1664             self->ottCLDidxPrev,                        /* int
1665                                                            idxPrev[MAX_NUM_OTT][MAX_PARAMETER_BANDS],
1666                                                          */
1667             i, t_CLD, 0,                                /* int   startBand, */
1668             self->pConfigCurrent->bitstreamOttBands[i], /*  int   stopBand, */
1669             self->pConfigCurrent->ottCLDdefault[i], /* int   defaultValue, */
1670             pCurBs->numParameterSets, /* int   numParameterSets) */
1671             pCurBs->paramSlot, self->extendFrame, self->quantMode,
1672             &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
1673         if (err != MPS_OK) goto bail;
1674 
1675       } /* for(i = 0; i < numOttBoxes ; i++ ) */
1676       break;
1677   } /* case */
1678 
1679   for (ottIdx = 0; ottIdx < numOttBoxes; ottIdx++) {
1680     /* Read ICC */
1681     err = mapIndexData(
1682         &pCurBs->ICCLosslessData[ottIdx], /* LOSSLESSDATA *llData,*/
1683         self->ottICC__FDK, self->outIdxData,
1684         pCurBs
1685             ->cmpOttICCidx,  /* int
1686                                 cmpIdxData[MAX_NUM_OTT][MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
1687                               */
1688         self->ottICCdiffidx, /* differential data */
1689         ottIdx, /* int   xttIdx,  Which ott/ttt index to use for input and
1690                    output buffers */
1691         self->ottICCidxPrev, /* int   idxPrev[MAX_NUM_OTT][MAX_PARAMETER_BANDS],
1692                               */
1693         ottIdx, t_ICC, 0,    /* int   startBand, */
1694         self->pConfigCurrent->bitstreamOttBands[ottIdx], /* int   stopBand, */
1695         ICCdefault,               /* int   defaultValue, */
1696         pCurBs->numParameterSets, /* int   numParameterSets) */
1697         pCurBs->paramSlot, self->extendFrame, self->quantMode,
1698         &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
1699     if (err != MPS_OK) goto bail;
1700   } /* ottIdx */
1701 
1702   if ((self->treeConfig == TREE_212) && (self->phaseCoding)) {
1703     if (pCurBs->phaseMode == 0) {
1704       for (int pb = 0; pb < self->pConfigCurrent->numOttBandsIPD; pb++) {
1705         self->ottIPDidxPrev[0][pb] = 0;
1706       }
1707     }
1708     for (ottIdx = 0; ottIdx < numOttBoxes; ottIdx++) {
1709       err = mapIndexData(
1710           &pCurBs->IPDLosslessData[ottIdx], self->ottIPD__FDK, self->outIdxData,
1711           pCurBs->cmpOttIPDidx, NULL, ottIdx, self->ottIPDidxPrev, ottIdx,
1712           t_IPD, 0, self->numOttBandsIPD, IPDdefault, pCurBs->numParameterSets,
1713           pCurBs->paramSlot, self->extendFrame, self->quantMode,
1714           &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
1715     }
1716   }
1717 
1718 bail:
1719 
1720   return MPS_OK;
1721 
1722 } /* decodeAndMapFrameOtt */
1723 
1724 /*******************************************************************************
1725  Functionname: decodeAndMapFrameSmg
1726  *******************************************************************************
1727 
1728  Description:
1729    Decode smoothing flags
1730 
1731  Arguments:
1732 
1733 Input:
1734 
1735 Output:
1736 
1737 
1738 *******************************************************************************/
decodeAndMapFrameSmg(HANDLE_SPATIAL_DEC self,const SPATIAL_BS_FRAME * frame)1739 static SACDEC_ERROR decodeAndMapFrameSmg(HANDLE_SPATIAL_DEC self,
1740                                          const SPATIAL_BS_FRAME *frame) {
1741   int ps, pb, pg, pbStride, dataBands, pbStart, pbStop,
1742       aGroupToBand[MAX_PARAMETER_BANDS + 1];
1743 
1744   if (frame->numParameterSets > MAX_PARAMETER_SETS)
1745     return MPS_WRONG_PARAMETERSETS;
1746   if (self->bitstreamParameterBands > MAX_PARAMETER_BANDS)
1747     return MPS_WRONG_PARAMETERBANDS;
1748 
1749   for (ps = 0; ps < frame->numParameterSets; ps++) {
1750     switch (frame->bsSmoothMode[ps]) {
1751       case 0:
1752         self->smgTime[ps] = 256;
1753         FDKmemclear(self->smgData[ps],
1754                     self->bitstreamParameterBands * sizeof(UCHAR));
1755         break;
1756 
1757       case 1:
1758         if (ps > 0) {
1759           self->smgTime[ps] = self->smgTime[ps - 1];
1760           FDKmemcpy(self->smgData[ps], self->smgData[ps - 1],
1761                     self->bitstreamParameterBands * sizeof(UCHAR));
1762         } else {
1763           self->smgTime[ps] = self->smoothState->prevSmgTime;
1764           FDKmemcpy(self->smgData[ps], self->smoothState->prevSmgData,
1765                     self->bitstreamParameterBands * sizeof(UCHAR));
1766         }
1767         break;
1768 
1769       case 2:
1770         self->smgTime[ps] = smgTimeTable[frame->bsSmoothTime[ps]];
1771         for (pb = 0; pb < self->bitstreamParameterBands; pb++) {
1772           self->smgData[ps][pb] = 1;
1773         }
1774         break;
1775 
1776       case 3:
1777         self->smgTime[ps] = smgTimeTable[frame->bsSmoothTime[ps]];
1778         pbStride = pbStrideTable[frame->bsFreqResStrideSmg[ps]];
1779         dataBands = (self->bitstreamParameterBands - 1) / pbStride + 1;
1780         createMapping(aGroupToBand, 0, self->bitstreamParameterBands, pbStride);
1781         for (pg = 0; pg < dataBands; pg++) {
1782           pbStart = aGroupToBand[pg];
1783           pbStop = aGroupToBand[pg + 1];
1784           for (pb = pbStart; pb < pbStop; pb++) {
1785             self->smgData[ps][pb] = frame->bsSmgData[ps][pg];
1786           }
1787         }
1788         break;
1789     }
1790   }
1791 
1792   self->smoothState->prevSmgTime = self->smgTime[frame->numParameterSets - 1];
1793   FDKmemcpy(self->smoothState->prevSmgData,
1794             self->smgData[frame->numParameterSets - 1],
1795             self->bitstreamParameterBands * sizeof(UCHAR));
1796 
1797   if (self->extendFrame) {
1798     self->smgTime[frame->numParameterSets] =
1799         self->smgTime[frame->numParameterSets - 1];
1800     FDKmemcpy(self->smgData[frame->numParameterSets],
1801               self->smgData[frame->numParameterSets - 1],
1802               self->bitstreamParameterBands * sizeof(UCHAR));
1803   }
1804 
1805   return MPS_OK;
1806 }
1807 
1808 /*******************************************************************************
1809  Functionname: decodeAndMapFrameArbdmx
1810  *******************************************************************************
1811 
1812  Description:
1813    Do delta decoding and dequantization
1814 
1815  Arguments:
1816 
1817 Input:
1818 
1819 Output:
1820 
1821 *******************************************************************************/
decodeAndMapFrameArbdmx(HANDLE_SPATIAL_DEC self,const SPATIAL_BS_FRAME * frame)1822 static SACDEC_ERROR decodeAndMapFrameArbdmx(HANDLE_SPATIAL_DEC self,
1823                                             const SPATIAL_BS_FRAME *frame) {
1824   SACDEC_ERROR err = MPS_OK;
1825   int ch;
1826   int offset = self->numOttBoxes;
1827 
1828   for (ch = 0; ch < self->numInputChannels; ch++) {
1829     err = mapIndexData(&frame->CLDLosslessData[offset + ch],
1830                        self->arbdmxGain__FDK, self->outIdxData,
1831                        frame->cmpArbdmxGainIdx, NULL, /* no differential data */
1832                        ch, self->arbdmxGainIdxPrev, offset + ch, t_CLD, 0,
1833                        self->bitstreamParameterBands,
1834                        0 /*self->arbdmxGainDefault*/, frame->numParameterSets,
1835                        frame->paramSlot, self->extendFrame, 0,
1836                        &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
1837     if (err != MPS_OK) goto bail;
1838   }
1839 
1840 bail:
1841   return err;
1842 } /* decodeAndMapFrameArbdmx */
1843 
1844 /*******************************************************************************
1845  Functionname: SpatialDecDecodeFrame
1846  *******************************************************************************
1847 
1848  Description:
1849 
1850  Arguments:
1851 
1852  Return:
1853 
1854 *******************************************************************************/
SpatialDecDecodeFrame(spatialDec * self,SPATIAL_BS_FRAME * frame)1855 SACDEC_ERROR SpatialDecDecodeFrame(spatialDec *self, SPATIAL_BS_FRAME *frame) {
1856   SACDEC_ERROR err = MPS_OK;
1857 
1858   self->extendFrame = 0;
1859   if (frame->paramSlot[frame->numParameterSets - 1] != self->timeSlots - 1) {
1860     self->extendFrame = 1;
1861   }
1862 
1863   self->TsdTs = 0;
1864 
1865   /****** DTDF and MAP DATA ********/
1866   if ((err = decodeAndMapFrameOtt(self, frame)) != MPS_OK) goto bail;
1867 
1868   if ((err = decodeAndMapFrameSmg(self, frame)) != MPS_OK) goto bail;
1869 
1870   if (self->arbitraryDownmix != 0) {
1871     if ((err = decodeAndMapFrameArbdmx(self, frame)) != MPS_OK) goto bail;
1872   }
1873 
1874   if (self->extendFrame) {
1875     frame->numParameterSets =
1876         fixMin(MAX_PARAMETER_SETS, frame->numParameterSets + 1);
1877     frame->paramSlot[frame->numParameterSets - 1] = self->timeSlots - 1;
1878 
1879     for (int p = 0; p < frame->numParameterSets; p++) {
1880       if (frame->paramSlot[p] > self->timeSlots - 1) {
1881         frame->paramSlot[p] = self->timeSlots - 1;
1882         err = MPS_PARSE_ERROR;
1883       }
1884     }
1885     if (err != MPS_OK) {
1886       goto bail;
1887     }
1888   }
1889 
1890 bail:
1891   return err;
1892 } /* SpatialDecDecodeFrame() */
1893 
1894 /*******************************************************************************
1895  Functionname: SpatialDecodeHeader
1896  *******************************************************************************
1897 
1898  Description:
1899 
1900  Arguments:
1901 
1902  Return:
1903 
1904 *******************************************************************************/
1905 
SpatialDecDecodeHeader(spatialDec * self,SPATIAL_SPECIFIC_CONFIG * pSpatialSpecificConfig)1906 SACDEC_ERROR SpatialDecDecodeHeader(
1907     spatialDec *self, SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig) {
1908   SACDEC_ERROR err = MPS_OK;
1909   int i;
1910 
1911   self->samplingFreq = pSpatialSpecificConfig->samplingFreq;
1912   self->timeSlots = pSpatialSpecificConfig->nTimeSlots;
1913   self->frameLength = self->timeSlots * self->qmfBands;
1914   self->bitstreamParameterBands = pSpatialSpecificConfig->freqRes;
1915 
1916   if (self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_LD)
1917     self->hybridBands = self->qmfBands;
1918   else
1919     self->hybridBands = SacGetHybridSubbands(self->qmfBands);
1920   self->tp_hybBandBorder = 12;
1921 
1922   self->numParameterBands = self->bitstreamParameterBands;
1923 
1924   if (self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_LD) {
1925     switch (self->numParameterBands) {
1926       case 4:
1927         self->kernels = kernels_4_to_64;
1928         break;
1929       case 5:
1930         self->kernels = kernels_5_to_64;
1931         break;
1932       case 7:
1933         self->kernels = kernels_7_to_64;
1934         break;
1935       case 9:
1936         self->kernels = kernels_9_to_64;
1937         break;
1938       case 12:
1939         self->kernels = kernels_12_to_64;
1940         break;
1941       case 15:
1942         self->kernels = kernels_15_to_64;
1943         break;
1944       case 23:
1945         self->kernels = kernels_23_to_64;
1946         break;
1947       default:
1948         return MPS_INVALID_PARAMETERBANDS; /* unsupported numParameterBands */
1949     }
1950   } else {
1951     switch (self->numParameterBands) {
1952       case 4:
1953         self->kernels = kernels_4_to_71;
1954         break;
1955       case 5:
1956         self->kernels = kernels_5_to_71;
1957         break;
1958       case 7:
1959         self->kernels = kernels_7_to_71;
1960         break;
1961       case 10:
1962         self->kernels = kernels_10_to_71;
1963         break;
1964       case 14:
1965         self->kernels = kernels_14_to_71;
1966         break;
1967       case 20:
1968         self->kernels = kernels_20_to_71;
1969         break;
1970       case 28:
1971         self->kernels = kernels_28_to_71;
1972         break;
1973       default:
1974         return MPS_INVALID_PARAMETERBANDS; /* unsupported numParameterBands */
1975     }
1976   }
1977 
1978   /* create param to hyb band table */
1979   FDKmemclear(self->param2hyb, (MAX_PARAMETER_BANDS + 1) * sizeof(int));
1980   for (i = 0; i < self->hybridBands; i++) {
1981     self->param2hyb[self->kernels[i] + 1] = i + 1;
1982   }
1983   {
1984     int pb = self->kernels[i - 1] + 2;
1985     for (; pb < (MAX_PARAMETER_BANDS + 1); pb++) {
1986       self->param2hyb[pb] = i;
1987     }
1988     for (pb = 0; pb < MAX_PARAMETER_BANDS; pb += 1) {
1989       self->kernels_width[pb] = self->param2hyb[pb + 1] - self->param2hyb[pb];
1990     }
1991   }
1992 
1993   self->treeConfig = pSpatialSpecificConfig->treeConfig;
1994 
1995   self->numOttBoxes = pSpatialSpecificConfig->nOttBoxes;
1996 
1997   self->numInputChannels = pSpatialSpecificConfig->nInputChannels;
1998 
1999   self->numOutputChannels = pSpatialSpecificConfig->nOutputChannels;
2000 
2001   self->quantMode = pSpatialSpecificConfig->quantMode;
2002 
2003   self->arbitraryDownmix = pSpatialSpecificConfig->bArbitraryDownmix;
2004 
2005   self->numM2rows = self->numOutputChannels;
2006 
2007   {
2008     self->residualCoding = 0;
2009     if (self->arbitraryDownmix == 2)
2010       self->arbitraryDownmix = 1; /* no arbitrary downmix residuals */
2011   }
2012   if ((self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_USAC)) {
2013     self->residualCoding = pSpatialSpecificConfig->bResidualCoding;
2014   }
2015 
2016   self->clipProtectGain__FDK =
2017       FX_CFG2FX_DBL(clipGainTable__FDK[pSpatialSpecificConfig->bsFixedGainDMX]);
2018   self->clipProtectGainSF__FDK =
2019       clipGainSFTable__FDK[pSpatialSpecificConfig->bsFixedGainDMX];
2020 
2021   self->tempShapeConfig = pSpatialSpecificConfig->tempShapeConfig;
2022 
2023   self->decorrConfig = pSpatialSpecificConfig->decorrConfig;
2024 
2025   if (self->upmixType == UPMIXTYPE_BYPASS) {
2026     self->numOutputChannels = self->numInputChannels;
2027   }
2028 
2029   self->numOutputChannelsAT = self->numOutputChannels;
2030 
2031   self->numOttBandsIPD = pSpatialSpecificConfig->numOttBandsIPD;
2032   self->phaseCoding = pSpatialSpecificConfig->bsPhaseCoding;
2033   for (i = 0; i < self->numOttBoxes; i++) {
2034     {
2035       self->pConfigCurrent->bitstreamOttBands[i] =
2036           self->bitstreamParameterBands;
2037     }
2038     self->numOttBands[i] = self->pConfigCurrent->bitstreamOttBands[i];
2039   } /* i */
2040 
2041   if (self->residualCoding) {
2042     int numBoxes = self->numOttBoxes;
2043     for (i = 0; i < numBoxes; i++) {
2044       self->residualPresent[i] =
2045           pSpatialSpecificConfig->ResidualConfig[i].bResidualPresent;
2046 
2047       if (self->residualPresent[i]) {
2048         self->residualBands[i] =
2049             pSpatialSpecificConfig->ResidualConfig[i].nResidualBands;
2050         /* conversion from hybrid bands to qmf bands */
2051         self->residualQMFBands[i] =
2052             fMax(self->param2hyb[self->residualBands[i]] + 3 - 10,
2053                  3); /* simplification for the lowest 10 hybrid bands */
2054       } else {
2055         self->residualBands[i] = 0;
2056         self->residualQMFBands[i] = 0;
2057       }
2058     }
2059   } /* self->residualCoding */
2060   else {
2061     int boxes = self->numOttBoxes;
2062     for (i = 0; i < boxes; i += 1) {
2063       self->residualPresent[i] = 0;
2064       self->residualBands[i] = 0;
2065     }
2066   }
2067 
2068   switch (self->treeConfig) {
2069     case TREE_212:
2070       self->numDirektSignals = 1;
2071       self->numDecorSignals = 1;
2072       self->numXChannels = 1;
2073       if (self->arbitraryDownmix == 2) {
2074         self->numXChannels += 1;
2075       }
2076       self->numVChannels = self->numDirektSignals + self->numDecorSignals;
2077       break;
2078     default:
2079       return MPS_INVALID_TREECONFIG;
2080   }
2081 
2082   self->highRateMode = pSpatialSpecificConfig->bsHighRateMode;
2083   self->decorrType = pSpatialSpecificConfig->bsDecorrType;
2084 
2085   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
2086 
2087   return err;
2088 }
2089 
2090 /*******************************************************************************
2091  Functionname: SpatialDecCreateBsFrame
2092  *******************************************************************************
2093 
2094  Description: Create spatial bitstream structure
2095 
2096  Arguments:   spatialDec* self
2097               const SPATIAL_BS_FRAME **bsFrame
2098 
2099  Return:      -
2100 
2101 *******************************************************************************/
SpatialDecCreateBsFrame(SPATIAL_BS_FRAME * bsFrame,BS_LL_STATE * llState)2102 SACDEC_ERROR SpatialDecCreateBsFrame(SPATIAL_BS_FRAME *bsFrame,
2103                                      BS_LL_STATE *llState) {
2104   SPATIAL_BS_FRAME *pBs = bsFrame;
2105 
2106   const int maxNumOtt = MAX_NUM_OTT;
2107   const int maxNumInputChannels = MAX_INPUT_CHANNELS;
2108 
2109   FDK_ALLOCATE_MEMORY_1D_P(
2110       pBs->cmpOttIPDidx, maxNumOtt * MAX_PARAMETER_SETS * MAX_PARAMETER_BANDS,
2111       SCHAR, SCHAR(*)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS])
2112 
2113   /* Arbitrary Downmix */
2114   FDK_ALLOCATE_MEMORY_1D_P(
2115       pBs->cmpArbdmxGainIdx,
2116       maxNumInputChannels * MAX_PARAMETER_SETS * MAX_PARAMETER_BANDS, SCHAR,
2117       SCHAR(*)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS])
2118 
2119   /* Lossless control */
2120   FDK_ALLOCATE_MEMORY_1D(pBs->CLDLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
2121   FDK_ALLOCATE_MEMORY_1D(pBs->ICCLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
2122 
2123   FDK_ALLOCATE_MEMORY_1D(pBs->IPDLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
2124 
2125   pBs->newBsData = 0;
2126   pBs->numParameterSets = 1;
2127 
2128   /* Link lossless states */
2129   for (int x = 0; x < MAX_NUM_PARAMETERS; x++) {
2130     pBs->CLDLosslessData[x].state = &llState->CLDLosslessState[x];
2131     pBs->ICCLosslessData[x].state = &llState->ICCLosslessState[x];
2132 
2133     pBs->IPDLosslessData[x].state = &llState->IPDLosslessState[x];
2134   }
2135 
2136   return MPS_OK;
2137 
2138 bail:
2139   return MPS_OUTOFMEMORY;
2140 }
2141 
2142 /*******************************************************************************
2143  Functionname: SpatialDecCloseBsFrame
2144  *******************************************************************************
2145 
2146  Description: Close spatial bitstream structure
2147 
2148  Arguments:   spatialDec* self
2149 
2150  Return:      -
2151 
2152 *******************************************************************************/
SpatialDecCloseBsFrame(SPATIAL_BS_FRAME * pBs)2153 void SpatialDecCloseBsFrame(SPATIAL_BS_FRAME *pBs) {
2154   if (pBs != NULL) {
2155     /* These arrays contain the compact indices, only one value per pbstride,
2156      * only paramsets actually containing data. */
2157 
2158     FDK_FREE_MEMORY_1D(pBs->cmpOttIPDidx);
2159 
2160     /* Arbitrary Downmix */
2161     FDK_FREE_MEMORY_1D(pBs->cmpArbdmxGainIdx);
2162 
2163     /* Lossless control */
2164     FDK_FREE_MEMORY_1D(pBs->IPDLosslessData);
2165     FDK_FREE_MEMORY_1D(pBs->CLDLosslessData);
2166     FDK_FREE_MEMORY_1D(pBs->ICCLosslessData);
2167   }
2168 }
2169