FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
concatdec.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 License
8  * 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. See the
14  * 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 #include "libavutil/avassert.h"
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/parseutils.h"
26 #include "libavutil/timestamp.h"
27 #include "avformat.h"
28 #include "internal.h"
29 #include "url.h"
30 
31 typedef enum ConcatMatchMode {
35 
36 typedef struct ConcatStream {
40 } ConcatStream;
41 
42 typedef struct {
43  char *url;
44  int64_t start_time;
45  int64_t file_start_time;
46  int64_t file_inpoint;
47  int64_t duration;
49  int64_t inpoint;
50  int64_t outpoint;
53 } ConcatFile;
54 
55 typedef struct {
56  AVClass *class;
59  unsigned nb_files;
61  int safe;
62  int seekable;
63  int eof;
65  unsigned auto_convert;
68 
70 {
71  return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
73 }
74 
75 static char *get_keyword(uint8_t **cursor)
76 {
77  char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
78  *cursor += strcspn(*cursor, SPACE_CHARS);
79  if (**cursor) {
80  *((*cursor)++) = 0;
81  *cursor += strspn(*cursor, SPACE_CHARS);
82  }
83  return ret;
84 }
85 
86 static int safe_filename(const char *f)
87 {
88  const char *start = f;
89 
90  for (; *f; f++) {
91  /* A-Za-z0-9_- */
92  if (!((unsigned)((*f | 32) - 'a') < 26 ||
93  (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
94  if (f == start)
95  return 0;
96  else if (*f == '/')
97  start = f + 1;
98  else if (*f != '.')
99  return 0;
100  }
101  }
102  return 1;
103 }
104 
105 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
106 
107 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
108  unsigned *nb_files_alloc)
109 {
110  ConcatContext *cat = avf->priv_data;
111  ConcatFile *file;
112  char *url = NULL;
113  const char *proto;
114  size_t url_len, proto_len;
115  int ret;
116 
117  if (cat->safe > 0 && !safe_filename(filename)) {
118  av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
119  FAIL(AVERROR(EPERM));
120  }
121 
122  proto = avio_find_protocol_name(filename);
123  proto_len = proto ? strlen(proto) : 0;
124  if (!memcmp(filename, proto, proto_len) &&
125  (filename[proto_len] == ':' || filename[proto_len] == ',')) {
126  url = filename;
127  filename = NULL;
128  } else {
129  url_len = strlen(avf->filename) + strlen(filename) + 16;
130  if (!(url = av_malloc(url_len)))
131  FAIL(AVERROR(ENOMEM));
132  ff_make_absolute_url(url, url_len, avf->filename, filename);
133  av_freep(&filename);
134  }
135 
136  if (cat->nb_files >= *nb_files_alloc) {
137  size_t n = FFMAX(*nb_files_alloc * 2, 16);
138  ConcatFile *new_files;
139  if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
140  !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
141  FAIL(AVERROR(ENOMEM));
142  cat->files = new_files;
143  *nb_files_alloc = n;
144  }
145 
146  file = &cat->files[cat->nb_files++];
147  memset(file, 0, sizeof(*file));
148  *rfile = file;
149 
150  file->url = url;
151  file->start_time = AV_NOPTS_VALUE;
152  file->duration = AV_NOPTS_VALUE;
153  file->inpoint = AV_NOPTS_VALUE;
154  file->outpoint = AV_NOPTS_VALUE;
155 
156  return 0;
157 
158 fail:
159  av_free(url);
160  av_free(filename);
161  return ret;
162 }
163 
164 static int copy_stream_props(AVStream *st, AVStream *source_st)
165 {
166  int ret;
167 
168  if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
169  if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
170  if (st->codecpar->extradata) {
171  av_freep(&st->codecpar->extradata);
172  st->codecpar->extradata_size = 0;
173  }
174  ret = ff_alloc_extradata(st->codecpar,
175  source_st->codecpar->extradata_size);
176  if (ret < 0)
177  return ret;
178  }
179  memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
180  source_st->codecpar->extradata_size);
181  return 0;
182  }
183  if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
184  return ret;
185  st->r_frame_rate = source_st->r_frame_rate;
186  st->avg_frame_rate = source_st->avg_frame_rate;
187  st->time_base = source_st->time_base;
188  st->sample_aspect_ratio = source_st->sample_aspect_ratio;
189 
190  av_dict_copy(&st->metadata, source_st->metadata, 0);
191  return 0;
192 }
193 
194 static int detect_stream_specific(AVFormatContext *avf, int idx)
195 {
196  ConcatContext *cat = avf->priv_data;
197  AVStream *st = cat->avf->streams[idx];
198  ConcatStream *cs = &cat->cur_file->streams[idx];
200  int ret;
201 
202  if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
203  (st->codecpar->extradata_size < 4 || AV_RB32(st->codecpar->extradata) != 1)) {
204  av_log(cat->avf, AV_LOG_INFO,
205  "Auto-inserting h264_mp4toannexb bitstream filter\n");
206  if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) {
207  av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
208  "required for H.264 streams\n");
209  return AVERROR_BSF_NOT_FOUND;
210  }
211  cs->bsf = bsf;
212 
214  if (!cs->avctx)
215  return AVERROR(ENOMEM);
216 
217  /* This really should be part of the bsf work.
218  Note: input bitstream filtering will not work with bsf that
219  create extradata from the first packet. */
220  av_freep(&st->codecpar->extradata);
221  st->codecpar->extradata_size = 0;
222 
224  if (ret < 0) {
226  return ret;
227  }
228 
229  }
230  return 0;
231 }
232 
234 {
235  ConcatContext *cat = avf->priv_data;
236  AVStream *st;
237  int i, ret;
238 
239  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
240  if (i < avf->nb_streams) {
241  st = avf->streams[i];
242  } else {
243  if (!(st = avformat_new_stream(avf, NULL)))
244  return AVERROR(ENOMEM);
245  }
246  if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
247  return ret;
248  cat->cur_file->streams[i].out_stream_index = i;
249  }
250  return 0;
251 }
252 
254 {
255  ConcatContext *cat = avf->priv_data;
256  AVStream *st;
257  int i, j, ret;
258 
259  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
260  st = cat->avf->streams[i];
261  for (j = 0; j < avf->nb_streams; j++) {
262  if (avf->streams[j]->id == st->id) {
263  av_log(avf, AV_LOG_VERBOSE,
264  "Match slave stream #%d with stream #%d id 0x%x\n",
265  i, j, st->id);
266  if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
267  return ret;
268  cat->cur_file->streams[i].out_stream_index = j;
269  }
270  }
271  }
272  return 0;
273 }
274 
276 {
277  ConcatContext *cat = avf->priv_data;
278  ConcatStream *map;
279  int i, ret;
280 
281  if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
282  return 0;
283  map = av_realloc(cat->cur_file->streams,
284  cat->avf->nb_streams * sizeof(*map));
285  if (!map)
286  return AVERROR(ENOMEM);
287  cat->cur_file->streams = map;
288  memset(map + cat->cur_file->nb_streams, 0,
289  (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
290 
291  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
292  map[i].out_stream_index = -1;
293  switch (cat->stream_match_mode) {
294  case MATCH_ONE_TO_ONE:
295  ret = match_streams_one_to_one(avf);
296  break;
297  case MATCH_EXACT_ID:
298  ret = match_streams_exact_id(avf);
299  break;
300  default:
301  ret = AVERROR_BUG;
302  }
303  if (ret < 0)
304  return ret;
305  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
306  if ((ret = detect_stream_specific(avf, i)) < 0)
307  return ret;
308  cat->cur_file->nb_streams = cat->avf->nb_streams;
309  return 0;
310 }
311 
312 static int open_file(AVFormatContext *avf, unsigned fileno)
313 {
314  ConcatContext *cat = avf->priv_data;
315  ConcatFile *file = &cat->files[fileno];
316  int ret;
317 
318  if (cat->avf)
319  avformat_close_input(&cat->avf);
320 
321  cat->avf = avformat_alloc_context();
322  if (!cat->avf)
323  return AVERROR(ENOMEM);
324 
326 
327  if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
328  return ret;
329 
330  if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
331  (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
332  av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
333  avformat_close_input(&cat->avf);
334  return ret;
335  }
336  cat->cur_file = file;
337  if (file->start_time == AV_NOPTS_VALUE)
338  file->start_time = !fileno ? 0 :
339  cat->files[fileno - 1].start_time +
340  cat->files[fileno - 1].duration;
341  file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
342  file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
343  if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
344  file->duration = file->outpoint - file->file_inpoint;
345 
346  if (cat->segment_time_metadata) {
347  av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
348  if (file->duration != AV_NOPTS_VALUE)
349  av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
350  }
351 
352  if ((ret = match_streams(avf)) < 0)
353  return ret;
354  if (file->inpoint != AV_NOPTS_VALUE) {
355  if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
356  return ret;
357  }
358  return 0;
359 }
360 
362 {
363  ConcatContext *cat = avf->priv_data;
364  unsigned i, j;
365 
366  for (i = 0; i < cat->nb_files; i++) {
367  av_freep(&cat->files[i].url);
368  for (j = 0; j < cat->files[i].nb_streams; j++) {
369  if (cat->files[i].streams[j].avctx)
371  if (cat->files[i].streams[j].bsf)
373  }
374  av_freep(&cat->files[i].streams);
375  av_dict_free(&cat->files[i].metadata);
376  }
377  if (cat->avf)
378  avformat_close_input(&cat->avf);
379  av_freep(&cat->files);
380  return 0;
381 }
382 
384 {
385  ConcatContext *cat = avf->priv_data;
386  uint8_t buf[4096];
387  uint8_t *cursor, *keyword;
388  int ret, line = 0, i;
389  unsigned nb_files_alloc = 0;
390  ConcatFile *file = NULL;
391  int64_t time = 0;
392 
393  while (1) {
394  if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
395  break;
396  line++;
397  cursor = buf;
398  keyword = get_keyword(&cursor);
399  if (!*keyword || *keyword == '#')
400  continue;
401 
402  if (!strcmp(keyword, "file")) {
403  char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
404  if (!filename) {
405  av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
407  }
408  if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
409  goto fail;
410  } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
411  char *dur_str = get_keyword(&cursor);
412  int64_t dur;
413  if (!file) {
414  av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
415  line, keyword);
417  }
418  if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
419  av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
420  line, keyword, dur_str);
421  goto fail;
422  }
423  if (!strcmp(keyword, "duration"))
424  file->duration = dur;
425  else if (!strcmp(keyword, "inpoint"))
426  file->inpoint = dur;
427  else if (!strcmp(keyword, "outpoint"))
428  file->outpoint = dur;
429  } else if (!strcmp(keyword, "file_packet_metadata")) {
430  char *metadata;
431  if (!file) {
432  av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
433  line, keyword);
435  }
436  metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
437  if (!metadata) {
438  av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
440  }
441  if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
442  av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
443  av_freep(&metadata);
445  }
446  av_freep(&metadata);
447  } else if (!strcmp(keyword, "stream")) {
448  if (!avformat_new_stream(avf, NULL))
449  FAIL(AVERROR(ENOMEM));
450  } else if (!strcmp(keyword, "exact_stream_id")) {
451  if (!avf->nb_streams) {
452  av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
453  line);
455  }
456  avf->streams[avf->nb_streams - 1]->id =
457  strtol(get_keyword(&cursor), NULL, 0);
458  } else if (!strcmp(keyword, "ffconcat")) {
459  char *ver_kw = get_keyword(&cursor);
460  char *ver_val = get_keyword(&cursor);
461  if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
462  av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
464  }
465  if (cat->safe < 0)
466  cat->safe = 1;
467  } else {
468  av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
469  line, keyword);
471  }
472  }
473  if (ret < 0)
474  goto fail;
475  if (!cat->nb_files)
477 
478  for (i = 0; i < cat->nb_files; i++) {
479  if (cat->files[i].start_time == AV_NOPTS_VALUE)
480  cat->files[i].start_time = time;
481  else
482  time = cat->files[i].start_time;
483  if (cat->files[i].duration == AV_NOPTS_VALUE) {
484  if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
485  break;
486  cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
487  }
488  time += cat->files[i].duration;
489  }
490  if (i == cat->nb_files) {
491  avf->duration = time;
492  cat->seekable = 1;
493  }
494 
497  if ((ret = open_file(avf, 0)) < 0)
498  goto fail;
499  return 0;
500 
501 fail:
502  concat_read_close(avf);
503  return ret;
504 }
505 
507 {
508  ConcatContext *cat = avf->priv_data;
509  unsigned fileno = cat->cur_file - cat->files;
510 
511  if (cat->cur_file->duration == AV_NOPTS_VALUE)
512  cat->cur_file->duration = cat->avf->duration - (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
513 
514  if (++fileno >= cat->nb_files) {
515  cat->eof = 1;
516  return AVERROR_EOF;
517  }
518  return open_file(avf, fileno);
519 }
520 
522 {
523  AVStream *st = avf->streams[cs->out_stream_index];
525  AVPacket pkt2;
526  int ret;
527 
528  av_assert0(cs->out_stream_index >= 0);
529  for (bsf = cs->bsf; bsf; bsf = bsf->next) {
530  pkt2 = *pkt;
531 
532  ret = av_bitstream_filter_filter(bsf, cs->avctx, NULL,
533  &pkt2.data, &pkt2.size,
534  pkt->data, pkt->size,
535  !!(pkt->flags & AV_PKT_FLAG_KEY));
536  if (ret < 0) {
537  av_packet_unref(pkt);
538  return ret;
539  }
540 
541  if (cs->avctx->extradata_size > st->codecpar->extradata_size) {
542  int eret;
543  if (st->codecpar->extradata)
544  av_freep(&st->codecpar->extradata);
545 
547  if (eret < 0) {
548  av_packet_unref(pkt);
549  return AVERROR(ENOMEM);
550  }
552  memcpy(st->codecpar->extradata, cs->avctx->extradata, cs->avctx->extradata_size);
553  }
554 
555  av_assert0(pkt2.buf);
556  if (ret == 0 && pkt2.data != pkt->data) {
557  if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
558  av_free(pkt2.data);
559  return ret;
560  }
561  ret = 1;
562  }
563  if (ret > 0) {
564  av_packet_unref(pkt);
565  pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
567  if (!pkt2.buf) {
568  av_free(pkt2.data);
569  return AVERROR(ENOMEM);
570  }
571  }
572  *pkt = pkt2;
573  }
574  return 0;
575 }
576 
577 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
579 {
580  if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
581  return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
582  cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
583  }
584  return 0;
585 }
586 
588 {
589  ConcatContext *cat = avf->priv_data;
590  int ret;
591  int64_t delta;
592  ConcatStream *cs;
593  AVStream *st;
594 
595  if (cat->eof)
596  return AVERROR_EOF;
597 
598  if (!cat->avf)
599  return AVERROR(EIO);
600 
601  while (1) {
602  ret = av_read_frame(cat->avf, pkt);
603  if (ret == AVERROR_EOF) {
604  if ((ret = open_next_file(avf)) < 0)
605  return ret;
606  continue;
607  }
608  if (ret < 0)
609  return ret;
610  if ((ret = match_streams(avf)) < 0) {
611  av_packet_unref(pkt);
612  return ret;
613  }
614  if (packet_after_outpoint(cat, pkt)) {
615  av_packet_unref(pkt);
616  if ((ret = open_next_file(avf)) < 0)
617  return ret;
618  continue;
619  }
620  cs = &cat->cur_file->streams[pkt->stream_index];
621  if (cs->out_stream_index < 0) {
622  av_packet_unref(pkt);
623  continue;
624  }
625  pkt->stream_index = cs->out_stream_index;
626  break;
627  }
628  if ((ret = filter_packet(avf, cs, pkt)))
629  return ret;
630 
631  st = cat->avf->streams[pkt->stream_index];
632  av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
633  (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
634  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
635  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
636 
637  delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
639  cat->avf->streams[pkt->stream_index]->time_base);
640  if (pkt->pts != AV_NOPTS_VALUE)
641  pkt->pts += delta;
642  if (pkt->dts != AV_NOPTS_VALUE)
643  pkt->dts += delta;
644  av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
645  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
646  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
647  if (cat->cur_file->metadata) {
648  uint8_t* metadata;
649  int metadata_len;
650  char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
651  if (!packed_metadata)
652  return AVERROR(ENOMEM);
653  if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
654  av_freep(&packed_metadata);
655  return AVERROR(ENOMEM);
656  }
657  memcpy(metadata, packed_metadata, metadata_len);
658  av_freep(&packed_metadata);
659  }
660  return ret;
661 }
662 
663 static void rescale_interval(AVRational tb_in, AVRational tb_out,
664  int64_t *min_ts, int64_t *ts, int64_t *max_ts)
665 {
666  *ts = av_rescale_q (* ts, tb_in, tb_out);
667  *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
669  *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
671 }
672 
673 static int try_seek(AVFormatContext *avf, int stream,
674  int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
675 {
676  ConcatContext *cat = avf->priv_data;
677  int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
678 
679  ts -= t0;
680  min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
681  max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
682  if (stream >= 0) {
683  if (stream >= cat->avf->nb_streams)
684  return AVERROR(EIO);
686  &min_ts, &ts, &max_ts);
687  }
688  return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
689 }
690 
691 static int real_seek(AVFormatContext *avf, int stream,
692  int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
693 {
694  ConcatContext *cat = avf->priv_data;
695  int ret, left, right;
696 
697  if (stream >= 0) {
698  if (stream >= avf->nb_streams)
699  return AVERROR(EINVAL);
701  &min_ts, &ts, &max_ts);
702  }
703 
704  left = 0;
705  right = cat->nb_files;
706  while (right - left > 1) {
707  int mid = (left + right) / 2;
708  if (ts < cat->files[mid].start_time)
709  right = mid;
710  else
711  left = mid;
712  }
713 
714  if ((ret = open_file(avf, left)) < 0)
715  return ret;
716 
717  ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
718  if (ret < 0 &&
719  left < cat->nb_files - 1 &&
720  cat->files[left + 1].start_time < max_ts) {
721  if ((ret = open_file(avf, left + 1)) < 0)
722  return ret;
723  ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
724  }
725  return ret;
726 }
727 
728 static int concat_seek(AVFormatContext *avf, int stream,
729  int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
730 {
731  ConcatContext *cat = avf->priv_data;
732  ConcatFile *cur_file_saved = cat->cur_file;
733  AVFormatContext *cur_avf_saved = cat->avf;
734  int ret;
735 
736  if (!cat->seekable)
737  return AVERROR(ESPIPE); /* XXX: can we use it? */
738  if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
739  return AVERROR(ENOSYS);
740  cat->avf = NULL;
741  if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
742  if (cat->avf)
743  avformat_close_input(&cat->avf);
744  cat->avf = cur_avf_saved;
745  cat->cur_file = cur_file_saved;
746  } else {
747  avformat_close_input(&cur_avf_saved);
748  cat->eof = 0;
749  }
750  return ret;
751 }
752 
753 #define OFFSET(x) offsetof(ConcatContext, x)
754 #define DEC AV_OPT_FLAG_DECODING_PARAM
755 
756 static const AVOption options[] = {
757  { "safe", "enable safe mode",
758  OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
759  { "auto_convert", "automatically convert bitstream format",
760  OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
761  { "segment_time_metadata", "output file segment start time and duration as packet metadata",
762  OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
763  { NULL }
764 };
765 
766 static const AVClass concat_class = {
767  .class_name = "concat demuxer",
768  .item_name = av_default_item_name,
769  .option = options,
770  .version = LIBAVUTIL_VERSION_INT,
771 };
772 
773 
775  .name = "concat",
776  .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
777  .priv_data_size = sizeof(ConcatContext),
782  .read_seek2 = concat_seek,
783  .priv_class = &concat_class,
784 };
#define NULL
Definition: coverity.c:32
void ff_make_absolute_url(char *buf, int size, const char *base, const char *rel)
Convert a relative url into an absolute url, given a base url.
Definition: url.c:80
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1577
AVOption.
Definition: opt.h:245
static int concat_read_close(AVFormatContext *avf)
Definition: concatdec.c:361
ConcatMatchMode
Definition: concatdec.c:31
#define LIBAVUTIL_VERSION_INT
Definition: version.h:70
#define DEC
Definition: concatdec.c:754
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:559
#define FAIL(retcode)
Definition: concatdec.c:105
attribute_deprecated int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe)
Filter bitstream.
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3922
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:943
static void rescale_interval(AVRational tb_in, AVRational tb_out, int64_t *min_ts, int64_t *ts, int64_t *max_ts)
Definition: concatdec.c:663
int size
Definition: avcodec.h:1581
AVDictionary * metadata
Definition: concatdec.c:51
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:216
static AVPacket pkt
static const AVOption options[]
Definition: concatdec.c:756
int64_t outpoint
Definition: concatdec.c:50
Format I/O context.
Definition: avformat.h:1325
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static int concat_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition: concatdec.c:728
ConcatStream * streams
Definition: concatdec.c:48
static int64_t start_time
Definition: ffplay.c:330
uint8_t
Round toward +infinity.
Definition: mathematics.h:74
static int nb_streams
Definition: ffprobe.c:254
#define av_malloc(s)
float delta
static int match_streams(AVFormatContext *avf)
Definition: concatdec.c:275
AVOptions.
timestamp utils, mostly useful for debugging/logging purposes
int id
Format-specific stream ID.
Definition: avformat.h:883
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1764
int ff_copy_whiteblacklists(AVFormatContext *dst, AVFormatContext *src)
Copies the whilelists from one context to the other.
Definition: utils.c:145
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4065
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:87
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1393
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: utils.c:4133
#define t0
Definition: regdef.h:28
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:132
AVInputFormat ff_concat_demuxer
Definition: concatdec.c:774
uint8_t * data
Definition: avcodec.h:1580
#define AVERROR_EOF
End of file.
Definition: error.h:55
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
static int probe(AVProbeData *p)
Definition: act.c:36
struct AVBitStreamFilterContext * next
Definition: avcodec.h:5656
#define av_log(a,...)
int64_t inpoint
Definition: concatdec.c:49
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1612
static int concat_read_header(AVFormatContext *avf)
Definition: concatdec.c:383
void av_buffer_default_free(void *opaque, uint8_t *data)
Default free callback, which calls av_free() on the buffer data.
Definition: buffer.c:61
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
int out_stream_index
Definition: concatdec.c:39
int segment_time_metadata
Definition: concatdec.c:66
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: utils.c:4059
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
unsigned auto_convert
Definition: concatdec.c:65
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:76
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
static int concat_probe(AVProbeData *probe)
Definition: concatdec.c:69
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:202
attribute_deprecated AVBitStreamFilterContext * av_bitstream_filter_init(const char *name)
Create and initialize a bitstream filter context given a bitstream filter name.
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1563
Definition: graph2dot.c:48
simple assert() macros that are a bit more flexible than ISO C assert().
AVBufferRef * av_buffer_create(uint8_t *data, int size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition: buffer.c:28
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:954
#define FFMAX(a, b)
Definition: common.h:94
#define fail()
Definition: checkasm.h:81
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition: avstring.c:149
int64_t file_start_time
Definition: concatdec.c:45
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1586
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare 2 timestamps each in its own timebases.
Definition: mathematics.c:147
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3940
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:461
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1381
static int match_streams_one_to_one(AVFormatContext *avf)
Definition: concatdec.c:233
int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
Definition: mathematics.c:134
#define cat(a, bpp, b)
Definition: vp9dsp_init.h:29
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:3107
static int try_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition: concatdec.c:673
char filename[1024]
input or output filename
Definition: avformat.h:1401
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:156
static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
Definition: concatdec.c:578
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
Definition: concatdec.c:521
attribute_deprecated void av_bitstream_filter_close(AVBitStreamFilterContext *bsf)
Release bitstream filter context.
static const AVClass concat_class
Definition: concatdec.c:766
static int open_file(AVFormatContext *avf, unsigned fileno)
Definition: concatdec.c:312
#define AVERROR_BSF_NOT_FOUND
Bitstream filter not found.
Definition: error.h:49
int n
Definition: avisynth_c.h:547
AVDictionary * metadata
Definition: avformat.h:945
int ff_get_line(AVIOContext *s, char *buf, int maxlen)
Read a whole line of text from AVIOContext.
Definition: aviobuf.c:759
ConcatMatchMode stream_match_mode
Definition: concatdec.c:64
AVBitStreamFilterContext * bsf
Definition: concatdec.c:37
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:638
Stream structure.
Definition: avformat.h:876
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags)
Parse the key/value pairs list and add the parsed entries to a dictionary.
Definition: dict.c:179
ConcatFile * cur_file
Definition: concatdec.c:58
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
A list of zero terminated key/value strings.
Definition: avcodec.h:1468
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer...
Definition: options.c:171
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:252
AVIOContext * pb
I/O context.
Definition: avformat.h:1367
ConcatFile * files
Definition: concatdec.c:57
main external API structure.
Definition: avcodec.h:1649
uint8_t * av_packet_pack_dictionary(AVDictionary *dict, int *size)
Pack a dictionary for use in side_data.
Definition: avpacket.c:455
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:563
int av_copy_packet(AVPacket *dst, const AVPacket *src)
Copy packet, including contents.
Definition: avpacket.c:260
void * buf
Definition: avisynth_c.h:553
int extradata_size
Definition: avcodec.h:1765
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
int nb_streams
Definition: concatdec.c:52
Describe the class of an AVClass context structure.
Definition: log.h:67
#define SPACE_CHARS
Definition: internal.h:272
rational number numerator/denominator
Definition: rational.h:43
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition: avformat.h:2367
const VDPAUPixFmtMap * map
static int match_streams_exact_id(AVFormatContext *avf)
Definition: concatdec.c:253
unsigned nb_files
Definition: concatdec.c:59
This structure contains the data a format has to probe a file.
Definition: avformat.h:459
misc parsing utilities
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1631
Round toward -infinity.
Definition: mathematics.h:73
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
Definition: utils.c:2380
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition: avio.c:473
int64_t start_time
Definition: concatdec.c:44
static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
Definition: concatdec.c:587
static int flags
Definition: cpu.c:47
int64_t start_time
Position of the first frame of the component, in AV_TIME_BASE fractional seconds. ...
Definition: avformat.h:1410
char * url
Definition: concatdec.c:43
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:471
Main libavformat public API header.
static char * get_keyword(uint8_t **cursor)
Definition: concatdec.c:75
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:145
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3268
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set that converts the value to a string and stores it...
Definition: dict.c:146
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4037
Flag to pass INT64_MIN/MAX through instead of rescaling, this avoids special cases for AV_NOPTS_VALUE...
Definition: mathematics.h:76
static int open_next_file(AVFormatContext *avf)
Definition: concatdec.c:506
#define av_free(p)
static int copy_stream_props(AVStream *st, AVStream *source_st)
Definition: concatdec.c:164
int64_t duration
Definition: concatdec.c:47
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:54
AVCodecContext * avctx
Definition: concatdec.c:38
static int real_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition: concatdec.c:691
void * priv_data
Format private data.
Definition: avformat.h:1353
int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:471
#define AVSEEK_FLAG_FRAME
seeking based on frame number
Definition: avformat.h:2369
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3936
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1579
#define OFFSET(x)
Definition: concatdec.c:753
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1420
static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile, unsigned *nb_files_alloc)
Definition: concatdec.c:107
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:553
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:660
unbuffered private I/O API
AVCodecParameters * codecpar
Definition: avformat.h:1006
static int detect_stream_specific(AVFormatContext *avf, int idx)
Definition: concatdec.c:194
static int safe_filename(const char *f)
Definition: concatdec.c:86
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:313
int stream_index
Definition: avcodec.h:1582
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:913
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1101
int64_t file_inpoint
Definition: concatdec.c:46
This structure stores compressed data.
Definition: avcodec.h:1557
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1573
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
AVFormatContext * avf
Definition: concatdec.c:60