]> git.sesse.net Git - ffmpeg/blob - libavformat/img2dec.c
lavf/img2dec: fix out-of-range check in find_image_range()
[ffmpeg] / libavformat / img2dec.c
1 /*
2  * Image format
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  * Copyright (c) 2004 Michael Niedermayer
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/avstring.h"
24 #include "libavutil/log.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/pixdesc.h"
27 #include "libavutil/parseutils.h"
28 #include "avformat.h"
29 #include "internal.h"
30 #if HAVE_GLOB
31 #include <glob.h>
32
33 /* Locally define as 0 (bitwise-OR no-op) any missing glob options that
34    are non-posix glibc/bsd extensions. */
35 #ifndef GLOB_NOMAGIC
36 #define GLOB_NOMAGIC 0
37 #endif
38 #ifndef GLOB_BRACE
39 #define GLOB_BRACE 0
40 #endif
41
42 #endif /* HAVE_GLOB */
43
44 typedef struct {
45     const AVClass *class;  /**< Class for private options. */
46     int img_first;
47     int img_last;
48     int img_number;
49     int img_count;
50     int is_pipe;
51     int split_planes;       /**< use independent file for each Y, U, V plane */
52     char path[1024];
53     char *pixel_format;     /**< Set by a private option. */
54     char *video_size;       /**< Set by a private option. */
55     char *framerate;        /**< Set by a private option. */
56     int loop;
57     int use_glob;
58 #if HAVE_GLOB
59     glob_t globstate;
60 #endif
61     int start_number;
62 } VideoDemuxData;
63
64 static const int sizes[][2] = {
65     { 640, 480 },
66     { 720, 480 },
67     { 720, 576 },
68     { 352, 288 },
69     { 352, 240 },
70     { 160, 128 },
71     { 512, 384 },
72     { 640, 352 },
73     { 640, 240 },
74 };
75
76 static int infer_size(int *width_ptr, int *height_ptr, int size)
77 {
78     int i;
79
80     for(i=0;i<FF_ARRAY_ELEMS(sizes);i++) {
81         if ((sizes[i][0] * sizes[i][1]) == size) {
82             *width_ptr = sizes[i][0];
83             *height_ptr = sizes[i][1];
84             return 0;
85         }
86     }
87     return -1;
88 }
89
90 static int is_glob(const char *path)
91 {
92 #if HAVE_GLOB
93     size_t span = 0;
94     const char *p = path;
95
96     while (p = strchr(p, '%')) {
97         if (*(++p) == '%') {
98             ++p;
99             continue;
100         }
101         if (span = strspn(p, "*?[]{}"))
102             break;
103     }
104     /* Did we hit a glob char or get to the end? */
105     return span != 0;
106 #else
107     return 0;
108 #endif
109 }
110
111 /**
112  * Get index range of image files matched by path.
113  *
114  * @param pfirst_index pointer to index updated with the first number in the range
115  * @param plast_index  pointer to index updated with the last number in the range
116  * @param path         path which has to be matched by the image files in the range
117  * @param start_index  minimum accepted value for the first index in the range
118  * @return -1 if no image file could be found
119  */
120 static int find_image_range(int *pfirst_index, int *plast_index,
121                             const char *path, int start_index)
122 {
123     char buf[1024];
124     int range, last_index, range1, first_index;
125
126     /* find the first image */
127     for (first_index = start_index; first_index < start_index + 5; first_index++) {
128         if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
129             *pfirst_index =
130             *plast_index = 1;
131             if (avio_check(buf, AVIO_FLAG_READ) > 0)
132                 return 0;
133             return -1;
134         }
135         if (avio_check(buf, AVIO_FLAG_READ) > 0)
136             break;
137     }
138     if (first_index == start_index + 5)
139         goto fail;
140
141     /* find the last image */
142     last_index = first_index;
143     for(;;) {
144         range = 0;
145         for(;;) {
146             if (!range)
147                 range1 = 1;
148             else
149                 range1 = 2 * range;
150             if (av_get_frame_filename(buf, sizeof(buf), path,
151                                       last_index + range1) < 0)
152                 goto fail;
153             if (avio_check(buf, AVIO_FLAG_READ) <= 0)
154                 break;
155             range = range1;
156             /* just in case... */
157             if (range >= (1 << 30))
158                 goto fail;
159         }
160         /* we are sure than image last_index + range exists */
161         if (!range)
162             break;
163         last_index += range;
164     }
165     *pfirst_index = first_index;
166     *plast_index = last_index;
167     return 0;
168  fail:
169     return -1;
170 }
171
172
173 static int read_probe(AVProbeData *p)
174 {
175     if (p->filename && ff_guess_image2_codec(p->filename)) {
176         if (av_filename_number_test(p->filename))
177             return AVPROBE_SCORE_MAX;
178         else if (is_glob(p->filename))
179             return AVPROBE_SCORE_MAX;
180         else
181             return AVPROBE_SCORE_MAX/2;
182     }
183     return 0;
184 }
185
186 static int read_header(AVFormatContext *s1)
187 {
188     VideoDemuxData *s = s1->priv_data;
189     int first_index, last_index, ret = 0;
190     int width = 0, height = 0;
191     AVStream *st;
192     enum PixelFormat pix_fmt = PIX_FMT_NONE;
193     AVRational framerate;
194
195     s1->ctx_flags |= AVFMTCTX_NOHEADER;
196
197     st = avformat_new_stream(s1, NULL);
198     if (!st) {
199         return AVERROR(ENOMEM);
200     }
201
202     if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
203         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
204         return AVERROR(EINVAL);
205     }
206     if (s->video_size && (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
207         av_log(s, AV_LOG_ERROR, "Could not parse video size: %s.\n", s->video_size);
208         return ret;
209     }
210     if ((ret = av_parse_video_rate(&framerate, s->framerate)) < 0) {
211         av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s->framerate);
212         return ret;
213     }
214
215     av_strlcpy(s->path, s1->filename, sizeof(s->path));
216     s->img_number = 0;
217     s->img_count = 0;
218
219     /* find format */
220     if (s1->iformat->flags & AVFMT_NOFILE)
221         s->is_pipe = 0;
222     else{
223         s->is_pipe = 1;
224         st->need_parsing = AVSTREAM_PARSE_FULL;
225     }
226
227     avpriv_set_pts_info(st, 60, framerate.den, framerate.num);
228
229     if (width && height) {
230         st->codec->width  = width;
231         st->codec->height = height;
232     }
233
234     if (!s->is_pipe) {
235         s->use_glob = is_glob(s->path);
236         if (s->use_glob) {
237 #if HAVE_GLOB
238             char *p = s->path, *q, *dup;
239             int gerr;
240
241             dup = q = av_strdup(p);
242             while (*q) {
243                 /* Do we have room for the next char and a \ insertion? */
244                 if ((p - s->path) >= (sizeof(s->path) - 2))
245                   break;
246                 if (*q == '%' && strspn(q + 1, "%*?[]{}"))
247                     ++q;
248                 else if (strspn(q, "\\*?[]{}"))
249                     *p++ = '\\';
250                 *p++ = *q++;
251             }
252             *p = 0;
253             av_free(dup);
254
255             gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);
256             if (gerr != 0) {
257                 return AVERROR(ENOENT);
258             }
259             first_index = 0;
260             last_index = s->globstate.gl_pathc - 1;
261 #endif
262         } else {
263             if (find_image_range(&first_index, &last_index, s->path,
264                                  s->start_number) < 0)
265                 return AVERROR(ENOENT);
266         }
267         s->img_first = first_index;
268         s->img_last = last_index;
269         s->img_number = first_index;
270         /* compute duration */
271         st->start_time = 0;
272         st->duration = last_index - first_index + 1;
273     }
274
275     if(s1->video_codec_id){
276         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
277         st->codec->codec_id = s1->video_codec_id;
278     }else if(s1->audio_codec_id){
279         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
280         st->codec->codec_id = s1->audio_codec_id;
281     }else{
282         const char *str= strrchr(s->path, '.');
283         s->split_planes = str && !av_strcasecmp(str + 1, "y");
284         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
285         st->codec->codec_id = ff_guess_image2_codec(s->path);
286         if (st->codec->codec_id == CODEC_ID_LJPEG)
287             st->codec->codec_id = CODEC_ID_MJPEG;
288     }
289     if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pix_fmt != PIX_FMT_NONE)
290         st->codec->pix_fmt = pix_fmt;
291
292     return 0;
293 }
294
295 static int read_packet(AVFormatContext *s1, AVPacket *pkt)
296 {
297     VideoDemuxData *s = s1->priv_data;
298     char filename_bytes[1024];
299     char *filename = filename_bytes;
300     int i;
301     int size[3]={0}, ret[3]={0};
302     AVIOContext *f[3];
303     AVCodecContext *codec= s1->streams[0]->codec;
304
305     if (!s->is_pipe) {
306         /* loop over input */
307         if (s->loop && s->img_number > s->img_last) {
308             s->img_number = s->img_first;
309         }
310         if (s->img_number > s->img_last)
311             return AVERROR_EOF;
312         if (s->use_glob) {
313 #if HAVE_GLOB
314             filename = s->globstate.gl_pathv[s->img_number];
315 #endif
316         } else {
317         if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),
318                                   s->path, s->img_number)<0 && s->img_number > 1)
319             return AVERROR(EIO);
320         }
321         for(i=0; i<3; i++){
322             if (avio_open2(&f[i], filename, AVIO_FLAG_READ,
323                            &s1->interrupt_callback, NULL) < 0) {
324                 if(i==1)
325                     break;
326                 av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);
327                 return AVERROR(EIO);
328             }
329             size[i]= avio_size(f[i]);
330
331             if(!s->split_planes)
332                 break;
333             filename[ strlen(filename) - 1 ]= 'U' + i;
334         }
335
336         if(codec->codec_id == CODEC_ID_RAWVIDEO && !codec->width)
337             infer_size(&codec->width, &codec->height, size[0]);
338     } else {
339         f[0] = s1->pb;
340         if (url_feof(f[0]))
341             return AVERROR(EIO);
342         size[0]= 4096;
343     }
344
345     av_new_packet(pkt, size[0] + size[1] + size[2]);
346     pkt->stream_index = 0;
347     pkt->flags |= AV_PKT_FLAG_KEY;
348
349     pkt->size= 0;
350     for(i=0; i<3; i++){
351         if(size[i]){
352             ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);
353             if (!s->is_pipe)
354                 avio_close(f[i]);
355             if(ret[i]>0)
356                 pkt->size += ret[i];
357         }
358     }
359
360     if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {
361         av_free_packet(pkt);
362         return AVERROR(EIO); /* signal EOF */
363     } else {
364         s->img_count++;
365         s->img_number++;
366         return 0;
367     }
368 }
369
370 static int read_close(struct AVFormatContext* s1)
371 {
372     VideoDemuxData *s = s1->priv_data;
373 #if HAVE_GLOB
374     if (s->use_glob) {
375         globfree(&s->globstate);
376     }
377 #endif
378     return 0;
379 }
380
381 #define OFFSET(x) offsetof(VideoDemuxData, x)
382 #define DEC AV_OPT_FLAG_DECODING_PARAM
383 static const AVOption options[] = {
384     { "pixel_format", "", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
385     { "video_size",   "", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
386     { "framerate",    "", OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, DEC },
387     { "loop",         "", OFFSET(loop),         AV_OPT_TYPE_INT,    {.dbl = 0},    0, 1, DEC },
388     { "start_number", "first number in the sequence", OFFSET(start_number), AV_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, DEC },
389     { NULL },
390 };
391
392 #if CONFIG_IMAGE2_DEMUXER
393 static const AVClass img2_class = {
394     .class_name = "image2 demuxer",
395     .item_name  = av_default_item_name,
396     .option     = options,
397     .version    = LIBAVUTIL_VERSION_INT,
398 };
399 AVInputFormat ff_image2_demuxer = {
400     .name           = "image2",
401     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
402     .priv_data_size = sizeof(VideoDemuxData),
403     .read_probe     = read_probe,
404     .read_header    = read_header,
405     .read_packet    = read_packet,
406     .read_close     = read_close,
407     .flags          = AVFMT_NOFILE,
408     .priv_class     = &img2_class,
409 };
410 #endif
411 #if CONFIG_IMAGE2PIPE_DEMUXER
412 static const AVClass img2pipe_class = {
413     .class_name = "image2pipe demuxer",
414     .item_name  = av_default_item_name,
415     .option     = options,
416     .version    = LIBAVUTIL_VERSION_INT,
417 };
418 AVInputFormat ff_image2pipe_demuxer = {
419     .name           = "image2pipe",
420     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
421     .priv_data_size = sizeof(VideoDemuxData),
422     .read_header    = read_header,
423     .read_packet    = read_packet,
424     .priv_class     = &img2pipe_class,
425 };
426 #endif