2 * Copyright (c) 2012 Nicolas George
4 * This file is part of FFmpeg.
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.
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.
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
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"
31 typedef enum ConcatMatchMode {
36 typedef struct ConcatStream {
44 int64_t file_start_time;
48 ConcatStream *streams;
51 AVDictionary *metadata;
64 ConcatMatchMode stream_match_mode;
65 unsigned auto_convert;
66 int segment_time_metadata;
69 static int concat_probe(AVProbeData *probe)
71 return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
72 0 : AVPROBE_SCORE_MAX;
75 static char *get_keyword(uint8_t **cursor)
77 char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
78 *cursor += strcspn(*cursor, SPACE_CHARS);
81 *cursor += strspn(*cursor, SPACE_CHARS);
86 static int safe_filename(const char *f)
88 const char *start = f;
92 if (!((unsigned)((*f | 32) - 'a') < 26 ||
93 (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
105 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
107 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
108 unsigned *nb_files_alloc)
110 ConcatContext *cat = avf->priv_data;
114 size_t url_len, proto_len;
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));
122 proto = avio_find_protocol_name(filename);
123 proto_len = proto ? strlen(proto) : 0;
124 if (proto && !memcmp(filename, proto, proto_len) &&
125 (filename[proto_len] == ':' || filename[proto_len] == ',')) {
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);
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;
146 file = &cat->files[cat->nb_files++];
147 memset(file, 0, sizeof(*file));
151 file->start_time = AV_NOPTS_VALUE;
152 file->duration = AV_NOPTS_VALUE;
153 file->next_dts = AV_NOPTS_VALUE;
154 file->inpoint = AV_NOPTS_VALUE;
155 file->outpoint = AV_NOPTS_VALUE;
165 static int copy_stream_props(AVStream *st, AVStream *source_st)
169 if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
170 if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
171 if (st->codecpar->extradata) {
172 av_freep(&st->codecpar->extradata);
173 st->codecpar->extradata_size = 0;
175 ret = ff_alloc_extradata(st->codecpar,
176 source_st->codecpar->extradata_size);
180 memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
181 source_st->codecpar->extradata_size);
184 if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
186 st->r_frame_rate = source_st->r_frame_rate;
187 st->avg_frame_rate = source_st->avg_frame_rate;
188 st->time_base = source_st->time_base;
189 st->sample_aspect_ratio = source_st->sample_aspect_ratio;
191 av_dict_copy(&st->metadata, source_st->metadata, 0);
195 static int detect_stream_specific(AVFormatContext *avf, int idx)
197 ConcatContext *cat = avf->priv_data;
198 AVStream *st = cat->avf->streams[idx];
199 ConcatStream *cs = &cat->cur_file->streams[idx];
200 const AVBitStreamFilter *filter;
204 if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264) {
205 if (!st->codecpar->extradata_size ||
206 (st->codecpar->extradata_size >= 3 && AV_RB24(st->codecpar->extradata) == 1) ||
207 (st->codecpar->extradata_size >= 4 && AV_RB32(st->codecpar->extradata) == 1))
209 av_log(cat->avf, AV_LOG_INFO,
210 "Auto-inserting h264_mp4toannexb bitstream filter\n");
211 filter = av_bsf_get_by_name("h264_mp4toannexb");
213 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
214 "required for H.264 streams\n");
215 return AVERROR_BSF_NOT_FOUND;
217 ret = av_bsf_alloc(filter, &bsf);
222 ret = avcodec_parameters_copy(bsf->par_in, st->codecpar);
226 ret = av_bsf_init(bsf);
230 ret = avcodec_parameters_copy(st->codecpar, bsf->par_out);
237 static int match_streams_one_to_one(AVFormatContext *avf)
239 ConcatContext *cat = avf->priv_data;
243 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
244 if (i < avf->nb_streams) {
245 st = avf->streams[i];
247 if (!(st = avformat_new_stream(avf, NULL)))
248 return AVERROR(ENOMEM);
250 if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
252 cat->cur_file->streams[i].out_stream_index = i;
257 static int match_streams_exact_id(AVFormatContext *avf)
259 ConcatContext *cat = avf->priv_data;
263 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
264 st = cat->avf->streams[i];
265 for (j = 0; j < avf->nb_streams; j++) {
266 if (avf->streams[j]->id == st->id) {
267 av_log(avf, AV_LOG_VERBOSE,
268 "Match slave stream #%d with stream #%d id 0x%x\n",
270 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
272 cat->cur_file->streams[i].out_stream_index = j;
279 static int match_streams(AVFormatContext *avf)
281 ConcatContext *cat = avf->priv_data;
285 if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
287 map = av_realloc(cat->cur_file->streams,
288 cat->avf->nb_streams * sizeof(*map));
290 return AVERROR(ENOMEM);
291 cat->cur_file->streams = map;
292 memset(map + cat->cur_file->nb_streams, 0,
293 (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
295 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
296 map[i].out_stream_index = -1;
297 if ((ret = detect_stream_specific(avf, i)) < 0)
300 switch (cat->stream_match_mode) {
301 case MATCH_ONE_TO_ONE:
302 ret = match_streams_one_to_one(avf);
305 ret = match_streams_exact_id(avf);
312 cat->cur_file->nb_streams = cat->avf->nb_streams;
316 static int open_file(AVFormatContext *avf, unsigned fileno)
318 ConcatContext *cat = avf->priv_data;
319 ConcatFile *file = &cat->files[fileno];
323 avformat_close_input(&cat->avf);
325 cat->avf = avformat_alloc_context();
327 return AVERROR(ENOMEM);
329 cat->avf->flags |= avf->flags & ~AVFMT_FLAG_CUSTOM_IO;
330 cat->avf->interrupt_callback = avf->interrupt_callback;
332 if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
335 if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
336 (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
337 av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
338 avformat_close_input(&cat->avf);
341 cat->cur_file = file;
342 if (file->start_time == AV_NOPTS_VALUE)
343 file->start_time = !fileno ? 0 :
344 cat->files[fileno - 1].start_time +
345 cat->files[fileno - 1].duration;
346 file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
347 file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
348 if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
349 file->duration = file->outpoint - file->file_inpoint;
351 if (cat->segment_time_metadata) {
352 av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
353 if (file->duration != AV_NOPTS_VALUE)
354 av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
357 if ((ret = match_streams(avf)) < 0)
359 if (file->inpoint != AV_NOPTS_VALUE) {
360 if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
366 static int concat_read_close(AVFormatContext *avf)
368 ConcatContext *cat = avf->priv_data;
371 for (i = 0; i < cat->nb_files; i++) {
372 av_freep(&cat->files[i].url);
373 for (j = 0; j < cat->files[i].nb_streams; j++) {
374 if (cat->files[i].streams[j].bsf)
375 av_bsf_free(&cat->files[i].streams[j].bsf);
377 av_freep(&cat->files[i].streams);
378 av_dict_free(&cat->files[i].metadata);
381 avformat_close_input(&cat->avf);
382 av_freep(&cat->files);
386 static int concat_read_header(AVFormatContext *avf)
388 ConcatContext *cat = avf->priv_data;
390 uint8_t *cursor, *keyword;
391 int ret, line = 0, i;
392 unsigned nb_files_alloc = 0;
393 ConcatFile *file = NULL;
397 if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
401 keyword = get_keyword(&cursor);
402 if (!*keyword || *keyword == '#')
405 if (!strcmp(keyword, "file")) {
406 char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
408 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
409 FAIL(AVERROR_INVALIDDATA);
411 if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
413 } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
414 char *dur_str = get_keyword(&cursor);
417 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
419 FAIL(AVERROR_INVALIDDATA);
421 if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
422 av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
423 line, keyword, dur_str);
426 if (!strcmp(keyword, "duration"))
427 file->duration = dur;
428 else if (!strcmp(keyword, "inpoint"))
430 else if (!strcmp(keyword, "outpoint"))
431 file->outpoint = dur;
432 } else if (!strcmp(keyword, "file_packet_metadata")) {
435 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
437 FAIL(AVERROR_INVALIDDATA);
439 metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
441 av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
442 FAIL(AVERROR_INVALIDDATA);
444 if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
445 av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
447 FAIL(AVERROR_INVALIDDATA);
450 } else if (!strcmp(keyword, "stream")) {
451 if (!avformat_new_stream(avf, NULL))
452 FAIL(AVERROR(ENOMEM));
453 } else if (!strcmp(keyword, "exact_stream_id")) {
454 if (!avf->nb_streams) {
455 av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
457 FAIL(AVERROR_INVALIDDATA);
459 avf->streams[avf->nb_streams - 1]->id =
460 strtol(get_keyword(&cursor), NULL, 0);
461 } else if (!strcmp(keyword, "ffconcat")) {
462 char *ver_kw = get_keyword(&cursor);
463 char *ver_val = get_keyword(&cursor);
464 if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
465 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
466 FAIL(AVERROR_INVALIDDATA);
471 av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
473 FAIL(AVERROR_INVALIDDATA);
479 FAIL(AVERROR_INVALIDDATA);
481 for (i = 0; i < cat->nb_files; i++) {
482 if (cat->files[i].start_time == AV_NOPTS_VALUE)
483 cat->files[i].start_time = time;
485 time = cat->files[i].start_time;
486 if (cat->files[i].duration == AV_NOPTS_VALUE) {
487 if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
489 cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
491 time += cat->files[i].duration;
493 if (i == cat->nb_files) {
494 avf->duration = time;
498 cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
500 if ((ret = open_file(avf, 0)) < 0)
505 concat_read_close(avf);
509 static int open_next_file(AVFormatContext *avf)
511 ConcatContext *cat = avf->priv_data;
512 unsigned fileno = cat->cur_file - cat->files;
514 if (cat->cur_file->duration == AV_NOPTS_VALUE) {
515 if (cat->avf->duration > 0 || cat->cur_file->next_dts == AV_NOPTS_VALUE) {
516 cat->cur_file->duration = cat->avf->duration;
518 cat->cur_file->duration = cat->cur_file->next_dts;
520 cat->cur_file->duration -= (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
523 if (++fileno >= cat->nb_files) {
527 return open_file(avf, fileno);
530 static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
535 ret = av_bsf_send_packet(cs->bsf, pkt);
537 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
538 "failed to send input packet\n");
539 av_packet_unref(pkt);
544 ret = av_bsf_receive_packet(cs->bsf, pkt);
546 if (ret < 0 && (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)) {
547 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
548 "failed to receive output packet\n");
555 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
556 static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
558 if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
559 return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
560 cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
565 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
567 ConcatContext *cat = avf->priv_data;
580 ret = av_read_frame(cat->avf, pkt);
581 if (ret == AVERROR_EOF) {
582 if ((ret = open_next_file(avf)) < 0)
588 if ((ret = match_streams(avf)) < 0) {
589 av_packet_unref(pkt);
592 if (packet_after_outpoint(cat, pkt)) {
593 av_packet_unref(pkt);
594 if ((ret = open_next_file(avf)) < 0)
598 cs = &cat->cur_file->streams[pkt->stream_index];
599 if (cs->out_stream_index < 0) {
600 av_packet_unref(pkt);
603 pkt->stream_index = cs->out_stream_index;
606 if ((ret = filter_packet(avf, cs, pkt)))
609 st = cat->avf->streams[pkt->stream_index];
610 av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
611 (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
612 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
613 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
615 delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
617 cat->avf->streams[pkt->stream_index]->time_base);
618 if (pkt->pts != AV_NOPTS_VALUE)
620 if (pkt->dts != AV_NOPTS_VALUE)
622 av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
623 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
624 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
625 if (cat->cur_file->metadata) {
628 char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
629 if (!packed_metadata)
630 return AVERROR(ENOMEM);
631 if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
632 av_freep(&packed_metadata);
633 return AVERROR(ENOMEM);
635 memcpy(metadata, packed_metadata, metadata_len);
636 av_freep(&packed_metadata);
639 if (cat->cur_file->duration == AV_NOPTS_VALUE && st->cur_dts != AV_NOPTS_VALUE) {
640 int64_t next_dts = av_rescale_q(st->cur_dts, st->time_base, AV_TIME_BASE_Q);
641 if (cat->cur_file->next_dts == AV_NOPTS_VALUE || next_dts > cat->cur_file->next_dts) {
642 cat->cur_file->next_dts = next_dts;
649 static void rescale_interval(AVRational tb_in, AVRational tb_out,
650 int64_t *min_ts, int64_t *ts, int64_t *max_ts)
652 *ts = av_rescale_q (* ts, tb_in, tb_out);
653 *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
654 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
655 *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
656 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
659 static int try_seek(AVFormatContext *avf, int stream,
660 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
662 ConcatContext *cat = avf->priv_data;
663 int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
666 min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
667 max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
669 if (stream >= cat->avf->nb_streams)
671 rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
672 &min_ts, &ts, &max_ts);
674 return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
677 static int real_seek(AVFormatContext *avf, int stream,
678 int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
680 ConcatContext *cat = avf->priv_data;
681 int ret, left, right;
684 if (stream >= avf->nb_streams)
685 return AVERROR(EINVAL);
686 rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
687 &min_ts, &ts, &max_ts);
691 right = cat->nb_files;
692 while (right - left > 1) {
693 int mid = (left + right) / 2;
694 if (ts < cat->files[mid].start_time)
700 if (cat->cur_file != &cat->files[left]) {
701 if ((ret = open_file(avf, left)) < 0)
707 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
709 left < cat->nb_files - 1 &&
710 cat->files[left + 1].start_time < max_ts) {
711 if (cat->cur_file == &cat->files[left])
713 if ((ret = open_file(avf, left + 1)) < 0)
715 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
720 static int concat_seek(AVFormatContext *avf, int stream,
721 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
723 ConcatContext *cat = avf->priv_data;
724 ConcatFile *cur_file_saved = cat->cur_file;
725 AVFormatContext *cur_avf_saved = cat->avf;
729 return AVERROR(ESPIPE); /* XXX: can we use it? */
730 if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
731 return AVERROR(ENOSYS);
733 if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags, cur_avf_saved)) < 0) {
734 if (cat->cur_file != cur_file_saved) {
736 avformat_close_input(&cat->avf);
738 cat->avf = cur_avf_saved;
739 cat->cur_file = cur_file_saved;
741 if (cat->cur_file != cur_file_saved) {
742 avformat_close_input(&cur_avf_saved);
749 #define OFFSET(x) offsetof(ConcatContext, x)
750 #define DEC AV_OPT_FLAG_DECODING_PARAM
752 static const AVOption options[] = {
753 { "safe", "enable safe mode",
754 OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
755 { "auto_convert", "automatically convert bitstream format",
756 OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
757 { "segment_time_metadata", "output file segment start time and duration as packet metadata",
758 OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
762 static const AVClass concat_class = {
763 .class_name = "concat demuxer",
764 .item_name = av_default_item_name,
766 .version = LIBAVUTIL_VERSION_INT,
770 AVInputFormat ff_concat_demuxer = {
772 .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
773 .priv_data_size = sizeof(ConcatContext),
774 .read_probe = concat_probe,
775 .read_header = concat_read_header,
776 .read_packet = concat_read_packet,
777 .read_close = concat_read_close,
778 .read_seek2 = concat_seek,
779 .priv_class = &concat_class,