]> git.sesse.net Git - ffmpeg/blob - libavcodec/libfdk-aacdec.c
Merge commit '2edaafe5b93832715781851dfe2663da228a05ad'
[ffmpeg] / libavcodec / libfdk-aacdec.c
1 /*
2  * AAC decoder 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/aacdecoder_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 "internal.h"
27
28 #define FDKDEC_VER_AT_LEAST(vl0, vl1) \
29     (defined(AACDECODER_LIB_VL0) && \
30         ((AACDECODER_LIB_VL0 > vl0) || \
31          (AACDECODER_LIB_VL0 == vl0 && AACDECODER_LIB_VL1 >= vl1)))
32
33 #if !FDKDEC_VER_AT_LEAST(2, 5) // < 2.5.10
34 #define AAC_PCM_MAX_OUTPUT_CHANNELS AAC_PCM_OUTPUT_CHANNELS
35 #endif
36
37 enum ConcealMethod {
38     CONCEAL_METHOD_SPECTRAL_MUTING      =  0,
39     CONCEAL_METHOD_NOISE_SUBSTITUTION   =  1,
40     CONCEAL_METHOD_ENERGY_INTERPOLATION =  2,
41     CONCEAL_METHOD_NB,
42 };
43
44 typedef struct FDKAACDecContext {
45     const AVClass *class;
46     HANDLE_AACDECODER handle;
47     uint8_t *decoder_buffer;
48     int decoder_buffer_size;
49     uint8_t *anc_buffer;
50     int conceal_method;
51     int drc_level;
52     int drc_boost;
53     int drc_heavy;
54     int drc_effect;
55     int drc_cut;
56     int level_limit;
57 } FDKAACDecContext;
58
59
60 #define DMX_ANC_BUFFSIZE       128
61 #define DECODER_MAX_CHANNELS     8
62 #define DECODER_BUFFSIZE      2048 * sizeof(INT_PCM)
63
64 #define OFFSET(x) offsetof(FDKAACDecContext, x)
65 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
66 static const AVOption fdk_aac_dec_options[] = {
67     { "conceal", "Error concealment method", OFFSET(conceal_method), AV_OPT_TYPE_INT, { .i64 = CONCEAL_METHOD_NOISE_SUBSTITUTION }, CONCEAL_METHOD_SPECTRAL_MUTING, CONCEAL_METHOD_NB - 1, AD, "conceal" },
68     { "spectral", "Spectral muting",      0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_SPECTRAL_MUTING },      INT_MIN, INT_MAX, AD, "conceal" },
69     { "noise",    "Noise Substitution",   0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_NOISE_SUBSTITUTION },   INT_MIN, INT_MAX, AD, "conceal" },
70     { "energy",   "Energy Interpolation", 0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_ENERGY_INTERPOLATION }, INT_MIN, INT_MAX, AD, "conceal" },
71     { "drc_boost", "Dynamic Range Control: boost, where [0] is none and [127] is max boost",
72                      OFFSET(drc_boost),      AV_OPT_TYPE_INT,   { .i64 = -1 }, -1, 127, AD, NULL    },
73     { "drc_cut",   "Dynamic Range Control: attenuation factor, where [0] is none and [127] is max compression",
74                      OFFSET(drc_cut),        AV_OPT_TYPE_INT,   { .i64 = -1 }, -1, 127, AD, NULL    },
75     { "drc_level", "Dynamic Range Control: reference level, quantized to 0.25dB steps where [0] is 0dB and [127] is -31.75dB",
76                      OFFSET(drc_level),      AV_OPT_TYPE_INT,   { .i64 = -1},  -1, 127, AD, NULL    },
77     { "drc_heavy", "Dynamic Range Control: heavy compression, where [1] is on (RF mode) and [0] is off",
78                      OFFSET(drc_heavy),      AV_OPT_TYPE_INT,   { .i64 = -1},  -1, 1,   AD, NULL    },
79 #if FDKDEC_VER_AT_LEAST(2, 5) // 2.5.10
80     { "level_limit", "Signal level limiting", OFFSET(level_limit), AV_OPT_TYPE_INT, { .i64 = 0 }, -1, 1, AD },
81 #endif
82 #if FDKDEC_VER_AT_LEAST(3, 0) // 3.0.0
83     { "drc_effect","Dynamic Range Control: effect type, where e.g. [0] is none and [6] is general",
84                      OFFSET(drc_effect),     AV_OPT_TYPE_INT,   { .i64 = -1},  -1, 8,   AD, NULL    },
85 #endif
86     { NULL }
87 };
88
89 static const AVClass fdk_aac_dec_class = {
90     .class_name = "libfdk-aac decoder",
91     .item_name  = av_default_item_name,
92     .option     = fdk_aac_dec_options,
93     .version    = LIBAVUTIL_VERSION_INT,
94 };
95
96 static int get_stream_info(AVCodecContext *avctx)
97 {
98     FDKAACDecContext *s   = avctx->priv_data;
99     CStreamInfo *info     = aacDecoder_GetStreamInfo(s->handle);
100     int channel_counts[0x24] = { 0 };
101     int i, ch_error       = 0;
102     uint64_t ch_layout    = 0;
103
104     if (!info) {
105         av_log(avctx, AV_LOG_ERROR, "Unable to get stream info\n");
106         return AVERROR_UNKNOWN;
107     }
108
109     if (info->sampleRate <= 0) {
110         av_log(avctx, AV_LOG_ERROR, "Stream info not initialized\n");
111         return AVERROR_UNKNOWN;
112     }
113     avctx->sample_rate = info->sampleRate;
114     avctx->frame_size  = info->frameSize;
115
116     for (i = 0; i < info->numChannels; i++) {
117         AUDIO_CHANNEL_TYPE ctype = info->pChannelType[i];
118         if (ctype <= ACT_NONE || ctype >= FF_ARRAY_ELEMS(channel_counts)) {
119             av_log(avctx, AV_LOG_WARNING, "unknown channel type\n");
120             break;
121         }
122         channel_counts[ctype]++;
123     }
124     av_log(avctx, AV_LOG_DEBUG,
125            "%d channels - front:%d side:%d back:%d lfe:%d top:%d\n",
126            info->numChannels,
127            channel_counts[ACT_FRONT], channel_counts[ACT_SIDE],
128            channel_counts[ACT_BACK],  channel_counts[ACT_LFE],
129            channel_counts[ACT_FRONT_TOP] + channel_counts[ACT_SIDE_TOP] +
130            channel_counts[ACT_BACK_TOP]  + channel_counts[ACT_TOP]);
131
132     switch (channel_counts[ACT_FRONT]) {
133     case 4:
134         ch_layout |= AV_CH_LAYOUT_STEREO | AV_CH_FRONT_LEFT_OF_CENTER |
135                      AV_CH_FRONT_RIGHT_OF_CENTER;
136         break;
137     case 3:
138         ch_layout |= AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER;
139         break;
140     case 2:
141         ch_layout |= AV_CH_LAYOUT_STEREO;
142         break;
143     case 1:
144         ch_layout |= AV_CH_FRONT_CENTER;
145         break;
146     default:
147         av_log(avctx, AV_LOG_WARNING,
148                "unsupported number of front channels: %d\n",
149                channel_counts[ACT_FRONT]);
150         ch_error = 1;
151         break;
152     }
153     if (channel_counts[ACT_SIDE] > 0) {
154         if (channel_counts[ACT_SIDE] == 2) {
155             ch_layout |= AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT;
156         } else {
157             av_log(avctx, AV_LOG_WARNING,
158                    "unsupported number of side channels: %d\n",
159                    channel_counts[ACT_SIDE]);
160             ch_error = 1;
161         }
162     }
163     if (channel_counts[ACT_BACK] > 0) {
164         switch (channel_counts[ACT_BACK]) {
165         case 3:
166             ch_layout |= AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT | AV_CH_BACK_CENTER;
167             break;
168         case 2:
169             ch_layout |= AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT;
170             break;
171         case 1:
172             ch_layout |= AV_CH_BACK_CENTER;
173             break;
174         default:
175             av_log(avctx, AV_LOG_WARNING,
176                    "unsupported number of back channels: %d\n",
177                    channel_counts[ACT_BACK]);
178             ch_error = 1;
179             break;
180         }
181     }
182     if (channel_counts[ACT_LFE] > 0) {
183         if (channel_counts[ACT_LFE] == 1) {
184             ch_layout |= AV_CH_LOW_FREQUENCY;
185         } else {
186             av_log(avctx, AV_LOG_WARNING,
187                    "unsupported number of LFE channels: %d\n",
188                    channel_counts[ACT_LFE]);
189             ch_error = 1;
190         }
191     }
192     if (!ch_error &&
193         av_get_channel_layout_nb_channels(ch_layout) != info->numChannels) {
194         av_log(avctx, AV_LOG_WARNING, "unsupported channel configuration\n");
195         ch_error = 1;
196     }
197     if (ch_error)
198         avctx->channel_layout = 0;
199     else
200         avctx->channel_layout = ch_layout;
201
202     avctx->channels = info->numChannels;
203
204     return 0;
205 }
206
207 static av_cold int fdk_aac_decode_close(AVCodecContext *avctx)
208 {
209     FDKAACDecContext *s = avctx->priv_data;
210
211     if (s->handle)
212         aacDecoder_Close(s->handle);
213     av_freep(&s->decoder_buffer);
214     av_freep(&s->anc_buffer);
215
216     return 0;
217 }
218
219 static av_cold int fdk_aac_decode_init(AVCodecContext *avctx)
220 {
221     FDKAACDecContext *s = avctx->priv_data;
222     AAC_DECODER_ERROR err;
223
224     s->handle = aacDecoder_Open(avctx->extradata_size ? TT_MP4_RAW : TT_MP4_ADTS, 1);
225     if (!s->handle) {
226         av_log(avctx, AV_LOG_ERROR, "Error opening decoder\n");
227         return AVERROR_UNKNOWN;
228     }
229
230     if (avctx->extradata_size) {
231         if ((err = aacDecoder_ConfigRaw(s->handle, &avctx->extradata,
232                                         &avctx->extradata_size)) != AAC_DEC_OK) {
233             av_log(avctx, AV_LOG_ERROR, "Unable to set extradata\n");
234             return AVERROR_INVALIDDATA;
235         }
236     }
237
238     if ((err = aacDecoder_SetParam(s->handle, AAC_CONCEAL_METHOD,
239                                    s->conceal_method)) != AAC_DEC_OK) {
240         av_log(avctx, AV_LOG_ERROR, "Unable to set error concealment method\n");
241         return AVERROR_UNKNOWN;
242     }
243
244     if (avctx->request_channel_layout > 0 &&
245         avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE) {
246         int downmix_channels = -1;
247
248         switch (avctx->request_channel_layout) {
249         case AV_CH_LAYOUT_STEREO:
250         case AV_CH_LAYOUT_STEREO_DOWNMIX:
251             downmix_channels = 2;
252             break;
253         case AV_CH_LAYOUT_MONO:
254             downmix_channels = 1;
255             break;
256         default:
257             av_log(avctx, AV_LOG_WARNING, "Invalid request_channel_layout\n");
258             break;
259         }
260
261         if (downmix_channels != -1) {
262             if (aacDecoder_SetParam(s->handle, AAC_PCM_MAX_OUTPUT_CHANNELS,
263                                     downmix_channels) != AAC_DEC_OK) {
264                av_log(avctx, AV_LOG_WARNING, "Unable to set output channels in the decoder\n");
265             } else {
266                s->anc_buffer = av_malloc(DMX_ANC_BUFFSIZE);
267                if (!s->anc_buffer) {
268                    av_log(avctx, AV_LOG_ERROR, "Unable to allocate ancillary buffer for the decoder\n");
269                    return AVERROR(ENOMEM);
270                }
271                if (aacDecoder_AncDataInit(s->handle, s->anc_buffer, DMX_ANC_BUFFSIZE)) {
272                    av_log(avctx, AV_LOG_ERROR, "Unable to register downmix ancillary buffer in the decoder\n");
273                    return AVERROR_UNKNOWN;
274                }
275             }
276         }
277     }
278
279     if (s->drc_boost != -1) {
280         if (aacDecoder_SetParam(s->handle, AAC_DRC_BOOST_FACTOR, s->drc_boost) != AAC_DEC_OK) {
281             av_log(avctx, AV_LOG_ERROR, "Unable to set DRC boost factor in the decoder\n");
282             return AVERROR_UNKNOWN;
283         }
284     }
285
286     if (s->drc_cut != -1) {
287         if (aacDecoder_SetParam(s->handle, AAC_DRC_ATTENUATION_FACTOR, s->drc_cut) != AAC_DEC_OK) {
288             av_log(avctx, AV_LOG_ERROR, "Unable to set DRC attenuation factor in the decoder\n");
289             return AVERROR_UNKNOWN;
290         }
291     }
292
293     if (s->drc_level != -1) {
294         if (aacDecoder_SetParam(s->handle, AAC_DRC_REFERENCE_LEVEL, s->drc_level) != AAC_DEC_OK) {
295             av_log(avctx, AV_LOG_ERROR, "Unable to set DRC reference level in the decoder\n");
296             return AVERROR_UNKNOWN;
297         }
298     }
299
300     if (s->drc_heavy != -1) {
301         if (aacDecoder_SetParam(s->handle, AAC_DRC_HEAVY_COMPRESSION, s->drc_heavy) != AAC_DEC_OK) {
302             av_log(avctx, AV_LOG_ERROR, "Unable to set DRC heavy compression in the decoder\n");
303             return AVERROR_UNKNOWN;
304         }
305     }
306
307 #if FDKDEC_VER_AT_LEAST(2, 5) // 2.5.10
308     if (aacDecoder_SetParam(s->handle, AAC_PCM_LIMITER_ENABLE, s->level_limit) != AAC_DEC_OK) {
309         av_log(avctx, AV_LOG_ERROR, "Unable to set in signal level limiting in the decoder\n");
310         return AVERROR_UNKNOWN;
311     }
312 #endif
313
314 #if FDKDEC_VER_AT_LEAST(3, 0) // 3.0.0
315     if (s->drc_effect != -1) {
316         if (aacDecoder_SetParam(s->handle, AAC_UNIDRC_SET_EFFECT, s->drc_effect) != AAC_DEC_OK) {
317             av_log(avctx, AV_LOG_ERROR, "Unable to set DRC effect type in the decoder\n");
318             return AVERROR_UNKNOWN;
319         }
320     }
321 #endif
322
323     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
324
325     s->decoder_buffer_size = DECODER_BUFFSIZE * DECODER_MAX_CHANNELS;
326     s->decoder_buffer = av_malloc(s->decoder_buffer_size);
327     if (!s->decoder_buffer)
328         return AVERROR(ENOMEM);
329
330     return 0;
331 }
332
333 static int fdk_aac_decode_frame(AVCodecContext *avctx, void *data,
334                                 int *got_frame_ptr, AVPacket *avpkt)
335 {
336     FDKAACDecContext *s = avctx->priv_data;
337     AVFrame *frame = data;
338     int ret;
339     AAC_DECODER_ERROR err;
340     UINT valid = avpkt->size;
341
342     err = aacDecoder_Fill(s->handle, &avpkt->data, &avpkt->size, &valid);
343     if (err != AAC_DEC_OK) {
344         av_log(avctx, AV_LOG_ERROR, "aacDecoder_Fill() failed: %x\n", err);
345         return AVERROR_INVALIDDATA;
346     }
347
348     err = aacDecoder_DecodeFrame(s->handle, (INT_PCM *) s->decoder_buffer, s->decoder_buffer_size / sizeof(INT_PCM), 0);
349     if (err == AAC_DEC_NOT_ENOUGH_BITS) {
350         ret = avpkt->size - valid;
351         goto end;
352     }
353     if (err != AAC_DEC_OK) {
354         av_log(avctx, AV_LOG_ERROR,
355                "aacDecoder_DecodeFrame() failed: %x\n", err);
356         ret = AVERROR_UNKNOWN;
357         goto end;
358     }
359
360     if ((ret = get_stream_info(avctx)) < 0)
361         goto end;
362     frame->nb_samples = avctx->frame_size;
363
364     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
365         goto end;
366
367     memcpy(frame->extended_data[0], s->decoder_buffer,
368            avctx->channels * avctx->frame_size *
369            av_get_bytes_per_sample(avctx->sample_fmt));
370
371     *got_frame_ptr = 1;
372     ret = avpkt->size - valid;
373
374 end:
375     return ret;
376 }
377
378 static av_cold void fdk_aac_decode_flush(AVCodecContext *avctx)
379 {
380     FDKAACDecContext *s = avctx->priv_data;
381     AAC_DECODER_ERROR err;
382
383     if (!s->handle)
384         return;
385
386     if ((err = aacDecoder_SetParam(s->handle,
387                                    AAC_TPDEC_CLEAR_BUFFER, 1)) != AAC_DEC_OK)
388         av_log(avctx, AV_LOG_WARNING, "failed to clear buffer when flushing\n");
389 }
390
391 AVCodec ff_libfdk_aac_decoder = {
392     .name           = "libfdk_aac",
393     .long_name      = NULL_IF_CONFIG_SMALL("Fraunhofer FDK AAC"),
394     .type           = AVMEDIA_TYPE_AUDIO,
395     .id             = AV_CODEC_ID_AAC,
396     .priv_data_size = sizeof(FDKAACDecContext),
397     .init           = fdk_aac_decode_init,
398     .decode         = fdk_aac_decode_frame,
399     .close          = fdk_aac_decode_close,
400     .flush          = fdk_aac_decode_flush,
401     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_CHANNEL_CONF,
402     .priv_class     = &fdk_aac_dec_class,
403     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
404                       FF_CODEC_CAP_INIT_CLEANUP,
405     .wrapper_name   = "libfdk",
406 };