]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_amerge.c
Merge commit '39f3b6f3fc2b46b405b680cce3599f1b370e342d'
[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 #define FF_INTERNAL_FIELDS 1
27 #include "framequeue.h"
28
29 #include "libavutil/avstring.h"
30 #include "libavutil/bprint.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/opt.h"
33 #include "avfilter.h"
34 #include "filters.h"
35 #include "audio.h"
36 #include "internal.h"
37
38 #define SWR_CH_MAX 64
39
40 typedef struct AMergeContext {
41     const AVClass *class;
42     int nb_inputs;
43     int route[SWR_CH_MAX]; /**< channels routing, see copy_samples */
44     int bps;
45     struct amerge_input {
46         int nb_ch;         /**< number of channels for the input */
47     } *in;
48 } AMergeContext;
49
50 #define OFFSET(x) offsetof(AMergeContext, x)
51 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
52
53 static const AVOption amerge_options[] = {
54     { "inputs", "specify the number of inputs", OFFSET(nb_inputs),
55       AV_OPT_TYPE_INT, { .i64 = 2 }, 1, SWR_CH_MAX, FLAGS },
56     { NULL }
57 };
58
59 AVFILTER_DEFINE_CLASS(amerge);
60
61 static av_cold void uninit(AVFilterContext *ctx)
62 {
63     AMergeContext *s = ctx->priv;
64     int i;
65
66     for (i = 0; i < s->nb_inputs; i++) {
67         if (ctx->input_pads)
68             av_freep(&ctx->input_pads[i].name);
69     }
70     av_freep(&s->in);
71 }
72
73 static int query_formats(AVFilterContext *ctx)
74 {
75     AMergeContext *s = ctx->priv;
76     int64_t inlayout[SWR_CH_MAX], outlayout = 0;
77     AVFilterFormats *formats;
78     AVFilterChannelLayouts *layouts;
79     int i, ret, overlap = 0, nb_ch = 0;
80
81     for (i = 0; i < s->nb_inputs; i++) {
82         if (!ctx->inputs[i]->in_channel_layouts ||
83             !ctx->inputs[i]->in_channel_layouts->nb_channel_layouts) {
84             av_log(ctx, AV_LOG_WARNING,
85                    "No channel layout for input %d\n", i + 1);
86             return AVERROR(EAGAIN);
87         }
88         inlayout[i] = ctx->inputs[i]->in_channel_layouts->channel_layouts[0];
89         if (ctx->inputs[i]->in_channel_layouts->nb_channel_layouts > 1) {
90             char buf[256];
91             av_get_channel_layout_string(buf, sizeof(buf), 0, inlayout[i]);
92             av_log(ctx, AV_LOG_INFO, "Using \"%s\" for input %d\n", buf, i + 1);
93         }
94         s->in[i].nb_ch = FF_LAYOUT2COUNT(inlayout[i]);
95         if (s->in[i].nb_ch) {
96             overlap++;
97         } else {
98             s->in[i].nb_ch = av_get_channel_layout_nb_channels(inlayout[i]);
99             if (outlayout & inlayout[i])
100                 overlap++;
101             outlayout |= inlayout[i];
102         }
103         nb_ch += s->in[i].nb_ch;
104     }
105     if (nb_ch > SWR_CH_MAX) {
106         av_log(ctx, AV_LOG_ERROR, "Too many channels (max %d)\n", SWR_CH_MAX);
107         return AVERROR(EINVAL);
108     }
109     if (overlap) {
110         av_log(ctx, AV_LOG_WARNING,
111                "Input channel layouts overlap: "
112                "output layout will be determined by the number of distinct input channels\n");
113         for (i = 0; i < nb_ch; i++)
114             s->route[i] = i;
115         outlayout = av_get_default_channel_layout(nb_ch);
116         if (!outlayout && nb_ch)
117             outlayout = 0xFFFFFFFFFFFFFFFFULL >> (64 - nb_ch);
118     } else {
119         int *route[SWR_CH_MAX];
120         int c, out_ch_number = 0;
121
122         route[0] = s->route;
123         for (i = 1; i < s->nb_inputs; i++)
124             route[i] = route[i - 1] + s->in[i - 1].nb_ch;
125         for (c = 0; c < 64; c++)
126             for (i = 0; i < s->nb_inputs; i++)
127                 if ((inlayout[i] >> c) & 1)
128                     *(route[i]++) = out_ch_number++;
129     }
130     formats = ff_make_format_list(ff_packed_sample_fmts_array);
131     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
132         return ret;
133     for (i = 0; i < s->nb_inputs; i++) {
134         layouts = NULL;
135         if ((ret = ff_add_channel_layout(&layouts, inlayout[i])) < 0)
136             return ret;
137         if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts)) < 0)
138             return ret;
139     }
140     layouts = NULL;
141     if ((ret = ff_add_channel_layout(&layouts, outlayout)) < 0)
142         return ret;
143     if ((ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
144         return ret;
145
146     return ff_set_common_samplerates(ctx, ff_all_samplerates());
147 }
148
149 static int config_output(AVFilterLink *outlink)
150 {
151     AVFilterContext *ctx = outlink->src;
152     AMergeContext *s = ctx->priv;
153     AVBPrint bp;
154     int i;
155
156     for (i = 1; i < s->nb_inputs; i++) {
157         if (ctx->inputs[i]->sample_rate != ctx->inputs[0]->sample_rate) {
158             av_log(ctx, AV_LOG_ERROR,
159                    "Inputs must have the same sample rate "
160                    "%d for in%d vs %d\n",
161                    ctx->inputs[i]->sample_rate, i, ctx->inputs[0]->sample_rate);
162             return AVERROR(EINVAL);
163         }
164     }
165     s->bps = av_get_bytes_per_sample(ctx->outputs[0]->format);
166     outlink->sample_rate = ctx->inputs[0]->sample_rate;
167     outlink->time_base   = ctx->inputs[0]->time_base;
168
169     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
170     for (i = 0; i < s->nb_inputs; i++) {
171         av_bprintf(&bp, "%sin%d:", i ? " + " : "", i);
172         av_bprint_channel_layout(&bp, -1, ctx->inputs[i]->channel_layout);
173     }
174     av_bprintf(&bp, " -> out:");
175     av_bprint_channel_layout(&bp, -1, ctx->outputs[0]->channel_layout);
176     av_log(ctx, AV_LOG_VERBOSE, "%s\n", bp.str);
177
178     return 0;
179 }
180
181 /**
182  * Copy samples from several input streams to one output stream.
183  * @param nb_inputs number of inputs
184  * @param in        inputs; used only for the nb_ch field;
185  * @param route     routing values;
186  *                  input channel i goes to output channel route[i];
187  *                  i <  in[0].nb_ch are the channels from the first output;
188  *                  i >= in[0].nb_ch are the channels from the second output
189  * @param ins       pointer to the samples of each inputs, in packed format;
190  *                  will be left at the end of the copied samples
191  * @param outs      pointer to the samples of the output, in packet format;
192  *                  must point to a buffer big enough;
193  *                  will be left at the end of the copied samples
194  * @param ns        number of samples to copy
195  * @param bps       bytes per sample
196  */
197 static inline void copy_samples(int nb_inputs, struct amerge_input in[],
198                                 int *route, uint8_t *ins[],
199                                 uint8_t **outs, int ns, int bps)
200 {
201     int *route_cur;
202     int i, c, nb_ch = 0;
203
204     for (i = 0; i < nb_inputs; i++)
205         nb_ch += in[i].nb_ch;
206     while (ns--) {
207         route_cur = route;
208         for (i = 0; i < nb_inputs; i++) {
209             for (c = 0; c < in[i].nb_ch; c++) {
210                 memcpy((*outs) + bps * *(route_cur++), ins[i], bps);
211                 ins[i] += bps;
212             }
213         }
214         *outs += nb_ch * bps;
215     }
216 }
217
218 static void free_frames(int nb_inputs, AVFrame **input_frames)
219 {
220     int i;
221     for (i = 0; i < nb_inputs; i++)
222         av_frame_free(&input_frames[i]);
223 }
224
225 static int try_push_frame(AVFilterContext *ctx, int nb_samples)
226 {
227     AMergeContext *s = ctx->priv;
228     AVFilterLink *outlink = ctx->outputs[0];
229     int i, ret;
230     AVFrame *outbuf, *inbuf[SWR_CH_MAX] = { NULL };
231     uint8_t *outs, *ins[SWR_CH_MAX];
232
233     for (i = 0; i < ctx->nb_inputs; i++) {
234         ret = ff_inlink_consume_samples(ctx->inputs[i], nb_samples, nb_samples, &inbuf[i]);
235         if (ret < 0) {
236             free_frames(i, inbuf);
237             return ret;
238         }
239         ins[i] = inbuf[i]->data[0];
240     }
241
242     outbuf = ff_get_audio_buffer(ctx->outputs[0], nb_samples);
243     if (!outbuf) {
244         free_frames(s->nb_inputs, inbuf);
245         return AVERROR(ENOMEM);
246     }
247
248     outs = outbuf->data[0];
249     outbuf->pts = inbuf[0]->pts;
250
251     outbuf->nb_samples     = nb_samples;
252     outbuf->channel_layout = outlink->channel_layout;
253     outbuf->channels       = outlink->channels;
254
255     while (nb_samples) {
256         /* Unroll the most common sample formats: speed +~350% for the loop,
257            +~13% overall (including two common decoders) */
258         switch (s->bps) {
259             case 1:
260                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, nb_samples, 1);
261                 break;
262             case 2:
263                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, nb_samples, 2);
264                 break;
265             case 4:
266                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, nb_samples, 4);
267                 break;
268             default:
269                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, nb_samples, s->bps);
270                 break;
271         }
272
273         nb_samples = 0;
274     }
275
276     free_frames(s->nb_inputs, inbuf);
277     return ff_filter_frame(ctx->outputs[0], outbuf);
278 }
279
280 static int activate(AVFilterContext *ctx)
281 {
282     int i, status;
283     int ret, nb_samples;
284     int64_t pts;
285
286     FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[0], ctx);
287
288     nb_samples = ff_framequeue_queued_samples(&ctx->inputs[0]->fifo);
289     for (i = 1; i < ctx->nb_inputs && nb_samples > 0; i++) {
290         nb_samples = FFMIN(ff_framequeue_queued_samples(&ctx->inputs[i]->fifo), nb_samples);
291     }
292
293     if (nb_samples) {
294         ret = try_push_frame(ctx, nb_samples);
295         if (ret < 0)
296             return ret;
297     }
298
299     for (i = 0; i < ctx->nb_inputs; i++) {
300         if (ff_framequeue_queued_samples(&ctx->inputs[i]->fifo))
301             continue;
302
303         if (ff_inlink_acknowledge_status(ctx->inputs[i], &status, &pts)) {
304             ff_outlink_set_status(ctx->outputs[0], status, pts);
305             return 0;
306         } else if (ff_outlink_frame_wanted(ctx->outputs[0])) {
307             ff_inlink_request_frame(ctx->inputs[i]);
308             return 0;
309         }
310     }
311
312     return 0;
313 }
314
315 static av_cold int init(AVFilterContext *ctx)
316 {
317     AMergeContext *s = ctx->priv;
318     int i, ret;
319
320     s->in = av_calloc(s->nb_inputs, sizeof(*s->in));
321     if (!s->in)
322         return AVERROR(ENOMEM);
323     for (i = 0; i < s->nb_inputs; i++) {
324         char *name = av_asprintf("in%d", i);
325         AVFilterPad pad = {
326             .name             = name,
327             .type             = AVMEDIA_TYPE_AUDIO,
328         };
329         if (!name)
330             return AVERROR(ENOMEM);
331         if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
332             av_freep(&pad.name);
333             return ret;
334         }
335     }
336     return 0;
337 }
338
339 static const AVFilterPad amerge_outputs[] = {
340     {
341         .name          = "default",
342         .type          = AVMEDIA_TYPE_AUDIO,
343         .config_props  = config_output,
344     },
345     { NULL }
346 };
347
348 AVFilter ff_af_amerge = {
349     .name          = "amerge",
350     .description   = NULL_IF_CONFIG_SMALL("Merge two or more audio streams into "
351                                           "a single multi-channel stream."),
352     .priv_size     = sizeof(AMergeContext),
353     .init          = init,
354     .uninit        = uninit,
355     .query_formats = query_formats,
356     .activate      = activate,
357     .inputs        = NULL,
358     .outputs       = amerge_outputs,
359     .priv_class    = &amerge_class,
360     .flags         = AVFILTER_FLAG_DYNAMIC_INPUTS,
361 };