libavfilter/af_amerge.c
4962edf8
 /*
  * Copyright (c) 2011 Nicolas George <nicolas.george@normalesup.org>
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
752344da
  * GNU Lesser General Public License for more details.
4962edf8
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * Audio merging filter
  */
 
8156b5ac
 #define FF_INTERNAL_FIELDS 1
 #include "framequeue.h"
 
7b56dddd
 #include "libavutil/avstring.h"
e0545262
 #include "libavutil/bprint.h"
1acd2f6b
 #include "libavutil/channel_layout.h"
e0545262
 #include "libavutil/opt.h"
4962edf8
 #include "avfilter.h"
4522df52
 #include "audio.h"
7f17f4f1
 #include "bufferqueue.h"
4962edf8
 #include "internal.h"
 
7967474b
 #define SWR_CH_MAX 64
36bce999
 
ed93ed5e
 typedef struct AMergeContext {
e0545262
     const AVClass *class;
     int nb_inputs;
4962edf8
     int route[SWR_CH_MAX]; /**< channels routing, see copy_samples */
     int bps;
7f17f4f1
     struct amerge_input {
         struct FFBufQueue queue;
e8e492b3
         int nb_ch;         /**< number of channels for the input */
7f17f4f1
         int nb_samples;
         int pos;
e0545262
     } *in;
4962edf8
 } AMergeContext;
 
e0545262
 #define OFFSET(x) offsetof(AMergeContext, x)
42d621d1
 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
e0545262
 
 static const AVOption amerge_options[] = {
     { "inputs", "specify the number of inputs", OFFSET(nb_inputs),
025db5af
       AV_OPT_TYPE_INT, { .i64 = 2 }, 1, SWR_CH_MAX, FLAGS },
b211607b
     { NULL }
e0545262
 };
 
c17808ce
 AVFILTER_DEFINE_CLASS(amerge);
e0545262
 
4962edf8
 static av_cold void uninit(AVFilterContext *ctx)
 {
9ba511d5
     AMergeContext *s = ctx->priv;
7f17f4f1
     int i;
4962edf8
 
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
         if (s->in)
             ff_bufqueue_discard_all(&s->in[i].queue);
bf0712c2
         if (ctx->input_pads)
             av_freep(&ctx->input_pads[i].name);
7b56dddd
     }
9ba511d5
     av_freep(&s->in);
4962edf8
 }
 
 static int query_formats(AVFilterContext *ctx)
 {
9ba511d5
     AMergeContext *s = ctx->priv;
e0545262
     int64_t inlayout[SWR_CH_MAX], outlayout = 0;
4962edf8
     AVFilterFormats *formats;
1cbf7fb4
     AVFilterChannelLayouts *layouts;
6aaac24d
     int i, ret, overlap = 0, nb_ch = 0;
4962edf8
 
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
1cbf7fb4
         if (!ctx->inputs[i]->in_channel_layouts ||
             !ctx->inputs[i]->in_channel_layouts->nb_channel_layouts) {
00da527b
             av_log(ctx, AV_LOG_WARNING,
4962edf8
                    "No channel layout for input %d\n", i + 1);
00da527b
             return AVERROR(EAGAIN);
4962edf8
         }
1cbf7fb4
         inlayout[i] = ctx->inputs[i]->in_channel_layouts->channel_layouts[0];
         if (ctx->inputs[i]->in_channel_layouts->nb_channel_layouts > 1) {
4962edf8
             char buf[256];
             av_get_channel_layout_string(buf, sizeof(buf), 0, inlayout[i]);
             av_log(ctx, AV_LOG_INFO, "Using \"%s\" for input %d\n", buf, i + 1);
         }
0db48ee4
         s->in[i].nb_ch = FF_LAYOUT2COUNT(inlayout[i]);
         if (s->in[i].nb_ch) {
e0545262
             overlap++;
0db48ee4
         } else {
             s->in[i].nb_ch = av_get_channel_layout_nb_channels(inlayout[i]);
             if (outlayout & inlayout[i])
                 overlap++;
             outlayout |= inlayout[i];
         }
9ba511d5
         nb_ch += s->in[i].nb_ch;
4962edf8
     }
