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 {
37 AVBitStreamFilterContext *bsf;
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->codec->codec_id || !source_st->codec->codec_id) {
168 if (st->codec->extradata_size < source_st->codec->extradata_size) {
169 ret = ff_alloc_extradata(st->codec,
170 source_st->codec->extradata_size);
174 memcpy(st->codec->extradata, source_st->codec->extradata,
175 source_st->codec->extradata_size);
178 if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
180 st->r_frame_rate = source_st->r_frame_rate;
181 st->avg_frame_rate = source_st->avg_frame_rate;
182 st->time_base = source_st->time_base;
183 st->sample_aspect_ratio = source_st->sample_aspect_ratio;
185 av_dict_copy(&st->metadata, source_st->metadata, 0);
189 static int detect_stream_specific(AVFormatContext *avf, int idx)
191 ConcatContext *cat = avf->priv_data;
192 AVStream *st = cat->avf->streams[idx];
193 ConcatStream *cs = &cat->cur_file->streams[idx];
194 AVBitStreamFilterContext *bsf;
196 if (cat->auto_convert && st->codec->codec_id == AV_CODEC_ID_H264 &&
197 (st->codec->extradata_size < 4 || AV_RB32(st->codec->extradata) != 1)) {
198 av_log(cat->avf, AV_LOG_INFO,
199 "Auto-inserting h264_mp4toannexb bitstream filter\n");
200 if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) {
201 av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
202 "required for H.264 streams\n");
203 return AVERROR_BSF_NOT_FOUND;
210 static int match_streams_one_to_one(AVFormatContext *avf)
212 ConcatContext *cat = avf->priv_data;
216 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
217 if (i < avf->nb_streams) {
218 st = avf->streams[i];
220 if (!(st = avformat_new_stream(avf, NULL)))
221 return AVERROR(ENOMEM);
223 if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
225 cat->cur_file->streams[i].out_stream_index = i;
230 static int match_streams_exact_id(AVFormatContext *avf)
232 ConcatContext *cat = avf->priv_data;
236 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
237 st = cat->avf->streams[i];
238 for (j = 0; j < avf->nb_streams; j++) {
239 if (avf->streams[j]->id == st->id) {
240 av_log(avf, AV_LOG_VERBOSE,
241 "Match slave stream #%d with stream #%d id 0x%x\n",
243 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
245 cat->cur_file->streams[i].out_stream_index = j;
252 static int match_streams(AVFormatContext *avf)
254 ConcatContext *cat = avf->priv_data;
258 if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
260 map = av_realloc(cat->cur_file->streams,
261 cat->avf->nb_streams * sizeof(*map));
263 return AVERROR(ENOMEM);
264 cat->cur_file->streams = map;
265 memset(map + cat->cur_file->nb_streams, 0,
266 (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
268 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
269 map[i].out_stream_index = -1;
270 switch (cat->stream_match_mode) {
271 case MATCH_ONE_TO_ONE:
272 ret = match_streams_one_to_one(avf);
275 ret = match_streams_exact_id(avf);
282 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
283 if ((ret = detect_stream_specific(avf, i)) < 0)
285 cat->cur_file->nb_streams = cat->avf->nb_streams;
289 static int open_file(AVFormatContext *avf, unsigned fileno)
291 ConcatContext *cat = avf->priv_data;
292 ConcatFile *file = &cat->files[fileno];
296 avformat_close_input(&cat->avf);
298 cat->avf = avformat_alloc_context();
300 return AVERROR(ENOMEM);
302 cat->avf->interrupt_callback = avf->interrupt_callback;
304 if ((ret = ff_copy_whitelists(cat->avf, avf)) < 0)
307 if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
308 (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
309 av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
310 avformat_close_input(&cat->avf);
313 cat->cur_file = file;
314 if (file->start_time == AV_NOPTS_VALUE)
315 file->start_time = !fileno ? 0 :
316 cat->files[fileno - 1].start_time +
317 cat->files[fileno - 1].duration;
318 file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
319 file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
320 if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
321 file->duration = file->outpoint - file->file_inpoint;
323 if (cat->segment_time_metadata) {
324 av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
325 if (file->duration != AV_NOPTS_VALUE)
326 av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
329 if ((ret = match_streams(avf)) < 0)
331 if (file->inpoint != AV_NOPTS_VALUE) {
332 if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
338 static int concat_read_close(AVFormatContext *avf)
340 ConcatContext *cat = avf->priv_data;
344 avformat_close_input(&cat->avf);
345 for (i = 0; i < cat->nb_files; i++) {
346 av_freep(&cat->files[i].url);
347 av_freep(&cat->files[i].streams);
348 av_dict_free(&cat->files[i].metadata);
350 av_freep(&cat->files);
354 static int concat_read_header(AVFormatContext *avf)
356 ConcatContext *cat = avf->priv_data;
358 uint8_t *cursor, *keyword;
359 int ret, line = 0, i;
360 unsigned nb_files_alloc = 0;
361 ConcatFile *file = NULL;
365 if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
369 keyword = get_keyword(&cursor);
370 if (!*keyword || *keyword == '#')
373 if (!strcmp(keyword, "file")) {
374 char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
376 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
377 FAIL(AVERROR_INVALIDDATA);
379 if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
381 } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
382 char *dur_str = get_keyword(&cursor);
385 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
387 FAIL(AVERROR_INVALIDDATA);
389 if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
390 av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
391 line, keyword, dur_str);
394 if (!strcmp(keyword, "duration"))
395 file->duration = dur;
396 else if (!strcmp(keyword, "inpoint"))
398 else if (!strcmp(keyword, "outpoint"))
399 file->outpoint = dur;
400 } else if (!strcmp(keyword, "file_packet_metadata")) {
403 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
405 FAIL(AVERROR_INVALIDDATA);
407 metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
409 av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
410 FAIL(AVERROR_INVALIDDATA);
412 if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
413 av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
415 FAIL(AVERROR_INVALIDDATA);
418 } else if (!strcmp(keyword, "stream")) {
419 if (!avformat_new_stream(avf, NULL))
420 FAIL(AVERROR(ENOMEM));
421 } else if (!strcmp(keyword, "exact_stream_id")) {
422 if (!avf->nb_streams) {
423 av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
425 FAIL(AVERROR_INVALIDDATA);
427 avf->streams[avf->nb_streams - 1]->id =
428 strtol(get_keyword(&cursor), NULL, 0);
429 } else if (!strcmp(keyword, "ffconcat")) {
430 char *ver_kw = get_keyword(&cursor);
431 char *ver_val = get_keyword(&cursor);
432 if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
433 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
434 FAIL(AVERROR_INVALIDDATA);
439 av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
441 FAIL(AVERROR_INVALIDDATA);
447 FAIL(AVERROR_INVALIDDATA);
449 for (i = 0; i < cat->nb_files; i++) {
450 if (cat->files[i].start_time == AV_NOPTS_VALUE)
451 cat->files[i].start_time = time;
453 time = cat->files[i].start_time;
454 if (cat->files[i].duration == AV_NOPTS_VALUE) {
455 if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
457 cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
459 time += cat->files[i].duration;
461 if (i == cat->nb_files) {
462 avf->duration = time;
466 cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
468 if ((ret = open_file(avf, 0)) < 0)
473 concat_read_close(avf);
477 static int open_next_file(AVFormatContext *avf)
479 ConcatContext *cat = avf->priv_data;
480 unsigned fileno = cat->cur_file - cat->files;
482 if (cat->cur_file->duration == AV_NOPTS_VALUE)
483 cat->cur_file->duration = cat->avf->duration - (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
485 if (++fileno >= cat->nb_files) {
489 return open_file(avf, fileno);
492 static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
494 AVStream *st = avf->streams[cs->out_stream_index];
495 AVBitStreamFilterContext *bsf;
499 av_assert0(cs->out_stream_index >= 0);
500 for (bsf = cs->bsf; bsf; bsf = bsf->next) {
502 ret = av_bitstream_filter_filter(bsf, st->codec, NULL,
503 &pkt2.data, &pkt2.size,
504 pkt->data, pkt->size,
505 !!(pkt->flags & AV_PKT_FLAG_KEY));
507 av_packet_unref(pkt);
510 av_assert0(pkt2.buf);
511 if (ret == 0 && pkt2.data != pkt->data) {
512 if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
519 av_packet_unref(pkt);
520 pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
521 av_buffer_default_free, NULL, 0);
524 return AVERROR(ENOMEM);
532 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
533 static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
535 if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
536 return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
537 cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
542 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
544 ConcatContext *cat = avf->priv_data;
557 ret = av_read_frame(cat->avf, pkt);
558 if (ret == AVERROR_EOF) {
559 if ((ret = open_next_file(avf)) < 0)
565 if ((ret = match_streams(avf)) < 0) {
566 av_packet_unref(pkt);
569 if (packet_after_outpoint(cat, pkt)) {
570 av_packet_unref(pkt);
571 if ((ret = open_next_file(avf)) < 0)
575 cs = &cat->cur_file->streams[pkt->stream_index];
576 if (cs->out_stream_index < 0) {
577 av_packet_unref(pkt);
580 pkt->stream_index = cs->out_stream_index;
583 if ((ret = filter_packet(avf, cs, pkt)))
586 st = cat->avf->streams[pkt->stream_index];
587 av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
588 (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
589 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
590 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
592 delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
594 cat->avf->streams[pkt->stream_index]->time_base);
595 if (pkt->pts != AV_NOPTS_VALUE)
597 if (pkt->dts != AV_NOPTS_VALUE)
599 av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
600 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
601 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
602 if (cat->cur_file->metadata) {
605 char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
606 if (!packed_metadata)
607 return AVERROR(ENOMEM);
608 if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
609 av_freep(&packed_metadata);
610 return AVERROR(ENOMEM);
612 memcpy(metadata, packed_metadata, metadata_len);
613 av_freep(&packed_metadata);
618 static void rescale_interval(AVRational tb_in, AVRational tb_out,
619 int64_t *min_ts, int64_t *ts, int64_t *max_ts)
621 *ts = av_rescale_q (* ts, tb_in, tb_out);
622 *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
623 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
624 *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
625 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
628 static int try_seek(AVFormatContext *avf, int stream,
629 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
631 ConcatContext *cat = avf->priv_data;
632 int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
635 min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
636 max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
638 if (stream >= cat->avf->nb_streams)
640 rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
641 &min_ts, &ts, &max_ts);
643 return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
646 static int real_seek(AVFormatContext *avf, int stream,
647 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
649 ConcatContext *cat = avf->priv_data;
650 int ret, left, right;
653 if (stream >= avf->nb_streams)
654 return AVERROR(EINVAL);
655 rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
656 &min_ts, &ts, &max_ts);
660 right = cat->nb_files;
661 while (right - left > 1) {
662 int mid = (left + right) / 2;
663 if (ts < cat->files[mid].start_time)
669 if ((ret = open_file(avf, left)) < 0)
672 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
674 left < cat->nb_files - 1 &&
675 cat->files[left + 1].start_time < max_ts) {
676 if ((ret = open_file(avf, left + 1)) < 0)
678 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
683 static int concat_seek(AVFormatContext *avf, int stream,
684 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
686 ConcatContext *cat = avf->priv_data;
687 ConcatFile *cur_file_saved = cat->cur_file;
688 AVFormatContext *cur_avf_saved = cat->avf;
692 return AVERROR(ESPIPE); /* XXX: can we use it? */
693 if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
694 return AVERROR(ENOSYS);
696 if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
698 avformat_close_input(&cat->avf);
699 cat->avf = cur_avf_saved;
700 cat->cur_file = cur_file_saved;
702 avformat_close_input(&cur_avf_saved);
708 #define OFFSET(x) offsetof(ConcatContext, x)
709 #define DEC AV_OPT_FLAG_DECODING_PARAM
711 static const AVOption options[] = {
712 { "safe", "enable safe mode",
713 OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, DEC },
714 { "auto_convert", "automatically convert bitstream format",
715 OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
716 { "segment_time_metadata", "output file segment start time and duration as packet metadata",
717 OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
721 static const AVClass concat_class = {
722 .class_name = "concat demuxer",
723 .item_name = av_default_item_name,
725 .version = LIBAVUTIL_VERSION_INT,
729 AVInputFormat ff_concat_demuxer = {
731 .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
732 .priv_data_size = sizeof(ConcatContext),
733 .read_probe = concat_probe,
734 .read_header = concat_read_header,
735 .read_packet = concat_read_packet,
736 .read_close = concat_read_close,
737 .read_seek2 = concat_seek,
738 .priv_class = &concat_class,