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/avstring.h"
22 #include "libavutil/opt.h"
23 #include "libavutil/parseutils.h"
28 typedef struct ConcatStream {
36 ConcatStream *streams;
51 static int concat_probe(AVProbeData *probe)
53 return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
54 0 : AVPROBE_SCORE_MAX;
57 static char *get_keyword(uint8_t **cursor)
59 char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
60 *cursor += strcspn(*cursor, SPACE_CHARS);
63 *cursor += strspn(*cursor, SPACE_CHARS);
68 static int safe_filename(const char *f)
70 const char *start = f;
74 if (!((unsigned)((*f | 32) - 'a') < 26 ||
75 (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
87 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
89 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
90 unsigned *nb_files_alloc)
92 ConcatContext *cat = avf->priv_data;
96 size_t url_len, proto_len;
99 if (cat->safe > 0 && !safe_filename(filename)) {
100 av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
101 FAIL(AVERROR(EPERM));
104 proto = avio_find_protocol_name(filename);
105 proto_len = proto ? strlen(proto) : 0;
106 if (!memcmp(filename, proto, proto_len) &&
107 (filename[proto_len] == ':' || filename[proto_len] == ',')) {
111 url_len = strlen(avf->filename) + strlen(filename) + 16;
112 if (!(url = av_malloc(url_len)))
113 FAIL(AVERROR(ENOMEM));
114 ff_make_absolute_url(url, url_len, avf->filename, filename);
118 if (cat->nb_files >= *nb_files_alloc) {
119 size_t n = FFMAX(*nb_files_alloc * 2, 16);
120 ConcatFile *new_files;
121 if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
122 !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
123 FAIL(AVERROR(ENOMEM));
124 cat->files = new_files;
128 file = &cat->files[cat->nb_files++];
129 memset(file, 0, sizeof(*file));
133 file->start_time = AV_NOPTS_VALUE;
134 file->duration = AV_NOPTS_VALUE;
144 static int copy_stream_props(AVStream *st, AVStream *source_st)
148 if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
150 st->r_frame_rate = source_st->r_frame_rate;
151 st->avg_frame_rate = source_st->avg_frame_rate;
152 st->time_base = source_st->time_base;
153 st->sample_aspect_ratio = source_st->sample_aspect_ratio;
157 static int match_streams(AVFormatContext *avf)
159 ConcatContext *cat = avf->priv_data;
164 if (!cat->match_streams ||
165 cat->cur_file->nb_streams >= cat->avf->nb_streams)
167 map = av_realloc(cat->cur_file->streams,
168 cat->avf->nb_streams * sizeof(*map));
170 return AVERROR(ENOMEM);
171 cat->cur_file->streams = map;
173 for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
174 st = cat->avf->streams[i];
175 map[i].out_stream_index = -1;
176 for (j = 0; j < avf->nb_streams; j++) {
177 if (avf->streams[j]->id == st->id) {
178 av_log(avf, AV_LOG_VERBOSE,
179 "Match slave stream #%d with stream #%d id 0x%x\n",
181 map[i].out_stream_index = j;
182 if (!avf->streams[j]->codec->codec_id && st->codec->codec_id)
183 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
189 cat->cur_file->nb_streams = cat->avf->nb_streams;
193 static int open_file(AVFormatContext *avf, unsigned fileno)
195 ConcatContext *cat = avf->priv_data;
196 ConcatFile *file = &cat->files[fileno];
200 avformat_close_input(&cat->avf);
202 cat->avf = avformat_alloc_context();
204 return AVERROR(ENOMEM);
206 cat->avf->interrupt_callback = avf->interrupt_callback;
207 if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
208 (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
209 av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
210 avformat_close_input(&cat->avf);
213 cat->cur_file = file;
214 if (file->start_time == AV_NOPTS_VALUE)
215 file->start_time = !fileno ? 0 :
216 cat->files[fileno - 1].start_time +
217 cat->files[fileno - 1].duration;
218 if ((ret = match_streams(avf)) < 0)
223 static int concat_read_close(AVFormatContext *avf)
225 ConcatContext *cat = avf->priv_data;
229 avformat_close_input(&cat->avf);
230 for (i = 0; i < cat->nb_files; i++)
231 av_freep(&cat->files[i].url);
232 av_freep(&cat->files);
236 static int concat_read_header(AVFormatContext *avf)
238 ConcatContext *cat = avf->priv_data;
240 uint8_t *cursor, *keyword;
241 int ret, line = 0, i;
242 unsigned nb_files_alloc = 0;
243 ConcatFile *file = NULL;
248 if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
252 keyword = get_keyword(&cursor);
253 if (!*keyword || *keyword == '#')
256 if (!strcmp(keyword, "file")) {
257 char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
259 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
260 FAIL(AVERROR_INVALIDDATA);
262 if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
264 } else if (!strcmp(keyword, "duration")) {
265 char *dur_str = get_keyword(&cursor);
268 av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
270 FAIL(AVERROR_INVALIDDATA);
272 if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
273 av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
277 file->duration = dur;
278 } else if (!strcmp(keyword, "stream")) {
279 if (!avformat_new_stream(avf, NULL))
280 FAIL(AVERROR(ENOMEM));
281 } else if (!strcmp(keyword, "exact_stream_id")) {
282 if (!avf->nb_streams) {
283 av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
285 FAIL(AVERROR_INVALIDDATA);
287 avf->streams[avf->nb_streams - 1]->id =
288 strtol(get_keyword(&cursor), NULL, 0);
289 } else if (!strcmp(keyword, "ffconcat")) {
290 char *ver_kw = get_keyword(&cursor);
291 char *ver_val = get_keyword(&cursor);
292 if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
293 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
294 FAIL(AVERROR_INVALIDDATA);
299 av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
301 FAIL(AVERROR_INVALIDDATA);
307 FAIL(AVERROR_INVALIDDATA);
309 for (i = 0; i < cat->nb_files; i++) {
310 if (cat->files[i].start_time == AV_NOPTS_VALUE)
311 cat->files[i].start_time = time;
313 time = cat->files[i].start_time;
314 if (cat->files[i].duration == AV_NOPTS_VALUE)
316 time += cat->files[i].duration;
318 if (i == cat->nb_files) {
319 avf->duration = time;
323 cat->match_streams = !!avf->nb_streams;
324 if ((ret = open_file(avf, 0)) < 0)
326 if (!cat->match_streams) {
327 for (i = 0; i < cat->avf->nb_streams; i++) {
328 if (!(st = avformat_new_stream(avf, NULL)))
329 FAIL(AVERROR(ENOMEM));
330 if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
338 concat_read_close(avf);
342 static int open_next_file(AVFormatContext *avf)
344 ConcatContext *cat = avf->priv_data;
345 unsigned fileno = cat->cur_file - cat->files;
347 if (cat->cur_file->duration == AV_NOPTS_VALUE)
348 cat->cur_file->duration = cat->avf->duration;
350 if (++fileno >= cat->nb_files)
352 return open_file(avf, fileno);
355 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
357 ConcatContext *cat = avf->priv_data;
363 ret = av_read_frame(cat->avf, pkt);
364 if (ret == AVERROR_EOF) {
365 if ((ret = open_next_file(avf)) < 0)
371 if (cat->match_streams) {
372 if ((ret = match_streams(avf)) < 0) {
373 av_packet_unref(pkt);
376 cs = &cat->cur_file->streams[pkt->stream_index];
377 if (cs->out_stream_index < 0) {
378 av_packet_unref(pkt);
381 pkt->stream_index = cs->out_stream_index;
386 delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
388 cat->avf->streams[pkt->stream_index]->time_base);
389 if (pkt->pts != AV_NOPTS_VALUE)
391 if (pkt->dts != AV_NOPTS_VALUE)
396 static void rescale_interval(AVRational tb_in, AVRational tb_out,
397 int64_t *min_ts, int64_t *ts, int64_t *max_ts)
399 *ts = av_rescale_q (* ts, tb_in, tb_out);
400 *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
401 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
402 *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
403 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
406 static int try_seek(AVFormatContext *avf, int stream,
407 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
409 ConcatContext *cat = avf->priv_data;
410 int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
413 min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
414 max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
416 if (stream >= cat->avf->nb_streams)
418 rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
419 &min_ts, &ts, &max_ts);
421 return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
424 static int real_seek(AVFormatContext *avf, int stream,
425 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
427 ConcatContext *cat = avf->priv_data;
428 int ret, left, right;
431 if (stream >= avf->nb_streams)
432 return AVERROR(EINVAL);
433 rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
434 &min_ts, &ts, &max_ts);
438 right = cat->nb_files;
439 while (right - left > 1) {
440 int mid = (left + right) / 2;
441 if (ts < cat->files[mid].start_time)
447 if ((ret = open_file(avf, left)) < 0)
450 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
452 left < cat->nb_files - 1 &&
453 cat->files[left + 1].start_time < max_ts) {
454 if ((ret = open_file(avf, left + 1)) < 0)
456 ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
461 static int concat_seek(AVFormatContext *avf, int stream,
462 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
464 ConcatContext *cat = avf->priv_data;
465 ConcatFile *cur_file_saved = cat->cur_file;
466 AVFormatContext *cur_avf_saved = cat->avf;
470 return AVERROR(ESPIPE); /* XXX: can we use it? */
471 if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
472 return AVERROR(ENOSYS);
474 if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
476 avformat_close_input(&cat->avf);
477 cat->avf = cur_avf_saved;
478 cat->cur_file = cur_file_saved;
480 avformat_close_input(&cur_avf_saved);
485 #define OFFSET(x) offsetof(ConcatContext, x)
486 #define DEC AV_OPT_FLAG_DECODING_PARAM
488 static const AVOption options[] = {
489 { "safe", "enable safe mode",
490 OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
494 static const AVClass concat_class = {
495 .class_name = "concat demuxer",
496 .item_name = av_default_item_name,
498 .version = LIBAVUTIL_VERSION_INT,
502 AVInputFormat ff_concat_demuxer = {
504 .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
505 .priv_data_size = sizeof(ConcatContext),
506 .read_probe = concat_probe,
507 .read_header = concat_read_header,
508 .read_packet = concat_read_packet,
509 .read_close = concat_read_close,
510 .read_seek2 = concat_seek,
511 .priv_class = &concat_class,