]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_aconvert.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / af_aconvert.c
1 /*
2  * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram <smeenaks@ucsd.edu>
3  * Copyright (c) 2011 Stefano Sabatini
4  * Copyright (c) 2011 Mina Nagy Zaki
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * sample format and channel layout conversion audio filter
26  * based on code in libavcodec/resample.c by Fabrice Bellard and
27  * libavcodec/audioconvert.c by Michael Niedermayer
28  */
29
30 #include "libavutil/audioconvert.h"
31 #include "libavutil/avstring.h"
32 #include "libavcodec/audioconvert.h"
33 #include "avfilter.h"
34 #include "internal.h"
35
36 typedef struct {
37     enum AVSampleFormat  out_sample_fmt,  in_sample_fmt;   ///< in/out sample formats
38     int64_t              out_chlayout,    in_chlayout;     ///< in/out channel layout
39     int                  out_nb_channels, in_nb_channels;  ///< number of in/output channels
40     enum AVFilterPacking out_packing_fmt, in_packing_fmt;  ///< output packing format
41
42     int max_nb_samples;                     ///< maximum number of buffered samples
43     AVFilterBufferRef *mix_samplesref;      ///< rematrixed buffer
44     AVFilterBufferRef *out_samplesref;      ///< output buffer after required conversions
45
46     uint8_t *in_mix[8], *out_mix[8];        ///< input/output for rematrixing functions
47     uint8_t *packed_data[8];                ///< pointers for packing conversion
48     int out_strides[8], in_strides[8];      ///< input/output strides for av_audio_convert
49     uint8_t **in_conv, **out_conv;          ///< input/output for av_audio_convert
50
51     AVAudioConvert *audioconvert_ctx;       ///< context for conversion to output sample format
52
53     void (*convert_chlayout)();             ///< function to do the requested rematrixing
54 } AConvertContext;
55
56 #define REMATRIX_FUNC_SIG(NAME) static void REMATRIX_FUNC_NAME(NAME) \
57     (FMT_TYPE *outp[], FMT_TYPE *inp[], int nb_samples, AConvertContext *aconvert)
58
59 #define FMT_TYPE uint8_t
60 #define REMATRIX_FUNC_NAME(NAME) NAME ## _u8
61 #include "af_aconvert_rematrix.c"
62
63 #define FMT_TYPE int16_t
64 #define REMATRIX_FUNC_NAME(NAME) NAME ## _s16
65 #include "af_aconvert_rematrix.c"
66
67 #define FMT_TYPE int32_t
68 #define REMATRIX_FUNC_NAME(NAME) NAME ## _s32
69 #include "af_aconvert_rematrix.c"
70
71 #define FLOATING
72
73 #define FMT_TYPE float
74 #define REMATRIX_FUNC_NAME(NAME) NAME ## _flt
75 #include "af_aconvert_rematrix.c"
76
77 #define FMT_TYPE double
78 #define REMATRIX_FUNC_NAME(NAME) NAME ## _dbl
79 #include "af_aconvert_rematrix.c"
80
81 #define FMT_TYPE uint8_t
82 #define REMATRIX_FUNC_NAME(NAME) NAME
83 REMATRIX_FUNC_SIG(stereo_remix_planar)
84 {
85     int size = av_get_bytes_per_sample(aconvert->in_sample_fmt) * nb_samples;
86
87     memcpy(outp[0], inp[0], size);
88     memcpy(outp[1], inp[aconvert->in_nb_channels == 1 ? 0 : 1], size);
89 }
90
91 #define REGISTER_FUNC_PACKING(INCHLAYOUT, OUTCHLAYOUT, FUNC, PACKING)   \
92     {INCHLAYOUT, OUTCHLAYOUT, PACKING, AV_SAMPLE_FMT_U8,  FUNC##_u8},   \
93     {INCHLAYOUT, OUTCHLAYOUT, PACKING, AV_SAMPLE_FMT_S16, FUNC##_s16},  \
94     {INCHLAYOUT, OUTCHLAYOUT, PACKING, AV_SAMPLE_FMT_S32, FUNC##_s32},  \
95     {INCHLAYOUT, OUTCHLAYOUT, PACKING, AV_SAMPLE_FMT_FLT, FUNC##_flt},  \
96     {INCHLAYOUT, OUTCHLAYOUT, PACKING, AV_SAMPLE_FMT_DBL, FUNC##_dbl},
97
98 #define REGISTER_FUNC(INCHLAYOUT, OUTCHLAYOUT, FUNC)                                \
99     REGISTER_FUNC_PACKING(INCHLAYOUT, OUTCHLAYOUT, FUNC##_packed, AVFILTER_PACKED)  \
100     REGISTER_FUNC_PACKING(INCHLAYOUT, OUTCHLAYOUT, FUNC##_planar, AVFILTER_PLANAR)
101
102 static const struct RematrixFunctionInfo {
103     int64_t in_chlayout, out_chlayout;
104     int planar, sfmt;
105     void (*func)();
106 } rematrix_funcs[] = {
107     REGISTER_FUNC        (AV_CH_LAYOUT_STEREO,  AV_CH_LAYOUT_5POINT1, stereo_to_surround_5p1)
108     REGISTER_FUNC        (AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_STEREO,  surround_5p1_to_stereo)
109     REGISTER_FUNC_PACKING(AV_CH_LAYOUT_STEREO,  AV_CH_LAYOUT_MONO,    stereo_to_mono_packed, AVFILTER_PACKED)
110     REGISTER_FUNC_PACKING(AV_CH_LAYOUT_MONO,    AV_CH_LAYOUT_STEREO,  mono_to_stereo_packed, AVFILTER_PACKED)
111     REGISTER_FUNC        (0,                    AV_CH_LAYOUT_MONO,    mono_downmix)
112     REGISTER_FUNC_PACKING(0,                    AV_CH_LAYOUT_STEREO,  stereo_downmix_packed, AVFILTER_PACKED)
113
114     // This function works for all sample formats
115     {0, AV_CH_LAYOUT_STEREO, AVFILTER_PLANAR, -1, stereo_remix_planar}
116 };
117
118 static av_cold int init(AVFilterContext *ctx, const char *args0, void *opaque)
119 {
120     AConvertContext *aconvert = ctx->priv;
121     char *arg, *ptr = NULL;
122     int ret = 0;
123     char *args = av_strdup(args0);
124
125     aconvert->out_sample_fmt  = AV_SAMPLE_FMT_NONE;
126     aconvert->out_chlayout    = 0;
127     aconvert->out_packing_fmt = -1;
128
129     if ((arg = av_strtok(args, ":", &ptr)) && strcmp(arg, "auto")) {
130         if ((ret = ff_parse_sample_format(&aconvert->out_sample_fmt, arg, ctx)) < 0)
131             goto end;
132     }
133     if ((arg = av_strtok(NULL, ":", &ptr)) && strcmp(arg, "auto")) {
134         if ((ret = ff_parse_channel_layout(&aconvert->out_chlayout, arg, ctx)) < 0)
135             goto end;
136     }
137     if ((arg = av_strtok(NULL, ":", &ptr)) && strcmp(arg, "auto")) {
138         if ((ret = ff_parse_packing_format((int *)&aconvert->out_packing_fmt, arg, ctx)) < 0)
139             goto end;
140     }
141
142 end:
143     av_freep(&args);
144     return ret;
145 }
146
147 static av_cold void uninit(AVFilterContext *ctx)
148 {
149     AConvertContext *aconvert = ctx->priv;
150     avfilter_unref_buffer(aconvert->mix_samplesref);
151     avfilter_unref_buffer(aconvert->out_samplesref);
152     if (aconvert->audioconvert_ctx)
153         av_audio_convert_free(aconvert->audioconvert_ctx);
154 }
155
156 static int query_formats(AVFilterContext *ctx)
157 {
158     AVFilterFormats *formats = NULL;
159     AConvertContext *aconvert = ctx->priv;
160     AVFilterLink *inlink  = ctx->inputs[0];
161     AVFilterLink *outlink = ctx->outputs[0];
162
163     avfilter_formats_ref(avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO),
164                          &inlink->out_formats);
165     if (aconvert->out_sample_fmt != AV_SAMPLE_FMT_NONE) {
166         formats = NULL;
167         avfilter_add_format(&formats, aconvert->out_sample_fmt);
168         avfilter_formats_ref(formats, &outlink->in_formats);
169     } else
170         avfilter_formats_ref(avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO),
171                              &outlink->in_formats);
172
173     avfilter_formats_ref(avfilter_make_all_channel_layouts(),
174                          &inlink->out_chlayouts);
175     if (aconvert->out_chlayout != 0) {
176         formats = NULL;
177         avfilter_add_format(&formats, aconvert->out_chlayout);
178         avfilter_formats_ref(formats, &outlink->in_chlayouts);
179     } else
180         avfilter_formats_ref(avfilter_make_all_channel_layouts(),
181                              &outlink->in_chlayouts);
182
183     avfilter_formats_ref(avfilter_make_all_packing_formats(),
184                          &inlink->out_packing);
185     if (aconvert->out_packing_fmt != -1) {
186         formats = NULL;
187         avfilter_add_format(&formats, aconvert->out_packing_fmt);
188         avfilter_formats_ref(formats, &outlink->in_packing);
189     } else
190         avfilter_formats_ref(avfilter_make_all_packing_formats(),
191                              &outlink->in_packing);
192
193     return 0;
194 }
195
196 static int config_output(AVFilterLink *outlink)
197 {
198     AVFilterLink *inlink = outlink->src->inputs[0];
199     AConvertContext *aconvert = outlink->src->priv;
200     char buf1[64], buf2[64];
201
202     aconvert->in_sample_fmt  = inlink->format;
203     aconvert->in_packing_fmt = inlink->planar;
204     if (aconvert->out_packing_fmt == -1)
205         aconvert->out_packing_fmt = outlink->planar;
206     aconvert->in_chlayout    = inlink->channel_layout;
207     aconvert->in_nb_channels =
208         av_get_channel_layout_nb_channels(inlink->channel_layout);
209
210     /* if not specified in args, use the format and layout of the output */
211     if (aconvert->out_sample_fmt == AV_SAMPLE_FMT_NONE)
212         aconvert->out_sample_fmt = outlink->format;
213     if (aconvert->out_chlayout   == 0)
214         aconvert->out_chlayout   = outlink->channel_layout;
215     aconvert->out_nb_channels  =
216         av_get_channel_layout_nb_channels(outlink->channel_layout);
217
218     av_get_channel_layout_string(buf1, sizeof(buf1),
219                                  -1, inlink ->channel_layout);
220     av_get_channel_layout_string(buf2, sizeof(buf2),
221                                  -1, outlink->channel_layout);
222     av_log(outlink->src, AV_LOG_INFO,
223            "fmt:%s cl:%s planar:%i -> fmt:%s cl:%s planar:%i\n",
224            av_get_sample_fmt_name(inlink ->format), buf1, inlink ->planar,
225            av_get_sample_fmt_name(outlink->format), buf2, outlink->planar);
226
227     /* compute which channel layout conversion to use */
228     if (inlink->channel_layout != outlink->channel_layout) {
229         int i;
230         for (i = 0; i < sizeof(rematrix_funcs); i++) {
231             const struct RematrixFunctionInfo *f = &rematrix_funcs[i];
232             if ((f->in_chlayout  == 0 || f->in_chlayout  == inlink ->channel_layout) &&
233                 (f->out_chlayout == 0 || f->out_chlayout == outlink->channel_layout) &&
234                 (f->planar == -1 || f->planar == inlink->planar) &&
235                 (f->sfmt   == -1 || f->sfmt   == inlink->format)
236                ) {
237                 aconvert->convert_chlayout = f->func;
238                 break;
239             }
240         }
241         if (!aconvert->convert_chlayout) {
242             av_log(outlink->src, AV_LOG_ERROR,
243                    "Unsupported channel layout conversion '%s -> %s' requested!\n",
244                    buf1, buf2);
245             return AVERROR(EINVAL);
246         }
247     }
248
249     return 0;
250 }
251
252 static int init_buffers(AVFilterLink *inlink, int nb_samples)
253 {
254     AConvertContext *aconvert = inlink->dst->priv;
255     AVFilterLink * const outlink = inlink->dst->outputs[0];
256     int i, packed_stride = 0;
257     const unsigned
258         packing_conv = inlink->planar != outlink->planar &&
259                        aconvert->out_nb_channels != 1,
260         format_conv  = inlink->format != outlink->format;
261     int nb_channels  = aconvert->out_nb_channels;
262
263     uninit(inlink->dst);
264     aconvert->max_nb_samples = nb_samples;
265
266     if (aconvert->convert_chlayout) {
267         /* allocate buffer for storing intermediary mixing samplesref */
268         uint8_t *data[8];
269         int linesize[8];
270         int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
271
272         if (av_samples_alloc(data, linesize, nb_channels, nb_samples,
273                              inlink->format, inlink->planar, 16) < 0)
274             goto fail_no_mem;
275         aconvert->mix_samplesref =
276             avfilter_get_audio_buffer_ref_from_arrays(data, linesize, AV_PERM_WRITE,
277                                                       nb_samples, inlink->format,
278                                                       outlink->channel_layout,
279                                                       inlink->planar);
280         if (!aconvert->mix_samplesref)
281             goto fail_no_mem;
282     }
283
284     // if there's a format/packing conversion we need an audio_convert context
285     if (format_conv || packing_conv) {
286         aconvert->out_samplesref =
287             avfilter_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
288         if (!aconvert->out_samplesref)
289             goto fail_no_mem;
290
291         aconvert->in_strides [0] = av_get_bytes_per_sample(inlink ->format);
292         aconvert->out_strides[0] = av_get_bytes_per_sample(outlink->format);
293
294         aconvert->out_conv = aconvert->out_samplesref->data;
295         if (aconvert->mix_samplesref)
296             aconvert->in_conv = aconvert->mix_samplesref->data;
297
298         if (packing_conv) {
299             // packed -> planar
300             if (outlink->planar == AVFILTER_PLANAR) {
301                 if (aconvert->mix_samplesref)
302                     aconvert->packed_data[0] = aconvert->mix_samplesref->data[0];
303                 aconvert->in_conv         = aconvert->packed_data;
304                 packed_stride             = aconvert->in_strides[0];
305                 aconvert->in_strides[0]  *= nb_channels;
306             // planar -> packed
307             } else {
308                 aconvert->packed_data[0]  = aconvert->out_samplesref->data[0];
309                 aconvert->out_conv        = aconvert->packed_data;
310                 packed_stride             = aconvert->out_strides[0];
311                 aconvert->out_strides[0] *= nb_channels;
312             }
313         } else if (outlink->planar == AVFILTER_PACKED) {
314             /* If there's no packing conversion, and the stream is packed
315              * then we treat the entire stream as one big channel
316              */
317             nb_channels = 1;
318         }
319
320         for (i = 1; i < nb_channels; i++) {
321             aconvert->packed_data[i] = aconvert->packed_data[i-1] + packed_stride;
322             aconvert->in_strides[i]  = aconvert->in_strides[0];
323             aconvert->out_strides[i] = aconvert->out_strides[0];
324         }
325
326         aconvert->audioconvert_ctx =
327                 av_audio_convert_alloc(outlink->format, nb_channels,
328                                        inlink->format,  nb_channels, NULL, 0);
329         if (!aconvert->audioconvert_ctx)
330             goto fail_no_mem;
331     }
332
333     return 0;
334
335 fail_no_mem:
336     av_log(inlink->dst, AV_LOG_ERROR, "Could not allocate memory.\n");
337     return AVERROR(ENOMEM);
338 }
339
340 static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)
341 {
342     AConvertContext *aconvert = inlink->dst->priv;
343     AVFilterBufferRef *curbuf = insamplesref;
344     AVFilterLink * const outlink = inlink->dst->outputs[0];
345     int chan_mult;
346
347     /* in/reinint the internal buffers if this is the first buffer
348      * provided or it is needed to use a bigger one */
349     if (!aconvert->max_nb_samples ||
350         (curbuf->audio->nb_samples > aconvert->max_nb_samples))
351         if (init_buffers(inlink, curbuf->audio->nb_samples) < 0) {
352             av_log(inlink->dst, AV_LOG_ERROR, "Could not initialize buffers.\n");
353             return;
354         }
355
356     /* if channel mixing is required */
357     if (aconvert->mix_samplesref) {
358         memcpy(aconvert->in_mix,  curbuf->data, sizeof(aconvert->in_mix));
359         memcpy(aconvert->out_mix, aconvert->mix_samplesref->data, sizeof(aconvert->out_mix));
360         aconvert->convert_chlayout(aconvert->out_mix,
361                                    aconvert->in_mix,
362                                    curbuf->audio->nb_samples,
363                                    aconvert);
364         curbuf = aconvert->mix_samplesref;
365     }
366
367     if (aconvert->audioconvert_ctx) {
368         if (!aconvert->mix_samplesref) {
369             if (aconvert->in_conv == aconvert->packed_data) {
370                 int i, packed_stride = av_get_bytes_per_sample(inlink->format);
371                 aconvert->packed_data[0] = curbuf->data[0];
372                 for (i = 1; i < aconvert->out_nb_channels; i++)
373                     aconvert->packed_data[i] = aconvert->packed_data[i-1] + packed_stride;
374             } else {
375                 aconvert->in_conv = curbuf->data;
376             }
377         }
378
379         chan_mult = inlink->planar == outlink->planar && inlink->planar == 0 ?
380             aconvert->out_nb_channels : 1;
381
382         av_audio_convert(aconvert->audioconvert_ctx,
383                          (void * const *) aconvert->out_conv,
384                          aconvert->out_strides,
385                          (const void * const *) aconvert->in_conv,
386                          aconvert->in_strides,
387                          curbuf->audio->nb_samples * chan_mult);
388
389         curbuf = aconvert->out_samplesref;
390     }
391
392     avfilter_copy_buffer_ref_props(curbuf, insamplesref);
393     curbuf->audio->channel_layout = outlink->channel_layout;
394     curbuf->audio->planar         = outlink->planar;
395
396     avfilter_filter_samples(inlink->dst->outputs[0],
397                             avfilter_ref_buffer(curbuf, ~0));
398     avfilter_unref_buffer(insamplesref);
399 }
400
401 AVFilter avfilter_af_aconvert = {
402     .name          = "aconvert",
403     .description   = NULL_IF_CONFIG_SMALL("Convert the input audio to sample_fmt:channel_layout:packed_fmt."),
404     .priv_size     = sizeof(AConvertContext),
405     .init          = init,
406     .uninit        = uninit,
407     .query_formats = query_formats,
408
409     .inputs    = (const AVFilterPad[]) {{ .name      = "default",
410                                     .type            = AVMEDIA_TYPE_AUDIO,
411                                     .filter_samples  = filter_samples,
412                                     .min_perms       = AV_PERM_READ, },
413                                   { .name = NULL}},
414     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
415                                     .type            = AVMEDIA_TYPE_AUDIO,
416                                     .config_props    = config_output, },
417                                   { .name = NULL}},
418 };