e0545262
     if (nb_ch > SWR_CH_MAX) {
4962edf8
         av_log(ctx, AV_LOG_ERROR, "Too many channels (max %d)\n", SWR_CH_MAX);
         return AVERROR(EINVAL);
     }
e0545262
     if (overlap) {
4962edf8
         av_log(ctx, AV_LOG_WARNING,
30151944
                "Input channel layouts overlap: "
                "output layout will be determined by the number of distinct input channels\n");
e0545262
         for (i = 0; i < nb_ch; i++)
9ba511d5
             s->route[i] = i;
e0545262
         outlayout = av_get_default_channel_layout(nb_ch);
a3ad51e0
         if (!outlayout && nb_ch)
             outlayout = 0xFFFFFFFFFFFFFFFFULL >> (64 - nb_ch);
4962edf8
     } else {
e0545262
         int *route[SWR_CH_MAX];
4962edf8
         int c, out_ch_number = 0;
 
9ba511d5
         route[0] = s->route;
         for (i = 1; i < s->nb_inputs; i++)
             route[i] = route[i - 1] + s->in[i - 1].nb_ch;
4962edf8
         for (c = 0; c < 64; c++)
9ba511d5
             for (i = 0; i < s->nb_inputs; i++)
4962edf8
                 if ((inlayout[i] >> c) & 1)
                     *(route[i]++) = out_ch_number++;
     }
c9e183b4
     formats = ff_make_format_list(ff_packed_sample_fmts_array);
6aaac24d
     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
         return ret;
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
1cbf7fb4
         layouts = NULL;
6aaac24d
         if ((ret = ff_add_channel_layout(&layouts, inlayout[i])) < 0)
             return ret;
         if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts)) < 0)
             return ret;
4962edf8
     }
1cbf7fb4
     layouts = NULL;
6aaac24d
     if ((ret = ff_add_channel_layout(&layouts, outlayout)) < 0)
         return ret;
     if ((ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
         return ret;
 
     return ff_set_common_samplerates(ctx, ff_all_samplerates());
4962edf8
 }
 
 static int config_output(AVFilterLink *outlink)
 {
     AVFilterContext *ctx = outlink->src;
9ba511d5
     AMergeContext *s = ctx->priv;
e0545262
     AVBPrint bp;
4962edf8
     int i;
 
9ba511d5
     for (i = 1; i < s->nb_inputs; i++) {
e0545262
         if (ctx->inputs[i]->sample_rate != ctx->inputs[0]->sample_rate) {
             av_log(ctx, AV_LOG_ERROR,
                    "Inputs must have the same sample rate "
3f59bbf5
                    "%d for in%d vs %d\n",
e0545262
                    ctx->inputs[i]->sample_rate, i, ctx->inputs[0]->sample_rate);
             return AVERROR(EINVAL);
         }
4962edf8
     }
9ba511d5
     s->bps = av_get_bytes_per_sample(ctx->outputs[0]->format);
4962edf8
     outlink->sample_rate = ctx->inputs[0]->sample_rate;
     outlink->time_base   = ctx->inputs[0]->time_base;
e0545262
 
     av_bprint_init(&bp, 0, 1);
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
e0545262
         av_bprintf(&bp, "%sin%d:", i ? " + " : "", i);
         av_bprint_channel_layout(&bp, -1, ctx->inputs[i]->channel_layout);
4962edf8
     }
e0545262
     av_bprintf(&bp, " -> out:");
     av_bprint_channel_layout(&bp, -1, ctx->outputs[0]->channel_layout);
fda968aa
     av_log(ctx, AV_LOG_VERBOSE, "%s\n", bp.str);
e0545262
 
4962edf8
     return 0;
 }
 
 static int request_frame(AVFilterLink *outlink)
 {
     AVFilterContext *ctx = outlink->src;
9ba511d5
     AMergeContext *s = ctx->priv;
5473a98e
     int i, ret;
4962edf8
 
9ba511d5
     for (i = 0; i < s->nb_inputs; i++)
8156b5ac
         if (!s->in[i].nb_samples ||
             /* detect EOF immediately */
             (ctx->inputs[i]->status_in && !ctx->inputs[i]->status_out))
1c600888
             if ((ret = ff_request_frame(ctx->inputs[i])) < 0)
5473a98e
                 return ret;
4962edf8
     return 0;
 }
 
 /**
e0545262
  * Copy samples from several input streams to one output stream.
  * @param nb_inputs number of inputs
e8e492b3
  * @param in        inputs; used only for the nb_ch field;
4962edf8
  * @param route     routing values;
  *                  input channel i goes to output channel route[i];
e8e492b3
  *                  i <  in[0].nb_ch are the channels from the first output;
  *                  i >= in[0].nb_ch are the channels from the second output
4962edf8
  * @param ins       pointer to the samples of each inputs, in packed format;
  *                  will be left at the end of the copied samples
  * @param outs      pointer to the samples of the output, in packet format;
  *                  must point to a buffer big enough;
  *                  will be left at the end of the copied samples
  * @param ns        number of samples to copy
  * @param bps       bytes per sample
  */
