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