1/*
2 * AAC encoder wrapper
3 * Copyright (c) 2012 Martin Storsjo
4 *
5 * This file is part of FFmpeg.
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <fdk-aac/aacenc_lib.h>
21
22#include "libavutil/channel_layout.h"
23#include "libavutil/common.h"
24#include "libavutil/opt.h"
25#include "avcodec.h"
26#include "audio_frame_queue.h"
27#include "codec_internal.h"
28#include "encode.h"
29#include "profiles.h"
30
31#ifdef AACENCODER_LIB_VL0
32#define FDKENC_VER_AT_LEAST(vl0, vl1) \
33    ((AACENCODER_LIB_VL0 > vl0) || \
34     (AACENCODER_LIB_VL0 == vl0 && AACENCODER_LIB_VL1 >= vl1))
35#else
36#define FDKENC_VER_AT_LEAST(vl0, vl1) 0
37#endif
38
39typedef struct AACContext {
40    const AVClass *class;
41    HANDLE_AACENCODER handle;
42    int afterburner;
43    int eld_sbr;
44    int eld_v2;
45    int signaling;
46    int latm;
47    int header_period;
48    int vbr;
49
50    AudioFrameQueue afq;
51} AACContext;
52
53static const AVOption aac_enc_options[] = {
54    { "afterburner", "Afterburner (improved quality)", offsetof(AACContext, afterburner), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
55    { "eld_sbr", "Enable SBR for ELD (for SBR in other configurations, use the -profile parameter)", offsetof(AACContext, eld_sbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
56#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
57    { "eld_v2", "Enable ELDv2 (LD-MPS extension for ELD stereo signals)", offsetof(AACContext, eld_v2), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
58#endif
59    { "signaling", "SBR/PS signaling style", offsetof(AACContext, signaling), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 2, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
60    { "default", "Choose signaling implicitly (explicit hierarchical by default, implicit if global header is disabled)", 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
61    { "implicit", "Implicit backwards compatible signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
62    { "explicit_sbr", "Explicit SBR, implicit PS signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
63    { "explicit_hierarchical", "Explicit hierarchical signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
64    { "latm", "Output LATM/LOAS encapsulated data", offsetof(AACContext, latm), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
65    { "header_period", "StreamMuxConfig and PCE repetition period (in frames)", offsetof(AACContext, header_period), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xffff, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
66    { "vbr", "VBR mode (1-5)", offsetof(AACContext, vbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 5, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
67    FF_AAC_PROFILE_OPTS
68    { NULL }
69};
70
71static const AVClass aac_enc_class = {
72    .class_name = "libfdk_aac",
73    .item_name  = av_default_item_name,
74    .option     = aac_enc_options,
75    .version    = LIBAVUTIL_VERSION_INT,
76};
77
78static const char *aac_get_error(AACENC_ERROR err)
79{
80    switch (err) {
81    case AACENC_OK:
82        return "No error";
83    case AACENC_INVALID_HANDLE:
84        return "Invalid handle";
85    case AACENC_MEMORY_ERROR:
86        return "Memory allocation error";
87    case AACENC_UNSUPPORTED_PARAMETER:
88        return "Unsupported parameter";
89    case AACENC_INVALID_CONFIG:
90        return "Invalid config";
91    case AACENC_INIT_ERROR:
92        return "Initialization error";
93    case AACENC_INIT_AAC_ERROR:
94        return "AAC library initialization error";
95    case AACENC_INIT_SBR_ERROR:
96        return "SBR library initialization error";
97    case AACENC_INIT_TP_ERROR:
98        return "Transport library initialization error";
99    case AACENC_INIT_META_ERROR:
100        return "Metadata library initialization error";
101    case AACENC_ENCODE_ERROR:
102        return "Encoding error";
103    case AACENC_ENCODE_EOF:
104        return "End of file";
105    default:
106        return "Unknown error";
107    }
108}
109
110static int aac_encode_close(AVCodecContext *avctx)
111{
112    AACContext *s = avctx->priv_data;
113
114    if (s->handle)
115        aacEncClose(&s->handle);
116    ff_af_queue_close(&s->afq);
117
118    return 0;
119}
120
121static av_cold int aac_encode_init(AVCodecContext *avctx)
122{
123    AACContext *s = avctx->priv_data;
124    int ret = AVERROR(EINVAL);
125    AACENC_InfoStruct info = { 0 };
126    CHANNEL_MODE mode;
127    AACENC_ERROR err;
128    int aot = FF_PROFILE_AAC_LOW + 1;
129    int sce = 0, cpe = 0;
130
131    if ((err = aacEncOpen(&s->handle, 0, avctx->ch_layout.nb_channels)) != AACENC_OK) {
132        av_log(avctx, AV_LOG_ERROR, "Unable to open the encoder: %s\n",
133               aac_get_error(err));
134        goto error;
135    }
136
137    if (avctx->profile != FF_PROFILE_UNKNOWN)
138        aot = avctx->profile + 1;
139
140    if ((err = aacEncoder_SetParam(s->handle, AACENC_AOT, aot)) != AACENC_OK) {
141        av_log(avctx, AV_LOG_ERROR, "Unable to set the AOT %d: %s\n",
142               aot, aac_get_error(err));
143        goto error;
144    }
145
146    if (aot == FF_PROFILE_AAC_ELD + 1 && s->eld_sbr) {
147        if ((err = aacEncoder_SetParam(s->handle, AACENC_SBR_MODE,
148                                       1)) != AACENC_OK) {
149            av_log(avctx, AV_LOG_ERROR, "Unable to enable SBR for ELD: %s\n",
150                   aac_get_error(err));
151            goto error;
152        }
153    }
154
155    if ((err = aacEncoder_SetParam(s->handle, AACENC_SAMPLERATE,
156                                   avctx->sample_rate)) != AACENC_OK) {
157        av_log(avctx, AV_LOG_ERROR, "Unable to set the sample rate %d: %s\n",
158               avctx->sample_rate, aac_get_error(err));
159        goto error;
160    }
161
162    switch (avctx->ch_layout.nb_channels) {
163    case 1: mode = MODE_1;       sce = 1; cpe = 0; break;
164    case 2:
165#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
166      // (profile + 1) to map from profile range to AOT range
167      if (aot == FF_PROFILE_AAC_ELD + 1 && s->eld_v2) {
168          if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELMODE,
169                                         128)) != AACENC_OK) {
170              av_log(avctx, AV_LOG_ERROR, "Unable to enable ELDv2: %s\n",
171                     aac_get_error(err));
172              goto error;
173          } else {
174            mode = MODE_212;
175            sce = 1;
176            cpe = 0;
177          }
178      } else
179#endif
180      {
181        mode = MODE_2;
182        sce = 0;
183        cpe = 1;
184      }
185      break;
186    case 3: mode = MODE_1_2;     sce = 1; cpe = 1; break;
187    case 4: mode = MODE_1_2_1;   sce = 2; cpe = 1; break;
188    case 5: mode = MODE_1_2_2;   sce = 1; cpe = 2; break;
189    case 6: mode = MODE_1_2_2_1; sce = 2; cpe = 2; break;
190/* The version macro is introduced the same time as the 7.1 support, so this
191   should suffice. */
192#if FDKENC_VER_AT_LEAST(3, 4) // 3.4.12
193    case 8:
194        sce = 2;
195        cpe = 3;
196        if (!av_channel_layout_compare(&avctx->ch_layout, &(AVChannelLayout)AV_CHANNEL_LAYOUT_7POINT1)) {
197            mode = MODE_7_1_REAR_SURROUND;
198        } else {
199            // MODE_1_2_2_2_1 and MODE_7_1_FRONT_CENTER use the same channel layout
200            mode = MODE_7_1_FRONT_CENTER;
201        }
202        break;
203#endif
204    default:
205        av_log(avctx, AV_LOG_ERROR,
206               "Unsupported number of channels %d\n", avctx->ch_layout.nb_channels);
207        goto error;
208    }
209
210    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELMODE,
211                                   mode)) != AACENC_OK) {
212        av_log(avctx, AV_LOG_ERROR,
213               "Unable to set channel mode %d: %s\n", mode, aac_get_error(err));
214        goto error;
215    }
216
217    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELORDER,
218                                   1)) != AACENC_OK) {
219        av_log(avctx, AV_LOG_ERROR,
220               "Unable to set wav channel order %d: %s\n",
221               mode, aac_get_error(err));
222        goto error;
223    }
224
225    if (avctx->flags & AV_CODEC_FLAG_QSCALE || s->vbr) {
226        int mode = s->vbr ? s->vbr : avctx->global_quality;
227        if (mode <  1 || mode > 5) {
228            av_log(avctx, AV_LOG_WARNING,
229                   "VBR quality %d out of range, should be 1-5\n", mode);
230            mode = av_clip(mode, 1, 5);
231        }
232        av_log(avctx, AV_LOG_WARNING,
233               "Note, the VBR setting is unsupported and only works with "
234               "some parameter combinations\n");
235        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATEMODE,
236                                       mode)) != AACENC_OK) {
237            av_log(avctx, AV_LOG_ERROR, "Unable to set the VBR bitrate mode %d: %s\n",
238                   mode, aac_get_error(err));
239            goto error;
240        }
241    } else {
242        if (avctx->bit_rate <= 0) {
243            if (avctx->profile == FF_PROFILE_AAC_HE_V2) {
244                sce = 1;
245                cpe = 0;
246            }
247            avctx->bit_rate = (96*sce + 128*cpe) * avctx->sample_rate / 44;
248            if (avctx->profile == FF_PROFILE_AAC_HE ||
249                avctx->profile == FF_PROFILE_AAC_HE_V2 ||
250                avctx->profile == FF_PROFILE_MPEG2_AAC_HE ||
251                s->eld_sbr)
252                avctx->bit_rate /= 2;
253        }
254        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATE,
255                                       avctx->bit_rate)) != AACENC_OK) {
256            av_log(avctx, AV_LOG_ERROR, "Unable to set the bitrate %"PRId64": %s\n",
257                   avctx->bit_rate, aac_get_error(err));
258            goto error;
259        }
260    }
261
262    /* Choose bitstream format - if global header is requested, use
263     * raw access units, otherwise use ADTS. */
264    if ((err = aacEncoder_SetParam(s->handle, AACENC_TRANSMUX,
265                                   avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER ? TT_MP4_RAW :
266                                   s->latm ? TT_MP4_LOAS : TT_MP4_ADTS)) != AACENC_OK) {
267        av_log(avctx, AV_LOG_ERROR, "Unable to set the transmux format: %s\n",
268               aac_get_error(err));
269        goto error;
270    }
271
272    if (s->latm && s->header_period) {
273        if ((err = aacEncoder_SetParam(s->handle, AACENC_HEADER_PERIOD,
274                                       s->header_period)) != AACENC_OK) {
275             av_log(avctx, AV_LOG_ERROR, "Unable to set header period: %s\n",
276                    aac_get_error(err));
277             goto error;
278        }
279    }
280
281    /* If no signaling mode is chosen, use explicit hierarchical signaling
282     * if using mp4 mode (raw access units, with global header) and
283     * implicit signaling if using ADTS. */
284    if (s->signaling < 0)
285        s->signaling = avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER ? 2 : 0;
286
287    if ((err = aacEncoder_SetParam(s->handle, AACENC_SIGNALING_MODE,
288                                   s->signaling)) != AACENC_OK) {
289        av_log(avctx, AV_LOG_ERROR, "Unable to set signaling mode %d: %s\n",
290               s->signaling, aac_get_error(err));
291        goto error;
292    }
293
294    if ((err = aacEncoder_SetParam(s->handle, AACENC_AFTERBURNER,
295                                   s->afterburner)) != AACENC_OK) {
296        av_log(avctx, AV_LOG_ERROR, "Unable to set afterburner to %d: %s\n",
297               s->afterburner, aac_get_error(err));
298        goto error;
299    }
300
301    if (avctx->cutoff > 0) {
302        if (avctx->cutoff < (avctx->sample_rate + 255) >> 8 || avctx->cutoff > 20000) {
303            av_log(avctx, AV_LOG_ERROR, "cutoff valid range is %d-20000\n",
304                   (avctx->sample_rate + 255) >> 8);
305            goto error;
306        }
307        if ((err = aacEncoder_SetParam(s->handle, AACENC_BANDWIDTH,
308                                       avctx->cutoff)) != AACENC_OK) {
309            av_log(avctx, AV_LOG_ERROR, "Unable to set the encoder bandwidth to %d: %s\n",
310                   avctx->cutoff, aac_get_error(err));
311            goto error;
312        }
313    }
314
315    if ((err = aacEncEncode(s->handle, NULL, NULL, NULL, NULL)) != AACENC_OK) {
316        av_log(avctx, AV_LOG_ERROR, "Unable to initialize the encoder: %s\n",
317               aac_get_error(err));
318        return AVERROR(EINVAL);
319    }
320
321    if ((err = aacEncInfo(s->handle, &info)) != AACENC_OK) {
322        av_log(avctx, AV_LOG_ERROR, "Unable to get encoder info: %s\n",
323               aac_get_error(err));
324        goto error;
325    }
326
327    avctx->frame_size = info.frameLength;
328#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
329    avctx->initial_padding = info.nDelay;
330#else
331    avctx->initial_padding = info.encoderDelay;
332#endif
333    ff_af_queue_init(avctx, &s->afq);
334
335    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
336        avctx->extradata_size = info.confSize;
337        avctx->extradata      = av_mallocz(avctx->extradata_size +
338                                           AV_INPUT_BUFFER_PADDING_SIZE);
339        if (!avctx->extradata) {
340            ret = AVERROR(ENOMEM);
341            goto error;
342        }
343
344        memcpy(avctx->extradata, info.confBuf, info.confSize);
345    }
346    return 0;
347error:
348    aac_encode_close(avctx);
349    return ret;
350}
351
352static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
353                            const AVFrame *frame, int *got_packet_ptr)
354{
355    AACContext    *s        = avctx->priv_data;
356    AACENC_BufDesc in_buf   = { 0 }, out_buf = { 0 };
357    AACENC_InArgs  in_args  = { 0 };
358    AACENC_OutArgs out_args = { 0 };
359    int in_buffer_identifier = IN_AUDIO_DATA;
360    int in_buffer_size, in_buffer_element_size;
361    int out_buffer_identifier = OUT_BITSTREAM_DATA;
362    int out_buffer_size, out_buffer_element_size;
363    void *in_ptr, *out_ptr;
364    int ret;
365    uint8_t dummy_buf[1];
366    AACENC_ERROR err;
367
368    /* handle end-of-stream small frame and flushing */
369    if (!frame) {
370        /* Must be a non-null pointer, even if it's a dummy. We could use
371         * the address of anything else on the stack as well. */
372        in_ptr               = dummy_buf;
373        in_buffer_size       = 0;
374
375        in_args.numInSamples = -1;
376    } else {
377        in_ptr               = frame->data[0];
378        in_buffer_size       = 2 * avctx->ch_layout.nb_channels * frame->nb_samples;
379
380        in_args.numInSamples = avctx->ch_layout.nb_channels * frame->nb_samples;
381
382        /* add current frame to the queue */
383        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
384            return ret;
385    }
386
387    in_buffer_element_size   = 2;
388    in_buf.numBufs           = 1;
389    in_buf.bufs              = &in_ptr;
390    in_buf.bufferIdentifiers = &in_buffer_identifier;
391    in_buf.bufSizes          = &in_buffer_size;
392    in_buf.bufElSizes        = &in_buffer_element_size;
393
394    /* The maximum packet size is 6144 bits aka 768 bytes per channel. */
395    ret = ff_alloc_packet(avctx, avpkt, FFMAX(8192, 768 * avctx->ch_layout.nb_channels));
396    if (ret < 0)
397        return ret;
398
399    out_ptr                   = avpkt->data;
400    out_buffer_size           = avpkt->size;
401    out_buffer_element_size   = 1;
402    out_buf.numBufs           = 1;
403    out_buf.bufs              = &out_ptr;
404    out_buf.bufferIdentifiers = &out_buffer_identifier;
405    out_buf.bufSizes          = &out_buffer_size;
406    out_buf.bufElSizes        = &out_buffer_element_size;
407
408    if ((err = aacEncEncode(s->handle, &in_buf, &out_buf, &in_args,
409                            &out_args)) != AACENC_OK) {
410        if (!frame && err == AACENC_ENCODE_EOF)
411            return 0;
412        av_log(avctx, AV_LOG_ERROR, "Unable to encode frame: %s\n",
413               aac_get_error(err));
414        return AVERROR(EINVAL);
415    }
416
417    if (!out_args.numOutBytes)
418        return 0;
419
420    /* Get the next frame pts & duration */
421    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
422                       &avpkt->duration);
423
424    avpkt->size     = out_args.numOutBytes;
425    *got_packet_ptr = 1;
426    return 0;
427}
428
429static const AVProfile profiles[] = {
430    { FF_PROFILE_AAC_LOW,   "LC"       },
431    { FF_PROFILE_AAC_HE,    "HE-AAC"   },
432    { FF_PROFILE_AAC_HE_V2, "HE-AACv2" },
433    { FF_PROFILE_AAC_LD,    "LD"       },
434    { FF_PROFILE_AAC_ELD,   "ELD"      },
435    { FF_PROFILE_UNKNOWN },
436};
437
438static const FFCodecDefault aac_encode_defaults[] = {
439    { "b", "0" },
440    { NULL }
441};
442
443#if FF_API_OLD_CHANNEL_LAYOUT
444static const uint64_t aac_channel_layout[] = {
445    AV_CH_LAYOUT_MONO,
446    AV_CH_LAYOUT_STEREO,
447    AV_CH_LAYOUT_SURROUND,
448    AV_CH_LAYOUT_4POINT0,
449    AV_CH_LAYOUT_5POINT0_BACK,
450    AV_CH_LAYOUT_5POINT1_BACK,
451#if FDKENC_VER_AT_LEAST(3, 4) // 3.4.12
452    AV_CH_LAYOUT_7POINT1_WIDE_BACK,
453    AV_CH_LAYOUT_7POINT1,
454#endif
455    0,
456};
457#endif /* FF_API_OLD_CHANNEL_LAYOUT */
458
459static const AVChannelLayout aac_ch_layouts[16] = {
460    AV_CHANNEL_LAYOUT_MONO,
461    AV_CHANNEL_LAYOUT_STEREO,
462    AV_CHANNEL_LAYOUT_SURROUND,
463    AV_CHANNEL_LAYOUT_4POINT0,
464    AV_CHANNEL_LAYOUT_5POINT0_BACK,
465    AV_CHANNEL_LAYOUT_5POINT1_BACK,
466#ifdef AACENCODER_LIB_VL0
467    AV_CHANNEL_LAYOUT_7POINT1_WIDE_BACK,
468    AV_CHANNEL_LAYOUT_7POINT1,
469#endif
470    { 0 },
471};
472
473static const int aac_sample_rates[] = {
474    96000, 88200, 64000, 48000, 44100, 32000,
475    24000, 22050, 16000, 12000, 11025, 8000, 0
476};
477
478const FFCodec ff_libfdk_aac_encoder = {
479    .p.name                = "libfdk_aac",
480    .p.long_name           = NULL_IF_CONFIG_SMALL("Fraunhofer FDK AAC"),
481    .p.type                = AVMEDIA_TYPE_AUDIO,
482    .p.id                  = AV_CODEC_ID_AAC,
483    .priv_data_size        = sizeof(AACContext),
484    .init                  = aac_encode_init,
485    FF_CODEC_ENCODE_CB(aac_encode_frame),
486    .close                 = aac_encode_close,
487    .p.capabilities        = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
488    .p.sample_fmts         = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
489                                                            AV_SAMPLE_FMT_NONE },
490    .p.priv_class          = &aac_enc_class,
491    .defaults              = aac_encode_defaults,
492    .p.profiles            = profiles,
493    .p.supported_samplerates = aac_sample_rates,
494    .p.wrapper_name        = "libfdk",
495#if FF_API_OLD_CHANNEL_LAYOUT
496    .p.channel_layouts     = aac_channel_layout,
497#endif
498    .p.ch_layouts          = aac_ch_layouts,
499};
500