e0545262
 static inline void copy_samples(int nb_inputs, struct amerge_input in[],
                                 int *route, uint8_t *ins[],
4962edf8
                                 uint8_t **outs, int ns, int bps)
 {
     int *route_cur;
e0545262
     int i, c, nb_ch = 0;
4962edf8
 
e0545262
     for (i = 0; i < nb_inputs; i++)
         nb_ch += in[i].nb_ch;
4962edf8
     while (ns--) {
         route_cur = route;
e0545262
         for (i = 0; i < nb_inputs; i++) {
e8e492b3
             for (c = 0; c < in[i].nb_ch; c++) {
4962edf8
                 memcpy((*outs) + bps * *(route_cur++), ins[i], bps);
                 ins[i] += bps;
             }
         }
e0545262
         *outs += nb_ch * bps;
4962edf8
     }
 }
 
a05a44e2
 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
4962edf8
 {
     AVFilterContext *ctx = inlink->dst;
9ba511d5
     AMergeContext *s = ctx->priv;
d50a4c4a
     AVFilterLink *const outlink = ctx->outputs[0];
e0545262
     int input_number;
4962edf8
     int nb_samples, ns, i;
a05a44e2
     AVFrame *outbuf, *inbuf[SWR_CH_MAX];
e0545262
     uint8_t *ins[SWR_CH_MAX], *outs;
4962edf8
 
9ba511d5
     for (input_number = 0; input_number < s->nb_inputs; input_number++)
e0545262
         if (inlink == ctx->inputs[input_number])
             break;
9ba511d5
     av_assert1(input_number < s->nb_inputs);
     if (ff_bufqueue_is_full(&s->in[input_number].queue)) {
a05a44e2
         av_frame_free(&insamples);
ae14887e
         return AVERROR(ENOMEM);
     }
9ba511d5
     ff_bufqueue_add(ctx, &s->in[input_number].queue, av_frame_clone(insamples));
     s->in[input_number].nb_samples += insamples->nb_samples;
a05a44e2
     av_frame_free(&insamples);
9ba511d5
     nb_samples = s->in[0].nb_samples;
     for (i = 1; i < s->nb_inputs; i++)
         nb_samples = FFMIN(nb_samples, s->in[i].nb_samples);
e0545262
     if (!nb_samples)
f8911b98
         return 0;
4962edf8
 
a05a44e2
     outbuf = ff_get_audio_buffer(ctx->outputs[0], nb_samples);
ed8373e7
     if (!outbuf)
         return AVERROR(ENOMEM);
4962edf8
     outs = outbuf->data[0];
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
         inbuf[i] = ff_bufqueue_peek(&s->in[i].queue, 0);
7f17f4f1
         ins[i] = inbuf[i]->data[0] +
9ba511d5
                  s->in[i].pos * s->in[i].nb_ch * s->bps;
4962edf8
     }
a05a44e2
     av_frame_copy_props(outbuf, inbuf[0]);
