FFmpeg  4.2.2
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/bprint.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/timestamp.h"
28 #include "avformat.h"
29 #include "internal.h"
30 #include "url.h"
31 
32 typedef enum ConcatMatchMode {
36 
37 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;
48  int64_t user_duration;
49  int64_t next_dts;
51  int64_t inpoint;
52  int64_t outpoint;
55 } ConcatFile;
56 
57 typedef struct {
58  AVClass *class;
61  unsigned nb_files;
63  int safe;
64  int seekable;
65  int eof;
67  unsigned auto_convert;
70 
71 static int concat_probe(const AVProbeData *probe)
72 {
73  return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
75 }
76 
77 static char *get_keyword(uint8_t **cursor)
78 {
79  char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
80  *cursor += strcspn(*cursor, SPACE_CHARS);
81  if (**cursor) {
82  *((*cursor)++) = 0;
83  *cursor += strspn(*cursor, SPACE_CHARS);
84  }
85  return ret;
86 }
87 
88 static int safe_filename(const char *f)
89 {
90  const char *start = f;
91 
92  for (; *f; f++) {
93  /* A-Za-z0-9_- */
94  if (!((unsigned)((*f | 32) - 'a') < 26 ||
95  (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
96  if (f == start)
97  return 0;
98  else if (*f == '/')
99  start = f + 1;
100  else if (*f != '.')
101  return 0;
102  }
103  }
104  return 1;
105 }
106 
107 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
108 
109 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
110  unsigned *nb_files_alloc)
111 {
112  ConcatContext *cat = avf->priv_data;
113  ConcatFile *file;
114  char *url = NULL;
115  const char *proto;
116  size_t url_len, proto_len;
117  int ret;
118 
119  if (cat->safe > 0 && !safe_filename(filename)) {
120  av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
121  FAIL(AVERROR(EPERM));
122  }
123 
124  proto = avio_find_protocol_name(filename);
125  proto_len = proto ? strlen(proto) : 0;
126  if (proto && !memcmp(filename, proto, proto_len) &&
127  (filename[proto_len] == ':' || filename[proto_len] == ',')) {
128  url = filename;
129  filename = NULL;
130  } else {
131  url_len = strlen(avf->url) + strlen(filename) + 16;
132  if (!(url = av_malloc(url_len)))
133  FAIL(AVERROR(ENOMEM));
134  ff_make_absolute_url(url, url_len, avf->url, filename);
135  av_freep(&filename);
136  }
137 
138  if (cat->nb_files >= *nb_files_alloc) {
139  size_t n = FFMAX(*nb_files_alloc * 2, 16);
140  ConcatFile *new_files;
141  if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
142  !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
143  FAIL(AVERROR(ENOMEM));
144  cat->files = new_files;
145  *nb_files_alloc = n;
146  }
147 
148  file = &cat->files[cat->nb_files++];
149  memset(file, 0, sizeof(*file));
150  *rfile = file;
151 
152  file->url = url;
153  file->start_time = AV_NOPTS_VALUE;
154  file->duration = AV_NOPTS_VALUE;
155  file->next_dts = AV_NOPTS_VALUE;
156  file->inpoint = AV_NOPTS_VALUE;
157  file->outpoint = AV_NOPTS_VALUE;
159 
160  return 0;
161 
162 fail:
163  av_free(url);
164  av_free(filename);
165  return ret;
166 }
167 
168 static int copy_stream_props(AVStream *st, AVStream *source_st)
169 {
170  int ret;
171 
172  if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
173  if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
174  if (st->codecpar->extradata) {
175  av_freep(&st->codecpar->extradata);
176  st->codecpar->extradata_size = 0;
177  }
178  ret = ff_alloc_extradata(st->codecpar,
179  source_st->codecpar->extradata_size);
180  if (ret < 0)
181  return ret;
182  }
183  memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
184  source_st->codecpar->extradata_size);
185  return 0;
186  }
187  if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
188  return ret;
189  st->r_frame_rate = source_st->r_frame_rate;
190  st->avg_frame_rate = source_st->avg_frame_rate;
191  st->sample_aspect_ratio = source_st->sample_aspect_ratio;
192  avpriv_set_pts_info(st, 64, source_st->time_base.num, source_st->time_base.den);
193 
194  av_dict_copy(&st->metadata, source_st->metadata, 0);
195  return 0;
196 }
197 
198 static int detect_stream_specific(AVFormatContext *avf, int idx)
199 {
200  ConcatContext *cat = avf->priv_data;
201  AVStream *st = cat->avf->streams[idx];
202  ConcatStream *cs = &cat->cur_file->streams[idx];
203  const AVBitStreamFilter *filter;
204  AVBSFContext *bsf;
205  int ret;
206 
207  if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264) {
208  if (!st->codecpar->extradata_size ||
209  (st->codecpar->extradata_size >= 3 && AV_RB24(st->codecpar->extradata) == 1) ||
210  (st->codecpar->extradata_size >= 4 && AV_RB32(st->codecpar->extradata) == 1))
211  return 0;
212  av_log(cat->avf, AV_LOG_INFO,
213  "Auto-inserting h264_mp4toannexb bitstream filter\n");
214  filter = av_bsf_get_by_name("h264_mp4toannexb");
215  if (!filter) {
216  av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
217  "required for H.264 streams\n");
218  return AVERROR_BSF_NOT_FOUND;
219  }
220  ret = av_bsf_alloc(filter, &bsf);
221  if (ret < 0)
222  return ret;
223  cs->bsf = bsf;
224 
225  ret = avcodec_parameters_copy(bsf->par_in, st->codecpar);
226  if (ret < 0)
227  return ret;
228 
229  ret = av_bsf_init(bsf);
230  if (ret < 0)
231  return ret;
232 
233  ret = avcodec_parameters_copy(st->codecpar, bsf->par_out);
234  if (ret < 0)
235  return ret;
236  }
237  return 0;
238 }
239 
241 {
242  ConcatContext *cat = avf->priv_data;
243  AVStream *st;
244  int i, ret;
245 
246  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
247  if (i < avf->nb_streams) {
248  st = avf->streams[i];
249  } else {
250  if (!(st = avformat_new_stream(avf, NULL)))
251  return AVERROR(ENOMEM);
252  }
253  if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
254  return ret;
256  }
257  return 0;
258 }
259 
261 {
262  ConcatContext *cat = avf->priv_data;
263  AVStream *st;
264  int i, j, ret;
265 
266  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
267  st = cat->avf->streams[i];
268  for (j = 0; j < avf->nb_streams; j++) {
269  if (avf->streams[j]->id == st->id) {
270  av_log(avf, AV_LOG_VERBOSE,
271  "Match slave stream #%d with stream #%d id 0x%x\n",
272  i, j, st->id);
273  if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
274  return ret;
275  cat->cur_file->streams[i].out_stream_index = j;
276  }
277  }
278  }
279  return 0;
280 }
281 
283 {
284  ConcatContext *cat = avf->priv_data;
285  ConcatStream *map;
286  int i, ret;
287 
288  if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
289  return 0;
290  map = av_realloc(cat->cur_file->streams,
291  cat->avf->nb_streams * sizeof(*map));
292  if (!map)
293  return AVERROR(ENOMEM);
294  cat->cur_file->streams = map;
295  memset(map + cat->cur_file->nb_streams, 0,
296  (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
297 
298  for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
299  map[i].out_stream_index = -1;
300  if ((ret = detect_stream_specific(avf, i)) < 0)
301  return ret;
302  }
303  switch (cat->stream_match_mode) {
304  case MATCH_ONE_TO_ONE:
305  ret = match_streams_one_to_one(avf);
306  break;
307  case MATCH_EXACT_ID:
308  ret = match_streams_exact_id(avf);
309  break;
310  default:
311  ret = AVERROR_BUG;
312  }
313  if (ret < 0)
314  return ret;
315  cat->cur_file->nb_streams = cat->avf->nb_streams;
316  return 0;
317 }
318 
320 {
321  if (file->user_duration != AV_NOPTS_VALUE)
322  return file->user_duration;
323  if (file->outpoint != AV_NOPTS_VALUE)
324  return file->outpoint - file->file_inpoint;
325  if (avf->duration > 0)
326  return avf->duration - (file->file_inpoint - file->file_start_time);
327  if (file->next_dts != AV_NOPTS_VALUE)
328  return file->next_dts - file->file_inpoint;
329  return AV_NOPTS_VALUE;
330 }
331 
332 static int open_file(AVFormatContext *avf, unsigned fileno)
333 {
334  ConcatContext *cat = avf->priv_data;
335  ConcatFile *file = &cat->files[fileno];
336  int ret;
337 
338  if (cat->avf)
339  avformat_close_input(&cat->avf);
340 
341  cat->avf = avformat_alloc_context();
342  if (!cat->avf)
343  return AVERROR(ENOMEM);
344 
345  cat->avf->flags |= avf->flags & ~AVFMT_FLAG_CUSTOM_IO;
347 
348  if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
349  return ret;
350 
351  if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
352  (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
353  av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
354  avformat_close_input(&cat->avf);
355  return ret;
356  }
357  cat->cur_file = file;
358  file->start_time = !fileno ? 0 :
359  cat->files[fileno - 1].start_time +
360  cat->files[fileno - 1].duration;
361  file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
362  file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
363  file->duration = get_best_effort_duration(file, cat->avf);
364 
365  if (cat->segment_time_metadata) {
366  av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
367  if (file->duration != AV_NOPTS_VALUE)
368  av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
369  }
370 
371  if ((ret = match_streams(avf)) < 0)
372  return ret;
373  if (file->inpoint != AV_NOPTS_VALUE) {
374  if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
375  return ret;
376  }
377  return 0;
378 }
379 
381 {
382  ConcatContext *cat = avf->priv_data;
383  unsigned i, j;
384 
385  for (i = 0; i < cat->nb_files; i++) {
386  av_freep(&cat->files[i].url);
387  for (j = 0; j < cat->files[i].nb_streams; j++) {
388  if (cat->files[i].streams[j].bsf)
389  av_bsf_free(&cat->files[i].streams[j].bsf);
390  }
391  av_freep(&cat->files[i].streams);
392  av_dict_free(&cat->files[i].metadata);
393  }
394  if (cat->avf)
395  avformat_close_input(&cat->avf);
396  av_freep(&cat->files);
397  return 0;
398 }
399 
401 {
402  ConcatContext *cat = avf->priv_data;
403  AVBPrint bp;
404  uint8_t *cursor, *keyword;
405  int line = 0, i;
406  unsigned nb_files_alloc = 0;
407  ConcatFile *file = NULL;
408  int64_t ret, time = 0;
409 
411 
412  while ((ret = ff_read_line_to_bprint_overwrite(avf->pb, &bp)) >= 0) {
413  line++;
414  cursor = bp.str;
415  keyword = get_keyword(&cursor);
416  if (!*keyword || *keyword == '#')
417  continue;
418 
419  if (!strcmp(keyword, "file")) {
420  char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
421  if (!filename) {
422  av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
424  }
425  if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
426  goto fail;
427  } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
428  char *dur_str = get_keyword(&cursor);
429  int64_t dur;
430  if (!file) {
431  av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
432  line, keyword);
434  }
435  if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
436  av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
437  line, keyword, dur_str);
438  goto fail;
439  }
440  if (!strcmp(keyword, "duration"))
441  file->user_duration = dur;
442  else if (!strcmp(keyword, "inpoint"))
443  file->inpoint = dur;
444  else if (!strcmp(keyword, "outpoint"))
445  file->outpoint = dur;
446  } else if (!strcmp(keyword, "file_packet_metadata")) {
447  char *metadata;
448  if (!file) {
449  av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
450  line, keyword);
452  }
453  metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
454  if (!metadata) {
455  av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
457  }
458  if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
459  av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
460  av_freep(&metadata);
462  }
463  av_freep(&metadata);
464  } else if (!strcmp(keyword, "stream")) {
465  if (!avformat_new_stream(avf, NULL))
466  FAIL(AVERROR(ENOMEM));
467  } else if (!strcmp(keyword, "exact_stream_id")) {
468  if (!avf->nb_streams) {
469  av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
470  line);
472  }
473  avf->streams[avf->nb_streams - 1]->id =
474  strtol(get_keyword(&cursor), NULL, 0);
475  } else if (!strcmp(keyword, "ffconcat")) {
476  char *ver_kw = get_keyword(&cursor);
477  char *ver_val = get_keyword(&cursor);
478  if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
479  av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
481  }
482  if (cat->safe < 0)
483  cat->safe = 1;
484  } else {
485  av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
486  line, keyword);
488  }
489  }
490  if (ret != AVERROR_EOF && ret < 0)
491  goto fail;
492  if (!cat->nb_files)
494 
495  for (i = 0; i < cat->nb_files; i++) {
496  if (cat->files[i].start_time == AV_NOPTS_VALUE)
497  cat->files[i].start_time = time;
498  else
499  time = cat->files[i].start_time;
500  if (cat->files[i].user_duration == AV_NOPTS_VALUE) {
501  if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
502  break;
503  cat->files[i].user_duration = cat->files[i].outpoint - cat->files[i].inpoint;
504  }
505  cat->files[i].duration = cat->files[i].user_duration;
506  time += cat->files[i].user_duration;
507  }
508  if (i == cat->nb_files) {
509  avf->duration = time;
510  cat->seekable = 1;
511  }
512 
515  if ((ret = open_file(avf, 0)) < 0)
516  goto fail;
517  av_bprint_finalize(&bp, NULL);
518  return 0;
519 
520 fail:
521  av_bprint_finalize(&bp, NULL);
522  concat_read_close(avf);
523  return ret;
524 }
525 
527 {
528  ConcatContext *cat = avf->priv_data;
529  unsigned fileno = cat->cur_file - cat->files;
530 
532 
533  if (++fileno >= cat->nb_files) {
534  cat->eof = 1;
535  return AVERROR_EOF;
536  }
537  return open_file(avf, fileno);
538 }
539 
541 {
542  int ret;
543 
544  if (cs->bsf) {
545  ret = av_bsf_send_packet(cs->bsf, pkt);
546  if (ret < 0) {
547  av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
548  "failed to send input packet\n");
549  av_packet_unref(pkt);
550  return ret;
551  }
552 
553  while (!ret)
554  ret = av_bsf_receive_packet(cs->bsf, pkt);
555 
556  if (ret < 0 && (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)) {
557  av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
558  "failed to receive output packet\n");
559  return ret;
560  }
561  }
562  return 0;
563 }
564 
565 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
567 {
568  if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
569  return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
570  cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
571  }
572  return 0;
573 }
574 
576 {
577  ConcatContext *cat = avf->priv_data;
578  int ret;
579  int64_t delta;
580  ConcatStream *cs;
581  AVStream *st;
582 
583  if (cat->eof)
584  return AVERROR_EOF;
585 
586  if (!cat->avf)
587  return AVERROR(EIO);
588 
589  while (1) {
590  ret = av_read_frame(cat->avf, pkt);
591  if (ret == AVERROR_EOF) {
592  if ((ret = open_next_file(avf)) < 0)
593  return ret;
594  continue;
595  }
596  if (ret < 0)
597  return ret;
598  if ((ret = match_streams(avf)) < 0) {
599  av_packet_unref(pkt);
600  return ret;
601  }
602  if (packet_after_outpoint(cat, pkt)) {
603  av_packet_unref(pkt);
604  if ((ret = open_next_file(avf)) < 0)
605  return ret;
606  continue;
607  }
608  cs = &cat->cur_file->streams[pkt->stream_index];
609  if (cs->out_stream_index < 0) {
610  av_packet_unref(pkt);
611  continue;
612  }
613  break;
614  }
615  if ((ret = filter_packet(avf, cs, pkt)))
616  return ret;
617 
618  st = cat->avf->streams[pkt->stream_index];
619  av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
620  (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
621  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
622  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
623 
624  delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
626  cat->avf->streams[pkt->stream_index]->time_base);
627  if (pkt->pts != AV_NOPTS_VALUE)
628  pkt->pts += delta;
629  if (pkt->dts != AV_NOPTS_VALUE)
630  pkt->dts += delta;
631  av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
632  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
633  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
634  if (cat->cur_file->metadata) {
635  uint8_t* metadata;
636  int metadata_len;
637  char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
638  if (!packed_metadata)
639  return AVERROR(ENOMEM);
640  if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
641  av_freep(&packed_metadata);
642  return AVERROR(ENOMEM);
643  }
644  memcpy(metadata, packed_metadata, metadata_len);
645  av_freep(&packed_metadata);
646  }
647 
648  if (cat->cur_file->duration == AV_NOPTS_VALUE && st->cur_dts != AV_NOPTS_VALUE) {
649  int64_t next_dts = av_rescale_q(st->cur_dts, st->time_base, AV_TIME_BASE_Q);
650  if (cat->cur_file->next_dts == AV_NOPTS_VALUE || next_dts > cat->cur_file->next_dts) {
651  cat->cur_file->next_dts = next_dts;
652  }
653  }
654 
655  pkt->stream_index = cs->out_stream_index;
656  return ret;
657 }
658 
659 static void rescale_interval(AVRational tb_in, AVRational tb_out,
660  int64_t *min_ts, int64_t *ts, int64_t *max_ts)
661 {
662  *ts = av_rescale_q (* ts, tb_in, tb_out);
663  *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
665  *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
667 }
668 
669 static int try_seek(AVFormatContext *avf, int stream,
670  int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
671 {
672  ConcatContext *cat = avf->priv_data;
673  int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
674 
675  ts -= t0;
676  min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
677  max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
678  if (stream >= 0) {
679  if (stream >= cat->avf->nb_streams)
680  return AVERROR(EIO);
682  &min_ts, &ts, &max_ts);
683  }
684  return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
685 }
686 
687 static int real_seek(AVFormatContext *avf, int stream,
688  int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
689 {
690  ConcatContext *cat = avf->priv_data;
691  int ret, left, right;
692 
693  if (stream >= 0) {
694  if (stream >= avf->nb_streams)
695  return AVERROR(EINVAL);
697  &min_ts, &ts, &max_ts);
698  }
699 
700  left = 0;
701  right = cat->nb_files;
702 
703  /* Always support seek to start */
704  if (ts <= 0)
705  right = 1;
706  else if (!cat->seekable)
707  return AVERROR(ESPIPE); /* XXX: can we use it? */
708 
709  while (right - left > 1) {
710  int mid = (left + right) / 2;
711  if (ts < cat->files[mid].start_time)
712  right = mid;
713  else
714  left = mid;
715  }
716 
717  if (cat->cur_file != &cat->files[left]) {
718  if ((ret = open_file(avf, left)) < 0)
719  return ret;
720  } else {
721  cat->avf = cur_avf;
722  }
723 
724  ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
725  if (ret < 0 &&
726  left < cat->nb_files - 1 &&
727  cat->files[left + 1].start_time < max_ts) {
728  if (cat->cur_file == &cat->files[left])
729  cat->avf = NULL;
730  if ((ret = open_file(avf, left + 1)) < 0)
731  return ret;
732  ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
733  }
734  return ret;
735 }
736 
737 static int concat_seek(AVFormatContext *avf, int stream,
738  int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
739 {
740  ConcatContext *cat = avf->priv_data;
741  ConcatFile *cur_file_saved = cat->cur_file;
742  AVFormatContext *cur_avf_saved = cat->avf;
743  int ret;
744 
745  if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
746  return AVERROR(ENOSYS);
747  cat->avf = NULL;
748  if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags, cur_avf_saved)) < 0) {
749  if (cat->cur_file != cur_file_saved) {
750  if (cat->avf)
751  avformat_close_input(&cat->avf);
752  }
753  cat->avf = cur_avf_saved;
754  cat->cur_file = cur_file_saved;
755  } else {
756  if (cat->cur_file != cur_file_saved) {
757  avformat_close_input(&cur_avf_saved);
758  }
759  cat->eof = 0;
760  }
761  return ret;
762 }
763 
764 #define OFFSET(x) offsetof(ConcatContext, x)
765 #define DEC AV_OPT_FLAG_DECODING_PARAM
766 
767 static const AVOption options[] = {
768  { "safe", "enable safe mode",
769  OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
770  { "auto_convert", "automatically convert bitstream format",
771  OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
772  { "segment_time_metadata", "output file segment start time and duration as packet metadata",
773  OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
774  { NULL }
775 };
776 
777 static const AVClass concat_class = {
778  .class_name = "concat demuxer",
779  .item_name = av_default_item_name,
780  .option = options,
781  .version = LIBAVUTIL_VERSION_INT,
782 };
783 
784 
786  .name = "concat",
787  .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
788  .priv_data_size = sizeof(ConcatContext),
793  .read_seek2 = concat_seek,
794  .priv_class = &concat_class,
795 };
static int64_t get_best_effort_duration(ConcatFile *file, AVFormatContext *avf)
Definition: concatdec.c:319
void av_bsf_free(AVBSFContext **ctx)
Free a bitstream filter context and everything associated with it; write NULL into the supplied point...
Definition: bsf.c:35
#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
int64_t next_dts
Definition: concatdec.c:49
AVCodecParameters * par_out
Parameters of the output stream.
Definition: avcodec.h:5797
void * av_realloc(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory.
Definition: mem.c:135
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1636
AVOption.
Definition: opt.h:246
static int concat_read_close(AVFormatContext *avf)
Definition: concatdec.c:380
ConcatMatchMode
Definition: concatdec.c:32
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
#define DEC
Definition: concatdec.c:765
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4886
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:587
int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
Copies the whilelists from one context to the other.
Definition: utils.c:164
#define FAIL(retcode)
Definition: concatdec.c:107
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3957
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:659
int num
Numerator.
Definition: rational.h:59
The bitstream filter state.
Definition: avcodec.h:5763
AVDictionary * metadata
Definition: concatdec.c:53
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:191
const AVBitStreamFilter * av_bsf_get_by_name(const char *name)
#define AV_RB24
Definition: intreadwrite.h:64
AVBSFContext * bsf
Definition: concatdec.c:38
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:217
int avformat_open_input(AVFormatContext **ps, const char *url, ff_const59 AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:537
static AVPacket pkt
static const AVOption options[]
Definition: concatdec.c:767
int av_bsf_init(AVBSFContext *ctx)
Prepare the filter for use, after all the parameters and options have been set.
Definition: bsf.c:135
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
int64_t outpoint
Definition: concatdec.c:52
Format I/O context.
Definition: avformat.h:1358
int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **ctx)
Allocate a context for a given bitstream filter.
Definition: bsf.c:82
int64_t cur_dts
Definition: avformat.h:1084
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
int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt)
Retrieve a filtered packet.
Definition: bsf.c:212
static void filter(int16_t *output, ptrdiff_t out_stride, int16_t *low, ptrdiff_t low_stride, int16_t *high, ptrdiff_t high_stride, int len, int clip)
Definition: cfhd.c:153
static int concat_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition: concatdec.c:737
ConcatStream * streams
Definition: concatdec.c:50
static int64_t start_time
Definition: ffplay.c:331
uint8_t
Round toward +infinity.
Definition: mathematics.h:83
static int nb_streams
Definition: ffprobe.c:280
#define av_malloc(s)
float delta
static int match_streams(AVFormatContext *avf)
Definition: concatdec.c:282
AVOptions.
timestamp utils, mostly useful for debugging/logging purposes
#define f(width, name)
Definition: cbs_vp9.c:255
#define AV_RB32
Definition: intreadwrite.h:130
int id
Format-specific stream ID.
Definition: avformat.h:888
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4459
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1426
#define t0
Definition: regdef.h:28
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:144
AVInputFormat ff_concat_demuxer
Definition: concatdec.c:785
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1489
#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
#define av_log(a,...)
int64_t inpoint
Definition: concatdec.c:51
static int concat_read_header(AVFormatContext *avf)
Definition: concatdec.c:400
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:68
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:259
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: utils.c:2040
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
#define AV_BPRINT_SIZE_UNLIMITED
unsigned auto_convert
Definition: concatdec.c:67
#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
int64_t ff_read_line_to_bprint_overwrite(AVIOContext *s, AVBPrint *bp)
Read a whole line of text from AVIOContext to an AVBPrint buffer overwriting its contents.
Definition: aviobuf.c:864
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
char * url
input or output URL.
Definition: avformat.h:1454
#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:203
Definition: graph2dot.c:48
simple assert() macros that are a bit more flexible than ISO C assert().
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:954
#define FFMAX(a, b)
Definition: common.h:94
#define fail()
Definition: checkasm.h:120
static int concat_probe(const AVProbeData *probe)
Definition: concatdec.c:71
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 av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
Definition: mathematics.c:147
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3975
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:448
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1414
static int match_streams_one_to_one(AVFormatContext *avf)
Definition: concatdec.c:240
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:3288
static int try_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition: concatdec.c:669
static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
Definition: concatdec.c:566
static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
Definition: concatdec.c:540
static const AVClass concat_class
Definition: concatdec.c:777
int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)
Submit a packet for filtering.
Definition: bsf.c:186
static int open_file(AVFormatContext *avf, unsigned fileno)
Definition: concatdec.c:332
#define AVERROR_BSF_NOT_FOUND
Bitstream filter not found.
Definition: error.h:49
int n
Definition: avisynth_c.h:760
AVDictionary * metadata
Definition: avformat.h:945
#define AVFMT_FLAG_CUSTOM_IO
The caller has supplied a custom AVIOContext, don&#39;t avio_close() it.
Definition: avformat.h:1497
ConcatMatchMode stream_match_mode
Definition: concatdec.c:66
#define cat(a, bpp, b)
Definition: vp9dsp_init.h:29
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:530
Stream structure.
Definition: avformat.h:881
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:180
ConcatFile * cur_file
Definition: concatdec.c:60
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
A list of zero terminated key/value strings.
Definition: avcodec.h:1316
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
AVIOContext * pb
I/O context.
Definition: avformat.h:1400
ConcatFile * files
Definition: concatdec.c:59
uint8_t * av_packet_pack_dictionary(AVDictionary *dict, int *size)
Pack a dictionary for use in side_data.
Definition: avpacket.c:488
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:599
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
int nb_streams
Definition: concatdec.c:54
Describe the class of an AVClass context structure.
Definition: log.h:67
#define SPACE_CHARS
Definition: internal.h:354
Rational number (pair of numerator and denominator).
Definition: rational.h:58
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition: avformat.h:2512
const VDPAUPixFmtMap * map
static int match_streams_exact_id(AVFormatContext *avf)
Definition: concatdec.c:260
unsigned nb_files
Definition: concatdec.c:61
This structure contains the data a format has to probe a file.
Definition: avformat.h:446
misc parsing utilities
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1768
Round toward -infinity.
Definition: mathematics.h:82
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:2529
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
#define flags(name, subs,...)
Definition: cbs_av1.c:561
static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
Definition: concatdec.c:575
int64_t start_time
Position of the first frame of the component, in AV_TIME_BASE fractional seconds. ...
Definition: avformat.h:1463
static int read_probe(const AVProbeData *pd)
Definition: jvdec.c:55
char * url
Definition: concatdec.c:43
static int probe(const AVProbeData *p)
Definition: act.c:36
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:458
Main libavformat public API header.
static char * get_keyword(uint8_t **cursor)
Definition: concatdec.c:77
int64_t user_duration
Definition: concatdec.c:48
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3567
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:147
int den
Denominator.
Definition: rational.h:60
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4431
Flag telling rescaling functions to pass INT64_MIN/MAX through unchanged, avoiding special cases for ...
Definition: mathematics.h:108
static int open_next_file(AVFormatContext *avf)
Definition: concatdec.c:526
#define av_free(p)
static int copy_stream_props(AVStream *st, AVStream *source_st)
Definition: concatdec.c:168
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
void * priv_data
Format private data.
Definition: avformat.h:1386
#define AVSEEK_FLAG_FRAME
seeking based on frame number
Definition: avformat.h:2514
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3971
static int real_seek(AVFormatContext *avf, int stream, int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
Definition: concatdec.c:687
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1476
#define OFFSET(x)
Definition: concatdec.c:764
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1473
static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile, unsigned *nb_files_alloc)
Definition: concatdec.c:109
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:766
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:654
unbuffered private I/O API
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1028
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
static int detect_stream_specific(AVFormatContext *avf, int idx)
Definition: concatdec.c:198
static int safe_filename(const char *f)
Definition: concatdec.c:88
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:329
int stream_index
Definition: avcodec.h:1479
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:910
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1005
int64_t file_inpoint
Definition: concatdec.c:46
This structure stores compressed data.
Definition: avcodec.h:1454
AVCodecParameters * par_in
Parameters of the input stream.
Definition: avcodec.h:5791
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1470
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AVFormatContext * avf
Definition: concatdec.c:62