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 /**************************** AAC encoder library ******************************
96 
97    Author(s):   M. Schug / A. Groeschel
98 
99    Description: fast aac coder interface library functions
100 
101 *******************************************************************************/
102 
103 #ifndef AACENC_H
104 #define AACENC_H
105 
106 #include "common_fix.h"
107 #include "FDK_audio.h"
108 
109 #include "tpenc_lib.h"
110 
111 #include "sbr_encoder.h"
112 
113 #define MIN_BUFSIZE_PER_EFF_CHAN 6144
114 
115 #ifdef __cplusplus
116 extern "C" {
117 #endif
118 
119 /*
120  * AAC-LC error codes.
121  */
122 typedef enum {
123   AAC_ENC_OK = 0x0000, /*!< All fine. */
124 
125   AAC_ENC_UNKNOWN = 0x0002, /*!< Error condition is of unknown reason, or from
126                                another module.              */
127 
128   /* initialization errors */
129   aac_enc_init_error_start = 0x2000,
130   AAC_ENC_INVALID_HANDLE = 0x2020, /*!< The handle passed to the function call
131                                       was invalid (probably NULL).        */
132   AAC_ENC_INVALID_FRAME_LENGTH =
133       0x2080, /*!< Invalid frame length (must be 1024 or 960). */
134   AAC_ENC_INVALID_N_CHANNELS =
135       0x20e0, /*!< Invalid amount of audio input channels. */
136   AAC_ENC_INVALID_SFB_TABLE = 0x2140, /*!< Internal encoder error. */
137 
138   AAC_ENC_UNSUPPORTED_AOT =
139       0x3000, /*!< The Audio Object Type (AOT) is not supported. */
140   AAC_ENC_UNSUPPORTED_FILTERBANK =
141       0x3010, /*!< Filterbank type is not supported. */
142   AAC_ENC_UNSUPPORTED_BITRATE =
143       0x3020, /*!< The chosen bitrate is not supported. */
144   AAC_ENC_UNSUPPORTED_BITRATE_MODE =
145       0x3028, /*!< Unsupported bit rate mode (CBR or VBR). */
146   AAC_ENC_UNSUPPORTED_ANC_BITRATE =
147       0x3040, /*!< Unsupported ancillay bitrate. */
148   AAC_ENC_UNSUPPORTED_ANC_MODE = 0x3060,
149   AAC_ENC_UNSUPPORTED_TRANSPORT_TYPE =
150       0x3080, /*!< The bitstream format is not supported. */
151   AAC_ENC_UNSUPPORTED_ER_FORMAT =
152       0x30a0, /*!< The error resilience tool format is not supported. */
153   AAC_ENC_UNSUPPORTED_EPCONFIG =
154       0x30c0, /*!< The error protection format is not supported. */
155   AAC_ENC_UNSUPPORTED_CHANNELCONFIG =
156       0x30e0, /*!< The channel configuration (either number or arrangement) is
157                  not supported. */
158   AAC_ENC_UNSUPPORTED_SAMPLINGRATE =
159       0x3100, /*!< Sample rate of audio input is not supported. */
160   AAC_ENC_NO_MEMORY = 0x3120,               /*!< Could not allocate memory. */
161   AAC_ENC_PE_INIT_TABLE_NOT_FOUND = 0x3140, /*!< Internal encoder error.    */
162 
163   aac_enc_init_error_end,
164 
165   /* encode errors */
166   aac_enc_error_start = 0x4000,
167   AAC_ENC_QUANT_ERROR = 0x4020, /*!< Too many bits used in quantization. */
168   AAC_ENC_WRITTEN_BITS_ERROR =
169       0x4040, /*!< Unexpected number of written bits, differs to
170                    calculated number of bits.                      */
171   AAC_ENC_PNS_TABLE_ERROR = 0x4060,      /*!< PNS level out of range.      */
172   AAC_ENC_GLOBAL_GAIN_TOO_HIGH = 0x4080, /*!< Internal quantizer error. */
173   AAC_ENC_BITRES_TOO_LOW = 0x40a0, /*!< Too few  bits in bit reservoir.       */
174   AAC_ENC_BITRES_TOO_HIGH = 0x40a1, /*!< Too many bits in bit reservoir.      */
175   AAC_ENC_INVALID_CHANNEL_BITRATE = 0x4100,
176   AAC_ENC_INVALID_ELEMENTINFO_TYPE = 0x4120, /*!< Internal encoder error. */
177 
178   AAC_ENC_WRITE_SCAL_ERROR = 0x41e0, /*!< Error writing scalefacData. */
179   AAC_ENC_WRITE_SEC_ERROR = 0x4200,  /*!< Error writing sectionData.  */
180   AAC_ENC_WRITE_SPEC_ERROR = 0x4220, /*!< Error writing spectralData. */
181   aac_enc_error_end
182 
183 } AAC_ENCODER_ERROR;
184 /*-------------------------- defines --------------------------------------*/
185 
186 #define ANC_DATA_BUFFERSIZE 1024 /* ancBuffer size */
187 
188 #define MAX_TOTAL_EXT_PAYLOADS ((((8)) * (1)) + (2 + 2))
189 
190 typedef enum {
191   AACENC_BR_MODE_INVALID = -1, /*!< Invalid bitrate mode. */
192   AACENC_BR_MODE_CBR = 0,      /*!< Constant bitrate mode.      */
193   AACENC_BR_MODE_VBR_1 = 1, /*!< Variable bitrate mode, very low bitrate.    */
194   AACENC_BR_MODE_VBR_2 = 2, /*!< Variable bitrate mode, low bitrate.    */
195   AACENC_BR_MODE_VBR_3 = 3, /*!< Variable bitrate mode, medium bitrate.    */
196   AACENC_BR_MODE_VBR_4 = 4, /*!< Variable bitrate mode, high bitrate.    */
197   AACENC_BR_MODE_VBR_5 = 5, /*!< Variable bitrate mode, very high bitrate.    */
198   AACENC_BR_MODE_FF = 6,    /*!< Fixed frame mode.       */
199   AACENC_BR_MODE_SFR = 7    /*!< Superframe mode.       */
200 
201 } AACENC_BITRATE_MODE;
202 
203 #define AACENC_BR_MODE_IS_VBR(brMode) ((brMode >= 1) && (brMode <= 5))
204 
205 typedef enum {
206 
207   CH_ORDER_MPEG =
208       0, /*!< MPEG channel ordering (e. g. 5.1: C, L, R, SL, SR, LFE)       */
209   CH_ORDER_WAV, /*!< WAV fileformat channel ordering (e. g. 5.1: L, R, C, LFE,
210                    SL, SR) */
211   CH_ORDER_WG4  /*!< WG4 fileformat channel ordering (e. g. 5.1: L, R, SL, SR, C, LFE) */
212 
213 } CHANNEL_ORDER;
214 
215 /*-------------------- structure definitions ------------------------------*/
216 
217 struct AACENC_CONFIG {
218   INT sampleRate;     /* encoder sample rate */
219   INT bitRate;        /* encoder bit rate in bits/sec */
220   INT ancDataBitRate; /* additional bits consumed by anc data or sbr have to be
221                          consiedered while configuration */
222 
223   INT nSubFrames; /* number of frames in super frame (not ADTS/LATM subframes !)
224                    */
225   AUDIO_OBJECT_TYPE audioObjectType; /* Audio Object Type  */
226 
227   INT averageBits;                 /* encoder bit rate in bits/superframe */
228   AACENC_BITRATE_MODE bitrateMode; /* encoder bitrate mode (CBR/VBR) */
229   INT nChannels;                   /* number of channels to process */
230   CHANNEL_ORDER channelOrder;      /* input Channel ordering scheme. */
231   INT bandWidth;                   /* targeted audio bandwidth in Hz */
232   CHANNEL_MODE channelMode;        /* encoder channel mode configuration */
233   INT framelength;                 /* used frame size */
234 
235   UINT syntaxFlags; /* bitstreams syntax configuration */
236   SCHAR epConfig;   /* error protection configuration */
237 
238   INT anc_Rate; /* ancillary rate, 0 (disabled), -1 (default) else desired rate
239                  */
240   UINT maxAncBytesPerAU;
241   INT minBitsPerFrame; /* minimum number of bits in AU */
242   INT maxBitsPerFrame; /* maximum number of bits in AU */
243 
244   INT audioMuxVersion; /* audio mux version in loas/latm transport format */
245 
246   UINT sbrRatio; /* sbr sampling rate ratio: dual- or single-rate */
247 
248   UCHAR useTns; /* flag: use temporal noise shaping */
249   UCHAR usePns; /* flag: use perceptual noise substitution */
250   UCHAR useIS;  /* flag: use intensity coding */
251   UCHAR useMS;  /* flag: use ms stereo tool */
252 
253   UCHAR useRequant; /* flag: use afterburner */
254 
255   UINT downscaleFactor;
256 };
257 
258 typedef struct {
259   UCHAR *pData;              /* pointer to extension payload data */
260   UINT dataSize;             /* extension payload data size in bits */
261   EXT_PAYLOAD_TYPE dataType; /* extension payload data type */
262   INT associatedChElement; /* number of the channel element the data is assigned
263                               to */
264 } AACENC_EXT_PAYLOAD;
265 
266 typedef struct AAC_ENC *HANDLE_AAC_ENC;
267 
268 /**
269  * \brief Calculate framesize in bits for given bit rate, frame length and
270  * sampling rate.
271  *
272  * \param bitRate               Ttarget bitrate in bits per second.
273  * \param frameLength           Number of audio samples in one frame.
274  * \param samplingRate          Sampling rate in Hz.
275  *
276  * \return                      Framesize in bits per frame.
277  */
278 INT FDKaacEnc_CalcBitsPerFrame(const INT bitRate, const INT frameLength,
279                                const INT samplingRate);
280 
281 /**
282  * \brief Calculate bitrate in bits per second for given framesize, frame length
283  * and sampling rate.
284  *
285  * \param bitsPerFrame          Framesize in bits per frame
286  * \param frameLength           Number of audio samples in one frame.
287  * \param samplingRate          Sampling rate in Hz.
288  *
289  * \return                      Bitrate in bits per second.
290  */
291 INT FDKaacEnc_CalcBitrate(const INT bitsPerFrame, const INT frameLength,
292                           const INT samplingRate);
293 
294 /**
295  * \brief Limit given bit rate to a valid value
296  * \param hTpEnc transport encoder handle
297  * \param aot audio object type
298  * \param coreSamplingRate the sample rate to be used for the AAC encoder
299  * \param frameLength the frameLength to be used for the AAC encoder
300  * \param nChannels number of total channels
301  * \param nChannelsEff number of effective channels
302  * \param bitRate the initial bit rate value for which the closest valid bit
303  * rate value is searched for
304  * \param averageBits average bits per frame for fixed framing. Set to -1 if not
305  * available.
306  * \param optional pointer where the current bits per frame are stored into.
307  * \param bitrateMode the current bit rate mode
308  * \param nSubFrames number of sub frames for super framing (not transport
309  * frames).
310  * \return a valid bit rate value as close as possible or identical to bitRate
311  */
312 INT FDKaacEnc_LimitBitrate(HANDLE_TRANSPORTENC hTpEnc, AUDIO_OBJECT_TYPE aot,
313                            INT coreSamplingRate, INT frameLength, INT nChannels,
314                            INT nChannelsEff, INT bitRate, INT averageBits,
315                            INT *pAverageBitsPerFrame,
316                            AACENC_BITRATE_MODE bitrateMode, INT nSubFrames);
317 
318 /**
319  * \brief Get current state of the bit reservoir
320  * \param hAacEncoder encoder handle
321  * \return bit reservoir state in bits
322  */
323 INT FDKaacEnc_GetBitReservoirState(const HANDLE_AAC_ENC hAacEncoder);
324 
325 /*-----------------------------------------------------------------------------
326 
327     functionname: FDKaacEnc_GetVBRBitrate
328     description:  Get VBR bitrate from vbr quality
329     input params: int vbrQuality (VBR0, VBR1, VBR2)
330                   channelMode
331     returns:      vbr bitrate
332 
333 ------------------------------------------------------------------------------*/
334 INT FDKaacEnc_GetVBRBitrate(AACENC_BITRATE_MODE bitrateMode,
335                             CHANNEL_MODE channelMode);
336 
337 /*-----------------------------------------------------------------------------
338 
339     functionname: FDKaacEnc_AdjustVBRBitrateMode
340     description:  Adjust bitrate mode to given bitrate parameter
341     input params: int vbrQuality (VBR0, VBR1, VBR2)
342                   bitrate
343                   channelMode
344     returns:      vbr bitrate mode
345 
346  ------------------------------------------------------------------------------*/
347 AACENC_BITRATE_MODE FDKaacEnc_AdjustVBRBitrateMode(
348     AACENC_BITRATE_MODE bitrateMode, INT bitrate, CHANNEL_MODE channelMode);
349 
350 /*-----------------------------------------------------------------------------
351 
352      functionname: FDKaacEnc_AacInitDefaultConfig
353      description:  gives reasonable default configuration
354      returns:      ---
355 
356  ------------------------------------------------------------------------------*/
357 void FDKaacEnc_AacInitDefaultConfig(AACENC_CONFIG *config);
358 
359 /*---------------------------------------------------------------------------
360 
361     functionname:FDKaacEnc_Open
362     description: allocate and initialize a new encoder instance
363     returns:     0 if success
364 
365   ---------------------------------------------------------------------------*/
366 AAC_ENCODER_ERROR FDKaacEnc_Open(
367     HANDLE_AAC_ENC
368         *phAacEnc, /* pointer to an encoder handle, initialized on return */
369     const INT nElements, /* number of maximal elements in instance to support */
370     const INT nChannels, /* number of maximal channels in instance to support */
371     const INT nSubFrames); /* support superframing in instance */
372 
373 AAC_ENCODER_ERROR FDKaacEnc_Initialize(
374     HANDLE_AAC_ENC
375         hAacEncoder, /* pointer to an encoder handle, initialized on return */
376     AACENC_CONFIG *config, /* pre-initialized config struct */
377     HANDLE_TRANSPORTENC hTpEnc, ULONG initFlags);
378 
379 /*---------------------------------------------------------------------------
380 
381     functionname: FDKaacEnc_EncodeFrame
382     description:  encode one frame
383     returns:      0 if success
384 
385   ---------------------------------------------------------------------------*/
386 
387 AAC_ENCODER_ERROR FDKaacEnc_EncodeFrame(
388     HANDLE_AAC_ENC hAacEnc, /* encoder handle */
389     HANDLE_TRANSPORTENC hTpEnc, INT_PCM *inputBuffer,
390     const UINT inputBufferBufSize, INT *numOutBytes,
391     AACENC_EXT_PAYLOAD extPayload[MAX_TOTAL_EXT_PAYLOADS]);
392 
393 /*---------------------------------------------------------------------------
394 
395     functionname:FDKaacEnc_Close
396     description: delete encoder instance
397     returns:
398 
399   ---------------------------------------------------------------------------*/
400 
401 void FDKaacEnc_Close(HANDLE_AAC_ENC *phAacEnc); /* encoder handle */
402 
403 #ifdef __cplusplus
404 }
405 #endif
406 
407 #endif /* AACENC_H */
408