]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_amerge.c
lavfi/drawbox: reindent after previous commit
[ffmpeg] / libavfilter / af_amerge.c
1 /*
2  * Copyright (c) 2011 Nicolas George <nicolas.george@normalesup.org>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Audio merging filter
24  */
25
26 #include "libavutil/audioconvert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/bprint.h"
29 #include "libavutil/opt.h"
30 #include "libswresample/swresample.h" // only for SWR_CH_MAX
31 #include "avfilter.h"
32 #include "audio.h"
33 #include "bufferqueue.h"
34 #include "internal.h"
35
36 typedef struct {
37     const AVClass *class;
38     int nb_inputs;
39     int route[SWR_CH_MAX]; /**< channels routing, see copy_samples */
40     int bps;
41     struct amerge_input {
42         struct FFBufQueue queue;
43         int nb_ch;         /**< number of channels for the input */
44         int nb_samples;
45         int pos;
46     } *in;
47 } AMergeContext;
48
49 #define OFFSET(x) offsetof(AMergeContext, x)
50 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
51
52 static const AVOption amerge_options[] = {
53     { "inputs", "specify the number of inputs", OFFSET(nb_inputs),
54       AV_OPT_TYPE_INT, { .i64 = 2 }, 2, SWR_CH_MAX, FLAGS },
55     {0}
56 };
57
58 AVFILTER_DEFINE_CLASS(amerge);
59
60 static av_cold void uninit(AVFilterContext *ctx)
61 {
62     AMergeContext *am = ctx->priv;
63     int i;
64
65     for (i = 0; i < am->nb_inputs; i++) {
66         ff_bufqueue_discard_all(&am->in[i].queue);
67         av_freep(&ctx->input_pads[i].name);
68     }
69     av_freep(&am->in);
70 }
71
72 static int query_formats(AVFilterContext *ctx)
73 {
74     AMergeContext *am = ctx->priv;
75     int64_t inlayout[SWR_CH_MAX], outlayout = 0;
76     AVFilterFormats *formats;
77     AVFilterChannelLayouts *layouts;
78     int i, overlap = 0, nb_ch = 0;
79
80     for (i = 0; i < am->nb_inputs; i++) {
81         if (!ctx->inputs[i]->in_channel_layouts ||
82             !ctx->inputs[i]->in_channel_layouts->nb_channel_layouts) {
83             av_log(ctx, AV_LOG_ERROR,
84                    "No channel layout for input %d\n", i + 1);
85             return AVERROR(EINVAL);
86         }
87         inlayout[i] = ctx->inputs[i]->in_channel_layouts->channel_layouts[0];
88         if (ctx->inputs[i]->in_channel_layouts->nb_channel_layouts > 1) {
89             char buf[256];
90             av_get_channel_layout_string(buf, sizeof(buf), 0, inlayout[i]);
91             av_log(ctx, AV_LOG_INFO, "Using \"%s\" for input %d\n", buf, i + 1);
92         }
93         am->in[i].nb_ch = av_get_channel_layout_nb_channels(inlayout[i]);
94         if (outlayout & inlayout[i])
95             overlap++;
96         outlayout |= inlayout[i];
97         nb_ch += am->in[i].nb_ch;
98     }
99     if (nb_ch > SWR_CH_MAX) {
100         av_log(ctx, AV_LOG_ERROR, "Too many channels (max %d)\n", SWR_CH_MAX);
101         return AVERROR(EINVAL);
102     }
103     if (overlap) {
104         av_log(ctx, AV_LOG_WARNING,
105                "Input channel layouts overlap: "
106                "output layout will be determined by the number of distinct input channels\n");
107         for (i = 0; i < nb_ch; i++)
108             am->route[i] = i;
109         outlayout = av_get_default_channel_layout(nb_ch);
110         if (!outlayout)
111             outlayout = ((int64_t)1 << nb_ch) - 1;
112     } else {
113         int *route[SWR_CH_MAX];
114         int c, out_ch_number = 0;
115
116         route[0] = am->route;
117         for (i = 1; i < am->nb_inputs; i++)
118             route[i] = route[i - 1] + am->in[i - 1].nb_ch;
119         for (c = 0; c < 64; c++)
120             for (i = 0; i < am->nb_inputs; i++)
121                 if ((inlayout[i] >> c) & 1)
122                     *(route[i]++) = out_ch_number++;
123     }
124     formats = ff_make_format_list(ff_packed_sample_fmts_array);
125     ff_set_common_formats(ctx, formats);
126     for (i = 0; i < am->nb_inputs; i++) {
127         layouts = NULL;
128         ff_add_channel_layout(&layouts, inlayout[i]);
129         ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts);
130     }
131     layouts = NULL;
132     ff_add_channel_layout(&layouts, outlayout);
133     ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
134     ff_set_common_samplerates(ctx, ff_all_samplerates());
135     return 0;
136 }
137
138 static int config_output(AVFilterLink *outlink)
139 {
140     AVFilterContext *ctx = outlink->src;
141     AMergeContext *am = ctx->priv;
142     AVBPrint bp;
143     int i;
144
145     for (i = 1; i < am->nb_inputs; i++) {
146         if (ctx->inputs[i]->sample_rate != ctx->inputs[0]->sample_rate) {
147             av_log(ctx, AV_LOG_ERROR,
148                    "Inputs must have the same sample rate "
149                    "%d for in%d vs %d\n",
150                    ctx->inputs[i]->sample_rate, i, ctx->inputs[0]->sample_rate);
151             return AVERROR(EINVAL);
152         }
153     }
154     am->bps = av_get_bytes_per_sample(ctx->outputs[0]->format);
155     outlink->sample_rate = ctx->inputs[0]->sample_rate;
156     outlink->time_base   = ctx->inputs[0]->time_base;
157
158     av_bprint_init(&bp, 0, 1);
159     for (i = 0; i < am->nb_inputs; i++) {
160         av_bprintf(&bp, "%sin%d:", i ? " + " : "", i);
161         av_bprint_channel_layout(&bp, -1, ctx->inputs[i]->channel_layout);
162     }
163     av_bprintf(&bp, " -> out:");
164     av_bprint_channel_layout(&bp, -1, ctx->outputs[0]->channel_layout);
165     av_log(ctx, AV_LOG_VERBOSE, "%s\n", bp.str);
166
167     return 0;
168 }
169
170 static int request_frame(AVFilterLink *outlink)
171 {
172     AVFilterContext *ctx = outlink->src;
173     AMergeContext *am = ctx->priv;
174     int i, ret;
175
176     for (i = 0; i < am->nb_inputs; i++)
177         if (!am->in[i].nb_samples)
178             if ((ret = ff_request_frame(ctx->inputs[i])) < 0)
179                 return ret;
180     return 0;
181 }
182
183 /**
184  * Copy samples from several input streams to one output stream.
185  * @param nb_inputs number of inputs
186  * @param in        inputs; used only for the nb_ch field;
187  * @param route     routing values;
188  *                  input channel i goes to output channel route[i];
189  *                  i <  in[0].nb_ch are the channels from the first output;
190  *                  i >= in[0].nb_ch are the channels from the second output
191  * @param ins       pointer to the samples of each inputs, in packed format;
192  *                  will be left at the end of the copied samples
193  * @param outs      pointer to the samples of the output, in packet format;
194  *                  must point to a buffer big enough;
195  *                  will be left at the end of the copied samples
196  * @param ns        number of samples to copy
197  * @param bps       bytes per sample
198  */
199 static inline void copy_samples(int nb_inputs, struct amerge_input in[],
200                                 int *route, uint8_t *ins[],
201                                 uint8_t **outs, int ns, int bps)
202 {
203     int *route_cur;
204     int i, c, nb_ch = 0;
205
206     for (i = 0; i < nb_inputs; i++)
207         nb_ch += in[i].nb_ch;
208     while (ns--) {
209         route_cur = route;
210         for (i = 0; i < nb_inputs; i++) {
211             for (c = 0; c < in[i].nb_ch; c++) {
212                 memcpy((*outs) + bps * *(route_cur++), ins[i], bps);
213                 ins[i] += bps;
214             }
215         }
216         *outs += nb_ch * bps;
217     }
218 }
219
220 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
221 {
222     AVFilterContext *ctx = inlink->dst;
223     AMergeContext *am = ctx->priv;
224     AVFilterLink *const outlink = ctx->outputs[0];
225     int input_number;
226     int nb_samples, ns, i;
227     AVFilterBufferRef *outbuf, *inbuf[SWR_CH_MAX];
228     uint8_t *ins[SWR_CH_MAX], *outs;
229
230     for (input_number = 0; input_number < am->nb_inputs; input_number++)
231         if (inlink == ctx->inputs[input_number])
232             break;
233     av_assert1(input_number < am->nb_inputs);
234     ff_bufqueue_add(ctx, &am->in[input_number].queue, insamples);
235     am->in[input_number].nb_samples += insamples->audio->nb_samples;
236     nb_samples = am->in[0].nb_samples;
237     for (i = 1; i < am->nb_inputs; i++)
238         nb_samples = FFMIN(nb_samples, am->in[i].nb_samples);
239     if (!nb_samples)
240         return 0;
241
242     outbuf = ff_get_audio_buffer(ctx->outputs[0], AV_PERM_WRITE, nb_samples);
243     outs = outbuf->data[0];
244     for (i = 0; i < am->nb_inputs; i++) {
245         inbuf[i] = ff_bufqueue_peek(&am->in[i].queue, 0);
246         ins[i] = inbuf[i]->data[0] +
247                  am->in[i].pos * am->in[i].nb_ch * am->bps;
248     }
249     avfilter_copy_buffer_ref_props(outbuf, inbuf[0]);
250     outbuf->pts = inbuf[0]->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
251                   inbuf[0]->pts +
252                   av_rescale_q(am->in[0].pos,
253                                (AVRational){ 1, ctx->inputs[0]->sample_rate },
254                                ctx->outputs[0]->time_base);
255
256     outbuf->audio->nb_samples     = nb_samples;
257     outbuf->audio->channel_layout = outlink->channel_layout;
258
259     while (nb_samples) {
260         ns = nb_samples;
261         for (i = 0; i < am->nb_inputs; i++)
262             ns = FFMIN(ns, inbuf[i]->audio->nb_samples - am->in[i].pos);
263         /* Unroll the most common sample formats: speed +~350% for the loop,
264            +~13% overall (including two common decoders) */
265         switch (am->bps) {
266             case 1:
267                 copy_samples(am->nb_inputs, am->in, am->route, ins, &outs, ns, 1);
268                 break;
269             case 2:
270                 copy_samples(am->nb_inputs, am->in, am->route, ins, &outs, ns, 2);
271                 break;
272             case 4:
273                 copy_samples(am->nb_inputs, am->in, am->route, ins, &outs, ns, 4);
274                 break;
275             default:
276                 copy_samples(am->nb_inputs, am->in, am->route, ins, &outs, ns, am->bps);
277                 break;
278         }
279
280         nb_samples -= ns;
281         for (i = 0; i < am->nb_inputs; i++) {
282             am->in[i].nb_samples -= ns;
283             am->in[i].pos += ns;
284             if (am->in[i].pos == inbuf[i]->audio->nb_samples) {
285                 am->in[i].pos = 0;
286                 avfilter_unref_buffer(inbuf[i]);
287                 ff_bufqueue_get(&am->in[i].queue);
288                 inbuf[i] = ff_bufqueue_peek(&am->in[i].queue, 0);
289                 ins[i] = inbuf[i] ? inbuf[i]->data[0] : NULL;
290             }
291         }
292     }
293     return ff_filter_samples(ctx->outputs[0], outbuf);
294 }
295
296 static av_cold int init(AVFilterContext *ctx, const char *args)
297 {
298     AMergeContext *am = ctx->priv;
299     int ret, i;
300
301     am->class = &amerge_class;
302     av_opt_set_defaults(am);
303     ret = av_set_options_string(am, args, "=", ":");
304     if (ret < 0) {
305         av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
306         return ret;
307     }
308     am->in = av_calloc(am->nb_inputs, sizeof(*am->in));
309     if (!am->in)
310         return AVERROR(ENOMEM);
311     for (i = 0; i < am->nb_inputs; i++) {
312         char *name = av_asprintf("in%d", i);
313         AVFilterPad pad = {
314             .name             = name,
315             .type             = AVMEDIA_TYPE_AUDIO,
316             .filter_samples   = filter_samples,
317             .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
318         };
319         if (!name)
320             return AVERROR(ENOMEM);
321         ff_insert_inpad(ctx, i, &pad);
322     }
323     return 0;
324 }
325
326 AVFilter avfilter_af_amerge = {
327     .name          = "amerge",
328     .description   = NULL_IF_CONFIG_SMALL("Merge two audio streams into "
329                                           "a single multi-channel stream."),
330     .priv_size     = sizeof(AMergeContext),
331     .init          = init,
332     .uninit        = uninit,
333     .query_formats = query_formats,
334
335     .inputs    = (const AVFilterPad[]) { { .name = NULL } },
336     .outputs   = (const AVFilterPad[]) {
337         { .name             = "default",
338           .type             = AVMEDIA_TYPE_AUDIO,
339           .config_props     = config_output,
340           .request_frame    = request_frame, },
341         { .name = NULL }
342     },
343     .priv_class = &amerge_class,
344 };