]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_concat.c
Merge commit '36ef5369ee9b336febc2c270f8718cec4476cb85'
[ffmpeg] / libavfilter / avf_concat.c
1 /*
2  * Copyright (c) 2012 Nicolas George
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.
14  * See the GNU Lesser General Public License for more details.
15  *
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
19  */
20
21 /**
22  * @file
23  * concat audio-video filter
24  */
25
26 #include "libavutil/audioconvert.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/opt.h"
29 #include "avfilter.h"
30 #define FF_BUFQUEUE_SIZE 256
31 #include "bufferqueue.h"
32 #include "internal.h"
33 #include "video.h"
34 #include "audio.h"
35
36 #define TYPE_ALL 2
37
38 typedef struct {
39     const AVClass *class;
40     unsigned nb_streams[TYPE_ALL]; /**< number of out streams of each type */
41     unsigned nb_segments;
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 */
45     struct concat_in {
46         int64_t pts;
47         int64_t nb_frames;
48         unsigned eof;
49         struct FFBufQueue queue;
50     } *in;
51 } ConcatContext;
52
53 #define OFFSET(x) offsetof(ConcatContext, x)
54
55 static const AVOption concat_options[] = {
56     { "n", "specify the number of segments", OFFSET(nb_segments),
57       AV_OPT_TYPE_INT, { .dbl = 2 }, 2, INT_MAX },
58     { "v", "specify the number of video streams",
59       OFFSET(nb_streams[AVMEDIA_TYPE_VIDEO]),
60       AV_OPT_TYPE_INT, { .dbl = 1 }, 0, INT_MAX },
61     { "a", "specify the number of audio streams",
62       OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
63       AV_OPT_TYPE_INT, { .dbl = 0 }, 0, INT_MAX },
64     { 0 }
65 };
66
67 AVFILTER_DEFINE_CLASS(concat);
68
69 static int query_formats(AVFilterContext *ctx)
70 {
71     ConcatContext *cat = ctx->priv;
72     unsigned type, nb_str, idx0 = 0, idx, str, seg;
73     AVFilterFormats *formats, *rates;
74     AVFilterChannelLayouts *layouts;
75
76     for (type = 0; type < TYPE_ALL; type++) {
77         nb_str = cat->nb_streams[type];
78         for (str = 0; str < nb_str; str++) {
79             idx = idx0;
80
81             /* Set the output formats */
82             formats = ff_all_formats(type);
83             if (!formats)
84                 return AVERROR(ENOMEM);
85             ff_formats_ref(formats, &ctx->outputs[idx]->in_formats);
86             if (type == AVMEDIA_TYPE_AUDIO) {
87                 rates = ff_all_samplerates();
88                 if (!rates)
89                     return AVERROR(ENOMEM);
90                 ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
91                 layouts = ff_all_channel_layouts();
92                 if (!layouts)
93                     return AVERROR(ENOMEM);
94                 ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
95             }
96
97             /* Set the same formats for each corresponding input */
98             for (seg = 0; seg < cat->nb_segments; seg++) {
99                 ff_formats_ref(formats, &ctx->inputs[idx]->out_formats);
100                 if (type == AVMEDIA_TYPE_AUDIO) {
101                     ff_formats_ref(rates, &ctx->inputs[idx]->out_samplerates);
102                     ff_channel_layouts_ref(layouts, &ctx->inputs[idx]->out_channel_layouts);
103                 }
104                 idx += ctx->nb_outputs;
105             }
106
107             idx0++;
108         }
109     }
110     return 0;
111 }
112
113 static int config_output(AVFilterLink *outlink)
114 {
115     AVFilterContext *ctx = outlink->src;
116     ConcatContext *cat   = ctx->priv;
117     unsigned out_no = FF_OUTLINK_IDX(outlink);
118     unsigned in_no  = out_no, seg;
119     AVFilterLink *inlink = ctx->inputs[in_no];
120
121     /* enhancement: find a common one */
122     outlink->time_base           = AV_TIME_BASE_Q;
123     outlink->w                   = inlink->w;
124     outlink->h                   = inlink->h;
125     outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
126     outlink->format              = inlink->format;
127     for (seg = 1; seg < cat->nb_segments; seg++) {
128         inlink = ctx->inputs[in_no += ctx->nb_outputs];
129         /* possible enhancement: unsafe mode, do not check */
130         if (outlink->w                       != inlink->w                       ||
131             outlink->h                       != inlink->h                       ||
132             outlink->sample_aspect_ratio.num != inlink->sample_aspect_ratio.num ||
133             outlink->sample_aspect_ratio.den != inlink->sample_aspect_ratio.den) {
134             av_log(ctx, AV_LOG_ERROR, "Input link %s parameters "
135                    "(size %dx%d, SAR %d:%d) do not match the corresponding "
136                    "output link %s parameters (%dx%d, SAR %d:%d)\n",
137                    ctx->input_pads[in_no].name, inlink->w, inlink->h,
138                    inlink->sample_aspect_ratio.num,
139                    inlink->sample_aspect_ratio.den,
140                    ctx->input_pads[out_no].name, outlink->w, outlink->h,
141                    outlink->sample_aspect_ratio.num,
142                    outlink->sample_aspect_ratio.den);
143             return AVERROR(EINVAL);
144         }
145     }
146
147     return 0;
148 }
149
150 static void push_frame(AVFilterContext *ctx, unsigned in_no,
151                        AVFilterBufferRef *buf)
152 {
153     ConcatContext *cat = ctx->priv;
154     unsigned out_no = in_no % ctx->nb_outputs;
155     AVFilterLink * inlink = ctx-> inputs[ in_no];
156     AVFilterLink *outlink = ctx->outputs[out_no];
157     struct concat_in *in = &cat->in[in_no];
158
159     buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
160     in->pts = buf->pts;
161     in->nb_frames++;
162     /* add duration to input PTS */
163     if (inlink->sample_rate)
164         /* use number of audio samples */
165         in->pts += av_rescale_q(buf->audio->nb_samples,
166                                 (AVRational){ 1, inlink->sample_rate },
167                                 outlink->time_base);
168     else if (in->nb_frames >= 2)
169         /* use mean duration */
170         in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
171
172     buf->pts += cat->delta_ts;
173     switch (buf->type) {
174     case AVMEDIA_TYPE_VIDEO:
175         ff_start_frame(outlink, buf);
176         ff_draw_slice(outlink, 0, outlink->h, 1);
177         ff_end_frame(outlink);
178         break;
179     case AVMEDIA_TYPE_AUDIO:
180         ff_filter_samples(outlink, buf);
181         break;
182     }
183 }
184
185 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
186 {
187     AVFilterContext *ctx  = inlink->dst;
188     ConcatContext *cat    = ctx->priv;
189     unsigned in_no = FF_INLINK_IDX(inlink);
190
191     if (in_no < cat->cur_idx) {
192         av_log(ctx, AV_LOG_ERROR, "Frame after EOF on input %s\n",
193                ctx->input_pads[in_no].name);
194         avfilter_unref_buffer(buf);
195     } if (in_no >= cat->cur_idx + ctx->nb_outputs) {
196         ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
197     } else {
198         push_frame(ctx, in_no, buf);
199     }
200 }
201
202 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
203                                            int w, int h)
204 {
205     AVFilterContext *ctx = inlink->dst;
206     unsigned in_no = FF_INLINK_IDX(inlink);
207     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
208
209     return ff_get_video_buffer(outlink, perms, w, h);
210 }
211
212 static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
213                                            int nb_samples)
214 {
215     AVFilterContext *ctx = inlink->dst;
216     unsigned in_no = FF_INLINK_IDX(inlink);
217     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
218
219     return ff_get_audio_buffer(outlink, perms, nb_samples);
220 }
221
222 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
223 {
224     return 0;
225 }
226
227 static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
228 {
229     return 0;
230 }
231
232 static int end_frame(AVFilterLink *inlink)
233 {
234     process_frame(inlink, inlink->cur_buf);
235     inlink->cur_buf = NULL;
236     return 0;
237 }
238
239 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
240 {
241     process_frame(inlink, buf);
242     return 0; /* enhancement: handle error return */
243 }
244
245 static void close_input(AVFilterContext *ctx, unsigned in_no)
246 {
247     ConcatContext *cat = ctx->priv;
248
249     cat->in[in_no].eof = 1;
250     cat->nb_in_active--;
251     av_log(ctx, AV_LOG_VERBOSE, "EOF on %s, %d streams left in segment.\n",
252            ctx->input_pads[in_no].name, cat->nb_in_active);
253 }
254
255 static void find_next_delta_ts(AVFilterContext *ctx)
256 {
257     ConcatContext *cat = ctx->priv;
258     unsigned i = cat->cur_idx;
259     unsigned imax = i + ctx->nb_outputs;
260     int64_t pts;
261
262     pts = cat->in[i++].pts;
263     for (; i < imax; i++)
264         pts = FFMAX(pts, cat->in[i].pts);
265     cat->delta_ts += pts;
266 }
267
268 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
269 {
270     ConcatContext *cat = ctx->priv;
271     AVFilterLink *outlink = ctx->outputs[out_no];
272     int64_t base_pts = cat->in[in_no].pts + cat->delta_ts;
273     int64_t nb_samples, sent = 0;
274     int frame_nb_samples;
275     AVRational rate_tb = { 1, ctx->inputs[in_no]->sample_rate };
276     AVFilterBufferRef *buf;
277     int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
278
279     if (!rate_tb.den)
280         return;
281     nb_samples = av_rescale_q(cat->delta_ts - base_pts,
282                               outlink->time_base, rate_tb);
283     frame_nb_samples = FFMAX(9600, rate_tb.den / 5); /* arbitrary */
284     while (nb_samples) {
285         frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
286         buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
287         if (!buf)
288             return;
289         av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
290                                nb_channels, outlink->format);
291         buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
292         ff_filter_samples(outlink, buf);
293         sent       += frame_nb_samples;
294         nb_samples -= frame_nb_samples;
295     }
296 }
297
298 static void flush_segment(AVFilterContext *ctx)
299 {
300     ConcatContext *cat = ctx->priv;
301     unsigned str, str_max;
302
303     find_next_delta_ts(ctx);
304     cat->cur_idx += ctx->nb_outputs;
305     cat->nb_in_active = ctx->nb_outputs;
306     av_log(ctx, AV_LOG_VERBOSE, "Segment finished at pts=%"PRId64"\n",
307            cat->delta_ts);
308
309     if (cat->cur_idx < ctx->nb_inputs) {
310         /* pad audio streams with silence */
311         str = cat->nb_streams[AVMEDIA_TYPE_VIDEO];
312         str_max = str + cat->nb_streams[AVMEDIA_TYPE_AUDIO];
313         for (; str < str_max; str++)
314             send_silence(ctx, cat->cur_idx - ctx->nb_outputs + str, str);
315         /* flush queued buffers */
316         /* possible enhancement: flush in PTS order */
317         str_max = cat->cur_idx + ctx->nb_outputs;
318         for (str = cat->cur_idx; str < str_max; str++)
319             while (cat->in[str].queue.available)
320                 push_frame(ctx, str, ff_bufqueue_get(&cat->in[str].queue));
321     }
322 }
323
324 static int request_frame(AVFilterLink *outlink)
325 {
326     AVFilterContext *ctx = outlink->src;
327     ConcatContext *cat   = ctx->priv;
328     unsigned out_no = FF_OUTLINK_IDX(outlink);
329     unsigned in_no  = out_no + cat->cur_idx;
330     unsigned str, str_max;
331     int ret;
332
333     while (1) {
334         if (in_no >= ctx->nb_inputs)
335             return AVERROR_EOF;
336         if (!cat->in[in_no].eof) {
337             ret = ff_request_frame(ctx->inputs[in_no]);
338             if (ret != AVERROR_EOF)
339                 return ret;
340             close_input(ctx, in_no);
341         }
342         /* cycle on all inputs to finish the segment */
343         /* possible enhancement: request in PTS order */
344         str_max = cat->cur_idx + ctx->nb_outputs - 1;
345         for (str = cat->cur_idx; cat->nb_in_active;
346              str = str == str_max ? cat->cur_idx : str + 1) {
347             if (cat->in[str].eof)
348                 continue;
349             ret = ff_request_frame(ctx->inputs[str]);
350             if (ret == AVERROR_EOF)
351                 close_input(ctx, str);
352             else if (ret < 0)
353                 return ret;
354         }
355         flush_segment(ctx);
356         in_no += ctx->nb_outputs;
357     }
358 }
359
360 static av_cold int init(AVFilterContext *ctx, const char *args)
361 {
362     ConcatContext *cat = ctx->priv;
363     int ret;
364     unsigned seg, type, str;
365     char name[32];
366
367     cat->class = &concat_class;
368     av_opt_set_defaults(cat);
369     ret = av_set_options_string(cat, args, "=", ":");
370     if (ret < 0) {
371         av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
372         return ret;
373     }
374
375     /* create input pads */
376     for (seg = 0; seg < cat->nb_segments; seg++) {
377         for (type = 0; type < TYPE_ALL; type++) {
378             for (str = 0; str < cat->nb_streams[type]; str++) {
379                 AVFilterPad pad = {
380                     .type             = type,
381                     .min_perms        = AV_PERM_READ,
382                     .rej_perms        = AV_PERM_REUSE2,
383                     .get_video_buffer = get_video_buffer,
384                     .get_audio_buffer = get_audio_buffer,
385                 };
386                 snprintf(name, sizeof(name), "in%d:%c%d", seg, "va"[type], str);
387                 pad.name = av_strdup(name);
388                 if (type == AVMEDIA_TYPE_VIDEO) {
389                     pad.start_frame = start_frame;
390                     pad.draw_slice  = draw_slice;
391                     pad.end_frame   = end_frame;
392                 } else {
393                     pad.filter_samples = filter_samples;
394                 }
395                 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
396             }
397         }
398     }
399     /* create output pads */
400     for (type = 0; type < TYPE_ALL; type++) {
401         for (str = 0; str < cat->nb_streams[type]; str++) {
402             AVFilterPad pad = {
403                 .type          = type,
404                 .config_props  = config_output,
405                 .request_frame = request_frame,
406             };
407             snprintf(name, sizeof(name), "out:%c%d", "va"[type], str);
408             pad.name = av_strdup(name);
409             ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
410         }
411     }
412
413     cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
414     if (!cat->in)
415         return AVERROR(ENOMEM);
416     cat->nb_in_active = ctx->nb_outputs;
417     return 0;
418 }
419
420 static av_cold void uninit(AVFilterContext *ctx)
421 {
422     ConcatContext *cat = ctx->priv;
423     unsigned i;
424
425     for (i = 0; i < ctx->nb_inputs; i++) {
426         av_freep(&ctx->input_pads[i].name);
427         ff_bufqueue_discard_all(&cat->in[i].queue);
428     }
429     for (i = 0; i < ctx->nb_outputs; i++)
430         av_freep(&ctx->output_pads[i].name);
431     av_free(cat->in);
432 }
433
434 AVFilter avfilter_avf_concat = {
435     .name          = "concat",
436     .description   = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
437     .init          = init,
438     .uninit        = uninit,
439     .query_formats = query_formats,
440     .priv_size     = sizeof(ConcatContext),
441     .inputs        = (const AVFilterPad[]) { { .name = NULL } },
442     .outputs       = (const AVFilterPad[]) { { .name = NULL } },
443 };