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 /**************************** SBR decoder library ******************************
96
97 Author(s):
98
99 Description:
100
101 *******************************************************************************/
102
103 /*!
104 \file
105 \brief SBR decoder frontend
106 This module provides a frontend to the SBR decoder. The function openSBR() is
107 called for initialization. The function sbrDecoder_Apply() is called for each
108 frame. sbr_Apply() will call the required functions to decode the raw SBR data
109 (provided by env_extr.cpp), to decode the envelope data and noise floor levels
110 [decodeSbrData()], and to finally apply SBR to the current frame [sbr_dec()].
111
112 \sa sbrDecoder_Apply(), \ref documentationOverview
113 */
114
115 /*!
116 \page documentationOverview Overview of important information resources and
117 source code documentation
118
119 As part of this documentation you can find more extensive descriptions about
120 key concepts and algorithms at the following locations:
121
122 <h2>Programming</h2>
123
124 \li Buffer management: sbrDecoder_Apply() and sbr_dec()
125 \li Internal scale factors to maximize SNR on fixed point processors:
126 #QMF_SCALE_FACTOR \li Special mantissa-exponent format: Created in
127 requantizeEnvelopeData() and used in calculateSbrEnvelope()
128
129 <h2>Algorithmic details</h2>
130 \li About the SBR data format: \ref SBR_HEADER_ELEMENT and \ref
131 SBR_STANDARD_ELEMENT \li Details about the bitstream decoder: env_extr.cpp \li
132 Details about the QMF filterbank and the provided polyphase implementation:
133 qmf_dec.cpp \li Details about the transposer: lpp_tran.cpp \li Details about
134 the envelope adjuster: env_calc.cpp
135
136 */
137
138 #include "sbrdecoder.h"
139
140 #include "FDK_bitstream.h"
141
142 #include "sbrdec_freq_sca.h"
143 #include "env_extr.h"
144 #include "sbr_dec.h"
145 #include "env_dec.h"
146 #include "sbr_crc.h"
147 #include "sbr_ram.h"
148 #include "sbr_rom.h"
149 #include "lpp_tran.h"
150 #include "transcendent.h"
151
152 #include "FDK_crc.h"
153
154 #include "sbrdec_drc.h"
155
156 #include "psbitdec.h"
157
158 /* Decoder library info */
159 #define SBRDECODER_LIB_VL0 3
160 #define SBRDECODER_LIB_VL1 0
161 #define SBRDECODER_LIB_VL2 0
162 #define SBRDECODER_LIB_TITLE "SBR Decoder"
163 #ifdef __ANDROID__
164 #define SBRDECODER_LIB_BUILD_DATE ""
165 #define SBRDECODER_LIB_BUILD_TIME ""
166 #else
167 #define SBRDECODER_LIB_BUILD_DATE __DATE__
168 #define SBRDECODER_LIB_BUILD_TIME __TIME__
169 #endif
170
setFrameErrorFlag(SBR_DECODER_ELEMENT * pSbrElement,UCHAR value)171 static void setFrameErrorFlag(SBR_DECODER_ELEMENT *pSbrElement, UCHAR value) {
172 if (pSbrElement != NULL) {
173 switch (value) {
174 case FRAME_ERROR_ALLSLOTS:
175 FDKmemset(pSbrElement->frameErrorFlag, FRAME_ERROR,
176 sizeof(pSbrElement->frameErrorFlag));
177 break;
178 default:
179 pSbrElement->frameErrorFlag[pSbrElement->useFrameSlot] = value;
180 }
181 }
182 }
183
getHeaderSlot(UCHAR currentSlot,UCHAR hdrSlotUsage[(1)+1])184 static UCHAR getHeaderSlot(UCHAR currentSlot, UCHAR hdrSlotUsage[(1) + 1]) {
185 UINT occupied = 0;
186 int s;
187 UCHAR slot = hdrSlotUsage[currentSlot];
188
189 FDK_ASSERT((1) + 1 < 32);
190
191 for (s = 0; s < (1) + 1; s++) {
192 if ((hdrSlotUsage[s] == slot) && (s != slot)) {
193 occupied = 1;
194 break;
195 }
196 }
197
198 if (occupied) {
199 occupied = 0;
200
201 for (s = 0; s < (1) + 1; s++) {
202 occupied |= 1 << hdrSlotUsage[s];
203 }
204 for (s = 0; s < (1) + 1; s++) {
205 if (!(occupied & 0x1)) {
206 slot = s;
207 break;
208 }
209 occupied >>= 1;
210 }
211 }
212
213 return slot;
214 }
215
copySbrHeader(HANDLE_SBR_HEADER_DATA hDst,const HANDLE_SBR_HEADER_DATA hSrc)216 static void copySbrHeader(HANDLE_SBR_HEADER_DATA hDst,
217 const HANDLE_SBR_HEADER_DATA hSrc) {
218 /* copy the whole header memory (including pointers) */
219 FDKmemcpy(hDst, hSrc, sizeof(SBR_HEADER_DATA));
220
221 /* update pointers */
222 hDst->freqBandData.freqBandTable[0] = hDst->freqBandData.freqBandTableLo;
223 hDst->freqBandData.freqBandTable[1] = hDst->freqBandData.freqBandTableHi;
224 }
225
compareSbrHeader(const HANDLE_SBR_HEADER_DATA hHdr1,const HANDLE_SBR_HEADER_DATA hHdr2)226 static int compareSbrHeader(const HANDLE_SBR_HEADER_DATA hHdr1,
227 const HANDLE_SBR_HEADER_DATA hHdr2) {
228 int result = 0;
229
230 /* compare basic data */
231 result |= (hHdr1->syncState != hHdr2->syncState) ? 1 : 0;
232 result |= (hHdr1->status != hHdr2->status) ? 1 : 0;
233 result |= (hHdr1->frameErrorFlag != hHdr2->frameErrorFlag) ? 1 : 0;
234 result |= (hHdr1->numberTimeSlots != hHdr2->numberTimeSlots) ? 1 : 0;
235 result |=
236 (hHdr1->numberOfAnalysisBands != hHdr2->numberOfAnalysisBands) ? 1 : 0;
237 result |= (hHdr1->timeStep != hHdr2->timeStep) ? 1 : 0;
238 result |= (hHdr1->sbrProcSmplRate != hHdr2->sbrProcSmplRate) ? 1 : 0;
239
240 /* compare bitstream data */
241 result |=
242 FDKmemcmp(&hHdr1->bs_data, &hHdr2->bs_data, sizeof(SBR_HEADER_DATA_BS));
243 result |=
244 FDKmemcmp(&hHdr1->bs_dflt, &hHdr2->bs_dflt, sizeof(SBR_HEADER_DATA_BS));
245 result |= FDKmemcmp(&hHdr1->bs_info, &hHdr2->bs_info,
246 sizeof(SBR_HEADER_DATA_BS_INFO));
247
248 /* compare frequency band data */
249 result |= FDKmemcmp(&hHdr1->freqBandData, &hHdr2->freqBandData,
250 (8 + MAX_NUM_LIMITERS + 1) * sizeof(UCHAR));
251 result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableLo,
252 hHdr2->freqBandData.freqBandTableLo,
253 (MAX_FREQ_COEFFS / 2 + 1) * sizeof(UCHAR));
254 result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableHi,
255 hHdr2->freqBandData.freqBandTableHi,
256 (MAX_FREQ_COEFFS + 1) * sizeof(UCHAR));
257 result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableNoise,
258 hHdr2->freqBandData.freqBandTableNoise,
259 (MAX_NOISE_COEFFS + 1) * sizeof(UCHAR));
260 result |=
261 FDKmemcmp(hHdr1->freqBandData.v_k_master, hHdr2->freqBandData.v_k_master,
262 (MAX_FREQ_COEFFS + 1) * sizeof(UCHAR));
263
264 return result;
265 }
266
267 /*!
268 \brief Reset SBR decoder.
269
270 Reset should only be called if SBR has been sucessfully detected by
271 an appropriate checkForPayload() function.
272
273 \return Error code.
274 */
sbrDecoder_ResetElement(HANDLE_SBRDECODER self,int sampleRateIn,int sampleRateOut,int samplesPerFrame,const MP4_ELEMENT_ID elementID,const int elementIndex,const int overlap)275 static SBR_ERROR sbrDecoder_ResetElement(HANDLE_SBRDECODER self,
276 int sampleRateIn, int sampleRateOut,
277 int samplesPerFrame,
278 const MP4_ELEMENT_ID elementID,
279 const int elementIndex,
280 const int overlap) {
281 SBR_ERROR sbrError = SBRDEC_OK;
282 HANDLE_SBR_HEADER_DATA hSbrHeader;
283 UINT qmfFlags = 0;
284
285 int i, synDownsampleFac;
286
287 /* USAC: assuming theoretical case 8 kHz output sample rate with 4:1 SBR */
288 const int sbr_min_sample_rate_in = IS_USAC(self->coreCodec) ? 2000 : 6400;
289
290 /* Check in/out samplerates */
291 if (sampleRateIn < sbr_min_sample_rate_in || sampleRateIn > (96000)) {
292 sbrError = SBRDEC_UNSUPPORTED_CONFIG;
293 goto bail;
294 }
295
296 if (sampleRateOut > (96000)) {
297 sbrError = SBRDEC_UNSUPPORTED_CONFIG;
298 goto bail;
299 }
300
301 /* Set QMF mode flags */
302 if (self->flags & SBRDEC_LOW_POWER) qmfFlags |= QMF_FLAG_LP;
303
304 if (self->coreCodec == AOT_ER_AAC_ELD) {
305 if (self->flags & SBRDEC_LD_MPS_QMF) {
306 qmfFlags |= QMF_FLAG_MPSLDFB;
307 } else {
308 qmfFlags |= QMF_FLAG_CLDFB;
309 }
310 }
311
312 /* Set downsampling factor for synthesis filter bank */
313 if (sampleRateOut == 0) {
314 /* no single rate mode */
315 sampleRateOut =
316 sampleRateIn
317 << 1; /* In case of implicit signalling, assume dual rate SBR */
318 }
319
320 if (sampleRateIn == sampleRateOut) {
321 synDownsampleFac = 2;
322 self->flags |= SBRDEC_DOWNSAMPLE;
323 } else {
324 synDownsampleFac = 1;
325 self->flags &= ~SBRDEC_DOWNSAMPLE;
326 }
327
328 self->synDownsampleFac = synDownsampleFac;
329 self->sampleRateOut = sampleRateOut;
330
331 {
332 for (i = 0; i < (1) + 1; i++) {
333 int setDflt;
334 hSbrHeader = &(self->sbrHeader[elementIndex][i]);
335 setDflt = ((hSbrHeader->syncState == SBR_NOT_INITIALIZED) ||
336 (self->flags & SBRDEC_FORCE_RESET))
337 ? 1
338 : 0;
339
340 /* init a default header such that we can at least do upsampling later */
341 sbrError = initHeaderData(hSbrHeader, sampleRateIn, sampleRateOut,
342 self->downscaleFactor, samplesPerFrame,
343 self->flags, setDflt);
344
345 /* Set synchState to UPSAMPLING in case it already is initialized */
346 hSbrHeader->syncState = hSbrHeader->syncState > UPSAMPLING
347 ? UPSAMPLING
348 : hSbrHeader->syncState;
349 }
350 }
351
352 if (sbrError != SBRDEC_OK) {
353 goto bail;
354 }
355
356 if (!self->pQmfDomain->globalConf.qmfDomainExplicitConfig) {
357 self->pQmfDomain->globalConf.flags_requested |= qmfFlags;
358 self->pQmfDomain->globalConf.nBandsAnalysis_requested =
359 self->sbrHeader[elementIndex][0].numberOfAnalysisBands;
360 self->pQmfDomain->globalConf.nBandsSynthesis_requested =
361 (synDownsampleFac == 1) ? 64 : 32; /* may be overwritten by MPS */
362 self->pQmfDomain->globalConf.nBandsSynthesis_requested /=
363 self->downscaleFactor;
364 self->pQmfDomain->globalConf.nQmfTimeSlots_requested =
365 self->sbrHeader[elementIndex][0].numberTimeSlots *
366 self->sbrHeader[elementIndex][0].timeStep;
367 self->pQmfDomain->globalConf.nQmfOvTimeSlots_requested = overlap;
368 self->pQmfDomain->globalConf.nQmfProcBands_requested = 64; /* always 64 */
369 self->pQmfDomain->globalConf.nQmfProcChannels_requested =
370 1; /* may be overwritten by MPS */
371 }
372
373 /* Init SBR channels going to be assigned to a SBR element */
374 {
375 int ch;
376 for (ch = 0; ch < self->pSbrElement[elementIndex]->nChannels; ch++) {
377 int headerIndex =
378 getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
379 self->pSbrElement[elementIndex]->useHeaderSlot);
380
381 /* and create sbrDec */
382 sbrError =
383 createSbrDec(self->pSbrElement[elementIndex]->pSbrChannel[ch],
384 &self->sbrHeader[elementIndex][headerIndex],
385 &self->pSbrElement[elementIndex]->transposerSettings,
386 synDownsampleFac, qmfFlags, self->flags, overlap, ch,
387 self->codecFrameSize);
388
389 if (sbrError != SBRDEC_OK) {
390 goto bail;
391 }
392 }
393 }
394
395 // FDKmemclear(sbr_OverlapBuffer, sizeof(sbr_OverlapBuffer));
396
397 if (self->numSbrElements == 1) {
398 switch (self->coreCodec) {
399 case AOT_AAC_LC:
400 case AOT_SBR:
401 case AOT_PS:
402 case AOT_ER_AAC_SCAL:
403 case AOT_DRM_AAC:
404 case AOT_DRM_SURROUND:
405 if (CreatePsDec(&self->hParametricStereoDec, samplesPerFrame)) {
406 sbrError = SBRDEC_CREATE_ERROR;
407 goto bail;
408 }
409 break;
410 default:
411 break;
412 }
413 }
414
415 /* Init frame delay slot handling */
416 self->pSbrElement[elementIndex]->useFrameSlot = 0;
417 for (i = 0; i < ((1) + 1); i++) {
418 self->pSbrElement[elementIndex]->useHeaderSlot[i] = i;
419 }
420
421 bail:
422
423 return sbrError;
424 }
425
426 /*!
427 \brief Assign QMF domain provided QMF channels to SBR channels.
428
429 \return void
430 */
sbrDecoder_AssignQmfChannels2SbrChannels(HANDLE_SBRDECODER self)431 static void sbrDecoder_AssignQmfChannels2SbrChannels(HANDLE_SBRDECODER self) {
432 int ch, el, absCh_offset = 0;
433 for (el = 0; el < self->numSbrElements; el++) {
434 if (self->pSbrElement[el] != NULL) {
435 for (ch = 0; ch < self->pSbrElement[el]->nChannels; ch++) {
436 FDK_ASSERT(((absCh_offset + ch) < ((8) + (1))) &&
437 ((absCh_offset + ch) < ((8) + (1))));
438 self->pSbrElement[el]->pSbrChannel[ch]->SbrDec.qmfDomainInCh =
439 &self->pQmfDomain->QmfDomainIn[absCh_offset + ch];
440 self->pSbrElement[el]->pSbrChannel[ch]->SbrDec.qmfDomainOutCh =
441 &self->pQmfDomain->QmfDomainOut[absCh_offset + ch];
442 }
443 absCh_offset += self->pSbrElement[el]->nChannels;
444 }
445 }
446 }
447
sbrDecoder_Open(HANDLE_SBRDECODER * pSelf,HANDLE_FDK_QMF_DOMAIN pQmfDomain)448 SBR_ERROR sbrDecoder_Open(HANDLE_SBRDECODER *pSelf,
449 HANDLE_FDK_QMF_DOMAIN pQmfDomain) {
450 HANDLE_SBRDECODER self = NULL;
451 SBR_ERROR sbrError = SBRDEC_OK;
452 int elIdx;
453
454 if ((pSelf == NULL) || (pQmfDomain == NULL)) {
455 return SBRDEC_INVALID_ARGUMENT;
456 }
457
458 /* Get memory for this instance */
459 self = GetRam_SbrDecoder();
460 if (self == NULL) {
461 sbrError = SBRDEC_MEM_ALLOC_FAILED;
462 goto bail;
463 }
464
465 self->pQmfDomain = pQmfDomain;
466
467 /*
468 Already zero because of calloc
469 self->numSbrElements = 0;
470 self->numSbrChannels = 0;
471 self->codecFrameSize = 0;
472 */
473
474 self->numDelayFrames = (1); /* set to the max value by default */
475
476 /* Initialize header sync state */
477 for (elIdx = 0; elIdx < (8); elIdx += 1) {
478 int i;
479 for (i = 0; i < (1) + 1; i += 1) {
480 self->sbrHeader[elIdx][i].syncState = SBR_NOT_INITIALIZED;
481 }
482 }
483
484 *pSelf = self;
485
486 bail:
487 return sbrError;
488 }
489
490 /**
491 * \brief determine if the given core codec AOT can be processed or not.
492 * \param coreCodec core codec audio object type.
493 * \return 1 if SBR can be processed, 0 if SBR cannot be processed/applied.
494 */
sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec)495 static int sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec) {
496 switch (coreCodec) {
497 case AOT_AAC_LC:
498 case AOT_SBR:
499 case AOT_PS:
500 case AOT_ER_AAC_SCAL:
501 case AOT_ER_AAC_ELD:
502 case AOT_DRM_AAC:
503 case AOT_DRM_SURROUND:
504 case AOT_USAC:
505 return 1;
506 default:
507 return 0;
508 }
509 }
510
sbrDecoder_DestroyElement(HANDLE_SBRDECODER self,const int elementIndex)511 static void sbrDecoder_DestroyElement(HANDLE_SBRDECODER self,
512 const int elementIndex) {
513 if (self->pSbrElement[elementIndex] != NULL) {
514 int ch;
515
516 for (ch = 0; ch < SBRDEC_MAX_CH_PER_ELEMENT; ch++) {
517 if (self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
518 deleteSbrDec(self->pSbrElement[elementIndex]->pSbrChannel[ch]);
519 FreeRam_SbrDecChannel(
520 &self->pSbrElement[elementIndex]->pSbrChannel[ch]);
521 self->numSbrChannels -= 1;
522 }
523 }
524 FreeRam_SbrDecElement(&self->pSbrElement[elementIndex]);
525 self->numSbrElements -= 1;
526 }
527 }
528
sbrDecoder_InitElement(HANDLE_SBRDECODER self,const int sampleRateIn,const int sampleRateOut,const int samplesPerFrame,const AUDIO_OBJECT_TYPE coreCodec,const MP4_ELEMENT_ID elementID,const int elementIndex,const UCHAR harmonicSBR,const UCHAR stereoConfigIndex,const UCHAR configMode,UCHAR * configChanged,const INT downscaleFactor)529 SBR_ERROR sbrDecoder_InitElement(
530 HANDLE_SBRDECODER self, const int sampleRateIn, const int sampleRateOut,
531 const int samplesPerFrame, const AUDIO_OBJECT_TYPE coreCodec,
532 const MP4_ELEMENT_ID elementID, const int elementIndex,
533 const UCHAR harmonicSBR, const UCHAR stereoConfigIndex,
534 const UCHAR configMode, UCHAR *configChanged, const INT downscaleFactor) {
535 SBR_ERROR sbrError = SBRDEC_OK;
536 int chCnt = 0;
537 int nSbrElementsStart;
538 int nSbrChannelsStart;
539 if (self == NULL) {
540 return SBRDEC_INVALID_ARGUMENT;
541 }
542
543 nSbrElementsStart = self->numSbrElements;
544 nSbrChannelsStart = self->numSbrChannels;
545
546 /* Check core codec AOT */
547 if (!sbrDecoder_isCoreCodecValid(coreCodec) || elementIndex >= (8)) {
548 sbrError = SBRDEC_UNSUPPORTED_CONFIG;
549 goto bail;
550 }
551
552 if (elementID != ID_SCE && elementID != ID_CPE && elementID != ID_LFE) {
553 sbrError = SBRDEC_UNSUPPORTED_CONFIG;
554 goto bail;
555 }
556
557 if (self->sampleRateIn == sampleRateIn &&
558 self->codecFrameSize == samplesPerFrame && self->coreCodec == coreCodec &&
559 self->pSbrElement[elementIndex] != NULL &&
560 self->pSbrElement[elementIndex]->elementID == elementID &&
561 !(self->flags & SBRDEC_FORCE_RESET) &&
562 ((sampleRateOut == 0) ? 1 : (self->sampleRateOut == sampleRateOut)) &&
563 ((harmonicSBR == 2) ? 1
564 : (self->harmonicSBR ==
565 harmonicSBR)) /* The value 2 signalizes that
566 harmonicSBR shall be ignored in
567 the config change detection */
568 ) {
569 /* Nothing to do */
570 return SBRDEC_OK;
571 } else {
572 if (configMode & AC_CM_DET_CFG_CHANGE) {
573 *configChanged = 1;
574 }
575 }
576
577 /* reaching this point the SBR-decoder gets (re-)configured */
578
579 /* The flags field is used for all elements! */
580 self->flags &=
581 (SBRDEC_FORCE_RESET | SBRDEC_FLUSH); /* Keep the global flags. They will
582 be reset after decoding. */
583 self->flags |= (downscaleFactor > 1) ? SBRDEC_ELD_DOWNSCALE : 0;
584 self->flags |= (coreCodec == AOT_ER_AAC_ELD) ? SBRDEC_ELD_GRID : 0;
585 self->flags |= (coreCodec == AOT_ER_AAC_SCAL) ? SBRDEC_SYNTAX_SCAL : 0;
586 self->flags |=
587 (coreCodec == AOT_DRM_AAC) ? SBRDEC_SYNTAX_SCAL | SBRDEC_SYNTAX_DRM : 0;
588 self->flags |= (coreCodec == AOT_DRM_SURROUND)
589 ? SBRDEC_SYNTAX_SCAL | SBRDEC_SYNTAX_DRM
590 : 0;
591 self->flags |= (coreCodec == AOT_USAC) ? SBRDEC_SYNTAX_USAC : 0;
592 /* Robustness: Take integer division rounding into consideration. E.g. 22050
593 * Hz with 4:1 SBR => 5512 Hz core sampling rate. */
594 self->flags |= (sampleRateIn == sampleRateOut / 4) ? SBRDEC_QUAD_RATE : 0;
595 self->flags |= (harmonicSBR == 1) ? SBRDEC_USAC_HARMONICSBR : 0;
596
597 if (configMode & AC_CM_DET_CFG_CHANGE) {
598 return SBRDEC_OK;
599 }
600
601 self->sampleRateIn = sampleRateIn;
602 self->codecFrameSize = samplesPerFrame;
603 self->coreCodec = coreCodec;
604 self->harmonicSBR = harmonicSBR;
605 self->downscaleFactor = downscaleFactor;
606
607 /* Init SBR elements */
608 {
609 int elChannels, ch;
610
611 if (self->pSbrElement[elementIndex] == NULL) {
612 self->pSbrElement[elementIndex] = GetRam_SbrDecElement(elementIndex);
613 if (self->pSbrElement[elementIndex] == NULL) {
614 sbrError = SBRDEC_MEM_ALLOC_FAILED;
615 goto bail;
616 }
617 self->numSbrElements++;
618 } else {
619 self->numSbrChannels -= self->pSbrElement[elementIndex]->nChannels;
620 }
621
622 /* Save element ID for sanity checks and to have a fallback for concealment.
623 */
624 self->pSbrElement[elementIndex]->elementID = elementID;
625
626 /* Determine amount of channels for this element */
627 switch (elementID) {
628 case ID_NONE:
629 case ID_CPE:
630 elChannels = 2;
631 break;
632 case ID_LFE:
633 case ID_SCE:
634 elChannels = 1;
635 break;
636 default:
637 elChannels = 0;
638 break;
639 }
640
641 /* Handle case of Parametric Stereo */
642 if (elementIndex == 0 && elementID == ID_SCE) {
643 switch (coreCodec) {
644 case AOT_AAC_LC:
645 case AOT_SBR:
646 case AOT_PS:
647 case AOT_ER_AAC_SCAL:
648 case AOT_DRM_AAC:
649 case AOT_DRM_SURROUND:
650 elChannels = 2;
651 break;
652 default:
653 break;
654 }
655 }
656
657 /* Sanity check to avoid memory leaks */
658 if (elChannels < self->pSbrElement[elementIndex]->nChannels) {
659 self->numSbrChannels += self->pSbrElement[elementIndex]->nChannels;
660 sbrError = SBRDEC_PARSE_ERROR;
661 goto bail;
662 }
663
664 self->pSbrElement[elementIndex]->nChannels = elChannels;
665
666 for (ch = 0; ch < elChannels; ch++) {
667 if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
668 self->pSbrElement[elementIndex]->pSbrChannel[ch] =
669 GetRam_SbrDecChannel(chCnt);
670 if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
671 sbrError = SBRDEC_MEM_ALLOC_FAILED;
672 goto bail;
673 }
674 }
675 self->numSbrChannels++;
676
677 sbrDecoder_drcInitChannel(&self->pSbrElement[elementIndex]
678 ->pSbrChannel[ch]
679 ->SbrDec.sbrDrcChannel);
680
681 chCnt++;
682 }
683 }
684
685 if (!self->pQmfDomain->globalConf.qmfDomainExplicitConfig) {
686 self->pQmfDomain->globalConf.nInputChannels_requested =
687 self->numSbrChannels;
688 self->pQmfDomain->globalConf.nOutputChannels_requested =
689 fMax((INT)self->numSbrChannels,
690 (INT)self->pQmfDomain->globalConf.nOutputChannels_requested);
691 }
692
693 /* Make sure each SBR channel has one QMF channel assigned even if
694 * numSbrChannels or element set-up has changed. */
695 sbrDecoder_AssignQmfChannels2SbrChannels(self);
696
697 /* clear error flags for all delay slots */
698 FDKmemclear(self->pSbrElement[elementIndex]->frameErrorFlag,
699 ((1) + 1) * sizeof(UCHAR));
700
701 {
702 int overlap;
703
704 if (coreCodec == AOT_ER_AAC_ELD) {
705 overlap = 0;
706 } else if (self->flags & SBRDEC_QUAD_RATE) {
707 overlap = (3 * 4);
708 } else {
709 overlap = (3 * 2);
710 }
711 /* Initialize this instance */
712 sbrError = sbrDecoder_ResetElement(self, sampleRateIn, sampleRateOut,
713 samplesPerFrame, elementID, elementIndex,
714 overlap);
715 }
716
717 bail:
718 if (sbrError != SBRDEC_OK) {
719 if ((nSbrElementsStart < self->numSbrElements) ||
720 (nSbrChannelsStart < self->numSbrChannels)) {
721 /* Free the memory allocated for this element */
722 sbrDecoder_DestroyElement(self, elementIndex);
723 } else if ((elementIndex < (8)) &&
724 (self->pSbrElement[elementIndex] !=
725 NULL)) { /* Set error flag to trigger concealment */
726 setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_ERROR);
727 }
728 }
729
730 return sbrError;
731 }
732
733 /**
734 * \brief Free config dependent SBR memory.
735 * \param self SBR decoder instance handle
736 */
sbrDecoder_FreeMem(HANDLE_SBRDECODER * self)737 SBR_ERROR sbrDecoder_FreeMem(HANDLE_SBRDECODER *self) {
738 int i;
739 int elIdx;
740
741 if (self != NULL && *self != NULL) {
742 for (i = 0; i < (8); i++) {
743 sbrDecoder_DestroyElement(*self, i);
744 }
745
746 for (elIdx = 0; elIdx < (8); elIdx += 1) {
747 for (i = 0; i < (1) + 1; i += 1) {
748 (*self)->sbrHeader[elIdx][i].syncState = SBR_NOT_INITIALIZED;
749 }
750 }
751 }
752
753 return SBRDEC_OK;
754 }
755
756 /**
757 * \brief Apply decoded SBR header for one element.
758 * \param self SBR decoder instance handle
759 * \param hSbrHeader SBR header handle to be processed.
760 * \param hSbrChannel pointer array to the SBR element channels corresponding to
761 * the SBR header.
762 * \param headerStatus header status value returned from SBR header parser.
763 * \param numElementChannels amount of channels for the SBR element whos header
764 * is to be processed.
765 */
sbrDecoder_HeaderUpdate(HANDLE_SBRDECODER self,HANDLE_SBR_HEADER_DATA hSbrHeader,SBR_HEADER_STATUS headerStatus,HANDLE_SBR_CHANNEL hSbrChannel[],const int numElementChannels)766 static SBR_ERROR sbrDecoder_HeaderUpdate(HANDLE_SBRDECODER self,
767 HANDLE_SBR_HEADER_DATA hSbrHeader,
768 SBR_HEADER_STATUS headerStatus,
769 HANDLE_SBR_CHANNEL hSbrChannel[],
770 const int numElementChannels) {
771 SBR_ERROR errorStatus = SBRDEC_OK;
772
773 /*
774 change of control data, reset decoder
775 */
776 errorStatus = resetFreqBandTables(hSbrHeader, self->flags);
777
778 if (errorStatus == SBRDEC_OK) {
779 if (hSbrHeader->syncState == UPSAMPLING && headerStatus != HEADER_RESET) {
780 #if (SBRDEC_MAX_HB_FADE_FRAMES > 0)
781 int ch;
782 for (ch = 0; ch < numElementChannels; ch += 1) {
783 hSbrChannel[ch]->SbrDec.highBandFadeCnt = SBRDEC_MAX_HB_FADE_FRAMES;
784 }
785
786 #endif
787 /* As the default header would limit the frequency range,
788 lowSubband and highSubband must be patched. */
789 hSbrHeader->freqBandData.lowSubband = hSbrHeader->numberOfAnalysisBands;
790 hSbrHeader->freqBandData.highSubband = hSbrHeader->numberOfAnalysisBands;
791 }
792
793 /* Trigger a reset before processing this slot */
794 hSbrHeader->status |= SBRDEC_HDR_STAT_RESET;
795 }
796
797 return errorStatus;
798 }
799
sbrDecoder_Header(HANDLE_SBRDECODER self,HANDLE_FDK_BITSTREAM hBs,const INT sampleRateIn,const INT sampleRateOut,const INT samplesPerFrame,const AUDIO_OBJECT_TYPE coreCodec,const MP4_ELEMENT_ID elementID,const INT elementIndex,const UCHAR harmonicSBR,const UCHAR stereoConfigIndex,const UCHAR configMode,UCHAR * configChanged,const INT downscaleFactor)800 INT sbrDecoder_Header(HANDLE_SBRDECODER self, HANDLE_FDK_BITSTREAM hBs,
801 const INT sampleRateIn, const INT sampleRateOut,
802 const INT samplesPerFrame,
803 const AUDIO_OBJECT_TYPE coreCodec,
804 const MP4_ELEMENT_ID elementID, const INT elementIndex,
805 const UCHAR harmonicSBR, const UCHAR stereoConfigIndex,
806 const UCHAR configMode, UCHAR *configChanged,
807 const INT downscaleFactor) {
808 SBR_HEADER_STATUS headerStatus;
809 HANDLE_SBR_HEADER_DATA hSbrHeader;
810 SBR_ERROR sbrError = SBRDEC_OK;
811 int headerIndex;
812 UINT flagsSaved =
813 0; /* flags should not be changed in AC_CM_DET_CFG_CHANGE - mode after
814 parsing */
815
816 if (self == NULL || elementIndex >= (8)) {
817 return SBRDEC_UNSUPPORTED_CONFIG;
818 }
819
820 if (!sbrDecoder_isCoreCodecValid(coreCodec)) {
821 return SBRDEC_UNSUPPORTED_CONFIG;
822 }
823
824 if (configMode & AC_CM_DET_CFG_CHANGE) {
825 flagsSaved = self->flags; /* store */
826 }
827
828 sbrError = sbrDecoder_InitElement(
829 self, sampleRateIn, sampleRateOut, samplesPerFrame, coreCodec, elementID,
830 elementIndex, harmonicSBR, stereoConfigIndex, configMode, configChanged,
831 downscaleFactor);
832
833 if ((sbrError != SBRDEC_OK) || (elementID == ID_LFE)) {
834 goto bail;
835 }
836
837 if (configMode & AC_CM_DET_CFG_CHANGE) {
838 hSbrHeader = NULL;
839 } else {
840 headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
841 self->pSbrElement[elementIndex]->useHeaderSlot);
842
843 hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
844 }
845
846 headerStatus = sbrGetHeaderData(hSbrHeader, hBs, self->flags, 0, configMode);
847
848 if (coreCodec == AOT_USAC) {
849 if (configMode & AC_CM_DET_CFG_CHANGE) {
850 self->flags = flagsSaved; /* restore */
851 }
852 return sbrError;
853 }
854
855 if (configMode & AC_CM_ALLOC_MEM) {
856 SBR_DECODER_ELEMENT *pSbrElement;
857
858 pSbrElement = self->pSbrElement[elementIndex];
859
860 /* Sanity check */
861 if (pSbrElement != NULL) {
862 if ((elementID == ID_CPE && pSbrElement->nChannels != 2) ||
863 (elementID != ID_CPE && pSbrElement->nChannels != 1)) {
864 return SBRDEC_UNSUPPORTED_CONFIG;
865 }
866 if (headerStatus == HEADER_RESET) {
867 sbrError = sbrDecoder_HeaderUpdate(self, hSbrHeader, headerStatus,
868 pSbrElement->pSbrChannel,
869 pSbrElement->nChannels);
870
871 if (sbrError == SBRDEC_OK) {
872 hSbrHeader->syncState = SBR_HEADER;
873 hSbrHeader->status |= SBRDEC_HDR_STAT_UPDATE;
874 }
875 /* else {
876 Since we already have overwritten the old SBR header the only way out
877 is UPSAMPLING! This will be prepared in the next step.
878 } */
879 }
880 }
881 }
882 bail:
883 if (configMode & AC_CM_DET_CFG_CHANGE) {
884 self->flags = flagsSaved; /* restore */
885 }
886 return sbrError;
887 }
888
sbrDecoder_SetParam(HANDLE_SBRDECODER self,const SBRDEC_PARAM param,const INT value)889 SBR_ERROR sbrDecoder_SetParam(HANDLE_SBRDECODER self, const SBRDEC_PARAM param,
890 const INT value) {
891 SBR_ERROR errorStatus = SBRDEC_OK;
892
893 /* configure the subsystems */
894 switch (param) {
895 case SBR_SYSTEM_BITSTREAM_DELAY:
896 if (value < 0 || value > (1)) {
897 errorStatus = SBRDEC_SET_PARAM_FAIL;
898 break;
899 }
900 if (self == NULL) {
901 errorStatus = SBRDEC_NOT_INITIALIZED;
902 } else {
903 self->numDelayFrames = (UCHAR)value;
904 }
905 break;
906 case SBR_QMF_MODE:
907 if (self == NULL) {
908 errorStatus = SBRDEC_NOT_INITIALIZED;
909 } else {
910 if (value == 1) {
911 self->flags |= SBRDEC_LOW_POWER;
912 } else {
913 self->flags &= ~SBRDEC_LOW_POWER;
914 }
915 }
916 break;
917 case SBR_LD_QMF_TIME_ALIGN:
918 if (self == NULL) {
919 errorStatus = SBRDEC_NOT_INITIALIZED;
920 } else {
921 if (value == 1) {
922 self->flags |= SBRDEC_LD_MPS_QMF;
923 } else {
924 self->flags &= ~SBRDEC_LD_MPS_QMF;
925 }
926 }
927 break;
928 case SBR_FLUSH_DATA:
929 if (value != 0) {
930 if (self == NULL) {
931 errorStatus = SBRDEC_NOT_INITIALIZED;
932 } else {
933 self->flags |= SBRDEC_FLUSH;
934 }
935 }
936 break;
937 case SBR_CLEAR_HISTORY:
938 if (value != 0) {
939 if (self == NULL) {
940 errorStatus = SBRDEC_NOT_INITIALIZED;
941 } else {
942 self->flags |= SBRDEC_FORCE_RESET;
943 }
944 }
945 break;
946 case SBR_BS_INTERRUPTION: {
947 int elementIndex;
948
949 if (self == NULL) {
950 errorStatus = SBRDEC_NOT_INITIALIZED;
951 break;
952 }
953
954 /* Loop over SBR elements */
955 for (elementIndex = 0; elementIndex < self->numSbrElements;
956 elementIndex++) {
957 if (self->pSbrElement[elementIndex] != NULL) {
958 HANDLE_SBR_HEADER_DATA hSbrHeader;
959 int headerIndex =
960 getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
961 self->pSbrElement[elementIndex]->useHeaderSlot);
962
963 hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
964
965 /* Set sync state UPSAMPLING for the corresponding slot.
966 This switches off bitstream parsing until a new header arrives. */
967 hSbrHeader->syncState = UPSAMPLING;
968 hSbrHeader->status |= SBRDEC_HDR_STAT_UPDATE;
969 }
970 }
971 } break;
972
973 case SBR_SKIP_QMF:
974 if (self == NULL) {
975 errorStatus = SBRDEC_NOT_INITIALIZED;
976 } else {
977 if (value == 1) {
978 self->flags |= SBRDEC_SKIP_QMF_ANA;
979 } else {
980 self->flags &= ~SBRDEC_SKIP_QMF_ANA;
981 }
982 if (value == 2) {
983 self->flags |= SBRDEC_SKIP_QMF_SYN;
984 } else {
985 self->flags &= ~SBRDEC_SKIP_QMF_SYN;
986 }
987 }
988 break;
989 default:
990 errorStatus = SBRDEC_SET_PARAM_FAIL;
991 break;
992 } /* switch(param) */
993
994 return (errorStatus);
995 }
996
sbrDecoder_drcGetChannel(const HANDLE_SBRDECODER self,const INT channel)997 static SBRDEC_DRC_CHANNEL *sbrDecoder_drcGetChannel(
998 const HANDLE_SBRDECODER self, const INT channel) {
999 SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
1000 int elementIndex, elChanIdx = 0, numCh = 0;
1001
1002 for (elementIndex = 0; (elementIndex < (8)) && (numCh <= channel);
1003 elementIndex++) {
1004 SBR_DECODER_ELEMENT *pSbrElement = self->pSbrElement[elementIndex];
1005 int c, elChannels;
1006
1007 elChanIdx = 0;
1008 if (pSbrElement == NULL) break;
1009
1010 /* Determine amount of channels for this element */
1011 switch (pSbrElement->elementID) {
1012 case ID_CPE:
1013 elChannels = 2;
1014 break;
1015 case ID_LFE:
1016 case ID_SCE:
1017 elChannels = 1;
1018 break;
1019 case ID_NONE:
1020 default:
1021 elChannels = 0;
1022 break;
1023 }
1024
1025 /* Limit with actual allocated element channels */
1026 elChannels = fMin(elChannels, pSbrElement->nChannels);
1027
1028 for (c = 0; (c < elChannels) && (numCh <= channel); c++) {
1029 if (pSbrElement->pSbrChannel[elChanIdx] != NULL) {
1030 numCh++;
1031 elChanIdx++;
1032 }
1033 }
1034 }
1035 elementIndex -= 1;
1036 elChanIdx -= 1;
1037
1038 if (elChanIdx < 0 || elementIndex < 0) {
1039 return NULL;
1040 }
1041
1042 if (self->pSbrElement[elementIndex] != NULL) {
1043 if (self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx] != NULL) {
1044 pSbrDrcChannelData = &self->pSbrElement[elementIndex]
1045 ->pSbrChannel[elChanIdx]
1046 ->SbrDec.sbrDrcChannel;
1047 }
1048 }
1049
1050 return (pSbrDrcChannelData);
1051 }
1052
sbrDecoder_drcFeedChannel(HANDLE_SBRDECODER self,INT ch,UINT numBands,FIXP_DBL * pNextFact_mag,INT nextFact_exp,SHORT drcInterpolationScheme,UCHAR winSequence,USHORT * pBandTop)1053 SBR_ERROR sbrDecoder_drcFeedChannel(HANDLE_SBRDECODER self, INT ch,
1054 UINT numBands, FIXP_DBL *pNextFact_mag,
1055 INT nextFact_exp,
1056 SHORT drcInterpolationScheme,
1057 UCHAR winSequence, USHORT *pBandTop) {
1058 SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
1059 int band, isValidData = 0;
1060
1061 if (self == NULL) {
1062 return SBRDEC_NOT_INITIALIZED;
1063 }
1064 if (ch > (8) || pNextFact_mag == NULL) {
1065 return SBRDEC_SET_PARAM_FAIL;
1066 }
1067
1068 /* Search for gain values different to 1.0f */
1069 for (band = 0; band < (int)numBands; band += 1) {
1070 if (!((pNextFact_mag[band] == FL2FXCONST_DBL(0.5)) &&
1071 (nextFact_exp == 1)) &&
1072 !((pNextFact_mag[band] == (FIXP_DBL)MAXVAL_DBL) &&
1073 (nextFact_exp == 0))) {
1074 isValidData = 1;
1075 break;
1076 }
1077 }
1078
1079 /* Find the right SBR channel */
1080 pSbrDrcChannelData = sbrDecoder_drcGetChannel(self, ch);
1081
1082 if (pSbrDrcChannelData != NULL) {
1083 if (pSbrDrcChannelData->enable ||
1084 isValidData) { /* Activate processing only with real and valid data */
1085 int i;
1086
1087 pSbrDrcChannelData->enable = 1;
1088 pSbrDrcChannelData->numBandsNext = numBands;
1089
1090 pSbrDrcChannelData->winSequenceNext = winSequence;
1091 pSbrDrcChannelData->drcInterpolationSchemeNext = drcInterpolationScheme;
1092 pSbrDrcChannelData->nextFact_exp = nextFact_exp;
1093
1094 for (i = 0; i < (int)numBands; i++) {
1095 pSbrDrcChannelData->bandTopNext[i] = pBandTop[i];
1096 pSbrDrcChannelData->nextFact_mag[i] = pNextFact_mag[i];
1097 }
1098 }
1099 }
1100
1101 return SBRDEC_OK;
1102 }
1103
sbrDecoder_drcDisable(HANDLE_SBRDECODER self,INT ch)1104 void sbrDecoder_drcDisable(HANDLE_SBRDECODER self, INT ch) {
1105 SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
1106
1107 if ((self == NULL) || (ch > (8)) || (self->numSbrElements == 0) ||
1108 (self->numSbrChannels == 0)) {
1109 return;
1110 }
1111
1112 /* Find the right SBR channel */
1113 pSbrDrcChannelData = sbrDecoder_drcGetChannel(self, ch);
1114
1115 if (pSbrDrcChannelData != NULL) {
1116 sbrDecoder_drcInitChannel(pSbrDrcChannelData);
1117 }
1118 }
1119
sbrDecoder_Parse(HANDLE_SBRDECODER self,HANDLE_FDK_BITSTREAM hBs,UCHAR * pDrmBsBuffer,USHORT drmBsBufferSize,int * count,int bsPayLen,int crcFlag,MP4_ELEMENT_ID prevElement,int elementIndex,UINT acFlags,UINT acElFlags[])1120 SBR_ERROR sbrDecoder_Parse(HANDLE_SBRDECODER self, HANDLE_FDK_BITSTREAM hBs,
1121 UCHAR *pDrmBsBuffer, USHORT drmBsBufferSize,
1122 int *count, int bsPayLen, int crcFlag,
1123 MP4_ELEMENT_ID prevElement, int elementIndex,
1124 UINT acFlags, UINT acElFlags[]) {
1125 SBR_DECODER_ELEMENT *hSbrElement = NULL;
1126 HANDLE_SBR_HEADER_DATA hSbrHeader = NULL;
1127 HANDLE_SBR_CHANNEL *pSbrChannel;
1128
1129 SBR_FRAME_DATA *hFrameDataLeft = NULL;
1130 SBR_FRAME_DATA *hFrameDataRight = NULL;
1131 SBR_FRAME_DATA frameDataLeftCopy;
1132 SBR_FRAME_DATA frameDataRightCopy;
1133
1134 SBR_ERROR errorStatus = SBRDEC_OK;
1135 SBR_HEADER_STATUS headerStatus = HEADER_NOT_PRESENT;
1136
1137 INT startPos = FDKgetValidBits(hBs);
1138 INT CRCLen = 0;
1139 HANDLE_FDK_BITSTREAM hBsOriginal = hBs;
1140 FDK_BITSTREAM bsBwd;
1141
1142 FDK_CRCINFO crcInfo;
1143 INT crcReg = 0;
1144 USHORT drmSbrCrc = 0;
1145 const int fGlobalIndependencyFlag = acFlags & AC_INDEP;
1146 const int bs_pvc = acElFlags[elementIndex] & AC_EL_USAC_PVC;
1147 const int bs_interTes = acElFlags[elementIndex] & AC_EL_USAC_ITES;
1148 int stereo;
1149 int fDoDecodeSbrData = 1;
1150
1151 int lastSlot, lastHdrSlot = 0, thisHdrSlot = 0;
1152
1153 /* SBR sanity checks */
1154 if (self == NULL) {
1155 errorStatus = SBRDEC_NOT_INITIALIZED;
1156 goto bail;
1157 }
1158
1159 /* Reverse bits of DRM SBR payload */
1160 if ((self->flags & SBRDEC_SYNTAX_DRM) && *count > 0) {
1161 int dataBytes, dataBits;
1162
1163 FDK_ASSERT(drmBsBufferSize >= (512));
1164 dataBits = *count;
1165
1166 if (dataBits > ((512) * 8)) {
1167 /* do not flip more data than needed */
1168 dataBits = (512) * 8;
1169 }
1170
1171 dataBytes = (dataBits + 7) >> 3;
1172
1173 int j;
1174
1175 if ((j = (int)FDKgetValidBits(hBs)) != 8) {
1176 FDKpushBiDirectional(hBs, (j - 8));
1177 }
1178
1179 j = 0;
1180 for (; dataBytes > 0; dataBytes--) {
1181 int i;
1182 UCHAR tmpByte;
1183 UCHAR buffer = 0x00;
1184
1185 tmpByte = (UCHAR)FDKreadBits(hBs, 8);
1186 for (i = 0; i < 4; i++) {
1187 int shift = 2 * i + 1;
1188 buffer |= (tmpByte & (0x08 >> i)) << shift;
1189 buffer |= (tmpByte & (0x10 << i)) >> shift;
1190 }
1191 pDrmBsBuffer[j++] = buffer;
1192 FDKpushBack(hBs, 16);
1193 }
1194
1195 FDKinitBitStream(&bsBwd, pDrmBsBuffer, (512), dataBits, BS_READER);
1196
1197 /* Use reversed data */
1198 hBs = &bsBwd;
1199 bsPayLen = *count;
1200 }
1201
1202 /* Remember start position of SBR element */
1203 startPos = FDKgetValidBits(hBs);
1204
1205 /* SBR sanity checks */
1206 if (self->pSbrElement[elementIndex] == NULL) {
1207 errorStatus = SBRDEC_NOT_INITIALIZED;
1208 goto bail;
1209 }
1210 hSbrElement = self->pSbrElement[elementIndex];
1211
1212 lastSlot = (hSbrElement->useFrameSlot > 0) ? hSbrElement->useFrameSlot - 1
1213 : self->numDelayFrames;
1214 lastHdrSlot = hSbrElement->useHeaderSlot[lastSlot];
1215 thisHdrSlot = getHeaderSlot(
1216 hSbrElement->useFrameSlot,
1217 hSbrElement->useHeaderSlot); /* Get a free header slot not used by
1218 frames not processed yet. */
1219
1220 /* Assign the free slot to store a new header if there is one. */
1221 hSbrHeader = &self->sbrHeader[elementIndex][thisHdrSlot];
1222
1223 pSbrChannel = hSbrElement->pSbrChannel;
1224 stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
1225
1226 hFrameDataLeft = &self->pSbrElement[elementIndex]
1227 ->pSbrChannel[0]
1228 ->frameData[hSbrElement->useFrameSlot];
1229 if (stereo) {
1230 hFrameDataRight = &self->pSbrElement[elementIndex]
1231 ->pSbrChannel[1]
1232 ->frameData[hSbrElement->useFrameSlot];
1233 }
1234
1235 /* store frameData; new parsed frameData possibly corrupted */
1236 FDKmemcpy(&frameDataLeftCopy, hFrameDataLeft, sizeof(SBR_FRAME_DATA));
1237 if (stereo) {
1238 FDKmemcpy(&frameDataRightCopy, hFrameDataRight, sizeof(SBR_FRAME_DATA));
1239 }
1240
1241 /* reset PS flag; will be set after PS was found */
1242 self->flags &= ~SBRDEC_PS_DECODED;
1243
1244 if (hSbrHeader->status & SBRDEC_HDR_STAT_UPDATE) {
1245 /* Got a new header from extern (e.g. from an ASC) */
1246 headerStatus = HEADER_OK;
1247 hSbrHeader->status &= ~SBRDEC_HDR_STAT_UPDATE;
1248 } else if (thisHdrSlot != lastHdrSlot) {
1249 /* Copy the last header into this slot otherwise the
1250 header compare will trigger more HEADER_RESETs than needed. */
1251 copySbrHeader(hSbrHeader, &self->sbrHeader[elementIndex][lastHdrSlot]);
1252 }
1253
1254 /*
1255 Check if bit stream data is valid and matches the element context
1256 */
1257 if (((prevElement != ID_SCE) && (prevElement != ID_CPE)) ||
1258 prevElement != hSbrElement->elementID) {
1259 /* In case of LFE we also land here, since there is no LFE SBR element (do
1260 * upsampling only) */
1261 fDoDecodeSbrData = 0;
1262 }
1263
1264 if (fDoDecodeSbrData) {
1265 if ((INT)FDKgetValidBits(hBs) <= 0) {
1266 fDoDecodeSbrData = 0;
1267 }
1268 }
1269
1270 /*
1271 SBR CRC-check
1272 */
1273 if (fDoDecodeSbrData) {
1274 if (crcFlag) {
1275 switch (self->coreCodec) {
1276 case AOT_ER_AAC_ELD:
1277 FDKpushFor(hBs, 10);
1278 /* check sbrcrc later: we don't know the payload length now */
1279 break;
1280 case AOT_DRM_AAC:
1281 case AOT_DRM_SURROUND:
1282 drmSbrCrc = (USHORT)FDKreadBits(hBs, 8);
1283 /* Setup CRC decoder */
1284 FDKcrcInit(&crcInfo, 0x001d, 0xFFFF, 8);
1285 /* Start CRC region */
1286 crcReg = FDKcrcStartReg(&crcInfo, hBs, 0);
1287 break;
1288 default:
1289 CRCLen = bsPayLen - 10; /* change: 0 => i */
1290 if (CRCLen < 0) {
1291 fDoDecodeSbrData = 0;
1292 } else {
1293 fDoDecodeSbrData = SbrCrcCheck(hBs, CRCLen);
1294 }
1295 break;
1296 }
1297 }
1298 } /* if (fDoDecodeSbrData) */
1299
1300 /*
1301 Read in the header data and issue a reset if change occured
1302 */
1303 if (fDoDecodeSbrData) {
1304 int sbrHeaderPresent;
1305
1306 if (self->flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC)) {
1307 SBR_HEADER_DATA_BS_INFO newSbrInfo;
1308 int sbrInfoPresent;
1309
1310 if (bs_interTes) {
1311 self->flags |= SBRDEC_USAC_ITES;
1312 } else {
1313 self->flags &= ~SBRDEC_USAC_ITES;
1314 }
1315
1316 if (fGlobalIndependencyFlag) {
1317 self->flags |= SBRDEC_USAC_INDEP;
1318 sbrInfoPresent = 1;
1319 sbrHeaderPresent = 1;
1320 } else {
1321 self->flags &= ~SBRDEC_USAC_INDEP;
1322 sbrInfoPresent = FDKreadBit(hBs);
1323 if (sbrInfoPresent) {
1324 sbrHeaderPresent = FDKreadBit(hBs);
1325 } else {
1326 sbrHeaderPresent = 0;
1327 }
1328 }
1329
1330 if (sbrInfoPresent) {
1331 newSbrInfo.ampResolution = FDKreadBit(hBs);
1332 newSbrInfo.xover_band = FDKreadBits(hBs, 4);
1333 newSbrInfo.sbr_preprocessing = FDKreadBit(hBs);
1334 if (bs_pvc) {
1335 newSbrInfo.pvc_mode = FDKreadBits(hBs, 2);
1336 /* bs_pvc_mode: 0 -> no PVC, 1 -> PVC mode 1, 2 -> PVC mode 2, 3 ->
1337 * reserved */
1338 if (newSbrInfo.pvc_mode > 2) {
1339 headerStatus = HEADER_ERROR;
1340 }
1341 if (stereo && newSbrInfo.pvc_mode > 0) {
1342 /* bs_pvc is always transmitted but pvc_mode is set to zero in case
1343 * of stereo SBR. The config might be wrong but we cannot tell for
1344 * sure. */
1345 newSbrInfo.pvc_mode = 0;
1346 }
1347 } else {
1348 newSbrInfo.pvc_mode = 0;
1349 }
1350 if (headerStatus != HEADER_ERROR) {
1351 if (FDKmemcmp(&hSbrHeader->bs_info, &newSbrInfo,
1352 sizeof(SBR_HEADER_DATA_BS_INFO))) {
1353 /* in case of ampResolution and preprocessing change no full reset
1354 * required */
1355 /* HEADER reset would trigger HBE transposer reset which breaks
1356 * eSbr_3_Eaa.mp4 */
1357 if ((hSbrHeader->bs_info.pvc_mode != newSbrInfo.pvc_mode) ||
1358 (hSbrHeader->bs_info.xover_band != newSbrInfo.xover_band)) {
1359 headerStatus = HEADER_RESET;
1360 } else {
1361 headerStatus = HEADER_OK;
1362 }
1363
1364 hSbrHeader->bs_info = newSbrInfo;
1365 } else {
1366 headerStatus = HEADER_OK;
1367 }
1368 }
1369 }
1370 if (headerStatus == HEADER_ERROR) {
1371 /* Corrupt SBR info data, do not decode and switch to UPSAMPLING */
1372 hSbrHeader->syncState = UPSAMPLING;
1373 fDoDecodeSbrData = 0;
1374 sbrHeaderPresent = 0;
1375 }
1376
1377 if (sbrHeaderPresent && fDoDecodeSbrData) {
1378 int useDfltHeader;
1379
1380 useDfltHeader = FDKreadBit(hBs);
1381
1382 if (useDfltHeader) {
1383 sbrHeaderPresent = 0;
1384 if (FDKmemcmp(&hSbrHeader->bs_data, &hSbrHeader->bs_dflt,
1385 sizeof(SBR_HEADER_DATA_BS)) ||
1386 hSbrHeader->syncState != SBR_ACTIVE) {
1387 hSbrHeader->bs_data = hSbrHeader->bs_dflt;
1388 headerStatus = HEADER_RESET;
1389 }
1390 }
1391 }
1392 } else {
1393 sbrHeaderPresent = FDKreadBit(hBs);
1394 }
1395
1396 if (sbrHeaderPresent) {
1397 headerStatus = sbrGetHeaderData(hSbrHeader, hBs, self->flags, 1, 0);
1398 }
1399
1400 if (headerStatus == HEADER_RESET) {
1401 errorStatus = sbrDecoder_HeaderUpdate(
1402 self, hSbrHeader, headerStatus, pSbrChannel, hSbrElement->nChannels);
1403
1404 if (errorStatus == SBRDEC_OK) {
1405 hSbrHeader->syncState = SBR_HEADER;
1406 } else {
1407 hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1408 headerStatus = HEADER_ERROR;
1409 }
1410 }
1411
1412 if (errorStatus != SBRDEC_OK) {
1413 fDoDecodeSbrData = 0;
1414 }
1415 } /* if (fDoDecodeSbrData) */
1416
1417 /*
1418 Print debugging output only if state has changed
1419 */
1420
1421 /* read frame data */
1422 if ((hSbrHeader->syncState >= SBR_HEADER) && fDoDecodeSbrData) {
1423 int sbrFrameOk;
1424 /* read the SBR element data */
1425 if (!stereo && (self->hParametricStereoDec != NULL)) {
1426 /* update slot index for PS bitstream parsing */
1427 self->hParametricStereoDec->bsLastSlot =
1428 self->hParametricStereoDec->bsReadSlot;
1429 self->hParametricStereoDec->bsReadSlot = hSbrElement->useFrameSlot;
1430 }
1431 sbrFrameOk = sbrGetChannelElement(
1432 hSbrHeader, hFrameDataLeft, (stereo) ? hFrameDataRight : NULL,
1433 &pSbrChannel[0]->prevFrameData,
1434 pSbrChannel[0]->SbrDec.PvcStaticData.pvc_mode_last, hBs,
1435 (stereo) ? NULL : self->hParametricStereoDec, self->flags,
1436 self->pSbrElement[elementIndex]->transposerSettings.overlap);
1437
1438 if (!sbrFrameOk) {
1439 fDoDecodeSbrData = 0;
1440 } else {
1441 INT valBits;
1442
1443 if (bsPayLen > 0) {
1444 valBits = bsPayLen - ((INT)startPos - (INT)FDKgetValidBits(hBs));
1445 } else {
1446 valBits = (INT)FDKgetValidBits(hBs);
1447 }
1448
1449 if (crcFlag) {
1450 switch (self->coreCodec) {
1451 case AOT_ER_AAC_ELD: {
1452 /* late crc check for eld */
1453 INT payloadbits =
1454 (INT)startPos - (INT)FDKgetValidBits(hBs) - startPos;
1455 INT crcLen = payloadbits - 10;
1456 FDKpushBack(hBs, payloadbits);
1457 fDoDecodeSbrData = SbrCrcCheck(hBs, crcLen);
1458 FDKpushFor(hBs, crcLen);
1459 } break;
1460 case AOT_DRM_AAC:
1461 case AOT_DRM_SURROUND:
1462 /* End CRC region */
1463 FDKcrcEndReg(&crcInfo, hBs, crcReg);
1464 /* Check CRC */
1465 if ((FDKcrcGetCRC(&crcInfo) ^ 0xFF) != drmSbrCrc) {
1466 fDoDecodeSbrData = 0;
1467 if (headerStatus != HEADER_NOT_PRESENT) {
1468 headerStatus = HEADER_ERROR;
1469 hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1470 }
1471 }
1472 break;
1473 default:
1474 break;
1475 }
1476 }
1477
1478 /* sanity check of remaining bits */
1479 if (valBits < 0) {
1480 fDoDecodeSbrData = 0;
1481 } else {
1482 switch (self->coreCodec) {
1483 case AOT_SBR:
1484 case AOT_PS:
1485 case AOT_AAC_LC: {
1486 /* This sanity check is only meaningful with General Audio
1487 * bitstreams */
1488 int alignBits = valBits & 0x7;
1489
1490 if (valBits > alignBits) {
1491 fDoDecodeSbrData = 0;
1492 }
1493 } break;
1494 default:
1495 /* No sanity check available */
1496 break;
1497 }
1498 }
1499 }
1500 } else {
1501 /* The returned bit count will not be the actual payload size since we did
1502 not parse the frame data. Return an error so that the caller can react
1503 respectively. */
1504 errorStatus = SBRDEC_PARSE_ERROR;
1505 }
1506
1507 if (!fDoDecodeSbrData) {
1508 /* Set error flag for this slot to trigger concealment */
1509 setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_ERROR);
1510 /* restore old frameData for concealment */
1511 FDKmemcpy(hFrameDataLeft, &frameDataLeftCopy, sizeof(SBR_FRAME_DATA));
1512 if (stereo) {
1513 FDKmemcpy(hFrameDataRight, &frameDataRightCopy, sizeof(SBR_FRAME_DATA));
1514 }
1515 errorStatus = SBRDEC_PARSE_ERROR;
1516 } else {
1517 /* Everything seems to be ok so clear the error flag */
1518 setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_OK);
1519 }
1520
1521 if (!stereo) {
1522 /* Turn coupling off explicitely to avoid access to absent right frame data
1523 that might occur with corrupt bitstreams. */
1524 hFrameDataLeft->coupling = COUPLING_OFF;
1525 }
1526
1527 bail:
1528
1529 if (self != NULL) {
1530 if (self->flags & SBRDEC_SYNTAX_DRM) {
1531 hBs = hBsOriginal;
1532 }
1533
1534 if (errorStatus != SBRDEC_NOT_INITIALIZED) {
1535 int useOldHdr =
1536 ((headerStatus == HEADER_NOT_PRESENT) ||
1537 (headerStatus == HEADER_ERROR) ||
1538 (headerStatus == HEADER_RESET && errorStatus == SBRDEC_PARSE_ERROR))
1539 ? 1
1540 : 0;
1541
1542 if (!useOldHdr && (thisHdrSlot != lastHdrSlot) && (hSbrHeader != NULL)) {
1543 useOldHdr |=
1544 (compareSbrHeader(hSbrHeader,
1545 &self->sbrHeader[elementIndex][lastHdrSlot]) == 0)
1546 ? 1
1547 : 0;
1548 }
1549
1550 if (hSbrElement != NULL) {
1551 if (useOldHdr != 0) {
1552 /* Use the old header for this frame */
1553 hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = lastHdrSlot;
1554 } else {
1555 /* Use the new header for this frame */
1556 hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = thisHdrSlot;
1557 }
1558
1559 /* Move frame pointer to the next slot which is up to be decoded/applied
1560 * next */
1561 hSbrElement->useFrameSlot =
1562 (hSbrElement->useFrameSlot + 1) % (self->numDelayFrames + 1);
1563 }
1564 }
1565 }
1566
1567 *count -= startPos - (INT)FDKgetValidBits(hBs);
1568
1569 return errorStatus;
1570 }
1571
1572 /**
1573 * \brief Render one SBR element into time domain signal.
1574 * \param self SBR decoder handle
1575 * \param timeData pointer to output buffer
1576 * \param channelMapping pointer to UCHAR array where next 2 channel offsets are
1577 * stored.
1578 * \param elementIndex enumerating index of the SBR element to render.
1579 * \param numInChannels number of channels from core coder.
1580 * \param numOutChannels pointer to a location to return number of output
1581 * channels.
1582 * \param psPossible flag indicating if PS is possible or not.
1583 * \return SBRDEC_OK if successfull, else error code
1584 */
sbrDecoder_DecodeElement(HANDLE_SBRDECODER self,QDOM_PCM * input,INT_PCM * timeData,const int timeDataSize,const FDK_channelMapDescr * const mapDescr,const int mapIdx,int channelIndex,const int elementIndex,const int numInChannels,int * numOutChannels,const int psPossible)1585 static SBR_ERROR sbrDecoder_DecodeElement(
1586 HANDLE_SBRDECODER self, QDOM_PCM *input, INT_PCM *timeData,
1587 const int timeDataSize, const FDK_channelMapDescr *const mapDescr,
1588 const int mapIdx, int channelIndex, const int elementIndex,
1589 const int numInChannels, int *numOutChannels, const int psPossible) {
1590 SBR_DECODER_ELEMENT *hSbrElement = self->pSbrElement[elementIndex];
1591 HANDLE_SBR_CHANNEL *pSbrChannel =
1592 self->pSbrElement[elementIndex]->pSbrChannel;
1593 HANDLE_SBR_HEADER_DATA hSbrHeader =
1594 &self->sbrHeader[elementIndex]
1595 [hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
1596 HANDLE_PS_DEC h_ps_d = self->hParametricStereoDec;
1597
1598 /* get memory for frame data from scratch */
1599 SBR_FRAME_DATA *hFrameDataLeft = NULL;
1600 SBR_FRAME_DATA *hFrameDataRight = NULL;
1601
1602 SBR_ERROR errorStatus = SBRDEC_OK;
1603
1604 INT strideOut, offset0 = 255, offset0_block = 0, offset1 = 255,
1605 offset1_block = 0;
1606 INT codecFrameSize = self->codecFrameSize;
1607
1608 int stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
1609 int numElementChannels =
1610 hSbrElement
1611 ->nChannels; /* Number of channels of the current SBR element */
1612
1613 hFrameDataLeft =
1614 &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1615 if (stereo) {
1616 hFrameDataRight =
1617 &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1618 }
1619
1620 if (self->flags & SBRDEC_FLUSH) {
1621 if (self->numFlushedFrames > self->numDelayFrames) {
1622 int hdrIdx;
1623 /* No valid SBR payload available, hence switch to upsampling (in all
1624 * headers) */
1625 for (hdrIdx = 0; hdrIdx < ((1) + 1); hdrIdx += 1) {
1626 self->sbrHeader[elementIndex][hdrIdx].syncState = UPSAMPLING;
1627 }
1628 } else {
1629 /* Move frame pointer to the next slot which is up to be decoded/applied
1630 * next */
1631 hSbrElement->useFrameSlot =
1632 (hSbrElement->useFrameSlot + 1) % (self->numDelayFrames + 1);
1633 /* Update header and frame data pointer because they have already been set
1634 */
1635 hSbrHeader =
1636 &self->sbrHeader[elementIndex]
1637 [hSbrElement
1638 ->useHeaderSlot[hSbrElement->useFrameSlot]];
1639 hFrameDataLeft =
1640 &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1641 if (stereo) {
1642 hFrameDataRight =
1643 &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1644 }
1645 }
1646 }
1647
1648 /* Update the header error flag */
1649 hSbrHeader->frameErrorFlag =
1650 hSbrElement->frameErrorFlag[hSbrElement->useFrameSlot];
1651
1652 /*
1653 Prepare filterbank for upsampling if no valid bit stream data is available.
1654 */
1655 if (hSbrHeader->syncState == SBR_NOT_INITIALIZED) {
1656 errorStatus =
1657 initHeaderData(hSbrHeader, self->sampleRateIn, self->sampleRateOut,
1658 self->downscaleFactor, codecFrameSize, self->flags,
1659 1 /* SET_DEFAULT_HDR */
1660 );
1661
1662 if (errorStatus != SBRDEC_OK) {
1663 return errorStatus;
1664 }
1665
1666 hSbrHeader->syncState = UPSAMPLING;
1667
1668 errorStatus = sbrDecoder_HeaderUpdate(self, hSbrHeader, HEADER_NOT_PRESENT,
1669 pSbrChannel, hSbrElement->nChannels);
1670
1671 if (errorStatus != SBRDEC_OK) {
1672 hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1673 return errorStatus;
1674 }
1675 }
1676
1677 /* reset */
1678 if (hSbrHeader->status & SBRDEC_HDR_STAT_RESET) {
1679 int ch;
1680 for (ch = 0; ch < numElementChannels; ch++) {
1681 SBR_ERROR errorStatusTmp = SBRDEC_OK;
1682
1683 errorStatusTmp = resetSbrDec(
1684 &pSbrChannel[ch]->SbrDec, hSbrHeader, &pSbrChannel[ch]->prevFrameData,
1685 self->synDownsampleFac, self->flags, pSbrChannel[ch]->frameData);
1686
1687 if (errorStatusTmp != SBRDEC_OK) {
1688 hSbrHeader->syncState = UPSAMPLING;
1689 }
1690 }
1691 hSbrHeader->status &= ~SBRDEC_HDR_STAT_RESET;
1692 }
1693
1694 /* decoding */
1695 if ((hSbrHeader->syncState == SBR_ACTIVE) ||
1696 ((hSbrHeader->syncState == SBR_HEADER) &&
1697 (hSbrHeader->frameErrorFlag == 0))) {
1698 errorStatus = SBRDEC_OK;
1699
1700 decodeSbrData(hSbrHeader, hFrameDataLeft, &pSbrChannel[0]->prevFrameData,
1701 (stereo) ? hFrameDataRight : NULL,
1702 (stereo) ? &pSbrChannel[1]->prevFrameData : NULL);
1703
1704 /* Now we have a full parameter set and can do parameter
1705 based concealment instead of plain upsampling. */
1706 hSbrHeader->syncState = SBR_ACTIVE;
1707 }
1708
1709 if (timeDataSize <
1710 hSbrHeader->numberTimeSlots * hSbrHeader->timeStep *
1711 self->pQmfDomain->globalConf.nBandsSynthesis *
1712 (psPossible ? fMax(2, numInChannels) : numInChannels)) {
1713 return SBRDEC_OUTPUT_BUFFER_TOO_SMALL;
1714 }
1715
1716 {
1717 self->flags &= ~SBRDEC_PS_DECODED;
1718 C_ALLOC_SCRATCH_START(pPsScratch, struct PS_DEC_COEFFICIENTS, 1)
1719
1720 /* decode PS data if available */
1721 if (h_ps_d != NULL && psPossible && (hSbrHeader->syncState == SBR_ACTIVE)) {
1722 int applyPs = 1;
1723
1724 /* define which frame delay line slot to process */
1725 h_ps_d->processSlot = hSbrElement->useFrameSlot;
1726
1727 applyPs = DecodePs(h_ps_d, hSbrHeader->frameErrorFlag, pPsScratch);
1728 self->flags |= (applyPs) ? SBRDEC_PS_DECODED : 0;
1729 }
1730
1731 offset0 = FDK_chMapDescr_getMapValue(mapDescr, channelIndex, mapIdx);
1732 offset0_block = offset0 * codecFrameSize;
1733 if (stereo || psPossible) {
1734 /* the value of offset1 only matters if the condition is true, however if
1735 it is not true channelIndex+1 may exceed the channel map resutling in an
1736 error, though the value of offset1 is actually meaningless. This is
1737 prevented here. */
1738 offset1 = FDK_chMapDescr_getMapValue(mapDescr, channelIndex + 1, mapIdx);
1739 offset1_block = offset1 * codecFrameSize;
1740 }
1741 /* Set strides for reading and writing */
1742 if (psPossible)
1743 strideOut = (numInChannels < 2) ? 2 : numInChannels;
1744 else
1745 strideOut = numInChannels;
1746
1747 /* use same buffers for left and right channel and apply PS per timeslot */
1748 /* Process left channel */
1749 sbr_dec(&pSbrChannel[0]->SbrDec, input + offset0_block, timeData + offset0,
1750 (self->flags & SBRDEC_PS_DECODED) ? &pSbrChannel[1]->SbrDec : NULL,
1751 timeData + offset1, strideOut, hSbrHeader, hFrameDataLeft,
1752 &pSbrChannel[0]->prevFrameData,
1753 (hSbrHeader->syncState == SBR_ACTIVE), h_ps_d, self->flags,
1754 codecFrameSize);
1755
1756 if (stereo) {
1757 /* Process right channel */
1758 sbr_dec(&pSbrChannel[1]->SbrDec, input + offset1_block,
1759 timeData + offset1, NULL, NULL, strideOut, hSbrHeader,
1760 hFrameDataRight, &pSbrChannel[1]->prevFrameData,
1761 (hSbrHeader->syncState == SBR_ACTIVE), NULL, self->flags,
1762 codecFrameSize);
1763 }
1764
1765 C_ALLOC_SCRATCH_END(pPsScratch, struct PS_DEC_COEFFICIENTS, 1)
1766 }
1767
1768 if (h_ps_d != NULL) {
1769 /* save PS status for next run */
1770 h_ps_d->psDecodedPrv = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
1771 }
1772
1773 if (psPossible && !(self->flags & SBRDEC_SKIP_QMF_SYN)) {
1774 FDK_ASSERT(strideOut > 1);
1775 if (!(self->flags & SBRDEC_PS_DECODED)) {
1776 /* A decoder which is able to decode PS has to produce a stereo output
1777 * even if no PS data is available. */
1778 /* So copy left channel to right channel. */
1779 int copyFrameSize =
1780 codecFrameSize * self->pQmfDomain->QmfDomainOut->fb.no_channels;
1781 copyFrameSize /= self->pQmfDomain->QmfDomainIn->fb.no_channels;
1782 INT_PCM *ptr;
1783 INT i;
1784 FDK_ASSERT(strideOut == 2);
1785
1786 ptr = timeData;
1787 for (i = copyFrameSize >> 1; i--;) {
1788 INT_PCM tmp; /* This temporal variable is required because some
1789 compilers can't do *ptr++ = *ptr++ correctly. */
1790 tmp = *ptr++;
1791 *ptr++ = tmp;
1792 tmp = *ptr++;
1793 *ptr++ = tmp;
1794 }
1795 }
1796 *numOutChannels = 2; /* Output minimum two channels when PS is enabled. */
1797 }
1798
1799 return errorStatus;
1800 }
1801
sbrDecoder_Apply(HANDLE_SBRDECODER self,INT_PCM * input,INT_PCM * timeData,const int timeDataSize,int * numChannels,int * sampleRate,const FDK_channelMapDescr * const mapDescr,const int mapIdx,const int coreDecodedOk,UCHAR * psDecoded)1802 SBR_ERROR sbrDecoder_Apply(HANDLE_SBRDECODER self, INT_PCM *input,
1803 INT_PCM *timeData, const int timeDataSize,
1804 int *numChannels, int *sampleRate,
1805 const FDK_channelMapDescr *const mapDescr,
1806 const int mapIdx, const int coreDecodedOk,
1807 UCHAR *psDecoded) {
1808 SBR_ERROR errorStatus = SBRDEC_OK;
1809
1810 int psPossible;
1811 int sbrElementNum;
1812 int numCoreChannels;
1813 int numSbrChannels = 0;
1814
1815 if ((self == NULL) || (timeData == NULL) || (numChannels == NULL) ||
1816 (sampleRate == NULL) || (psDecoded == NULL) ||
1817 !FDK_chMapDescr_isValid(mapDescr)) {
1818 return SBRDEC_INVALID_ARGUMENT;
1819 }
1820
1821 psPossible = *psDecoded;
1822 numCoreChannels = *numChannels;
1823 if (numCoreChannels <= 0) {
1824 return SBRDEC_INVALID_ARGUMENT;
1825 }
1826
1827 if (self->numSbrElements < 1) {
1828 /* exit immediately to avoid access violations */
1829 return SBRDEC_NOT_INITIALIZED;
1830 }
1831
1832 /* Sanity check of allocated SBR elements. */
1833 for (sbrElementNum = 0; sbrElementNum < self->numSbrElements;
1834 sbrElementNum++) {
1835 if (self->pSbrElement[sbrElementNum] == NULL) {
1836 return SBRDEC_NOT_INITIALIZED;
1837 }
1838 }
1839
1840 if (self->numSbrElements != 1 || self->pSbrElement[0]->elementID != ID_SCE) {
1841 psPossible = 0;
1842 }
1843
1844 /* Make sure that even if no SBR data was found/parsed *psDecoded is returned
1845 * 1 if psPossible was 0. */
1846 if (psPossible == 0) {
1847 self->flags &= ~SBRDEC_PS_DECODED;
1848 }
1849
1850 /* replaces channel based reset inside sbr_dec() */
1851 if (((self->flags & SBRDEC_LOW_POWER) ? 1 : 0) !=
1852 ((self->pQmfDomain->globalConf.flags & QMF_FLAG_LP) ? 1 : 0)) {
1853 if (self->flags & SBRDEC_LOW_POWER) {
1854 self->pQmfDomain->globalConf.flags |= QMF_FLAG_LP;
1855 self->pQmfDomain->globalConf.flags_requested |= QMF_FLAG_LP;
1856 } else {
1857 self->pQmfDomain->globalConf.flags &= ~QMF_FLAG_LP;
1858 self->pQmfDomain->globalConf.flags_requested &= ~QMF_FLAG_LP;
1859 }
1860 if (FDK_QmfDomain_InitFilterBank(self->pQmfDomain, QMF_FLAG_KEEP_STATES)) {
1861 return SBRDEC_UNSUPPORTED_CONFIG;
1862 }
1863 }
1864 if (self->numSbrChannels > self->pQmfDomain->globalConf.nInputChannels) {
1865 return SBRDEC_UNSUPPORTED_CONFIG;
1866 }
1867
1868 if (self->flags & SBRDEC_FLUSH) {
1869 /* flushing is signalized, hence increment the flush frame counter */
1870 self->numFlushedFrames++;
1871 } else {
1872 /* no flushing is signalized, hence reset the flush frame counter */
1873 self->numFlushedFrames = 0;
1874 }
1875
1876 /* Loop over SBR elements */
1877 for (sbrElementNum = 0; sbrElementNum < self->numSbrElements;
1878 sbrElementNum++) {
1879 int numElementChan;
1880
1881 if (psPossible &&
1882 self->pSbrElement[sbrElementNum]->pSbrChannel[1] == NULL) {
1883 /* Disable PS and try decoding SBR mono. */
1884 psPossible = 0;
1885 }
1886
1887 numElementChan =
1888 (self->pSbrElement[sbrElementNum]->elementID == ID_CPE) ? 2 : 1;
1889
1890 /* If core signal is bad then force upsampling */
1891 if (!coreDecodedOk) {
1892 setFrameErrorFlag(self->pSbrElement[sbrElementNum], FRAME_ERROR_ALLSLOTS);
1893 }
1894
1895 errorStatus = sbrDecoder_DecodeElement(
1896 self, input, timeData, timeDataSize, mapDescr, mapIdx, numSbrChannels,
1897 sbrElementNum,
1898 numCoreChannels, /* is correct even for USC SCI==2 case */
1899 &numElementChan, psPossible);
1900
1901 if (errorStatus != SBRDEC_OK) {
1902 goto bail;
1903 }
1904
1905 numSbrChannels += numElementChan;
1906
1907 if (numSbrChannels >= numCoreChannels) {
1908 break;
1909 }
1910 }
1911
1912 /* Update numChannels and samplerate */
1913 /* Do not mess with output channels in case of USAC. numSbrChannels !=
1914 * numChannels for stereoConfigIndex == 2 */
1915 if (!(self->flags & SBRDEC_SYNTAX_USAC)) {
1916 *numChannels = numSbrChannels;
1917 }
1918 *sampleRate = self->sampleRateOut;
1919 *psDecoded = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
1920
1921 /* Clear reset and flush flag because everything seems to be done
1922 * successfully. */
1923 self->flags &= ~SBRDEC_FORCE_RESET;
1924 self->flags &= ~SBRDEC_FLUSH;
1925
1926 bail:
1927
1928 return errorStatus;
1929 }
1930
sbrDecoder_Close(HANDLE_SBRDECODER * pSelf)1931 SBR_ERROR sbrDecoder_Close(HANDLE_SBRDECODER *pSelf) {
1932 HANDLE_SBRDECODER self = *pSelf;
1933 int i;
1934
1935 if (self != NULL) {
1936 if (self->hParametricStereoDec != NULL) {
1937 DeletePsDec(&self->hParametricStereoDec);
1938 }
1939
1940 for (i = 0; i < (8); i++) {
1941 sbrDecoder_DestroyElement(self, i);
1942 }
1943
1944 FreeRam_SbrDecoder(pSelf);
1945 }
1946
1947 return SBRDEC_OK;
1948 }
1949
sbrDecoder_GetLibInfo(LIB_INFO * info)1950 INT sbrDecoder_GetLibInfo(LIB_INFO *info) {
1951 int i;
1952
1953 if (info == NULL) {
1954 return -1;
1955 }
1956
1957 /* search for next free tab */
1958 for (i = 0; i < FDK_MODULE_LAST; i++) {
1959 if (info[i].module_id == FDK_NONE) break;
1960 }
1961 if (i == FDK_MODULE_LAST) return -1;
1962 info += i;
1963
1964 info->module_id = FDK_SBRDEC;
1965 info->version =
1966 LIB_VERSION(SBRDECODER_LIB_VL0, SBRDECODER_LIB_VL1, SBRDECODER_LIB_VL2);
1967 LIB_VERSION_STRING(info);
1968 info->build_date = SBRDECODER_LIB_BUILD_DATE;
1969 info->build_time = SBRDECODER_LIB_BUILD_TIME;
1970 info->title = SBRDECODER_LIB_TITLE;
1971
1972 /* Set flags */
1973 info->flags = 0 | CAPF_SBR_HQ | CAPF_SBR_LP | CAPF_SBR_PS_MPEG |
1974 CAPF_SBR_DRM_BS | CAPF_SBR_CONCEALMENT | CAPF_SBR_DRC |
1975 CAPF_SBR_ELD_DOWNSCALE | CAPF_SBR_HBEHQ;
1976 /* End of flags */
1977
1978 return 0;
1979 }
1980
sbrDecoder_GetDelay(const HANDLE_SBRDECODER self)1981 UINT sbrDecoder_GetDelay(const HANDLE_SBRDECODER self) {
1982 UINT outputDelay = 0;
1983
1984 if (self != NULL) {
1985 UINT flags = self->flags;
1986
1987 /* See chapter 1.6.7.2 of ISO/IEC 14496-3 for the GA-SBR figures below. */
1988
1989 /* Are we initialized? */
1990 if ((self->numSbrChannels > 0) && (self->numSbrElements > 0)) {
1991 /* Add QMF synthesis delay */
1992 if ((flags & SBRDEC_ELD_GRID) && IS_LOWDELAY(self->coreCodec)) {
1993 /* Low delay SBR: */
1994 if (!(flags & SBRDEC_SKIP_QMF_SYN)) {
1995 outputDelay +=
1996 (flags & SBRDEC_DOWNSAMPLE) ? 32 : 64; /* QMF synthesis */
1997 if (flags & SBRDEC_LD_MPS_QMF) {
1998 outputDelay += 32;
1999 }
2000 }
2001 } else if (!IS_USAC(self->coreCodec)) {
2002 /* By the method of elimination this is the GA (AAC-LC, HE-AAC, ...)
2003 * branch: */
2004 outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 481 : 962;
2005 if (flags & SBRDEC_SKIP_QMF_SYN) {
2006 outputDelay -= 257; /* QMF synthesis */
2007 }
2008 }
2009 }
2010 }
2011
2012 return (outputDelay);
2013 }
2014