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;
47 ConcatStream *streams;
50 AVDictionary *metadata;
63 ConcatMatchMode stream_match_mode;
64 unsigned auto_convert;
65 int segment_time_metadata;
68 static int concat_probe(AVProbeData *probe)
70 return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
71 0 : AVPROBE_SCORE_MAX;
74 static char *get_keyword(uint8_t **cursor)
76 char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
77 *cursor += strcspn(*cursor, SPACE_CHARS);
80 *cursor += strspn(*cursor, SPACE_CHARS);
85 static int safe_filename(const char *f)
87 const char *start = f;
91 if (!((unsigned)((*f | 32) - 'a') < 26 ||
92 (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
104 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
106 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
107 unsigned *nb_files_alloc)
109 ConcatContext *cat = avf->priv_data;
113 size_t url_len, proto_len;
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));
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] == ',')) {
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);
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;
145 file = &cat->files[cat->nb_files++];
146 memset(file, 0, sizeof(*file));
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;
163 static int copy_stream_props(AVStream *st, AVStream *source_st)
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;
173 ret = ff_alloc_extradata(st->codecpar,
174 source_st->codecpar->extradata_size);
178 memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
179 source_st->codecpar->extradata_size);
182 if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
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;
189 av_dict_copy(&st->metadata, source_st->metadata, 0);
193 static int detect_stream_specific(AVFormatContext *avf, int idx)
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;
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))
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");
211 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
212 "required for H.264 streams\n");
213 return AVERROR_BSF_NOT_FOUND;
215 ret = av_bsf_alloc(filter, &bsf);
220 ret = avcodec_parameters_copy(bsf->par_in, st->codecpar);
224 ret = av_bsf_init(bsf);
228 ret = avcodec_parameters_copy(st->codecpar, bsf->par_out);
235 static int match_streams_one_to_one(AVFormatContext *avf)
237 ConcatContext *cat = avf->priv_data;
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];
245 if (!(st = avformat_new_stream(avf, NULL)))
246 return AVERROR(ENOMEM);
248 if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
250 cat->cur_file->streams[i].out_stream_index = i;
255 static int match_streams_exact_id(AVFormatContext *avf)
257 ConcatContext *cat = avf->priv_data;
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",
268 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
270 cat->cur_file->streams[i].out_stream_index = j;
277 static int match_streams(AVFormatContext *avf)
279 ConcatContext *cat = avf->priv_data;
283 if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
285 map = av_realloc(cat->cur_file->streams,
286 cat->avf->nb_streams * sizeof(*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));
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)
298 switch (cat->stream_match_mode) {
299 case MATCH_ONE_TO_ONE:
300 ret = match_streams_one_to_one(avf);
303 ret = match_streams_exact_id(avf);
310 cat->cur_file->nb_streams = cat->avf->nb_streams;
314 static int open_file(AVFormatContext *avf, unsigned fileno)
316 ConcatContext *cat = avf->priv_data;
317 ConcatFile *file = &cat->files[fileno];
321 avformat_close_input(&cat->avf);
323 cat->avf = avformat_alloc_context();
325 return AVERROR(ENOMEM);
327 cat->avf->flags |= avf->flags;
328 cat->avf->interrupt_callback = avf->interrupt_callback;
330 if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
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);
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;
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);
355 if ((ret = match_streams(avf)) < 0)
357 if (file->inpoint != AV_NOPTS_VALUE) {
358 if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
364 static int concat_read_close(AVFormatContext *avf)
366 ConcatContext *cat = avf->priv_data;
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);
375 av_freep(&cat->files[i].streams);
376 av_dict_free(&cat->files[i].metadata);
379 avformat_close_input(&cat->avf);
380 av_freep(&cat->files);
384 static int concat_read_header(AVFormatContext *avf)
386 ConcatContext *cat = avf->priv_data;
388 uint8_t *cursor, *keyword;
389 int ret, line = 0, i;
390 unsigned nb_files_alloc = 0;
391 ConcatFile *file = NULL;
395 if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
399 keyword = get_keyword(&cursor);
400 if (!*keyword || *keyword == '#')
403 if (!strcmp(keyword, "file")) {
404 char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
406 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
407 FAIL(AVERROR_INVALIDDATA);
409 if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
411 } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
412 char *dur_str = get_keyword(&cursor);
415 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
417 FAIL(AVERROR_INVALIDDATA);
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);
424 if (!strcmp(keyword, "duration"))
425 file->duration = dur;
426 else if (!strcmp(keyword, "inpoint"))
428 else if (!strcmp(keyword, "outpoint"))
429 file->outpoint = dur;
430 } else if (!strcmp(keyword, "file_packet_metadata")) {
433 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
435 FAIL(AVERROR_INVALIDDATA);
437 metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
439 av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
440 FAIL(AVERROR_INVALIDDATA);
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);
445 FAIL(AVERROR_INVALIDDATA);
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",
455 FAIL(AVERROR_INVALIDDATA);
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);
464 FAIL(AVERROR_INVALIDDATA);
469 av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
471 FAIL(AVERROR_INVALIDDATA);
477 FAIL(AVERROR_INVALIDDATA);
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;
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)
487 cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
489 time += cat->files[i].duration;
491 if (i == cat->nb_files) {
492 avf->duration = time;
496 cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
498 if ((ret = open_file(avf, 0)) < 0)
503 concat_read_close(avf);
507 static int open_next_file(AVFormatContext *avf)
509 ConcatContext *cat = avf->priv_data;
510 unsigned fileno = cat->cur_file - cat->files;
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);
515 if (++fileno >= cat->nb_files) {
519 return open_file(avf, fileno);
522 static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
527 ret = av_bsf_send_packet(cs->bsf, pkt);
529 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
530 "failed to send input packet\n");
531 av_packet_unref(pkt);
536 ret = av_bsf_receive_packet(cs->bsf, pkt);
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");
547 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
548 static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
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;
557 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
559 ConcatContext *cat = avf->priv_data;
572 ret = av_read_frame(cat->avf, pkt);
573 if (ret == AVERROR_EOF) {
574 if ((ret = open_next_file(avf)) < 0)
580 if ((ret = match_streams(avf)) < 0) {
581 av_packet_unref(pkt);
584 if (packet_after_outpoint(cat, pkt)) {
585 av_packet_unref(pkt);
586 if ((ret = open_next_file(avf)) < 0)
590 cs = &cat->cur_file->streams[pkt->stream_index];
591 if (cs->out_stream_index < 0) {
592 av_packet_unref(pkt);
595 pkt->stream_index = cs->out_stream_index;
598 if ((ret = filter_packet(avf, cs, pkt)))
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));
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)
612 if (pkt->dts != AV_NOPTS_VALUE)
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) {
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);
627 memcpy(metadata, packed_metadata, metadata_len);
628 av_freep(&packed_metadata);
633 static void rescale_interval(AVRational tb_in, AVRational tb_out,
634 int64_t *min_ts, int64_t *ts, int64_t *max_ts)
636 *ts = av_rescale_q (* ts, tb_in, tb_out);
637 *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
638 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
639 *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
640 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
643 static int try_seek(AVFormatContext *avf, int stream,
644 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
646 ConcatContext *cat = avf->priv_data;
647 int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
650 min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
651 max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
653 if (stream >= cat->avf->nb_streams)
655 rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
656 &min_ts, &ts, &max_ts);
658 return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
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)
664 ConcatContext *cat = avf->priv_data;
665 int ret, left, right;
668 if (stream >= avf->nb_streams)
669 return AVERROR(EINVAL);
670 rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
671 &min_ts, &ts, &max_ts);
675 right = cat->nb_files;
676 while (right - left > 1) {
677 int mid = (left + right) / 2;
678 if (ts < cat->files[mid].start_time)
684 if (cat->cur_file != &cat->files[left]) {
685 if ((ret = open_file(avf, left)) < 0)
691 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
693 left < cat->nb_files - 1 &&
694 cat->files[left + 1].start_time < max_ts) {
695 if (cat->cur_file == &cat->files[left])
697 if ((ret = open_file(avf, left + 1)) < 0)
699 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
704 static int concat_seek(AVFormatContext *avf, int stream,
705 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
707 ConcatContext *cat = avf->priv_data;
708 ConcatFile *cur_file_saved = cat->cur_file;
709 AVFormatContext *cur_avf_saved = cat->avf;
713 return AVERROR(ESPIPE); /* XXX: can we use it? */
714 if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
715 return AVERROR(ENOSYS);
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) {
720 avformat_close_input(&cat->avf);
722 cat->avf = cur_avf_saved;
723 cat->cur_file = cur_file_saved;
725 if (cat->cur_file != cur_file_saved) {
726 avformat_close_input(&cur_avf_saved);
733 #define OFFSET(x) offsetof(ConcatContext, x)
734 #define DEC AV_OPT_FLAG_DECODING_PARAM
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 },
746 static const AVClass concat_class = {
747 .class_name = "concat demuxer",
748 .item_name = av_default_item_name,
750 .version = LIBAVUTIL_VERSION_INT,
754 AVInputFormat ff_concat_demuxer = {
756 .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
757 .priv_data_size = sizeof(ConcatContext),
758 .read_probe = concat_probe,
759 .read_header = concat_read_header,
760 .read_packet = concat_read_packet,
761 .read_close = concat_read_close,
762 .read_seek2 = concat_seek,
763 .priv_class = &concat_class,