2 * Copyright (c) 2012 Nicolas George
4 * This file is part of FFmpeg.
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.
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.
14 * See the GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * concat audio-video filter
26 #include "libavutil/audioconvert.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/opt.h"
30 #define FF_BUFQUEUE_SIZE 256
31 #include "bufferqueue.h"
40 unsigned nb_streams[TYPE_ALL]; /**< number of out streams of each type */
42 unsigned cur_idx; /**< index of the first input of current segment */
43 int64_t delta_ts; /**< timestamp to add to produce output timestamps */
44 unsigned nb_in_active; /**< number of active inputs in current segment */
49 struct FFBufQueue queue;
53 #define OFFSET(x) offsetof(ConcatContext, x)
54 #define A AV_OPT_FLAG_AUDIO_PARAM
55 #define F AV_OPT_FLAG_FILTERING_PARAM
56 #define V AV_OPT_FLAG_VIDEO_PARAM
58 static const AVOption concat_options[] = {
59 { "n", "specify the number of segments", OFFSET(nb_segments),
60 AV_OPT_TYPE_INT, { .i64 = 2 }, 2, INT_MAX, V|A|F},
61 { "v", "specify the number of video streams",
62 OFFSET(nb_streams[AVMEDIA_TYPE_VIDEO]),
63 AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, V|F },
64 { "a", "specify the number of audio streams",
65 OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
66 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|F},
70 AVFILTER_DEFINE_CLASS(concat);
72 static int query_formats(AVFilterContext *ctx)
74 ConcatContext *cat = ctx->priv;
75 unsigned type, nb_str, idx0 = 0, idx, str, seg;
76 AVFilterFormats *formats, *rates;
77 AVFilterChannelLayouts *layouts;
79 for (type = 0; type < TYPE_ALL; type++) {
80 nb_str = cat->nb_streams[type];
81 for (str = 0; str < nb_str; str++) {
84 /* Set the output formats */
85 formats = ff_all_formats(type);
87 return AVERROR(ENOMEM);
88 ff_formats_ref(formats, &ctx->outputs[idx]->in_formats);
89 if (type == AVMEDIA_TYPE_AUDIO) {
90 rates = ff_all_samplerates();
92 return AVERROR(ENOMEM);
93 ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
94 layouts = ff_all_channel_layouts();
96 return AVERROR(ENOMEM);
97 ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
100 /* Set the same formats for each corresponding input */
101 for (seg = 0; seg < cat->nb_segments; seg++) {
102 ff_formats_ref(formats, &ctx->inputs[idx]->out_formats);
103 if (type == AVMEDIA_TYPE_AUDIO) {
104 ff_formats_ref(rates, &ctx->inputs[idx]->out_samplerates);
105 ff_channel_layouts_ref(layouts, &ctx->inputs[idx]->out_channel_layouts);
107 idx += ctx->nb_outputs;
116 static int config_output(AVFilterLink *outlink)
118 AVFilterContext *ctx = outlink->src;
119 ConcatContext *cat = ctx->priv;
120 unsigned out_no = FF_OUTLINK_IDX(outlink);
121 unsigned in_no = out_no, seg;
122 AVFilterLink *inlink = ctx->inputs[in_no];
124 /* enhancement: find a common one */
125 outlink->time_base = AV_TIME_BASE_Q;
126 outlink->w = inlink->w;
127 outlink->h = inlink->h;
128 outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
129 outlink->format = inlink->format;
130 for (seg = 1; seg < cat->nb_segments; seg++) {
131 inlink = ctx->inputs[in_no += ctx->nb_outputs];
132 /* possible enhancement: unsafe mode, do not check */
133 if (outlink->w != inlink->w ||
134 outlink->h != inlink->h ||
135 outlink->sample_aspect_ratio.num != inlink->sample_aspect_ratio.num ||
136 outlink->sample_aspect_ratio.den != inlink->sample_aspect_ratio.den) {
137 av_log(ctx, AV_LOG_ERROR, "Input link %s parameters "
138 "(size %dx%d, SAR %d:%d) do not match the corresponding "
139 "output link %s parameters (%dx%d, SAR %d:%d)\n",
140 ctx->input_pads[in_no].name, inlink->w, inlink->h,
141 inlink->sample_aspect_ratio.num,
142 inlink->sample_aspect_ratio.den,
143 ctx->input_pads[out_no].name, outlink->w, outlink->h,
144 outlink->sample_aspect_ratio.num,
145 outlink->sample_aspect_ratio.den);
146 return AVERROR(EINVAL);
153 static void push_frame(AVFilterContext *ctx, unsigned in_no,
154 AVFilterBufferRef *buf)
156 ConcatContext *cat = ctx->priv;
157 unsigned out_no = in_no % ctx->nb_outputs;
158 AVFilterLink * inlink = ctx-> inputs[ in_no];
159 AVFilterLink *outlink = ctx->outputs[out_no];
160 struct concat_in *in = &cat->in[in_no];
162 buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
165 /* add duration to input PTS */
166 if (inlink->sample_rate)
167 /* use number of audio samples */
168 in->pts += av_rescale_q(buf->audio->nb_samples,
169 (AVRational){ 1, inlink->sample_rate },
171 else if (in->nb_frames >= 2)
172 /* use mean duration */
173 in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
175 buf->pts += cat->delta_ts;
177 case AVMEDIA_TYPE_VIDEO:
178 ff_start_frame(outlink, buf);
179 ff_draw_slice(outlink, 0, outlink->h, 1);
180 ff_end_frame(outlink);
182 case AVMEDIA_TYPE_AUDIO:
183 ff_filter_samples(outlink, buf);
188 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
190 AVFilterContext *ctx = inlink->dst;
191 ConcatContext *cat = ctx->priv;
192 unsigned in_no = FF_INLINK_IDX(inlink);
194 if (in_no < cat->cur_idx) {
195 av_log(ctx, AV_LOG_ERROR, "Frame after EOF on input %s\n",
196 ctx->input_pads[in_no].name);
197 avfilter_unref_buffer(buf);
198 } if (in_no >= cat->cur_idx + ctx->nb_outputs) {
199 ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
201 push_frame(ctx, in_no, buf);
205 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
208 AVFilterContext *ctx = inlink->dst;
209 unsigned in_no = FF_INLINK_IDX(inlink);
210 AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
212 return ff_get_video_buffer(outlink, perms, w, h);
215 static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
218 AVFilterContext *ctx = inlink->dst;
219 unsigned in_no = FF_INLINK_IDX(inlink);
220 AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
222 return ff_get_audio_buffer(outlink, perms, nb_samples);
225 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
230 static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
235 static int end_frame(AVFilterLink *inlink)
237 process_frame(inlink, inlink->cur_buf);
238 inlink->cur_buf = NULL;
242 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
244 process_frame(inlink, buf);
245 return 0; /* enhancement: handle error return */
248 static void close_input(AVFilterContext *ctx, unsigned in_no)
250 ConcatContext *cat = ctx->priv;
252 cat->in[in_no].eof = 1;
254 av_log(ctx, AV_LOG_VERBOSE, "EOF on %s, %d streams left in segment.\n",
255 ctx->input_pads[in_no].name, cat->nb_in_active);
258 static void find_next_delta_ts(AVFilterContext *ctx)
260 ConcatContext *cat = ctx->priv;
261 unsigned i = cat->cur_idx;
262 unsigned imax = i + ctx->nb_outputs;
265 pts = cat->in[i++].pts;
266 for (; i < imax; i++)
267 pts = FFMAX(pts, cat->in[i].pts);
268 cat->delta_ts += pts;
271 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
273 ConcatContext *cat = ctx->priv;
274 AVFilterLink *outlink = ctx->outputs[out_no];
275 int64_t base_pts = cat->in[in_no].pts + cat->delta_ts;
276 int64_t nb_samples, sent = 0;
277 int frame_nb_samples;
278 AVRational rate_tb = { 1, ctx->inputs[in_no]->sample_rate };
279 AVFilterBufferRef *buf;
280 int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
284 nb_samples = av_rescale_q(cat->delta_ts - base_pts,
285 outlink->time_base, rate_tb);
286 frame_nb_samples = FFMAX(9600, rate_tb.den / 5); /* arbitrary */
288 frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
289 buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
292 av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
293 nb_channels, outlink->format);
294 buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
295 ff_filter_samples(outlink, buf);
296 sent += frame_nb_samples;
297 nb_samples -= frame_nb_samples;
301 static void flush_segment(AVFilterContext *ctx)
303 ConcatContext *cat = ctx->priv;
304 unsigned str, str_max;
306 find_next_delta_ts(ctx);
307 cat->cur_idx += ctx->nb_outputs;
308 cat->nb_in_active = ctx->nb_outputs;
309 av_log(ctx, AV_LOG_VERBOSE, "Segment finished at pts=%"PRId64"\n",
312 if (cat->cur_idx < ctx->nb_inputs) {
313 /* pad audio streams with silence */
314 str = cat->nb_streams[AVMEDIA_TYPE_VIDEO];
315 str_max = str + cat->nb_streams[AVMEDIA_TYPE_AUDIO];
316 for (; str < str_max; str++)
317 send_silence(ctx, cat->cur_idx - ctx->nb_outputs + str, str);
318 /* flush queued buffers */
319 /* possible enhancement: flush in PTS order */
320 str_max = cat->cur_idx + ctx->nb_outputs;
321 for (str = cat->cur_idx; str < str_max; str++)
322 while (cat->in[str].queue.available)
323 push_frame(ctx, str, ff_bufqueue_get(&cat->in[str].queue));
327 static int request_frame(AVFilterLink *outlink)
329 AVFilterContext *ctx = outlink->src;
330 ConcatContext *cat = ctx->priv;
331 unsigned out_no = FF_OUTLINK_IDX(outlink);
332 unsigned in_no = out_no + cat->cur_idx;
333 unsigned str, str_max;
337 if (in_no >= ctx->nb_inputs)
339 if (!cat->in[in_no].eof) {
340 ret = ff_request_frame(ctx->inputs[in_no]);
341 if (ret != AVERROR_EOF)
343 close_input(ctx, in_no);
345 /* cycle on all inputs to finish the segment */
346 /* possible enhancement: request in PTS order */
347 str_max = cat->cur_idx + ctx->nb_outputs - 1;
348 for (str = cat->cur_idx; cat->nb_in_active;
349 str = str == str_max ? cat->cur_idx : str + 1) {
350 if (cat->in[str].eof)
352 ret = ff_request_frame(ctx->inputs[str]);
353 if (ret == AVERROR_EOF)
354 close_input(ctx, str);
359 in_no += ctx->nb_outputs;
363 static av_cold int init(AVFilterContext *ctx, const char *args)
365 ConcatContext *cat = ctx->priv;
367 unsigned seg, type, str;
370 cat->class = &concat_class;
371 av_opt_set_defaults(cat);
372 ret = av_set_options_string(cat, args, "=", ":");
374 av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
378 /* create input pads */
379 for (seg = 0; seg < cat->nb_segments; seg++) {
380 for (type = 0; type < TYPE_ALL; type++) {
381 for (str = 0; str < cat->nb_streams[type]; str++) {
384 .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
385 .get_video_buffer = get_video_buffer,
386 .get_audio_buffer = get_audio_buffer,
388 snprintf(name, sizeof(name), "in%d:%c%d", seg, "va"[type], str);
389 pad.name = av_strdup(name);
390 if (type == AVMEDIA_TYPE_VIDEO) {
391 pad.start_frame = start_frame;
392 pad.draw_slice = draw_slice;
393 pad.end_frame = end_frame;
395 pad.filter_samples = filter_samples;
397 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
401 /* create output pads */
402 for (type = 0; type < TYPE_ALL; type++) {
403 for (str = 0; str < cat->nb_streams[type]; str++) {
406 .config_props = config_output,
407 .request_frame = request_frame,
409 snprintf(name, sizeof(name), "out:%c%d", "va"[type], str);
410 pad.name = av_strdup(name);
411 ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
415 cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
417 return AVERROR(ENOMEM);
418 cat->nb_in_active = ctx->nb_outputs;
422 static av_cold void uninit(AVFilterContext *ctx)
424 ConcatContext *cat = ctx->priv;
427 for (i = 0; i < ctx->nb_inputs; i++) {
428 av_freep(&ctx->input_pads[i].name);
429 ff_bufqueue_discard_all(&cat->in[i].queue);
431 for (i = 0; i < ctx->nb_outputs; i++)
432 av_freep(&ctx->output_pads[i].name);
436 AVFilter avfilter_avf_concat = {
438 .description = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
441 .query_formats = query_formats,
442 .priv_size = sizeof(ConcatContext),
443 .inputs = (const AVFilterPad[]) { { .name = NULL } },
444 .outputs = (const AVFilterPad[]) { { .name = NULL } },
445 .priv_class = &concat_class,