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