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