]> git.sesse.net Git - ffmpeg/blob - libavformat/concatdec.c
Merge commit '1c79b1625d4d257bfd01eccb84cc0ab355fb9a9e'
[ffmpeg] / libavformat / concatdec.c
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/avstring.h"
22 #include "libavutil/opt.h"
23 #include "libavutil/parseutils.h"
24 #include "avformat.h"
25 #include "internal.h"
26 #include "url.h"
27
28 typedef struct {
29     char *url;
30     int64_t start_time;
31     int64_t duration;
32 } ConcatFile;
33
34 typedef struct {
35     AVClass *class;
36     ConcatFile *files;
37     ConcatFile *cur_file;
38     unsigned nb_files;
39     AVFormatContext *avf;
40     int safe;
41     int seekable;
42 } ConcatContext;
43
44 static int concat_probe(AVProbeData *probe)
45 {
46     return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
47            0 : AVPROBE_SCORE_MAX;
48 }
49
50 static char *get_keyword(uint8_t **cursor)
51 {
52     char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
53     *cursor += strcspn(*cursor, SPACE_CHARS);
54     if (**cursor) {
55         *((*cursor)++) = 0;
56         *cursor += strspn(*cursor, SPACE_CHARS);
57     }
58     return ret;
59 }
60
61 static int safe_filename(const char *f)
62 {
63     const char *start = f;
64
65     for (; *f; f++) {
66         /* A-Za-z0-9_- */
67         if (!((unsigned)((*f | 32) - 'a') < 26 ||
68               (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
69             if (f == start)
70                 return 0;
71             else if (*f == '/')
72                 start = f + 1;
73             else if (*f != '.')
74                 return 0;
75         }
76     }
77     return 1;
78 }
79
80 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
81
82 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
83                     unsigned *nb_files_alloc)
84 {
85     ConcatContext *cat = avf->priv_data;
86     ConcatFile *file;
87     char *url = NULL;
88     const char *proto;
89     size_t url_len, proto_len;
90     int ret;
91
92     if (cat->safe > 0 && !safe_filename(filename)) {
93         av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
94         FAIL(AVERROR(EPERM));
95     }
96
97     proto = avio_find_protocol_name(filename);
98     proto_len = proto ? strlen(proto) : 0;
99     if (!memcmp(filename, proto, proto_len) &&
100         (filename[proto_len] == ':' || filename[proto_len] == ',')) {
101         url = filename;
102         filename = NULL;
103     } else {
104         url_len = strlen(avf->filename) + strlen(filename) + 16;
105         if (!(url = av_malloc(url_len)))
106             FAIL(AVERROR(ENOMEM));
107         ff_make_absolute_url(url, url_len, avf->filename, filename);
108         av_freep(&filename);
109     }
110
111     if (cat->nb_files >= *nb_files_alloc) {
112         size_t n = FFMAX(*nb_files_alloc * 2, 16);
113         ConcatFile *new_files;
114         if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
115             !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
116             FAIL(AVERROR(ENOMEM));
117         cat->files = new_files;
118         *nb_files_alloc = n;
119     }
120
121     file = &cat->files[cat->nb_files++];
122     memset(file, 0, sizeof(*file));
123     *rfile = file;
124
125     file->url        = url;
126     file->start_time = AV_NOPTS_VALUE;
127     file->duration   = AV_NOPTS_VALUE;
128
129     return 0;
130
131 fail:
132     av_free(url);
133     av_free(filename);
134     return ret;
135 }
136
137 static int open_file(AVFormatContext *avf, unsigned fileno)
138 {
139     ConcatContext *cat = avf->priv_data;
140     ConcatFile *file = &cat->files[fileno];
141     int ret;
142
143     if (cat->avf)
144         avformat_close_input(&cat->avf);
145
146     cat->avf = avformat_alloc_context();
147     if (!cat->avf)
148         return AVERROR(ENOMEM);
149
150     cat->avf->interrupt_callback = avf->interrupt_callback;
151     if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
152         (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
153         av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
154         avformat_close_input(&cat->avf);
155         return ret;
156     }
157     cat->cur_file = file;
158     if (file->start_time == AV_NOPTS_VALUE)
159         file->start_time = !fileno ? 0 :
160                            cat->files[fileno - 1].start_time +
161                            cat->files[fileno - 1].duration;
162     return 0;
163 }
164
165 static int concat_read_close(AVFormatContext *avf)
166 {
167     ConcatContext *cat = avf->priv_data;
168     unsigned i;
169
170     if (cat->avf)
171         avformat_close_input(&cat->avf);
172     for (i = 0; i < cat->nb_files; i++)
173         av_freep(&cat->files[i].url);
174     av_freep(&cat->files);
175     return 0;
176 }
177
178 static int concat_read_header(AVFormatContext *avf)
179 {
180     ConcatContext *cat = avf->priv_data;
181     uint8_t buf[4096];
182     uint8_t *cursor, *keyword;
183     int ret, line = 0, i;
184     unsigned nb_files_alloc = 0;
185     ConcatFile *file = NULL;
186     AVStream *st, *source_st;
187     int64_t time = 0;
188
189     while (1) {
190         if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
191             break;
192         line++;
193         cursor = buf;
194         keyword = get_keyword(&cursor);
195         if (!*keyword || *keyword == '#')
196             continue;
197
198         if (!strcmp(keyword, "file")) {
199             char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
200             if (!filename) {
201                 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
202                 FAIL(AVERROR_INVALIDDATA);
203             }
204             if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
205                 FAIL(ret);
206         } else if (!strcmp(keyword, "duration")) {
207             char *dur_str = get_keyword(&cursor);
208             int64_t dur;
209             if (!file) {
210                 av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
211                        line);
212                 FAIL(AVERROR_INVALIDDATA);
213             }
214             if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
215                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
216                        line, dur_str);
217                 FAIL(ret);
218             }
219             file->duration = dur;
220         } else if (!strcmp(keyword, "ffconcat")) {
221             char *ver_kw  = get_keyword(&cursor);
222             char *ver_val = get_keyword(&cursor);
223             if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
224                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
225                 FAIL(AVERROR_INVALIDDATA);
226             }
227             if (cat->safe < 0)
228                 cat->safe = 1;
229         } else {
230             av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
231                    line, keyword);
232             FAIL(AVERROR_INVALIDDATA);
233         }
234     }
235     if (ret < 0)
236         FAIL(ret);
237     if (!cat->nb_files)
238         FAIL(AVERROR_INVALIDDATA);
239
240     for (i = 0; i < cat->nb_files; i++) {
241         if (cat->files[i].start_time == AV_NOPTS_VALUE)
242             cat->files[i].start_time = time;
243         else
244             time = cat->files[i].start_time;
245         if (cat->files[i].duration == AV_NOPTS_VALUE)
246             break;
247         time += cat->files[i].duration;
248     }
249     if (i == cat->nb_files) {
250         avf->duration = time;
251         cat->seekable = 1;
252     }
253
254     if ((ret = open_file(avf, 0)) < 0)
255         FAIL(ret);
256     for (i = 0; i < cat->avf->nb_streams; i++) {
257         if (!(st = avformat_new_stream(avf, NULL)))
258             FAIL(AVERROR(ENOMEM));
259         source_st = cat->avf->streams[i];
260         if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
261             FAIL(ret);
262         st->r_frame_rate        = source_st->r_frame_rate;
263         st->avg_frame_rate      = source_st->avg_frame_rate;
264         st->time_base           = source_st->time_base;
265         st->sample_aspect_ratio = source_st->sample_aspect_ratio;
266     }
267
268     return 0;
269
270 fail:
271     concat_read_close(avf);
272     return ret;
273 }
274
275 static int open_next_file(AVFormatContext *avf)
276 {
277     ConcatContext *cat = avf->priv_data;
278     unsigned fileno = cat->cur_file - cat->files;
279
280     if (cat->cur_file->duration == AV_NOPTS_VALUE)
281         cat->cur_file->duration = cat->avf->duration;
282
283     if (++fileno >= cat->nb_files)
284         return AVERROR_EOF;
285     return open_file(avf, fileno);
286 }
287
288 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
289 {
290     ConcatContext *cat = avf->priv_data;
291     int ret;
292     int64_t delta;
293
294     while (1) {
295         if ((ret = av_read_frame(cat->avf, pkt)) != AVERROR_EOF ||
296             (ret = open_next_file(avf)) < 0)
297             break;
298     }
299     if (ret < 0)
300         return ret;
301
302     delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
303                          AV_TIME_BASE_Q,
304                          cat->avf->streams[pkt->stream_index]->time_base);
305     if (pkt->pts != AV_NOPTS_VALUE)
306         pkt->pts += delta;
307     if (pkt->dts != AV_NOPTS_VALUE)
308         pkt->dts += delta;
309     return ret;
310 }
311
312 static void rescale_interval(AVRational tb_in, AVRational tb_out,
313                              int64_t *min_ts, int64_t *ts, int64_t *max_ts)
314 {
315     *ts     = av_rescale_q    (*    ts, tb_in, tb_out);
316     *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
317                                AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
318     *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
319                                AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
320 }
321
322 static int try_seek(AVFormatContext *avf, int stream,
323                     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
324 {
325     ConcatContext *cat = avf->priv_data;
326     int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
327
328     ts -= t0;
329     min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
330     max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
331     if (stream >= 0) {
332         if (stream >= cat->avf->nb_streams)
333             return AVERROR(EIO);
334         rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
335                          &min_ts, &ts, &max_ts);
336     }
337     return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
338 }
339
340 static int real_seek(AVFormatContext *avf, int stream,
341                      int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
342 {
343     ConcatContext *cat = avf->priv_data;
344     int ret, left, right;
345
346     if (stream >= 0) {
347         if (stream >= avf->nb_streams)
348             return AVERROR(EINVAL);
349         rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
350                          &min_ts, &ts, &max_ts);
351     }
352
353     left  = 0;
354     right = cat->nb_files;
355     while (right - left > 1) {
356         int mid = (left + right) / 2;
357         if (ts < cat->files[mid].start_time)
358             right = mid;
359         else
360             left  = mid;
361     }
362
363     if ((ret = open_file(avf, left)) < 0)
364         return ret;
365
366     ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
367     if (ret < 0 &&
368         left < cat->nb_files - 1 &&
369         cat->files[left + 1].start_time < max_ts) {
370         if ((ret = open_file(avf, left + 1)) < 0)
371             return ret;
372         ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
373     }
374     return ret;
375 }
376
377 static int concat_seek(AVFormatContext *avf, int stream,
378                        int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
379 {
380     ConcatContext *cat = avf->priv_data;
381     ConcatFile *cur_file_saved = cat->cur_file;
382     AVFormatContext *cur_avf_saved = cat->avf;
383     int ret;
384
385     if (!cat->seekable)
386         return AVERROR(ESPIPE); /* XXX: can we use it? */
387     if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
388         return AVERROR(ENOSYS);
389     cat->avf = NULL;
390     if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
391         if (cat->avf)
392             avformat_close_input(&cat->avf);
393         cat->avf      = cur_avf_saved;
394         cat->cur_file = cur_file_saved;
395     } else {
396         avformat_close_input(&cur_avf_saved);
397     }
398     return ret;
399 }
400
401 #define OFFSET(x) offsetof(ConcatContext, x)
402 #define DEC AV_OPT_FLAG_DECODING_PARAM
403
404 static const AVOption options[] = {
405     { "safe", "enable safe mode",
406       OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
407     { NULL }
408 };
409
410 static const AVClass concat_class = {
411     .class_name = "concat demuxer",
412     .item_name  = av_default_item_name,
413     .option     = options,
414     .version    = LIBAVUTIL_VERSION_INT,
415 };
416
417
418 AVInputFormat ff_concat_demuxer = {
419     .name           = "concat",
420     .long_name      = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
421     .priv_data_size = sizeof(ConcatContext),
422     .read_probe     = concat_probe,
423     .read_header    = concat_read_header,
424     .read_packet    = concat_read_packet,
425     .read_close     = concat_read_close,
426     .read_seek2     = concat_seek,
427     .priv_class     = &concat_class,
428 };