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