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 */
50 struct FFBufQueue queue;
54 #define OFFSET(x) offsetof(ConcatContext, x)
55 #define A AV_OPT_FLAG_AUDIO_PARAM
56 #define F AV_OPT_FLAG_FILTERING_PARAM
57 #define V AV_OPT_FLAG_VIDEO_PARAM
59 static const AVOption concat_options[] = {
60 { "n", "specify the number of segments", OFFSET(nb_segments),
61 AV_OPT_TYPE_INT, { .i64 = 2 }, 2, INT_MAX, V|A|F},
62 { "v", "specify the number of video streams",
63 OFFSET(nb_streams[AVMEDIA_TYPE_VIDEO]),
64 AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, V|F },
65 { "a", "specify the number of audio streams",
66 OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
67 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|F},
68 { "unsafe", "enable unsafe mode",
70 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|A|F},
74 AVFILTER_DEFINE_CLASS(concat);
76 static int query_formats(AVFilterContext *ctx)
78 ConcatContext *cat = ctx->priv;
79 unsigned type, nb_str, idx0 = 0, idx, str, seg;
80 AVFilterFormats *formats, *rates;
81 AVFilterChannelLayouts *layouts;
83 for (type = 0; type < TYPE_ALL; type++) {
84 nb_str = cat->nb_streams[type];
85 for (str = 0; str < nb_str; str++) {
88 /* Set the output formats */
89 formats = ff_all_formats(type);
91 return AVERROR(ENOMEM);
92 ff_formats_ref(formats, &ctx->outputs[idx]->in_formats);
93 if (type == AVMEDIA_TYPE_AUDIO) {
94 rates = ff_all_samplerates();
96 return AVERROR(ENOMEM);
97 ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
98 layouts = ff_all_channel_layouts();
100 return AVERROR(ENOMEM);
101 ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
104 /* Set the same formats for each corresponding input */
105 for (seg = 0; seg < cat->nb_segments; seg++) {
106 ff_formats_ref(formats, &ctx->inputs[idx]->out_formats);
107 if (type == AVMEDIA_TYPE_AUDIO) {
108 ff_formats_ref(rates, &ctx->inputs[idx]->out_samplerates);
109 ff_channel_layouts_ref(layouts, &ctx->inputs[idx]->out_channel_layouts);
111 idx += ctx->nb_outputs;
120 static int config_output(AVFilterLink *outlink)
122 AVFilterContext *ctx = outlink->src;
123 ConcatContext *cat = ctx->priv;
124 unsigned out_no = FF_OUTLINK_IDX(outlink);
125 unsigned in_no = out_no, seg;
126 AVFilterLink *inlink = ctx->inputs[in_no];
128 /* enhancement: find a common one */
129 outlink->time_base = AV_TIME_BASE_Q;
130 outlink->w = inlink->w;
131 outlink->h = inlink->h;
132 outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
133 outlink->format = inlink->format;
134 for (seg = 1; seg < cat->nb_segments; seg++) {
135 inlink = ctx->inputs[in_no += ctx->nb_outputs];
136 /* possible enhancement: unsafe mode, do not check */
137 if (outlink->w != inlink->w ||
138 outlink->h != inlink->h ||
139 outlink->sample_aspect_ratio.num != inlink->sample_aspect_ratio.num ||
140 outlink->sample_aspect_ratio.den != inlink->sample_aspect_ratio.den) {
141 av_log(ctx, AV_LOG_ERROR, "Input link %s parameters "
142 "(size %dx%d, SAR %d:%d) do not match the corresponding "
143 "output link %s parameters (%dx%d, SAR %d:%d)\n",
144 ctx->input_pads[in_no].name, inlink->w, inlink->h,
145 inlink->sample_aspect_ratio.num,
146 inlink->sample_aspect_ratio.den,
147 ctx->input_pads[out_no].name, outlink->w, outlink->h,
148 outlink->sample_aspect_ratio.num,
149 outlink->sample_aspect_ratio.den);
151 return AVERROR(EINVAL);
158 static void push_frame(AVFilterContext *ctx, unsigned in_no,
159 AVFilterBufferRef *buf)
161 ConcatContext *cat = ctx->priv;
162 unsigned out_no = in_no % ctx->nb_outputs;
163 AVFilterLink * inlink = ctx-> inputs[ in_no];
164 AVFilterLink *outlink = ctx->outputs[out_no];
165 struct concat_in *in = &cat->in[in_no];
167 buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
170 /* add duration to input PTS */
171 if (inlink->sample_rate)
172 /* use number of audio samples */
173 in->pts += av_rescale_q(buf->audio->nb_samples,
174 (AVRational){ 1, inlink->sample_rate },
176 else if (in->nb_frames >= 2)
177 /* use mean duration */
178 in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
180 buf->pts += cat->delta_ts;
182 case AVMEDIA_TYPE_VIDEO:
183 ff_start_frame(outlink, buf);
184 ff_draw_slice(outlink, 0, outlink->h, 1);
185 ff_end_frame(outlink);
187 case AVMEDIA_TYPE_AUDIO:
188 ff_filter_samples(outlink, buf);
193 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
195 AVFilterContext *ctx = inlink->dst;
196 ConcatContext *cat = ctx->priv;
197 unsigned in_no = FF_INLINK_IDX(inlink);
199 if (in_no < cat->cur_idx) {
200 av_log(ctx, AV_LOG_ERROR, "Frame after EOF on input %s\n",
201 ctx->input_pads[in_no].name);
202 avfilter_unref_buffer(buf);
203 } else if (in_no >= cat->cur_idx + ctx->nb_outputs) {
204 ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
206 push_frame(ctx, in_no, buf);
210 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
213 AVFilterContext *ctx = inlink->dst;
214 unsigned in_no = FF_INLINK_IDX(inlink);
215 AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
217 return ff_get_video_buffer(outlink, perms, w, h);
220 static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
223 AVFilterContext *ctx = inlink->dst;
224 unsigned in_no = FF_INLINK_IDX(inlink);
225 AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
227 return ff_get_audio_buffer(outlink, perms, nb_samples);
230 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
235 static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
240 static int end_frame(AVFilterLink *inlink)
242 process_frame(inlink, inlink->cur_buf);
243 inlink->cur_buf = NULL;
247 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
249 process_frame(inlink, buf);
250 return 0; /* enhancement: handle error return */
253 static void close_input(AVFilterContext *ctx, unsigned in_no)
255 ConcatContext *cat = ctx->priv;
257 cat->in[in_no].eof = 1;
259 av_log(ctx, AV_LOG_VERBOSE, "EOF on %s, %d streams left in segment.\n",
260 ctx->input_pads[in_no].name, cat->nb_in_active);
263 static void find_next_delta_ts(AVFilterContext *ctx)
265 ConcatContext *cat = ctx->priv;
266 unsigned i = cat->cur_idx;
267 unsigned imax = i + ctx->nb_outputs;
270 pts = cat->in[i++].pts;
271 for (; i < imax; i++)
272 pts = FFMAX(pts, cat->in[i].pts);
273 cat->delta_ts += pts;
276 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
278 ConcatContext *cat = ctx->priv;
279 AVFilterLink *outlink = ctx->outputs[out_no];
280 int64_t base_pts = cat->in[in_no].pts + cat->delta_ts;
281 int64_t nb_samples, sent = 0;
282 int frame_nb_samples;
283 AVRational rate_tb = { 1, ctx->inputs[in_no]->sample_rate };
284 AVFilterBufferRef *buf;
285 int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
289 nb_samples = av_rescale_q(cat->delta_ts - base_pts,
290 outlink->time_base, rate_tb);
291 frame_nb_samples = FFMAX(9600, rate_tb.den / 5); /* arbitrary */
293 frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
294 buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
297 av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
298 nb_channels, outlink->format);
299 buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
300 ff_filter_samples(outlink, buf);
301 sent += frame_nb_samples;
302 nb_samples -= frame_nb_samples;
306 static void flush_segment(AVFilterContext *ctx)
308 ConcatContext *cat = ctx->priv;
309 unsigned str, str_max;
311 find_next_delta_ts(ctx);
312 cat->cur_idx += ctx->nb_outputs;
313 cat->nb_in_active = ctx->nb_outputs;
314 av_log(ctx, AV_LOG_VERBOSE, "Segment finished at pts=%"PRId64"\n",
317 if (cat->cur_idx < ctx->nb_inputs) {
318 /* pad audio streams with silence */
319 str = cat->nb_streams[AVMEDIA_TYPE_VIDEO];
320 str_max = str + cat->nb_streams[AVMEDIA_TYPE_AUDIO];
321 for (; str < str_max; str++)
322 send_silence(ctx, cat->cur_idx - ctx->nb_outputs + str, str);
323 /* flush queued buffers */
324 /* possible enhancement: flush in PTS order */
325 str_max = cat->cur_idx + ctx->nb_outputs;
326 for (str = cat->cur_idx; str < str_max; str++)
327 while (cat->in[str].queue.available)
328 push_frame(ctx, str, ff_bufqueue_get(&cat->in[str].queue));
332 static int request_frame(AVFilterLink *outlink)
334 AVFilterContext *ctx = outlink->src;
335 ConcatContext *cat = ctx->priv;
336 unsigned out_no = FF_OUTLINK_IDX(outlink);
337 unsigned in_no = out_no + cat->cur_idx;
338 unsigned str, str_max;
342 if (in_no >= ctx->nb_inputs)
344 if (!cat->in[in_no].eof) {
345 ret = ff_request_frame(ctx->inputs[in_no]);
346 if (ret != AVERROR_EOF)
348 close_input(ctx, in_no);
350 /* cycle on all inputs to finish the segment */
351 /* possible enhancement: request in PTS order */
352 str_max = cat->cur_idx + ctx->nb_outputs - 1;
353 for (str = cat->cur_idx; cat->nb_in_active;
354 str = str == str_max ? cat->cur_idx : str + 1) {
355 if (cat->in[str].eof)
357 ret = ff_request_frame(ctx->inputs[str]);
358 if (ret == AVERROR_EOF)
359 close_input(ctx, str);
364 in_no += ctx->nb_outputs;
368 static av_cold int init(AVFilterContext *ctx, const char *args)
370 ConcatContext *cat = ctx->priv;
372 unsigned seg, type, str;
375 cat->class = &concat_class;
376 av_opt_set_defaults(cat);
377 ret = av_set_options_string(cat, args, "=", ":");
379 av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
383 /* create input pads */
384 for (seg = 0; seg < cat->nb_segments; seg++) {
385 for (type = 0; type < TYPE_ALL; type++) {
386 for (str = 0; str < cat->nb_streams[type]; str++) {
389 .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
390 .get_video_buffer = get_video_buffer,
391 .get_audio_buffer = get_audio_buffer,
393 snprintf(name, sizeof(name), "in%d:%c%d", seg, "va"[type], str);
394 pad.name = av_strdup(name);
395 if (type == AVMEDIA_TYPE_VIDEO) {
396 pad.start_frame = start_frame;
397 pad.draw_slice = draw_slice;
398 pad.end_frame = end_frame;
400 pad.filter_samples = filter_samples;
402 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
406 /* create output pads */
407 for (type = 0; type < TYPE_ALL; type++) {
408 for (str = 0; str < cat->nb_streams[type]; str++) {
411 .config_props = config_output,
412 .request_frame = request_frame,
414 snprintf(name, sizeof(name), "out:%c%d", "va"[type], str);
415 pad.name = av_strdup(name);
416 ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
420 cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
422 return AVERROR(ENOMEM);
423 cat->nb_in_active = ctx->nb_outputs;
427 static av_cold void uninit(AVFilterContext *ctx)
429 ConcatContext *cat = ctx->priv;
432 for (i = 0; i < ctx->nb_inputs; i++) {
433 av_freep(&ctx->input_pads[i].name);
434 ff_bufqueue_discard_all(&cat->in[i].queue);
436 for (i = 0; i < ctx->nb_outputs; i++)
437 av_freep(&ctx->output_pads[i].name);
441 AVFilter avfilter_avf_concat = {
443 .description = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
446 .query_formats = query_formats,
447 .priv_size = sizeof(ConcatContext),
448 .inputs = (const AVFilterPad[]) { { .name = NULL } },
449 .outputs = (const AVFilterPad[]) { { .name = NULL } },
450 .priv_class = &concat_class,