7f17f4f1
     outbuf->pts = inbuf[0]->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
                   inbuf[0]->pts +
9ba511d5
                   av_rescale_q(s->in[0].pos,
bf9908c6
                                av_make_q(1, ctx->inputs[0]->sample_rate),
0da28d68
                                ctx->outputs[0]->time_base);
d50a4c4a
 
a05a44e2
     outbuf->nb_samples     = nb_samples;
     outbuf->channel_layout = outlink->channel_layout;
6af050d7
     outbuf->channels       = outlink->channels;
d50a4c4a
 
4962edf8
     while (nb_samples) {
         ns = nb_samples;
9ba511d5
         for (i = 0; i < s->nb_inputs; i++)
             ns = FFMIN(ns, inbuf[i]->nb_samples - s->in[i].pos);
4962edf8
         /* Unroll the most common sample formats: speed +~350% for the loop,
            +~13% overall (including two common decoders) */
9ba511d5
         switch (s->bps) {
4962edf8
             case 1:
9ba511d5
                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, ns, 1);
4962edf8
                 break;
             case 2:
9ba511d5
                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, ns, 2);
4962edf8
                 break;
             case 4:
9ba511d5
                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, ns, 4);
4962edf8
                 break;
             default:
9ba511d5
                 copy_samples(s->nb_inputs, s->in, s->route, ins, &outs, ns, s->bps);
4962edf8
                 break;
         }
 
         nb_samples -= ns;
9ba511d5
         for (i = 0; i < s->nb_inputs; i++) {
             s->in[i].nb_samples -= ns;
             s->in[i].pos += ns;
             if (s->in[i].pos == inbuf[i]->nb_samples) {
                 s->in[i].pos = 0;
a05a44e2
                 av_frame_free(&inbuf[i]);
9ba511d5
                 ff_bufqueue_get(&s->in[i].queue);
                 inbuf[i] = ff_bufqueue_peek(&s->in[i].queue, 0);
7f17f4f1
                 ins[i] = inbuf[i] ? inbuf[i]->data[0] : NULL;
4962edf8
             }
         }
     }
cd7febd3
     return ff_filter_frame(ctx->outputs[0], outbuf);
4962edf8
 }
 
fd6228e6
 static av_cold int init(AVFilterContext *ctx)
e0545262
 {
9ba511d5
     AMergeContext *s = ctx->priv;
f39136b0
     int i, ret;
e0545262
 
9ba511d5
     s->in = av_calloc(s->nb_inputs, sizeof(*s->in));
     if (!s->in)
e0545262
         return AVERROR(ENOMEM);
9ba511d5
     for (i = 0; i < s->nb_inputs; i++) {
7b56dddd
         char *name = av_asprintf("in%d", i);
e0545262
         AVFilterPad pad = {
             .name             = name,
             .type             = AVMEDIA_TYPE_AUDIO,
cd7febd3
             .filter_frame     = filter_frame,
e0545262
         };
bbae8cdf
         if (!name)
             return AVERROR(ENOMEM);
f39136b0
         if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
             av_freep(&pad.name);
             return ret;
         }
e0545262
     }
     return 0;
 }
 
2d9d4440
 static const AVFilterPad amerge_outputs[] = {
     {
         .name          = "default",
         .type          = AVMEDIA_TYPE_AUDIO,
         .config_props  = config_output,
         .request_frame = request_frame,
     },
     { NULL }
 };
 
325f6e0a
 AVFilter ff_af_amerge = {
4962edf8
     .name          = "amerge",
8160864b
     .description   = NULL_IF_CONFIG_SMALL("Merge two or more audio streams into "
4962edf8
                                           "a single multi-channel stream."),
     .priv_size     = sizeof(AMergeContext),
e0545262
     .init          = init,
4962edf8
     .uninit        = uninit,
     .query_formats = query_formats,
2d9d4440
     .inputs        = NULL,
     .outputs       = amerge_outputs,
     .priv_class    = &amerge_class,
73180f5b
     .flags         = AVFILTER_FLAG_DYNAMIC_INPUTS,
4962edf8
 };