1
2/* -----------------------------------------------------------------------------------------------------------
3Software License for The Fraunhofer FDK AAC Codec Library for Android
4
5� Copyright  1995 - 2013 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V.
6  All rights reserved.
7
8 1.    INTRODUCTION
9The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
12
13AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16of the MPEG specifications.
17
18Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20individually for the purpose of encoding or decoding bit streams in products that are compliant with
21the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23software may already be covered under those patent licenses when it is used for those licensed purposes only.
24
25Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27applications information and documentation.
28
292.    COPYRIGHT LICENSE
30
31Redistribution and use in source and binary forms, with or without modification, are permitted without
32payment of copyright license fees provided that you satisfy the following conditions:
33
34You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35your modifications thereto in source code form.
36
37You must retain the complete text of this software license in the documentation and/or other materials
38provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40modifications thereto to recipients of copies in binary form.
41
42The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43prior written permission.
44
45You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46software or your modifications thereto.
47
48Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49and the date of any change. For modified versions of the FDK AAC Codec, the term
50"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
51"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
52
533.    NO PATENT LICENSE
54
55NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57respect to this software.
58
59You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60by appropriate patent licenses.
61
624.    DISCLAIMER
63
64This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
65"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
66of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69or business interruption, however caused and on any theory of liability, whether in contract, strict
70liability, or tort (including negligence), arising in any way out of the use of this software, even if
71advised of the possibility of such damage.
72
735.    CONTACT INFORMATION
74
75Fraunhofer Institute for Integrated Circuits IIS
76Attention: Audio and Multimedia Departments - FDK AAC LL
77Am Wolfsmantel 33
7891058 Erlangen, Germany
79
80www.iis.fraunhofer.de/amm
81amm-info@iis.fraunhofer.de
82----------------------------------------------------------------------------------------------------------- */
83
84/**************************  MPEG-4 Transport Decoder  ***********************
85
86   Author(s): Manuel Jander
87   Description: MPEG Transport decoder
88
89******************************************************************************/
90
91#ifndef __TPDEC_LIB_H__
92#define __TPDEC_LIB_H__
93
94#include "tp_data.h"
95
96#include "FDK_bitstream.h"
97
98#define TRANSPORTDEC_INBUF_SIZE  ( 8192 )   /*!< Size is in bytes.
99                                                 Set the transport input buffer size carefully and
100                                                 assure that it fulfills the requirements of the
101                                                 supported transport format(s).                    */
102
103typedef enum {
104  TRANSPORTDEC_OK = 0,             /*!< All fine.                                                  */
105
106  /* Synchronization errors. Wait for new input data and try again. */
107  tpdec_sync_error_start   = 0x100,
108  TRANSPORTDEC_NOT_ENOUGH_BITS,    /*!< Out of bits. Provide more bits and try again.              */
109  TRANSPORTDEC_SYNC_ERROR,         /*!< No sync was found or sync got lost. Keep trying.           */
110  tpdec_sync_error_end,
111
112  /* Decode errors. Mostly caused due to bit errors. */
113  tpdec_decode_error_start = 0x400,
114  TRANSPORTDEC_PARSE_ERROR,        /*!< Bitstream data showed inconsistencies (wrong syntax).      */
115  TRANSPORTDEC_UNSUPPORTED_FORMAT, /*!< Unsupported format or feature found in the bitstream data. */
116  TRANSPORTDEC_CRC_ERROR,          /*!< CRC error encountered in bitstream data.                   */
117  tpdec_decode_error_end,
118
119  /* Fatal errors. Stop immediately on one of these errors! */
120  tpdec_fatal_error_start  = 0x200,
121  TRANSPORTDEC_UNKOWN_ERROR,       /*!< An unknown error occured.                                  */
122  TRANSPORTDEC_INVALID_PARAMETER,  /*!< An invalid parameter was passed to a function.             */
123  TRANSPORTDEC_NEED_TO_RESTART,    /*!< The decoder needs to be restarted, since the requiered
124                                        configuration change cannot be performed.                  */
125  tpdec_fatal_error_end
126
127} TRANSPORTDEC_ERROR;
128
129
130/** Macro to identify decode errors. */
131#define TPDEC_IS_DECODE_ERROR(err) ( ((err>=tpdec_decode_error_start) && (err<=tpdec_decode_error_end)) ? 1 : 0)
132/** Macro to identify fatal errors. */
133#define TPDEC_IS_FATAL_ERROR(err)  ( ((err>=tpdec_fatal_error_start)  && (err<=tpdec_fatal_error_end))  ? 1 : 0)
134
135
136/**
137 * \brief Parameter identifiers for transportDec_SetParam()
138 */
139typedef enum {
140  TPDEC_PARAM_MINIMIZE_DELAY = 1,        /** Delay minimization strategy. 0: none, 1: discard as many frames as possible. */
141  TPDEC_PARAM_EARLY_CONFIG,              /** Enable early config discovery. */
142  TPDEC_PARAM_IGNORE_BUFFERFULLNESS,     /** Ignore buffer fullness. */
143  TPDEC_PARAM_SET_BITRATE,               /** Set average bit rate for bit stream interruption frame misses estimation. */
144  TPDEC_PARAM_RESET,                     /** Reset transport decoder instance status. */
145  TPDEC_PARAM_BURST_PERIOD               /** Set data reception burst period in mili seconds. */
146} TPDEC_PARAM;
147
148/* ISO/IEC 14496-3 4.4.1.1 Table 4.2 Program config element */
149#define PC_FSB_CHANNELS_MAX 16 /* Front/Side/Back channels */
150#define PC_LFE_CHANNELS_MAX 4
151#define PC_ASSOCDATA_MAX    8
152#define PC_CCEL_MAX         16 /* CC elements */
153#define PC_COMMENTLENGTH    256
154#define PC_NUM_HEIGHT_LAYER 3
155
156
157/*!
158  \brief               Reset Program Config Element.
159  \param pPce          Program Config Element structure.
160  \return              void
161*/
162void  CProgramConfig_Reset ( CProgramConfig *pPce );
163
164/*!
165  \brief               Initialize Program Config Element.
166  \param pPce          Program Config Element structure.
167  \return              void
168*/
169void  CProgramConfig_Init ( CProgramConfig *pPce );
170
171/*!
172  \brief               Inquire state of present Program Config Element structure.
173  \param pPce          Program Config Element structure.
174  \return              1 if the PCE structure is filled correct,
175                       0 if no valid PCE present.
176*/
177int  CProgramConfig_IsValid ( const CProgramConfig *pPce );
178
179#ifdef TP_PCE_ENABLE
180/*!
181  \brief               Read Program Config Element.
182  \param pPce          Program Config Element structure.
183  \param bs            Bitstream buffer to read from.
184  \param alignAnchor   Align bitstream to alignAnchor bits after all read operations.
185  \return              void
186*/
187void  CProgramConfig_Read ( CProgramConfig       *pPce,
188                            HANDLE_FDK_BITSTREAM  bs,
189                            UINT                  alignAnchor );
190
191/*!
192  \brief               Compare two Program Config Elements.
193  \param pPce1         Pointer to first Program Config Element structure.
194  \param pPce2         Pointer to second Program Config Element structure.
195  \return              -1 if PCEs are completely different,
196                        0 if PCEs are completely equal,
197                        1 if PCEs are different but have the same channel config,
198                        2 if PCEs have different channel config but same number of channels.
199*/
200int CProgramConfig_Compare ( const CProgramConfig * const pPce1,
201                             const CProgramConfig * const pPce2 );
202
203/*!
204  \brief               Get a Program Config Element that matches the predefined MPEG-4 channel configurations 1-14.
205  \param pPce          Program Config Element structure.
206  \param channelConfig MPEG-4 channel configuration.
207  \return              void
208*/
209void CProgramConfig_GetDefault ( CProgramConfig *pPce,
210                                 const UINT channelConfig );
211#endif /* TP_PCE_ENABLE */
212
213/**
214 * \brief Lookup and verify a given element. The decoder calls this
215 *        method with every new element ID found in the bitstream.
216 *
217 * \param pPce        A valid Program config structure.
218 * \param tag         Tag of the current element to be looked up.
219 * \param channelIdx  The current channel count of the decoder parser.
220 * \param chMapping   Array to store the canonical channel mapping indexes.
221 * \param chType      Array to store the audio channel type.
222 * \param chIndex     Array to store the individual audio channel type index.
223 * \param elMapping   Pointer where the canonical element index is stored.
224 * \param elType      The element id of the current element to be looked up.
225 *
226 * \return            Non-zero if the element belongs to the current program, zero
227 *                    if it does not.
228 */
229int CProgramConfig_LookupElement(
230        CProgramConfig *pPce,
231        UINT            channelConfig,
232        const UINT      tag,
233        const UINT      channelIdx,
234        UCHAR           chMapping[],
235        AUDIO_CHANNEL_TYPE chType[],
236        UCHAR           chIndex[],
237        UCHAR          *elMapping,
238        MP4_ELEMENT_ID  elList[],
239        MP4_ELEMENT_ID  elType
240        );
241
242/**
243 * \brief             Get table of elements in canonical order from a
244 *                    give program config field.
245 * \param pPce        A valid program config structure.
246 * \param table       An array where the element IDs are stored.
247 * \param elListSize  The length of the table array.
248 * \param pChMapIdx   Pointer to a field receiving the corresponding
249 *                    implicit channel configuration index of the given
250 *                    PCE. If none can be found it receives the value 0.
251 * \return            Total element count including all SCE, CPE and LFE.
252 */
253int CProgramConfig_GetElementTable( const CProgramConfig *pPce,
254                                    MP4_ELEMENT_ID  table[],
255                                    const INT elListSize,
256                                    UCHAR *pChMapIdx );
257
258/**
259 * \brief       Initialize a given AudioSpecificConfig structure.
260 * \param pAsc  A pointer to an allocated CSAudioSpecificConfig struct.
261 * \return      void
262 */
263void AudioSpecificConfig_Init(CSAudioSpecificConfig *pAsc);
264
265/**
266 * \brief   Parse a AudioSpecificConfig from a given bitstream handle.
267 *
268 * \param pAsc                         A pointer to an allocated CSAudioSpecificConfig struct.
269 * \param hBs                          Bitstream handle.
270 * \param fExplicitBackwardCompatible  Do explicit backward compatibility parsing if set (flag).
271 * \param cb pointer to structure holding callback information
272 *
273 * \return  Total element count including all SCE, CPE and LFE.
274 */
275TRANSPORTDEC_ERROR AudioSpecificConfig_Parse(
276        CSAudioSpecificConfig *pAsc,
277        HANDLE_FDK_BITSTREAM hBs,
278        int fExplicitBackwardCompatible,
279        CSTpCallBacks *cb
280        );
281
282/* CELP stuff */
283enum {
284  MPE     = 0,
285  RPE     = 1,
286  fs8KHz  = 0,
287  fs16KHz = 1
288};
289
290/* Defintion of flags that can be passed to transportDecOpen() */
291#define TP_FLAG_MPEG4 1
292
293/* Capability flags */
294#define CAPF_TPDEC_ADIF        0x00001000  /**< Flag indicating support for ADIF transport format.        */
295#define CAPF_TPDEC_ADTS        0x00002000  /**< Flag indicating support for ADTS transport format.        */
296#define CAPF_TPDEC_LOAS        0x00004000  /**< Flag indicating support for LOAS transport format.        */
297#define CAPF_TPDEC_LATM        0x00008000  /**< Flag indicating support for LATM transport format.        */
298#define CAPF_TPDEC_RAWPACKETS  0x00010000  /**< Flag indicating support for raw packets transport format. */
299
300typedef struct TRANSPORTDEC *HANDLE_TRANSPORTDEC;
301
302
303/**
304 * \brief Configure Transport Decoder via a binary coded AudioSpecificConfig or StreamMuxConfig.
305 *        The previously requested configuration callback will be called as well. The buffer conf
306 *        must containt a SMC in case of LOAS/LATM transport format, and an ASC elseways.
307 *
308 * \param hTp     Handle of a transport decoder.
309 * \param conf    UCHAR buffer of the binary coded config (ASC or SMC).
310 * \param length  The length in bytes of the conf buffer.
311 *
312 * \return        Error code.
313 */
314TRANSPORTDEC_ERROR transportDec_OutOfBandConfig( const HANDLE_TRANSPORTDEC hTp,
315                                                 UCHAR              *conf,
316                                                 const UINT          length,
317                                                 const UINT          layer );
318
319/**
320 * \brief Open Transport medium for reading.
321 *
322 * \param transportDecFmt Format of the transport decoder medium to be accessed.
323 * \param flags           Transport decoder flags. Currently only TP_FLAG_MPEG4, which signals a
324 *                        MPEG4 capable decoder (relevant for ADTS only).
325 *
326 * \return   A pointer to a valid and allocated HANDLE_TRANSPORTDEC or a null pointer on failure.
327 */
328HANDLE_TRANSPORTDEC transportDec_Open( TRANSPORT_TYPE transportDecFmt,
329                                       const UINT flags );
330
331/**
332 * \brief                Register configuration change callback.
333 * \param hTp            Handle of transport decoder.
334 * \param cbUpdateConfig Pointer to a callback function to handle audio config changes.
335 * \param user_data      void pointer for user data passed to the callback as first parameter.
336 * \return               0 on success.
337 */
338int transportDec_RegisterAscCallback (
339        HANDLE_TRANSPORTDEC hTp,
340        const cbUpdateConfig_t cbUpdateConfig,
341        void* user_data );
342
343/**
344 * \brief                Register SSC parser callback.
345 * \param hTp            Handle of transport decoder.
346 * \param cbUpdateConfig Pointer to a callback function to handle SSC parsing.
347 * \param user_data      void pointer for user data passed to the callback as first parameter.
348 * \return               0 on success.
349 */
350int transportDec_RegisterSscCallback (
351        HANDLE_TRANSPORTDEC hTp,
352        const cbSsc_t cbSscParse,
353        void* user_data );
354
355/**
356 * \brief                Register SBR header parser callback.
357 * \param hTp            Handle of transport decoder.
358 * \param cbUpdateConfig Pointer to a callback function to handle SBR header parsing.
359 * \param user_data      void pointer for user data passed to the callback as first parameter.
360 * \return               0 on success.
361 */
362int transportDec_RegisterSbrCallback( HANDLE_TRANSPORTDEC hTpDec, const cbSbr_t cbSbr, void* user_data);
363
364/**
365 * \brief Fill internal input buffer with bitstream data from the external input buffer.
366 *  The function only copies such data as long as the decoder-internal input buffer is not full.
367 *  So it grabs whatever it can from pBuffer and returns information (bytesValid) so that at a
368 *  subsequent call of %transportDec_FillData(), the right position in pBuffer can be determined to
369 *  grab the next data.
370 *
371 * \param hTp         Handle of transportDec.
372 * \param pBuffer     Pointer to external input buffer.
373 * \param bufferSize  Size of external input buffer. This argument is required because decoder-internally
374 *                    we need the information to calculate the offset to pBuffer, where the next
375 *                    available data is, which is then fed into the decoder-internal buffer (as much
376 *                    as possible). Our example framework implementation fills the buffer at pBuffer
377 *                    again, once it contains no available valid bytes anymore (meaning bytesValid equal 0).
378 * \param bytesValid  Number of bitstream bytes in the external bitstream buffer that have not yet been
379 *                    copied into the decoder's internal bitstream buffer by calling this function.
380 *                    The value is updated according to the amount of newly copied bytes.
381 * \param layer       The layer the bitstream belongs to.
382 * \return            Error code.
383 */
384TRANSPORTDEC_ERROR transportDec_FillData(
385        const HANDLE_TRANSPORTDEC  hTp,
386        UCHAR                     *pBuffer,
387        const UINT                 bufferSize,
388        UINT                      *pBytesValid,
389        const INT                  layer );
390
391/**
392 * \brief      Get transportDec bitstream handle.
393 * \param hTp  Pointer to a transport decoder handle.
394 * \return     HANDLE_FDK_BITSTREAM bitstream handle.
395 */
396HANDLE_FDK_BITSTREAM transportDec_GetBitstream ( const HANDLE_TRANSPORTDEC hTp, const UINT layer );
397
398/**
399 * \brief      Get transport format.
400 * \param hTp  Pointer to a transport decoder handle.
401 * \return     The transport format.
402 */
403TRANSPORT_TYPE transportDec_GetFormat ( const HANDLE_TRANSPORTDEC hTp );
404
405/**
406 * \brief Get the current buffer fullness value.
407 *
408 * \param hTp     Handle of a transport decoder.
409 *
410 * \return        Buffer fullness
411 */
412INT transportDec_GetBufferFullness( const HANDLE_TRANSPORTDEC hTp );
413
414/**
415 * \brief       Close and deallocate transportDec.
416 * \param phTp  Pointer to a previously allocated transport decoder handle.
417 * \return      void
418 */
419void transportDec_Close ( HANDLE_TRANSPORTDEC *phTp );
420
421/**
422 * \brief         Read one access unit from the transportDec medium.
423 * \param hTp     Handle of transportDec.
424 * \param length  On return, this value is overwritten with the actual access unit length in bits.
425 *                Set to -1 if length is unknown.
426 * \return        Error code.
427 */
428TRANSPORTDEC_ERROR transportDec_ReadAccessUnit ( const HANDLE_TRANSPORTDEC hTp, const UINT layer );
429
430/**
431 * \brief Get the remaining amount of bits of the current access unit. The result
432 *        can be below zero, meaning that too many bits have been read.
433 * \param hTp     Handle of transportDec.
434 * \return amount of remaining bits.
435 */
436INT transportDec_GetAuBitsRemaining( const HANDLE_TRANSPORTDEC hTp, const UINT layer );
437
438/**
439 * \brief Get the total amount of bits of the current access unit.
440 * \param hTp     Handle of transportDec.
441 * \return amount of total bits.
442 */
443INT transportDec_GetAuBitsTotal( const HANDLE_TRANSPORTDEC hTp, const UINT layer );
444
445/**
446 * \brief      This function is required to be called when the decoder has finished parsing
447 *             one Access Unit for bitstream housekeeping.
448 * \param hTp  Transport Handle.
449 * \return     Error code.
450 */
451TRANSPORTDEC_ERROR transportDec_EndAccessUnit ( const HANDLE_TRANSPORTDEC hTp );
452
453/**
454 * \brief      Obtain the amount of missing access units if applicable in case of
455 *             a bit stream synchronization error. Each time transportDec_ReadAccessUnit()
456 *             returns TRANSPORTDEC_SYNC_ERROR this function can be called to retrieve an estimate
457 *             of the amount of missing access units. This works only in case of constant average
458 *             bit rate (has to be known) and if the parameter TPDEC_PARAM_SET_BITRATE has been set
459 *             accordingly.
460 * \param hTp  Transport Handle.
461 * \param pNAccessUnits pointer to a memory location where the estimated lost frame count will be stored into.
462 * \return     Error code.
463 */
464TRANSPORTDEC_ERROR transportDec_GetMissingAccessUnitCount ( INT *pNAccessUnits, HANDLE_TRANSPORTDEC hTp );
465
466
467/**
468 * \brief        Set a given setting.
469 * \param hTp    Transport Handle.
470 * \param param  Identifier of the parameter to be changed.
471 * \param value  Value for the parameter to be changed.
472 * \return       Error code.
473 */
474TRANSPORTDEC_ERROR transportDec_SetParam ( const HANDLE_TRANSPORTDEC hTp,
475                                           const TPDEC_PARAM         param,
476                                           const INT                 value );
477
478/**
479 * \brief        Get number of subframes (for LATM or ADTS)
480 * \param hTp    Transport Handle.
481 * \return       Number of ADTS/LATM subframes (return 1 for all other transport types).
482 */
483UINT transportDec_GetNrOfSubFrames(HANDLE_TRANSPORTDEC hTp);
484
485
486/**
487 * \brief       Get info structure of transport decoder library.
488 * \param info  A pointer to an allocated LIB_INFO struct.
489 * \return      Error code.
490 */
491TRANSPORTDEC_ERROR transportDec_GetLibInfo( LIB_INFO *info );
492
493/* ADTS CRC support */
494
495/**
496 * \brief        Set current bitstream position as start of a new data region.
497 * \param hTp    Transport handle.
498 * \param mBits  Size in bits of the data region. Set to 0 if it should not be of a fixed size.
499 * \return       Data region ID, which should be used when calling transportDec_CrcEndReg().
500 */
501int transportDec_CrcStartReg ( const HANDLE_TRANSPORTDEC hTp,
502                               const INT mBits );
503
504/**
505 * \brief        Set end of data region.
506 * \param hTp    Transport handle.
507 * \param reg    Data region ID, opbtained from transportDec_CrcStartReg().
508 * \return       void
509 */
510void transportDec_CrcEndReg ( const HANDLE_TRANSPORTDEC hTp,
511                              const INT reg );
512
513/**
514 * \brief      Calculate ADTS crc and check if it is correct. The ADTS checksum is held internally.
515 * \param hTp  Transport handle.
516 * \return     Return TRANSPORTDEC_OK if the CRC is ok, or error if CRC is not correct.
517 */
518TRANSPORTDEC_ERROR transportDec_CrcCheck ( const HANDLE_TRANSPORTDEC hTp );
519
520
521#endif /* #ifndef __TPDEC_LIB_H__ */
522