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