FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
avf_concat.c
Go to the documentation of this file.
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/avassert.h"
27 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
30 #include "avfilter.h"
31 #define FF_BUFQUEUE_SIZE 256
32 #include "bufferqueue.h"
33 #include "internal.h"
34 #include "video.h"
35 #include "audio.h"
36 
37 #define TYPE_ALL 2
38 
39 typedef struct {
40  const AVClass *class;
41  unsigned nb_streams[TYPE_ALL]; /**< number of out streams of each type */
42  unsigned nb_segments;
43  unsigned cur_idx; /**< index of the first input of current segment */
44  int64_t delta_ts; /**< timestamp to add to produce output timestamps */
45  unsigned nb_in_active; /**< number of active inputs in current segment */
46  unsigned unsafe;
47  struct concat_in {
48  int64_t pts;
49  int64_t nb_frames;
50  unsigned eof;
51  struct FFBufQueue queue;
52  } *in;
54 
55 #define OFFSET(x) offsetof(ConcatContext, x)
56 #define A AV_OPT_FLAG_AUDIO_PARAM
57 #define F AV_OPT_FLAG_FILTERING_PARAM
58 #define V AV_OPT_FLAG_VIDEO_PARAM
59 
60 static const AVOption concat_options[] = {
61  { "n", "specify the number of segments", OFFSET(nb_segments),
62  AV_OPT_TYPE_INT, { .i64 = 2 }, 2, INT_MAX, V|A|F},
63  { "v", "specify the number of video streams",
64  OFFSET(nb_streams[AVMEDIA_TYPE_VIDEO]),
65  AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, V|F },
66  { "a", "specify the number of audio streams",
67  OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
68  AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|F},
69  { "unsafe", "enable unsafe mode",
70  OFFSET(unsafe),
71  AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|A|F},
72  { 0 }
73 };
74 
75 AVFILTER_DEFINE_CLASS(concat);
76 
78 {
79  ConcatContext *cat = ctx->priv;
80  unsigned type, nb_str, idx0 = 0, idx, str, seg;
83 
84  for (type = 0; type < TYPE_ALL; type++) {
85  nb_str = cat->nb_streams[type];
86  for (str = 0; str < nb_str; str++) {
87  idx = idx0;
88 
89  /* Set the output formats */
90  formats = ff_all_formats(type);
91  if (!formats)
92  return AVERROR(ENOMEM);
93  ff_formats_ref(formats, &ctx->outputs[idx]->in_formats);
94  if (type == AVMEDIA_TYPE_AUDIO) {
95  rates = ff_all_samplerates();
96  if (!rates)
97  return AVERROR(ENOMEM);
98  ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
99  layouts = ff_all_channel_layouts();
100  if (!layouts)
101  return AVERROR(ENOMEM);
102  ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
103  }
104 
105  /* Set the same formats for each corresponding input */
106  for (seg = 0; seg < cat->nb_segments; seg++) {
107  ff_formats_ref(formats, &ctx->inputs[idx]->out_formats);
108  if (type == AVMEDIA_TYPE_AUDIO) {
109  ff_formats_ref(rates, &ctx->inputs[idx]->out_samplerates);
110  ff_channel_layouts_ref(layouts, &ctx->inputs[idx]->out_channel_layouts);
111  }
112  idx += ctx->nb_outputs;
113  }
114 
115  idx0++;
116  }
117  }
118  return 0;
119 }
120 
121 static int config_output(AVFilterLink *outlink)
122 {
123  AVFilterContext *ctx = outlink->src;
124  ConcatContext *cat = ctx->priv;
125  unsigned out_no = FF_OUTLINK_IDX(outlink);
126  unsigned in_no = out_no, seg;
127  AVFilterLink *inlink = ctx->inputs[in_no];
128 
129  /* enhancement: find a common one */
130  outlink->time_base = AV_TIME_BASE_Q;
131  outlink->w = inlink->w;
132  outlink->h = inlink->h;
133  outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
134  outlink->format = inlink->format;
135  for (seg = 1; seg < cat->nb_segments; seg++) {
136  inlink = ctx->inputs[in_no += ctx->nb_outputs];
137  /* possible enhancement: unsafe mode, do not check */
138  if (outlink->w != inlink->w ||
139  outlink->h != inlink->h ||
140  outlink->sample_aspect_ratio.num != inlink->sample_aspect_ratio.num ||
141  outlink->sample_aspect_ratio.den != inlink->sample_aspect_ratio.den) {
142  av_log(ctx, AV_LOG_ERROR, "Input link %s parameters "
143  "(size %dx%d, SAR %d:%d) do not match the corresponding "
144  "output link %s parameters (%dx%d, SAR %d:%d)\n",
145  ctx->input_pads[in_no].name, inlink->w, inlink->h,
146  inlink->sample_aspect_ratio.num,
147  inlink->sample_aspect_ratio.den,
148  ctx->input_pads[out_no].name, outlink->w, outlink->h,
149  outlink->sample_aspect_ratio.num,
150  outlink->sample_aspect_ratio.den);
151  if (!cat->unsafe)
152  return AVERROR(EINVAL);
153  }
154  }
155 
156  return 0;
157 }
158 
159 static void push_frame(AVFilterContext *ctx, unsigned in_no,
160  AVFilterBufferRef *buf)
161 {
162  ConcatContext *cat = ctx->priv;
163  unsigned out_no = in_no % ctx->nb_outputs;
164  AVFilterLink * inlink = ctx-> inputs[ in_no];
165  AVFilterLink *outlink = ctx->outputs[out_no];
166  struct concat_in *in = &cat->in[in_no];
167 
168  buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
169  in->pts = buf->pts;
170  in->nb_frames++;
171  /* add duration to input PTS */
172  if (inlink->sample_rate)
173  /* use number of audio samples */
174  in->pts += av_rescale_q(buf->audio->nb_samples,
175  (AVRational){ 1, inlink->sample_rate },
176  outlink->time_base);
177  else if (in->nb_frames >= 2)
178  /* use mean duration */
179  in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
180 
181  buf->pts += cat->delta_ts;
182  ff_filter_frame(outlink, buf);
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);
195  } else 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 
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 
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 filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
223 {
224  process_frame(inlink, buf);
225  return 0; /* enhancement: handle error return */
226 }
227 
228 static void close_input(AVFilterContext *ctx, unsigned in_no)
229 {
230  ConcatContext *cat = ctx->priv;
231 
232  cat->in[in_no].eof = 1;
233  cat->nb_in_active--;
234  av_log(ctx, AV_LOG_VERBOSE, "EOF on %s, %d streams left in segment.\n",
235  ctx->input_pads[in_no].name, cat->nb_in_active);
236 }
237 
239 {
240  ConcatContext *cat = ctx->priv;
241  unsigned i = cat->cur_idx;
242  unsigned imax = i + ctx->nb_outputs;
243  int64_t pts;
244 
245  pts = cat->in[i++].pts;
246  for (; i < imax; i++)
247  pts = FFMAX(pts, cat->in[i].pts);
248  cat->delta_ts += pts;
249 }
250 
251 static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
252 {
253  ConcatContext *cat = ctx->priv;
254  AVFilterLink *outlink = ctx->outputs[out_no];
255  int64_t base_pts = cat->in[in_no].pts + cat->delta_ts;
256  int64_t nb_samples, sent = 0;
257  int frame_nb_samples;
258  AVRational rate_tb = { 1, ctx->inputs[in_no]->sample_rate };
259  AVFilterBufferRef *buf;
261 
262  if (!rate_tb.den)
263  return;
264  nb_samples = av_rescale_q(cat->delta_ts - base_pts,
265  outlink->time_base, rate_tb);
266  frame_nb_samples = FFMAX(9600, rate_tb.den / 5); /* arbitrary */
267  while (nb_samples) {
268  frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
269  buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
270  if (!buf)
271  return;
272  av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
273  nb_channels, outlink->format);
274  buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
275  ff_filter_frame(outlink, buf);
276  sent += frame_nb_samples;
277  nb_samples -= frame_nb_samples;
278  }
279 }
280 
282 {
283  ConcatContext *cat = ctx->priv;
284  unsigned str, str_max;
285 
286  find_next_delta_ts(ctx);
287  cat->cur_idx += ctx->nb_outputs;
288  cat->nb_in_active = ctx->nb_outputs;
289  av_log(ctx, AV_LOG_VERBOSE, "Segment finished at pts=%"PRId64"\n",
290  cat->delta_ts);
291 
292  if (cat->cur_idx < ctx->nb_inputs) {
293  /* pad audio streams with silence */
294  str = cat->nb_streams[AVMEDIA_TYPE_VIDEO];
295  str_max = str + cat->nb_streams[AVMEDIA_TYPE_AUDIO];
296  for (; str < str_max; str++)
297  send_silence(ctx, cat->cur_idx - ctx->nb_outputs + str, str);
298  /* flush queued buffers */
299  /* possible enhancement: flush in PTS order */
300  str_max = cat->cur_idx + ctx->nb_outputs;
301  for (str = cat->cur_idx; str < str_max; str++)
302  while (cat->in[str].queue.available)
303  push_frame(ctx, str, ff_bufqueue_get(&cat->in[str].queue));
304  }
305 }
306 
307 static int request_frame(AVFilterLink *outlink)
308 {
309  AVFilterContext *ctx = outlink->src;
310  ConcatContext *cat = ctx->priv;
311  unsigned out_no = FF_OUTLINK_IDX(outlink);
312  unsigned in_no = out_no + cat->cur_idx;
313  unsigned str, str_max;
314  int ret;
315 
316  while (1) {
317  if (in_no >= ctx->nb_inputs)
318  return AVERROR_EOF;
319  if (!cat->in[in_no].eof) {
320  ret = ff_request_frame(ctx->inputs[in_no]);
321  if (ret != AVERROR_EOF)
322  return ret;
323  close_input(ctx, in_no);
324  }
325  /* cycle on all inputs to finish the segment */
326  /* possible enhancement: request in PTS order */
327  str_max = cat->cur_idx + ctx->nb_outputs - 1;
328  for (str = cat->cur_idx; cat->nb_in_active;
329  str = str == str_max ? cat->cur_idx : str + 1) {
330  if (cat->in[str].eof)
331  continue;
332  ret = ff_request_frame(ctx->inputs[str]);
333  if (ret == AVERROR_EOF)
334  close_input(ctx, str);
335  else if (ret < 0)
336  return ret;
337  }
338  flush_segment(ctx);
339  in_no += ctx->nb_outputs;
340  }
341 }
342 
343 static av_cold int init(AVFilterContext *ctx, const char *args)
344 {
345  ConcatContext *cat = ctx->priv;
346  int ret;
347  unsigned seg, type, str;
348 
349  cat->class = &concat_class;
350  av_opt_set_defaults(cat);
351  ret = av_set_options_string(cat, args, "=", ":");
352  if (ret < 0) {
353  av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
354  return ret;
355  }
356 
357  /* create input pads */
358  for (seg = 0; seg < cat->nb_segments; seg++) {
359  for (type = 0; type < TYPE_ALL; type++) {
360  for (str = 0; str < cat->nb_streams[type]; str++) {
361  AVFilterPad pad = {
362  .type = type,
363  .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
364  .get_video_buffer = get_video_buffer,
365  .get_audio_buffer = get_audio_buffer,
366  .filter_frame = filter_frame,
367  };
368  pad.name = av_asprintf("in%d:%c%d", seg, "va"[type], str);
369  ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
370  }
371  }
372  }
373  /* create output pads */
374  for (type = 0; type < TYPE_ALL; type++) {
375  for (str = 0; str < cat->nb_streams[type]; str++) {
376  AVFilterPad pad = {
377  .type = type,
378  .config_props = config_output,
379  .request_frame = request_frame,
380  };
381  pad.name = av_asprintf("out:%c%d", "va"[type], str);
382  ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
383  }
384  }
385 
386  cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
387  if (!cat->in)
388  return AVERROR(ENOMEM);
389  cat->nb_in_active = ctx->nb_outputs;
390  return 0;
391 }
392 
393 static av_cold void uninit(AVFilterContext *ctx)
394 {
395  ConcatContext *cat = ctx->priv;
396  unsigned i;
397 
398  for (i = 0; i < ctx->nb_inputs; i++) {
399  av_freep(&ctx->input_pads[i].name);
400  ff_bufqueue_discard_all(&cat->in[i].queue);
401  }
402  for (i = 0; i < ctx->nb_outputs; i++)
403  av_freep(&ctx->output_pads[i].name);
404  av_free(cat->in);
405 }
406 
408  .name = "concat",
409  .description = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
410  .init = init,
411  .uninit = uninit,
412  .query_formats = query_formats,
413  .priv_size = sizeof(ConcatContext),
414  .inputs = NULL,
415  .outputs = NULL,
416  .priv_class = &concat_class,
417 };