]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_concat.c
libavfilter: include needed header for AVDictionary
[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 #define A AV_OPT_FLAG_AUDIO_PARAM
55 #define F AV_OPT_FLAG_FILTERING_PARAM
56 #define V AV_OPT_FLAG_VIDEO_PARAM
57
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},
67     { 0 }
68 };
69
70 AVFILTER_DEFINE_CLASS(concat);
71
72 static int query_formats(AVFilterContext *ctx)
73 {
74     ConcatContext *cat = ctx->priv;
75     unsigned type, nb_str, idx0 = 0, idx, str, seg;
76     AVFilterFormats *formats, *rates;
77     AVFilterChannelLayouts *layouts;
78
79     for (type = 0; type < TYPE_ALL; type++) {
80         nb_str = cat->nb_streams[type];
81         for (str = 0; str < nb_str; str++) {
82             idx = idx0;
83
84             /* Set the output formats */
85             formats = ff_all_formats(type);
86             if (!formats)
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();
91                 if (!rates)
92                     return AVERROR(ENOMEM);
93                 ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
94                 layouts = ff_all_channel_layouts();
95                 if (!layouts)
96                     return AVERROR(ENOMEM);
97                 ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
98             }
99
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);
106                 }
107                 idx += ctx->nb_outputs;
108             }
109
110             idx0++;
111         }
112     }
113     return 0;
114 }
115
116 static int config_output(AVFilterLink *outlink)
117 {
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];
123
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);
147         }
148     }
149
150     return 0;
151 }
152
153 static void push_frame(AVFilterContext *ctx, unsigned in_no,
154                        AVFilterBufferRef *buf)
155 {
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];
161
162     buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
163     in->pts = buf->pts;
164     in->nb_frames++;
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 },
170                                 outlink->time_base);
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);
174
175     buf->pts += cat->delta_ts;
176     switch (buf->type) {
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);
181         break;
182     case AVMEDIA_TYPE_AUDIO:
183         ff_filter_samples(outlink, buf);
184         break;
185     }
186 }
187
188 static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
189 {
190     AVFilterContext *ctx  = inlink->dst;
191     ConcatContext *cat    = ctx->priv;
192     unsigned in_no = FF_INLINK_IDX(inlink);
193
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     } else if (in_no >= cat->cur_idx + ctx->nb_outputs) {
199         ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
200     } else {
201         push_frame(ctx, in_no, buf);
202     }
203 }
204
205 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
206                                            int w, int h)
207 {
208     AVFilterContext *ctx = inlink->dst;
209     unsigned in_no = FF_INLINK_IDX(inlink);
210     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
211
212     return ff_get_video_buffer(outlink, perms, w, h);
213 }
214
215 static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
216                                            int nb_samples)
217 {
218     AVFilterContext *ctx = inlink->dst;
219     unsigned in_no = FF_INLINK_IDX(inlink);
220     AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
221
222     return ff_get_audio_buffer(outlink, perms, nb_samples);
223 }
224
225 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
226 {
227     return 0;
228 }
229
230 static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
231 {
232     return 0;
233 }
234
235 static int end_frame(AVFilterLink *inlink)
236 {
237     process_frame(inlink, inlink->cur_buf);
238     inlink->cur_buf = NULL;
239     return 0;
240 }
241
242 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
243 {
244     process_frame(inlink, buf);
245     return 0; /* enhancement: handle error return */
246 }
247
248 static void close_input(AVFilterContext *ctx, unsigned in_no)
249 {
250     ConcatContext *cat = ctx->priv;
251
252     cat->in[in_no].eof = 1;
253     cat->nb_in_active--;
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);
256 }
257
258 static void find_next_delta_ts(AVFilterContext *ctx)
259 {
260     ConcatContext *cat = ctx->priv;
261     unsigned i = cat->cur_idx;
262     unsigned imax = i + ctx->nb_outputs;
263     int64_t pts;
264
265     pts = cat->in[i++].pts;
266     for (; i < imax; i++)
267         pts = FFMAX(pts, cat->in[i].pts);
268     cat->delta_ts += pts;
269 }
270
271 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
272 {
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);
281
282     if (!rate_tb.den)
283         return;
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 */
287     while (nb_samples) {
288         frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
289         buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
290         if (!buf)
291             return;
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;
298     }
299 }
300
301 static void flush_segment(AVFilterContext *ctx)
302 {
303     ConcatContext *cat = ctx->priv;
304     unsigned str, str_max;
305
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",
310            cat->delta_ts);
311
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));
324     }
325 }
326
327 static int request_frame(AVFilterLink *outlink)
328 {
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;
334     int ret;
335
336     while (1) {
337         if (in_no >= ctx->nb_inputs)
338             return AVERROR_EOF;
339         if (!cat->in[in_no].eof) {
340             ret = ff_request_frame(ctx->inputs[in_no]);
341             if (ret != AVERROR_EOF)
342                 return ret;
343             close_input(ctx, in_no);
344         }
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)
351                 continue;
352             ret = ff_request_frame(ctx->inputs[str]);
353             if (ret == AVERROR_EOF)
354                 close_input(ctx, str);
355             else if (ret < 0)
356                 return ret;
357         }
358         flush_segment(ctx);
359         in_no += ctx->nb_outputs;
360     }
361 }
362
363 static av_cold int init(AVFilterContext *ctx, const char *args)
364 {
365     ConcatContext *cat = ctx->priv;
366     int ret;
367     unsigned seg, type, str;
368     char name[32];
369
370     cat->class = &concat_class;
371     av_opt_set_defaults(cat);
372     ret = av_set_options_string(cat, args, "=", ":");
373     if (ret < 0) {
374         av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
375         return ret;
376     }
377
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++) {
382                 AVFilterPad pad = {
383                     .type             = type,
384                     .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
385                     .get_video_buffer = get_video_buffer,
386                     .get_audio_buffer = get_audio_buffer,
387                 };
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;
394                 } else {
395                     pad.filter_samples = filter_samples;
396                 }
397                 ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
398             }
399         }
400     }
401     /* create output pads */
402     for (type = 0; type < TYPE_ALL; type++) {
403         for (str = 0; str < cat->nb_streams[type]; str++) {
404             AVFilterPad pad = {
405                 .type          = type,
406                 .config_props  = config_output,
407                 .request_frame = request_frame,
408             };
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);
412         }
413     }
414
415     cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
416     if (!cat->in)
417         return AVERROR(ENOMEM);
418     cat->nb_in_active = ctx->nb_outputs;
419     return 0;
420 }
421
422 static av_cold void uninit(AVFilterContext *ctx)
423 {
424     ConcatContext *cat = ctx->priv;
425     unsigned i;
426
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);
430     }
431     for (i = 0; i < ctx->nb_outputs; i++)
432         av_freep(&ctx->output_pads[i].name);
433     av_free(cat->in);
434 }
435
436 AVFilter avfilter_avf_concat = {
437     .name          = "concat",
438     .description   = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
439     .init          = init,
440     .uninit        = uninit,
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,
446 };