]> git.sesse.net Git - ffmpeg/blob - libavformat/concatdec.c
Merge commit 'e2c272eb3660d7f4f1d7720980e30f6a617e7eb3'
[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
27 typedef struct {
28     char *url;
29     int64_t start_time;
30     int64_t duration;
31 } ConcatFile;
32
33 typedef struct {
34     AVClass *class;
35     ConcatFile *files;
36     ConcatFile *cur_file;
37     unsigned nb_files;
38     AVFormatContext *avf;
39     int safe;
40 } ConcatContext;
41
42 static int concat_probe(AVProbeData *probe)
43 {
44     return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
45            0 : AVPROBE_SCORE_MAX;
46 }
47
48 static char *get_keyword(uint8_t **cursor)
49 {
50     char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
51     *cursor += strcspn(*cursor, SPACE_CHARS);
52     if (**cursor) {
53         *((*cursor)++) = 0;
54         *cursor += strspn(*cursor, SPACE_CHARS);
55     }
56     return ret;
57 }
58
59 static int safe_filename(const char *f)
60 {
61     const char *start = f;
62
63     for (; *f; f++) {
64         /* A-Za-z0-9_- */
65         if (!((unsigned)((*f | 32) - 'a') < 26 ||
66               (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
67             if (f == start)
68                 return 0;
69             else if (*f == '/')
70                 start = f + 1;
71             else if (*f != '.')
72                 return 0;
73         }
74     }
75     return 1;
76 }
77
78 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
79
80 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
81                     unsigned *nb_files_alloc)
82 {
83     ConcatContext *cat = avf->priv_data;
84     ConcatFile *file;
85     char *url;
86     size_t url_len;
87
88     if (cat->safe > 0 && !safe_filename(filename)) {
89         av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
90         return AVERROR(EPERM);
91     }
92     url_len = strlen(avf->filename) + strlen(filename) + 16;
93     if (!(url = av_malloc(url_len)))
94         return AVERROR(ENOMEM);
95     ff_make_absolute_url(url, url_len, avf->filename, filename);
96     av_free(filename);
97
98     if (cat->nb_files >= *nb_files_alloc) {
99         size_t n = FFMAX(*nb_files_alloc * 2, 16);
100         ConcatFile *new_files;
101         if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
102             !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
103             return AVERROR(ENOMEM);
104         cat->files = new_files;
105         *nb_files_alloc = n;
106     }
107
108     file = &cat->files[cat->nb_files++];
109     memset(file, 0, sizeof(*file));
110     *rfile = file;
111
112     file->url        = url;
113     file->start_time = AV_NOPTS_VALUE;
114     file->duration   = AV_NOPTS_VALUE;
115
116     return 0;
117 }
118
119 static int open_file(AVFormatContext *avf, unsigned fileno)
120 {
121     ConcatContext *cat = avf->priv_data;
122     ConcatFile *file = &cat->files[fileno];
123     int ret;
124
125     if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
126         (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
127         av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
128         return ret;
129     }
130     cat->cur_file = file;
131     if (file->start_time == AV_NOPTS_VALUE)
132         file->start_time = !fileno ? 0 :
133                            cat->files[fileno - 1].start_time +
134                            cat->files[fileno - 1].duration;
135     return 0;
136 }
137
138 static int concat_read_close(AVFormatContext *avf)
139 {
140     ConcatContext *cat = avf->priv_data;
141     unsigned i;
142
143     if (cat->avf)
144         avformat_close_input(&cat->avf);
145     for (i = 0; i < cat->nb_files; i++)
146         av_freep(&cat->files[i].url);
147     av_freep(&cat->files);
148     return 0;
149 }
150
151 static int concat_read_header(AVFormatContext *avf)
152 {
153     ConcatContext *cat = avf->priv_data;
154     uint8_t buf[4096];
155     uint8_t *cursor, *keyword;
156     int ret, line = 0, i;
157     unsigned nb_files_alloc = 0;
158     ConcatFile *file = NULL;
159     AVStream *st, *source_st;
160
161     while (1) {
162         if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
163             break;
164         line++;
165         cursor = buf;
166         keyword = get_keyword(&cursor);
167         if (!*keyword || *keyword == '#')
168             continue;
169
170         if (!strcmp(keyword, "file")) {
171             char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
172             if (!filename) {
173                 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
174                 FAIL(AVERROR_INVALIDDATA);
175             }
176             if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
177                 FAIL(ret);
178         } else if (!strcmp(keyword, "duration")) {
179             char *dur_str = get_keyword(&cursor);
180             int64_t dur;
181             if (!file) {
182                 av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
183                        line);
184                 FAIL(AVERROR_INVALIDDATA);
185             }
186             if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
187                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
188                        line, dur_str);
189                 FAIL(ret);
190             }
191             file->duration = dur;
192         } else if (!strcmp(keyword, "ffconcat")) {
193             char *ver_kw  = get_keyword(&cursor);
194             char *ver_val = get_keyword(&cursor);
195             if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
196                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
197                 FAIL(AVERROR_INVALIDDATA);
198             }
199             if (cat->safe < 0)
200                 cat->safe = 1;
201         } else {
202             av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
203                    line, keyword);
204             FAIL(AVERROR_INVALIDDATA);
205         }
206     }
207     if (ret < 0)
208         FAIL(ret);
209
210     if ((ret = open_file(avf, 0)) < 0)
211         FAIL(ret);
212     for (i = 0; i < cat->avf->nb_streams; i++) {
213         if (!(st = avformat_new_stream(avf, NULL)))
214             FAIL(AVERROR(ENOMEM));
215         source_st = cat->avf->streams[i];
216         if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
217             FAIL(ret);
218         st->r_frame_rate        = source_st->r_frame_rate;
219         st->avg_frame_rate      = source_st->avg_frame_rate;
220         st->time_base           = source_st->time_base;
221         st->sample_aspect_ratio = source_st->sample_aspect_ratio;
222     }
223
224     return 0;
225
226 fail:
227     concat_read_close(avf);
228     return ret;
229 }
230
231 static int open_next_file(AVFormatContext *avf)
232 {
233     ConcatContext *cat = avf->priv_data;
234     unsigned fileno = cat->cur_file - cat->files;
235
236     if (cat->cur_file->duration == AV_NOPTS_VALUE)
237         cat->cur_file->duration = cat->avf->duration;
238
239     if (++fileno >= cat->nb_files)
240         return AVERROR_EOF;
241     avformat_close_input(&cat->avf);
242     return open_file(avf, fileno);
243 }
244
245 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
246 {
247     ConcatContext *cat = avf->priv_data;
248     int ret;
249     int64_t delta;
250
251     while (1) {
252         if ((ret = av_read_frame(cat->avf, pkt)) != AVERROR_EOF ||
253             (ret = open_next_file(avf)) < 0)
254             break;
255     }
256     delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
257                          AV_TIME_BASE_Q,
258                          cat->avf->streams[pkt->stream_index]->time_base);
259     if (pkt->pts != AV_NOPTS_VALUE)
260         pkt->pts += delta;
261     if (pkt->dts != AV_NOPTS_VALUE)
262         pkt->dts += delta;
263     return ret;
264 }
265
266 #define OFFSET(x) offsetof(ConcatContext, x)
267 #define DEC AV_OPT_FLAG_DECODING_PARAM
268
269 static const AVOption options[] = {
270     { "safe", "enable safe mode",
271       OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
272     { NULL }
273 };
274
275 static const AVClass concat_class = {
276     .class_name = "concat demuxer",
277     .item_name  = av_default_item_name,
278     .option     = options,
279     .version    = LIBAVUTIL_VERSION_INT,
280 };
281
282
283 AVInputFormat ff_concat_demuxer = {
284     .name           = "concat",
285     .long_name      = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
286     .priv_data_size = sizeof(ConcatContext),
287     .read_probe     = concat_probe,
288     .read_header    = concat_read_header,
289     .read_packet    = concat_read_packet,
290     .read_close     = concat_read_close,
291     .priv_class     = &concat_class,
292     .extensions     = "ffconcat,ffcat",
293 };