]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_concat.c
Merge commit '4521645b1aee9e9ad8f5cea7b2392cd5f6ffcd26'
[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     unsigned unsafe;
46     struct concat_in {
47         int64_t pts;
48         int64_t nb_frames;
49         unsigned eof;
50         struct FFBufQueue queue;
51     } *in;
52 } ConcatContext;
53
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
58
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",
69       OFFSET(unsafe),
70       AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|A|F},
71     { 0 }
72 };
73
74 AVFILTER_DEFINE_CLASS(concat);
75
76 static int query_formats(AVFilterContext *ctx)
77 {
78     ConcatContext *cat = ctx->priv;
79     unsigned type, nb_str, idx0 = 0, idx, str, seg;
80     AVFilterFormats *formats, *rates;
81     AVFilterChannelLayouts *layouts;
82
83     for (type = 0; type < TYPE_ALL; type++) {
84         nb_str = cat->nb_streams[type];
85         for (str = 0; str < nb_str; str++) {
86             idx = idx0;
87
88             /* Set the output formats */
89             formats = ff_all_formats(type);
90             if (!formats)
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();
95                 if (!rates)
96                     return AVERROR(ENOMEM);
97                 ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
98                 layouts = ff_all_channel_layouts();
99                 if (!layouts)
100                     return AVERROR(ENOMEM);
101                 ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
102             }
103
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);
110                 }
111                 idx += ctx->nb_outputs;
112             }
113
114             idx0++;
115         }
116     }
117     return 0;
118 }
119
120 static int config_output(AVFilterLink *outlink)
121 {
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];
127
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);
150             if (!cat->unsafe)
151                 return AVERROR(EINVAL);
152         }
153     }
154
155     return 0;
156 }
157
158 static void push_frame(AVFilterContext *ctx, unsigned in_no,
159                        AVFilterBufferRef *buf)
160 {
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];
166
167     buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
168     in->pts = buf->pts;
169     in->nb_frames++;
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 },
175                                 outlink->time_base);
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);
179
180     buf->pts += cat->delta_ts;
181     switch (buf->type) {
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);
186         break;
187     case AVMEDIA_TYPE_AUDIO:
188         ff_filter_samples(outlink, buf);
189         break;
190     }
191 }
192
193 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
194 {
195     AVFilterContext *ctx  = inlink->dst;
196     ConcatContext *cat    = ctx->priv;
197     unsigned in_no = FF_INLINK_IDX(inlink);
198
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);
205     } else {
206         push_frame(ctx, in_no, buf);
207     }
208 }
209
210 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
211                                            int w, int h)
212 {
213     AVFilterContext *ctx = inlink->dst;
214     unsigned in_no = FF_INLINK_IDX(inlink);
215     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
216
217     return ff_get_video_buffer(outlink, perms, w, h);
218 }
219
220 static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
221                                            int nb_samples)
222 {
223     AVFilterContext *ctx = inlink->dst;
224     unsigned in_no = FF_INLINK_IDX(inlink);
225     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
226
227     return ff_get_audio_buffer(outlink, perms, nb_samples);
228 }
229
230 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
231 {
232     return 0;
233 }
234
235 static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
236 {
237     return 0;
238 }
239
240 static int end_frame(AVFilterLink *inlink)
241 {
242     process_frame(inlink, inlink->cur_buf);
243     inlink->cur_buf = NULL;
244     return 0;
245 }
246
247 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
248 {
249     process_frame(inlink, buf);
250     return 0; /* enhancement: handle error return */
251 }
252
253 static void close_input(AVFilterContext *ctx, unsigned in_no)
254 {
255     ConcatContext *cat = ctx->priv;
256
257     cat->in[in_no].eof = 1;
258     cat->nb_in_active--;
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);
261 }
262
263 static void find_next_delta_ts(AVFilterContext *ctx)
264 {
265     ConcatContext *cat = ctx->priv;
266     unsigned i = cat->cur_idx;
267     unsigned imax = i + ctx->nb_outputs;
268     int64_t pts;
269
270     pts = cat->in[i++].pts;
271     for (; i < imax; i++)
272         pts = FFMAX(pts, cat->in[i].pts);
273     cat->delta_ts += pts;
274 }
275
276 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
277 {
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);
286
287     if (!rate_tb.den)
288         return;
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 */
292     while (nb_samples) {
293         frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
294         buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
295         if (!buf)
296             return;
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;
303     }
304 }
305
306 static void flush_segment(AVFilterContext *ctx)
307 {
308     ConcatContext *cat = ctx->priv;
309     unsigned str, str_max;
310
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",
315            cat->delta_ts);
316
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));
329     }
330 }
331
332 static int request_frame(AVFilterLink *outlink)
333 {
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;
339     int ret;
340
341     while (1) {
342         if (in_no >= ctx->nb_inputs)
343             return AVERROR_EOF;
344         if (!cat->in[in_no].eof) {
345             ret = ff_request_frame(ctx->inputs[in_no]);
346             if (ret != AVERROR_EOF)
347                 return ret;
348             close_input(ctx, in_no);
349         }
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)
356                 continue;
357             ret = ff_request_frame(ctx->inputs[str]);
358             if (ret == AVERROR_EOF)
359                 close_input(ctx, str);
360             else if (ret < 0)
361                 return ret;
362         }
363         flush_segment(ctx);
364         in_no += ctx->nb_outputs;
365     }
366 }
367
368 static av_cold int init(AVFilterContext *ctx, const char *args)
369 {
370     ConcatContext *cat = ctx->priv;
371     int ret;
372     unsigned seg, type, str;
373     char name[32];
374
375     cat->class = &concat_class;
376     av_opt_set_defaults(cat);
377     ret = av_set_options_string(cat, args, "=", ":");
378     if (ret < 0) {
379         av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
380         return ret;
381     }
382
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++) {
387                 AVFilterPad pad = {
388                     .type             = type,
389                     .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
390                     .get_video_buffer = get_video_buffer,
391                     .get_audio_buffer = get_audio_buffer,
392                 };
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;
399                 } else {
400                     pad.filter_samples = filter_samples;
401                 }
402                 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
403             }
404         }
405     }
406     /* create output pads */
407     for (type = 0; type < TYPE_ALL; type++) {
408         for (str = 0; str < cat->nb_streams[type]; str++) {
409             AVFilterPad pad = {
410                 .type          = type,
411                 .config_props  = config_output,
412                 .request_frame = request_frame,
413             };
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);
417         }
418     }
419
420     cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
421     if (!cat->in)
422         return AVERROR(ENOMEM);
423     cat->nb_in_active = ctx->nb_outputs;
424     return 0;
425 }
426
427 static av_cold void uninit(AVFilterContext *ctx)
428 {
429     ConcatContext *cat = ctx->priv;
430     unsigned i;
431
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);
435     }
436     for (i = 0; i < ctx->nb_outputs; i++)
437         av_freep(&ctx->output_pads[i].name);
438     av_free(cat->in);
439 }
440
441 AVFilter avfilter_avf_concat = {
442     .name          = "concat",
443     .description   = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
444     .init          = init,
445     .uninit        = uninit,
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,
451 };