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