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