]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_join.c
lavfi: remove palette libmpcodecs wrapper
[ffmpeg] / libavfilter / af_join.c
1 /*
2  *
3  * This file is part of Libav.
4  *
5  * Libav is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * Libav is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with Libav; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 /**
21  * @file
22  * Audio join filter
23  *
24  * Join multiple audio inputs as different channels in
25  * a single output
26  */
27
28 #include "libavutil/audioconvert.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/common.h"
31 #include "libavutil/opt.h"
32
33 #include "audio.h"
34 #include "avfilter.h"
35 #include "formats.h"
36 #include "internal.h"
37
38 typedef struct ChannelMap {
39     int input;                ///< input stream index
40     int       in_channel_idx; ///< index of in_channel in the input stream data
41     uint64_t  in_channel;     ///< layout describing the input channel
42     uint64_t out_channel;     ///< layout describing the output channel
43 } ChannelMap;
44
45 typedef struct JoinContext {
46     const AVClass *class;
47
48     int inputs;
49     char *map;
50     char    *channel_layout_str;
51     uint64_t channel_layout;
52
53     int      nb_channels;
54     ChannelMap *channels;
55
56     /**
57      * Temporary storage for input frames, until we get one on each input.
58      */
59     AVFilterBufferRef **input_frames;
60
61     /**
62      *  Temporary storage for data pointers, for assembling the output buffer.
63      */
64     uint8_t **data;
65 } JoinContext;
66
67 /**
68  * To avoid copying the data from input buffers, this filter creates
69  * a custom output buffer that stores references to all inputs and
70  * unrefs them on free.
71  */
72 typedef struct JoinBufferPriv {
73     AVFilterBufferRef **in_buffers;
74     int              nb_in_buffers;
75 } JoinBufferPriv;
76
77 #define OFFSET(x) offsetof(JoinContext, x)
78 #define A AV_OPT_FLAG_AUDIO_PARAM
79 #define F AV_OPT_FLAG_FILTERING_PARAM
80 static const AVOption join_options[] = {
81     { "inputs",         "Number of input streams.", OFFSET(inputs),             AV_OPT_TYPE_INT,    { .i64 = 2 }, 1, INT_MAX,       A|F },
82     { "channel_layout", "Channel layout of the "
83                         "output stream.",           OFFSET(channel_layout_str), AV_OPT_TYPE_STRING, {.str = "stereo"}, 0, 0, A|F },
84     { "map",            "A comma-separated list of channels maps in the format "
85                         "'input_stream.input_channel-output_channel.",
86                                                     OFFSET(map),                AV_OPT_TYPE_STRING,                 .flags = A|F },
87     { NULL },
88 };
89
90 static const AVClass join_class = {
91     .class_name = "join filter",
92     .item_name  = av_default_item_name,
93     .option     = join_options,
94     .version    = LIBAVUTIL_VERSION_INT,
95 };
96
97 static int filter_samples(AVFilterLink *link, AVFilterBufferRef *buf)
98 {
99     AVFilterContext *ctx = link->dst;
100     JoinContext       *s = ctx->priv;
101     int i;
102
103     for (i = 0; i < ctx->nb_inputs; i++)
104         if (link == ctx->inputs[i])
105             break;
106     av_assert0(i < ctx->nb_inputs);
107     av_assert0(!s->input_frames[i]);
108     s->input_frames[i] = buf;
109
110     return 0;
111 }
112
113 static int parse_maps(AVFilterContext *ctx)
114 {
115     JoinContext *s = ctx->priv;
116     char *cur      = s->map;
117
118     while (cur && *cur) {
119         char *sep, *next, *p;
120         uint64_t in_channel = 0, out_channel = 0;
121         int input_idx, out_ch_idx, in_ch_idx;
122
123         next = strchr(cur, ',');
124         if (next)
125             *next++ = 0;
126
127         /* split the map into input and output parts */
128         if (!(sep = strchr(cur, '-'))) {
129             av_log(ctx, AV_LOG_ERROR, "Missing separator '-' in channel "
130                    "map '%s'\n", cur);
131             return AVERROR(EINVAL);
132         }
133         *sep++ = 0;
134
135 #define PARSE_CHANNEL(str, var, inout)                                         \
136         if (!(var = av_get_channel_layout(str))) {                             \
137             av_log(ctx, AV_LOG_ERROR, "Invalid " inout " channel: %s.\n", str);\
138             return AVERROR(EINVAL);                                            \
139         }                                                                      \
140         if (av_get_channel_layout_nb_channels(var) != 1) {                     \
141             av_log(ctx, AV_LOG_ERROR, "Channel map describes more than one "   \
142                    inout " channel.\n");                                       \
143             return AVERROR(EINVAL);                                            \
144         }
145
146         /* parse output channel */
147         PARSE_CHANNEL(sep, out_channel, "output");
148         if (!(out_channel & s->channel_layout)) {
149             av_log(ctx, AV_LOG_ERROR, "Output channel '%s' is not present in "
150                    "requested channel layout.\n", sep);
151             return AVERROR(EINVAL);
152         }
153
154         out_ch_idx = av_get_channel_layout_channel_index(s->channel_layout,
155                                                          out_channel);
156         if (s->channels[out_ch_idx].input >= 0) {
157             av_log(ctx, AV_LOG_ERROR, "Multiple maps for output channel "
158                    "'%s'.\n", sep);
159             return AVERROR(EINVAL);
160         }
161
162         /* parse input channel */
163         input_idx = strtol(cur, &cur, 0);
164         if (input_idx < 0 || input_idx >= s->inputs) {
165             av_log(ctx, AV_LOG_ERROR, "Invalid input stream index: %d.\n",
166                    input_idx);
167             return AVERROR(EINVAL);
168         }
169
170         if (*cur)
171             cur++;
172
173         in_ch_idx = strtol(cur, &p, 0);
174         if (p == cur) {
175             /* channel specifier is not a number,
176              * try to parse as channel name */
177             PARSE_CHANNEL(cur, in_channel, "input");
178         }
179
180         s->channels[out_ch_idx].input      = input_idx;
181         if (in_channel)
182             s->channels[out_ch_idx].in_channel = in_channel;
183         else
184             s->channels[out_ch_idx].in_channel_idx = in_ch_idx;
185
186         cur = next;
187     }
188     return 0;
189 }
190
191 static int join_init(AVFilterContext *ctx, const char *args)
192 {
193     JoinContext *s = ctx->priv;
194     int ret, i;
195
196     s->class = &join_class;
197     av_opt_set_defaults(s);
198     if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
199         return ret;
200
201     if (!(s->channel_layout = av_get_channel_layout(s->channel_layout_str))) {
202         av_log(ctx, AV_LOG_ERROR, "Error parsing channel layout '%s'.\n",
203                s->channel_layout_str);
204         ret = AVERROR(EINVAL);
205         goto fail;
206     }
207
208     s->nb_channels  = av_get_channel_layout_nb_channels(s->channel_layout);
209     s->channels     = av_mallocz(sizeof(*s->channels) * s->nb_channels);
210     s->data         = av_mallocz(sizeof(*s->data)     * s->nb_channels);
211     s->input_frames = av_mallocz(sizeof(*s->input_frames) * s->inputs);
212     if (!s->channels || !s->data || !s->input_frames) {
213         ret = AVERROR(ENOMEM);
214         goto fail;
215     }
216
217     for (i = 0; i < s->nb_channels; i++) {
218         s->channels[i].out_channel = av_channel_layout_extract_channel(s->channel_layout, i);
219         s->channels[i].input       = -1;
220     }
221
222     if ((ret = parse_maps(ctx)) < 0)
223         goto fail;
224
225     for (i = 0; i < s->inputs; i++) {
226         char name[32];
227         AVFilterPad pad = { 0 };
228
229         snprintf(name, sizeof(name), "input%d", i);
230         pad.type           = AVMEDIA_TYPE_AUDIO;
231         pad.name           = av_strdup(name);
232         pad.filter_samples = filter_samples;
233
234         pad.needs_fifo = 1;
235
236         ff_insert_inpad(ctx, i, &pad);
237     }
238
239 fail:
240     av_opt_free(s);
241     return ret;
242 }
243
244 static void join_uninit(AVFilterContext *ctx)
245 {
246     JoinContext *s = ctx->priv;
247     int i;
248
249     for (i = 0; i < ctx->nb_inputs; i++) {
250         av_freep(&ctx->input_pads[i].name);
251         avfilter_unref_bufferp(&s->input_frames[i]);
252     }
253
254     av_freep(&s->channels);
255     av_freep(&s->data);
256     av_freep(&s->input_frames);
257 }
258
259 static int join_query_formats(AVFilterContext *ctx)
260 {
261     JoinContext *s = ctx->priv;
262     AVFilterChannelLayouts *layouts = NULL;
263     int i;
264
265     ff_add_channel_layout(&layouts, s->channel_layout);
266     ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
267
268     for (i = 0; i < ctx->nb_inputs; i++)
269         ff_channel_layouts_ref(ff_all_channel_layouts(),
270                                &ctx->inputs[i]->out_channel_layouts);
271
272     ff_set_common_formats    (ctx, ff_planar_sample_fmts());
273     ff_set_common_samplerates(ctx, ff_all_samplerates());
274
275     return 0;
276 }
277
278 static void guess_map_matching(AVFilterContext *ctx, ChannelMap *ch,
279                                uint64_t *inputs)
280 {
281     int i;
282
283     for (i = 0; i < ctx->nb_inputs; i++) {
284         AVFilterLink *link = ctx->inputs[i];
285
286         if (ch->out_channel & link->channel_layout &&
287             !(ch->out_channel & inputs[i])) {
288             ch->input      = i;
289             ch->in_channel = ch->out_channel;
290             inputs[i]     |= ch->out_channel;
291             return;
292         }
293     }
294 }
295
296 static void guess_map_any(AVFilterContext *ctx, ChannelMap *ch,
297                           uint64_t *inputs)
298 {
299     int i;
300
301     for (i = 0; i < ctx->nb_inputs; i++) {
302         AVFilterLink *link = ctx->inputs[i];
303
304         if ((inputs[i] & link->channel_layout) != link->channel_layout) {
305             uint64_t unused = link->channel_layout & ~inputs[i];
306
307             ch->input      = i;
308             ch->in_channel = av_channel_layout_extract_channel(unused, 0);
309             inputs[i]     |= ch->in_channel;
310             return;
311         }
312     }
313 }
314
315 static int join_config_output(AVFilterLink *outlink)
316 {
317     AVFilterContext *ctx = outlink->src;
318     JoinContext       *s = ctx->priv;
319     uint64_t *inputs;   // nth element tracks which channels are used from nth input
320     int i, ret = 0;
321
322     /* initialize inputs to user-specified mappings */
323     if (!(inputs = av_mallocz(sizeof(*inputs) * ctx->nb_inputs)))
324         return AVERROR(ENOMEM);
325     for (i = 0; i < s->nb_channels; i++) {
326         ChannelMap *ch = &s->channels[i];
327         AVFilterLink *inlink;
328
329         if (ch->input < 0)
330             continue;
331
332         inlink = ctx->inputs[ch->input];
333
334         if (!ch->in_channel)
335             ch->in_channel = av_channel_layout_extract_channel(inlink->channel_layout,
336                                                                ch->in_channel_idx);
337
338         if (!(ch->in_channel & inlink->channel_layout)) {
339             av_log(ctx, AV_LOG_ERROR, "Requested channel %s is not present in "
340                    "input stream #%d.\n", av_get_channel_name(ch->in_channel),
341                    ch->input);
342             ret = AVERROR(EINVAL);
343             goto fail;
344         }
345
346         inputs[ch->input] |= ch->in_channel;
347     }
348
349     /* guess channel maps when not explicitly defined */
350     /* first try unused matching channels */
351     for (i = 0; i < s->nb_channels; i++) {
352         ChannelMap *ch = &s->channels[i];
353
354         if (ch->input < 0)
355             guess_map_matching(ctx, ch, inputs);
356     }
357
358     /* if the above failed, try to find _any_ unused input channel */
359     for (i = 0; i < s->nb_channels; i++) {
360         ChannelMap *ch = &s->channels[i];
361
362         if (ch->input < 0)
363             guess_map_any(ctx, ch, inputs);
364
365         if (ch->input < 0) {
366             av_log(ctx, AV_LOG_ERROR, "Could not find input channel for "
367                    "output channel '%s'.\n",
368                    av_get_channel_name(ch->out_channel));
369             goto fail;
370         }
371
372         ch->in_channel_idx = av_get_channel_layout_channel_index(ctx->inputs[ch->input]->channel_layout,
373                                                                  ch->in_channel);
374     }
375
376     /* print mappings */
377     av_log(ctx, AV_LOG_VERBOSE, "mappings: ");
378     for (i = 0; i < s->nb_channels; i++) {
379         ChannelMap *ch = &s->channels[i];
380         av_log(ctx, AV_LOG_VERBOSE, "%d.%s => %s ", ch->input,
381                av_get_channel_name(ch->in_channel),
382                av_get_channel_name(ch->out_channel));
383     }
384     av_log(ctx, AV_LOG_VERBOSE, "\n");
385
386     for (i = 0; i < ctx->nb_inputs; i++) {
387         if (!inputs[i])
388             av_log(ctx, AV_LOG_WARNING, "No channels are used from input "
389                    "stream %d.\n", i);
390     }
391
392 fail:
393     av_freep(&inputs);
394     return ret;
395 }
396
397 static void join_free_buffer(AVFilterBuffer *buf)
398 {
399     JoinBufferPriv *priv = buf->priv;
400
401     if (priv) {
402         int i;
403
404         for (i = 0; i < priv->nb_in_buffers; i++)
405             avfilter_unref_bufferp(&priv->in_buffers[i]);
406
407         av_freep(&priv->in_buffers);
408         av_freep(&buf->priv);
409     }
410
411     if (buf->extended_data != buf->data)
412         av_freep(&buf->extended_data);
413     av_freep(&buf);
414 }
415
416 static int join_request_frame(AVFilterLink *outlink)
417 {
418     AVFilterContext *ctx = outlink->src;
419     JoinContext *s       = ctx->priv;
420     AVFilterBufferRef *buf;
421     JoinBufferPriv *priv;
422     int linesize   = INT_MAX;
423     int perms      = ~0;
424     int nb_samples = 0;
425     int i, j, ret;
426
427     /* get a frame on each input */
428     for (i = 0; i < ctx->nb_inputs; i++) {
429         AVFilterLink *inlink = ctx->inputs[i];
430
431         if (!s->input_frames[i] &&
432             (ret = ff_request_frame(inlink)) < 0)
433             return ret;
434
435         /* request the same number of samples on all inputs */
436         if (i == 0) {
437             nb_samples = s->input_frames[0]->audio->nb_samples;
438
439             for (j = 1; !i && j < ctx->nb_inputs; j++)
440                 ctx->inputs[j]->request_samples = nb_samples;
441         }
442     }
443
444     for (i = 0; i < s->nb_channels; i++) {
445         ChannelMap *ch = &s->channels[i];
446         AVFilterBufferRef *cur_buf = s->input_frames[ch->input];
447
448         s->data[i] = cur_buf->extended_data[ch->in_channel_idx];
449         linesize   = FFMIN(linesize, cur_buf->linesize[0]);
450         perms     &= cur_buf->perms;
451     }
452
453     av_assert0(nb_samples > 0);
454     buf = avfilter_get_audio_buffer_ref_from_arrays(s->data, linesize, perms,
455                                                     nb_samples, outlink->format,
456                                                     outlink->channel_layout);
457     if (!buf)
458         return AVERROR(ENOMEM);
459
460     buf->buf->free = join_free_buffer;
461     buf->pts       = s->input_frames[0]->pts;
462
463     if (!(priv = av_mallocz(sizeof(*priv))))
464         goto fail;
465     if (!(priv->in_buffers = av_mallocz(sizeof(*priv->in_buffers) * ctx->nb_inputs)))
466         goto fail;
467
468     for (i = 0; i < ctx->nb_inputs; i++)
469         priv->in_buffers[i] = s->input_frames[i];
470     priv->nb_in_buffers = ctx->nb_inputs;
471     buf->buf->priv      = priv;
472
473     ret = ff_filter_samples(outlink, buf);
474
475     memset(s->input_frames, 0, sizeof(*s->input_frames) * ctx->nb_inputs);
476
477     return ret;
478
479 fail:
480     avfilter_unref_buffer(buf);
481     if (priv)
482         av_freep(&priv->in_buffers);
483     av_freep(&priv);
484     return AVERROR(ENOMEM);
485 }
486
487 static const AVFilterPad avfilter_af_join_outputs[] = {
488     {
489         .name          = "default",
490         .type          = AVMEDIA_TYPE_AUDIO,
491         .config_props  = join_config_output,
492         .request_frame = join_request_frame,
493     },
494     { NULL }
495 };
496
497 AVFilter avfilter_af_join = {
498     .name           = "join",
499     .description    = NULL_IF_CONFIG_SMALL("Join multiple audio streams into "
500                                            "multi-channel output"),
501     .priv_size      = sizeof(JoinContext),
502
503     .init           = join_init,
504     .uninit         = join_uninit,
505     .query_formats  = join_query_formats,
506
507     .inputs  = NULL,
508     .outputs = avfilter_af_join_outputs,
509     .priv_class = &join_class,
510 };