]> git.sesse.net Git - ffmpeg/blob - libavformat/img2dec.c
avformat/img2dec: improve xbm probing
[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 #define _DEFAULT_SOURCE
24 #define _BSD_SOURCE
25 #include <sys/stat.h>
26 #include "libavutil/avstring.h"
27 #include "libavutil/log.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/parseutils.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavcodec/gif.h"
33 #include "avformat.h"
34 #include "avio_internal.h"
35 #include "internal.h"
36 #include "img2.h"
37 #include "libavcodec/mjpeg.h"
38 #include "libavcodec/xwd.h"
39 #include "subtitles.h"
40
41 #if HAVE_GLOB
42 /* Locally define as 0 (bitwise-OR no-op) any missing glob options that
43    are non-posix glibc/bsd extensions. */
44 #ifndef GLOB_NOMAGIC
45 #define GLOB_NOMAGIC 0
46 #endif
47 #ifndef GLOB_BRACE
48 #define GLOB_BRACE 0
49 #endif
50
51 #endif /* HAVE_GLOB */
52
53 static const int sizes[][2] = {
54     { 640, 480 },
55     { 720, 480 },
56     { 720, 576 },
57     { 352, 288 },
58     { 352, 240 },
59     { 160, 128 },
60     { 512, 384 },
61     { 640, 352 },
62     { 640, 240 },
63 };
64
65 static int infer_size(int *width_ptr, int *height_ptr, int size)
66 {
67     int i;
68
69     for (i = 0; i < FF_ARRAY_ELEMS(sizes); i++) {
70         if ((sizes[i][0] * sizes[i][1]) == size) {
71             *width_ptr  = sizes[i][0];
72             *height_ptr = sizes[i][1];
73             return 0;
74         }
75     }
76
77     return -1;
78 }
79
80 static int is_glob(const char *path)
81 {
82 #if HAVE_GLOB
83     size_t span = 0;
84     const char *p = path;
85
86     while (p = strchr(p, '%')) {
87         if (*(++p) == '%') {
88             ++p;
89             continue;
90         }
91         if (span = strspn(p, "*?[]{}"))
92             break;
93     }
94     /* Did we hit a glob char or get to the end? */
95     return span != 0;
96 #else
97     return 0;
98 #endif
99 }
100
101 /**
102  * Get index range of image files matched by path.
103  *
104  * @param pfirst_index pointer to index updated with the first number in the range
105  * @param plast_index  pointer to index updated with the last number in the range
106  * @param path         path which has to be matched by the image files in the range
107  * @param start_index  minimum accepted value for the first index in the range
108  * @return -1 if no image file could be found
109  */
110 static int find_image_range(AVIOContext *pb, int *pfirst_index, int *plast_index,
111                             const char *path, int start_index, int start_index_range)
112 {
113     char buf[1024];
114     int range, last_index, range1, first_index;
115
116     /* find the first image */
117     for (first_index = start_index; first_index < start_index + start_index_range; first_index++) {
118         if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0) {
119             *pfirst_index =
120             *plast_index  = 1;
121             if (pb || avio_check(buf, AVIO_FLAG_READ) > 0)
122                 return 0;
123             return -1;
124         }
125         if (avio_check(buf, AVIO_FLAG_READ) > 0)
126             break;
127     }
128     if (first_index == start_index + start_index_range)
129         goto fail;
130
131     /* find the last image */
132     last_index = first_index;
133     for (;;) {
134         range = 0;
135         for (;;) {
136             if (!range)
137                 range1 = 1;
138             else
139                 range1 = 2 * range;
140             if (av_get_frame_filename(buf, sizeof(buf), path,
141                                       last_index + range1) < 0)
142                 goto fail;
143             if (avio_check(buf, AVIO_FLAG_READ) <= 0)
144                 break;
145             range = range1;
146             /* just in case... */
147             if (range >= (1 << 30))
148                 goto fail;
149         }
150         /* we are sure than image last_index + range exists */
151         if (!range)
152             break;
153         last_index += range;
154     }
155     *pfirst_index = first_index;
156     *plast_index  = last_index;
157     return 0;
158
159 fail:
160     return -1;
161 }
162
163 static int img_read_probe(const AVProbeData *p)
164 {
165     if (p->filename && ff_guess_image2_codec(p->filename)) {
166         if (av_filename_number_test(p->filename))
167             return AVPROBE_SCORE_MAX;
168         else if (is_glob(p->filename))
169             return AVPROBE_SCORE_MAX;
170         else if (p->filename[strcspn(p->filename, "*?{")]) // probably PT_GLOB
171             return AVPROBE_SCORE_EXTENSION + 2; // score chosen to be a tad above the image pipes
172         else if (p->buf_size == 0)
173             return 0;
174         else if (av_match_ext(p->filename, "raw") || av_match_ext(p->filename, "gif"))
175             return 5;
176         else
177             return AVPROBE_SCORE_EXTENSION;
178     }
179     return 0;
180 }
181
182 int ff_img_read_header(AVFormatContext *s1)
183 {
184     VideoDemuxData *s = s1->priv_data;
185     int first_index = 1, last_index = 1;
186     AVStream *st;
187     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
188
189     s1->ctx_flags |= AVFMTCTX_NOHEADER;
190
191     st = avformat_new_stream(s1, NULL);
192     if (!st) {
193         return AVERROR(ENOMEM);
194     }
195
196     if (s->pixel_format &&
197         (pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) {
198         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n",
199                s->pixel_format);
200         return AVERROR(EINVAL);
201     }
202
203     av_strlcpy(s->path, s1->url, sizeof(s->path));
204     s->img_number = 0;
205     s->img_count  = 0;
206
207     /* find format */
208     if (s1->iformat->flags & AVFMT_NOFILE)
209         s->is_pipe = 0;
210     else {
211         s->is_pipe       = 1;
212         st->need_parsing = AVSTREAM_PARSE_FULL;
213     }
214
215     if (s->ts_from_file == 2) {
216 #if !HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
217         av_log(s1, AV_LOG_ERROR, "POSIX.1-2008 not supported, nanosecond file timestamps unavailable\n");
218         return AVERROR(ENOSYS);
219 #endif
220         avpriv_set_pts_info(st, 64, 1, 1000000000);
221     } else if (s->ts_from_file)
222         avpriv_set_pts_info(st, 64, 1, 1);
223     else {
224         avpriv_set_pts_info(st, 64, s->framerate.den, s->framerate.num);
225         st->avg_frame_rate = s->framerate;
226     }
227
228     if (s->width && s->height) {
229         st->codecpar->width  = s->width;
230         st->codecpar->height = s->height;
231     }
232
233     if (!s->is_pipe) {
234         if (s->pattern_type == PT_DEFAULT) {
235             if (s1->pb) {
236                 s->pattern_type = PT_NONE;
237             } else
238                 s->pattern_type = PT_GLOB_SEQUENCE;
239         }
240
241         if (s->pattern_type == PT_GLOB_SEQUENCE) {
242         s->use_glob = is_glob(s->path);
243         if (s->use_glob) {
244 #if HAVE_GLOB
245             char *p = s->path, *q, *dup;
246             int gerr;
247 #endif
248
249             av_log(s1, AV_LOG_WARNING, "Pattern type 'glob_sequence' is deprecated: "
250                    "use pattern_type 'glob' instead\n");
251 #if HAVE_GLOB
252             dup = q = av_strdup(p);
253             while (*q) {
254                 /* Do we have room for the next char and a \ insertion? */
255                 if ((p - s->path) >= (sizeof(s->path) - 2))
256                   break;
257                 if (*q == '%' && strspn(q + 1, "%*?[]{}"))
258                     ++q;
259                 else if (strspn(q, "\\*?[]{}"))
260                     *p++ = '\\';
261                 *p++ = *q++;
262             }
263             *p = 0;
264             av_free(dup);
265
266             gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);
267             if (gerr != 0) {
268                 return AVERROR(ENOENT);
269             }
270             first_index = 0;
271             last_index = s->globstate.gl_pathc - 1;
272 #endif
273         }
274         }
275         if ((s->pattern_type == PT_GLOB_SEQUENCE && !s->use_glob) || s->pattern_type == PT_SEQUENCE) {
276             if (find_image_range(s1->pb, &first_index, &last_index, s->path,
277                                  s->start_number, s->start_number_range) < 0) {
278                 av_log(s1, AV_LOG_ERROR,
279                        "Could find no file with path '%s' and index in the range %d-%d\n",
280                        s->path, s->start_number, s->start_number + s->start_number_range - 1);
281                 return AVERROR(ENOENT);
282             }
283         } else if (s->pattern_type == PT_GLOB) {
284 #if HAVE_GLOB
285             int gerr;
286             gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);
287             if (gerr != 0) {
288                 return AVERROR(ENOENT);
289             }
290             first_index = 0;
291             last_index = s->globstate.gl_pathc - 1;
292             s->use_glob = 1;
293 #else
294             av_log(s1, AV_LOG_ERROR,
295                    "Pattern type 'glob' was selected but globbing "
296                    "is not supported by this libavformat build\n");
297             return AVERROR(ENOSYS);
298 #endif
299         } else if (s->pattern_type != PT_GLOB_SEQUENCE && s->pattern_type != PT_NONE) {
300             av_log(s1, AV_LOG_ERROR,
301                    "Unknown value '%d' for pattern_type option\n", s->pattern_type);
302             return AVERROR(EINVAL);
303         }
304         s->img_first  = first_index;
305         s->img_last   = last_index;
306         s->img_number = first_index;
307         /* compute duration */
308         if (!s->ts_from_file) {
309             st->start_time = 0;
310             st->duration   = last_index - first_index + 1;
311         }
312     }
313
314     if (s1->video_codec_id) {
315         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
316         st->codecpar->codec_id   = s1->video_codec_id;
317     } else if (s1->audio_codec_id) {
318         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
319         st->codecpar->codec_id   = s1->audio_codec_id;
320     } else if (s1->iformat->raw_codec_id) {
321         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
322         st->codecpar->codec_id   = s1->iformat->raw_codec_id;
323     } else {
324         const char *str = strrchr(s->path, '.');
325         s->split_planes       = str && !av_strcasecmp(str + 1, "y");
326         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
327         if (s1->pb) {
328             int probe_buffer_size = 2048;
329             uint8_t *probe_buffer = av_realloc(NULL, probe_buffer_size + AVPROBE_PADDING_SIZE);
330             const AVInputFormat *fmt = NULL;
331             void *fmt_iter = NULL;
332             AVProbeData pd = { 0 };
333
334             if (!probe_buffer)
335                 return AVERROR(ENOMEM);
336
337             probe_buffer_size = avio_read(s1->pb, probe_buffer, probe_buffer_size);
338             if (probe_buffer_size < 0) {
339                 av_free(probe_buffer);
340                 return probe_buffer_size;
341             }
342             memset(probe_buffer + probe_buffer_size, 0, AVPROBE_PADDING_SIZE);
343
344             pd.buf = probe_buffer;
345             pd.buf_size = probe_buffer_size;
346             pd.filename = s1->url;
347
348             while ((fmt = av_demuxer_iterate(&fmt_iter))) {
349                 if (fmt->read_header != ff_img_read_header ||
350                     !fmt->read_probe ||
351                     (fmt->flags & AVFMT_NOFILE) ||
352                     !fmt->raw_codec_id)
353                     continue;
354                 if (fmt->read_probe(&pd) > 0) {
355                     st->codecpar->codec_id = fmt->raw_codec_id;
356                     break;
357                 }
358             }
359             if (s1->flags & AVFMT_FLAG_CUSTOM_IO) {
360                 avio_seek(s1->pb, 0, SEEK_SET);
361                 av_freep(&probe_buffer);
362             } else
363                 ffio_rewind_with_probe_data(s1->pb, &probe_buffer, probe_buffer_size);
364         }
365         if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
366             st->codecpar->codec_id = ff_guess_image2_codec(s->path);
367         if (st->codecpar->codec_id == AV_CODEC_ID_LJPEG)
368             st->codecpar->codec_id = AV_CODEC_ID_MJPEG;
369         if (st->codecpar->codec_id == AV_CODEC_ID_ALIAS_PIX) // we cannot distingiush this from BRENDER_PIX
370             st->codecpar->codec_id = AV_CODEC_ID_NONE;
371     }
372     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
373         pix_fmt != AV_PIX_FMT_NONE)
374         st->codecpar->format = pix_fmt;
375
376     return 0;
377 }
378
379 /**
380  * Add this frame's source path and basename to packet's sidedata
381  * as a dictionary, so it can be used by filters like 'drawtext'.
382  */
383 static int add_filename_as_pkt_side_data(char *filename, AVPacket *pkt) {
384     int metadata_len, ret;
385     AVDictionary *d = NULL;
386     char *packed_metadata = NULL;
387
388     av_dict_set(&d, "lavf.image2dec.source_path", filename, 0);
389     av_dict_set(&d, "lavf.image2dec.source_basename", av_basename(filename), 0);
390
391     packed_metadata = av_packet_pack_dictionary(d, &metadata_len);
392     av_dict_free(&d);
393     if (!packed_metadata)
394         return AVERROR(ENOMEM);
395     ret = av_packet_add_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
396                                   packed_metadata, metadata_len);
397     if (ret < 0) {
398         av_freep(&packed_metadata);
399         return ret;
400     }
401     return 0;
402 }
403
404 int ff_img_read_packet(AVFormatContext *s1, AVPacket *pkt)
405 {
406     VideoDemuxData *s = s1->priv_data;
407     char filename_bytes[1024];
408     char *filename = filename_bytes;
409     int i, res;
410     int size[3]           = { 0 }, ret[3] = { 0 };
411     AVIOContext *f[3]     = { NULL };
412     AVCodecParameters *par = s1->streams[0]->codecpar;
413
414     if (!s->is_pipe) {
415         /* loop over input */
416         if (s->loop && s->img_number > s->img_last) {
417             s->img_number = s->img_first;
418         }
419         if (s->img_number > s->img_last)
420             return AVERROR_EOF;
421         if (s->pattern_type == PT_NONE) {
422             av_strlcpy(filename_bytes, s->path, sizeof(filename_bytes));
423         } else if (s->use_glob) {
424 #if HAVE_GLOB
425             filename = s->globstate.gl_pathv[s->img_number];
426 #endif
427         } else {
428         if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),
429                                   s->path,
430                                   s->img_number) < 0 && s->img_number > 1)
431             return AVERROR(EIO);
432         }
433         for (i = 0; i < 3; i++) {
434             if (s1->pb &&
435                 !strcmp(filename_bytes, s->path) &&
436                 !s->loop &&
437                 !s->split_planes) {
438                 f[i] = s1->pb;
439             } else if (s1->io_open(s1, &f[i], filename, AVIO_FLAG_READ, NULL) < 0) {
440                 if (i >= 1)
441                     break;
442                 av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",
443                        filename);
444                 return AVERROR(EIO);
445             }
446             size[i] = avio_size(f[i]);
447
448             if (!s->split_planes)
449                 break;
450             filename[strlen(filename) - 1] = 'U' + i;
451         }
452
453         if (par->codec_id == AV_CODEC_ID_NONE) {
454             AVProbeData pd = { 0 };
455             const AVInputFormat *ifmt;
456             uint8_t header[PROBE_BUF_MIN + AVPROBE_PADDING_SIZE];
457             int ret;
458             int score = 0;
459
460             ret = avio_read(f[0], header, PROBE_BUF_MIN);
461             if (ret < 0)
462                 return ret;
463             memset(header + ret, 0, sizeof(header) - ret);
464             avio_skip(f[0], -ret);
465             pd.buf = header;
466             pd.buf_size = ret;
467             pd.filename = filename;
468
469             ifmt = av_probe_input_format3(&pd, 1, &score);
470             if (ifmt && ifmt->read_packet == ff_img_read_packet && ifmt->raw_codec_id)
471                 par->codec_id = ifmt->raw_codec_id;
472         }
473
474         if (par->codec_id == AV_CODEC_ID_RAWVIDEO && !par->width)
475             infer_size(&par->width, &par->height, size[0]);
476     } else {
477         f[0] = s1->pb;
478         if (avio_feof(f[0]) && s->loop && s->is_pipe)
479             avio_seek(f[0], 0, SEEK_SET);
480         if (avio_feof(f[0]))
481             return AVERROR_EOF;
482         if (s->frame_size > 0) {
483             size[0] = s->frame_size;
484         } else if (!s1->streams[0]->parser) {
485             size[0] = avio_size(s1->pb);
486         } else {
487             size[0] = 4096;
488         }
489     }
490
491     res = av_new_packet(pkt, size[0] + size[1] + size[2]);
492     if (res < 0) {
493         goto fail;
494     }
495     pkt->stream_index = 0;
496     pkt->flags       |= AV_PKT_FLAG_KEY;
497     if (s->ts_from_file) {
498         struct stat img_stat;
499         if (stat(filename, &img_stat)) {
500             res = AVERROR(EIO);
501             goto fail;
502         }
503         pkt->pts = (int64_t)img_stat.st_mtime;
504 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
505         if (s->ts_from_file == 2)
506             pkt->pts = 1000000000*pkt->pts + img_stat.st_mtim.tv_nsec;
507 #endif
508         av_add_index_entry(s1->streams[0], s->img_number, pkt->pts, 0, 0, AVINDEX_KEYFRAME);
509     } else if (!s->is_pipe) {
510         pkt->pts      = s->pts;
511     }
512
513     if (s->is_pipe)
514         pkt->pos = avio_tell(f[0]);
515
516     /*
517      * export_path_metadata must be explicitly enabled via
518      * command line options for path metadata to be exported
519      * as packet side_data.
520      */
521     if (!s->is_pipe && s->export_path_metadata == 1) {
522         res = add_filename_as_pkt_side_data(filename, pkt);
523         if (res < 0)
524             goto fail;
525     }
526
527     pkt->size = 0;
528     for (i = 0; i < 3; i++) {
529         if (f[i]) {
530             ret[i] = avio_read(f[i], pkt->data + pkt->size, size[i]);
531             if (s->loop && s->is_pipe && ret[i] == AVERROR_EOF) {
532                 if (avio_seek(f[i], 0, SEEK_SET) >= 0) {
533                     pkt->pos = 0;
534                     ret[i] = avio_read(f[i], pkt->data + pkt->size, size[i]);
535                 }
536             }
537             if (!s->is_pipe && f[i] != s1->pb)
538                 ff_format_io_close(s1, &f[i]);
539             if (ret[i] > 0)
540                 pkt->size += ret[i];
541         }
542     }
543
544     if (ret[0] <= 0 || ret[1] < 0 || ret[2] < 0) {
545         if (ret[0] < 0) {
546             res = ret[0];
547         } else if (ret[1] < 0) {
548             res = ret[1];
549         } else if (ret[2] < 0) {
550             res = ret[2];
551         } else {
552             res = AVERROR_EOF;
553         }
554         goto fail;
555     } else {
556         s->img_count++;
557         s->img_number++;
558         s->pts++;
559         return 0;
560     }
561
562 fail:
563     if (!s->is_pipe) {
564         for (i = 0; i < 3; i++) {
565             if (f[i] != s1->pb)
566                 ff_format_io_close(s1, &f[i]);
567         }
568     }
569     return res;
570 }
571
572 static int img_read_close(struct AVFormatContext* s1)
573 {
574 #if HAVE_GLOB
575     VideoDemuxData *s = s1->priv_data;
576     if (s->use_glob) {
577         globfree(&s->globstate);
578     }
579 #endif
580     return 0;
581 }
582
583 static int img_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
584 {
585     VideoDemuxData *s1 = s->priv_data;
586     AVStream *st = s->streams[0];
587
588     if (s1->ts_from_file) {
589         int index = av_index_search_timestamp(st, timestamp, flags);
590         if(index < 0)
591             return -1;
592         s1->img_number = st->internal->index_entries[index].pos;
593         return 0;
594     }
595
596     if (timestamp < 0 || !s1->loop && timestamp > s1->img_last - s1->img_first)
597         return -1;
598     s1->img_number = timestamp%(s1->img_last - s1->img_first + 1) + s1->img_first;
599     s1->pts = timestamp;
600     return 0;
601 }
602
603 #define OFFSET(x) offsetof(VideoDemuxData, x)
604 #define DEC AV_OPT_FLAG_DECODING_PARAM
605 #define COMMON_OPTIONS \
606     { "framerate",    "set the video framerate", OFFSET(framerate),    AV_OPT_TYPE_VIDEO_RATE, {.str = "25"}, 0, INT_MAX, DEC }, \
607     { "pixel_format", "set video pixel format",  OFFSET(pixel_format), AV_OPT_TYPE_STRING,     {.str = NULL}, 0, 0,       DEC }, \
608     { "video_size",   "set video size",          OFFSET(width),        AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0,       DEC }, \
609     { "loop",         "force loop over input file sequence", OFFSET(loop), AV_OPT_TYPE_BOOL,   {.i64 = 0   }, 0, 1,       DEC }, \
610     { NULL },
611
612 #if CONFIG_IMAGE2_DEMUXER
613 const AVOption ff_img_options[] = {
614     { "pattern_type", "set pattern type",                    OFFSET(pattern_type), AV_OPT_TYPE_INT,    {.i64=PT_DEFAULT}, 0,       INT_MAX, DEC, "pattern_type"},
615     { "glob_sequence","select glob/sequence pattern type",   0, AV_OPT_TYPE_CONST,  {.i64=PT_GLOB_SEQUENCE}, INT_MIN, INT_MAX, DEC, "pattern_type" },
616     { "glob",         "select glob pattern type",            0, AV_OPT_TYPE_CONST,  {.i64=PT_GLOB         }, INT_MIN, INT_MAX, DEC, "pattern_type" },
617     { "sequence",     "select sequence pattern type",        0, AV_OPT_TYPE_CONST,  {.i64=PT_SEQUENCE     }, INT_MIN, INT_MAX, DEC, "pattern_type" },
618     { "none",         "disable pattern matching",            0, AV_OPT_TYPE_CONST,  {.i64=PT_NONE         }, INT_MIN, INT_MAX, DEC, "pattern_type" },
619     { "start_number", "set first number in the sequence",    OFFSET(start_number), AV_OPT_TYPE_INT,    {.i64 = 0   }, INT_MIN, INT_MAX, DEC },
620     { "start_number_range", "set range for looking at the first sequence number", OFFSET(start_number_range), AV_OPT_TYPE_INT, {.i64 = 5}, 1, INT_MAX, DEC },
621     { "ts_from_file", "set frame timestamp from file's one", OFFSET(ts_from_file), AV_OPT_TYPE_INT,    {.i64 = 0   }, 0, 2,       DEC, "ts_type" },
622     { "none", "none",                   0, AV_OPT_TYPE_CONST,    {.i64 = 0   }, 0, 2,       DEC, "ts_type" },
623     { "sec",  "second precision",       0, AV_OPT_TYPE_CONST,    {.i64 = 1   }, 0, 2,       DEC, "ts_type" },
624     { "ns",   "nano second precision",  0, AV_OPT_TYPE_CONST,    {.i64 = 2   }, 0, 2,       DEC, "ts_type" },
625     { "export_path_metadata", "enable metadata containing input path information", OFFSET(export_path_metadata), AV_OPT_TYPE_BOOL,   {.i64 = 0   }, 0, 1,       DEC }, \
626     COMMON_OPTIONS
627 };
628
629 static const AVClass img2_class = {
630     .class_name = "image2 demuxer",
631     .item_name  = av_default_item_name,
632     .option     = ff_img_options,
633     .version    = LIBAVUTIL_VERSION_INT,
634 };
635 AVInputFormat ff_image2_demuxer = {
636     .name           = "image2",
637     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
638     .priv_data_size = sizeof(VideoDemuxData),
639     .read_probe     = img_read_probe,
640     .read_header    = ff_img_read_header,
641     .read_packet    = ff_img_read_packet,
642     .read_close     = img_read_close,
643     .read_seek      = img_read_seek,
644     .flags          = AVFMT_NOFILE,
645     .priv_class     = &img2_class,
646 };
647 #endif
648
649 const AVOption ff_img2pipe_options[] = {
650     { "frame_size", "force frame size in bytes", OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC },
651     COMMON_OPTIONS
652 };
653
654 #if CONFIG_IMAGE2PIPE_DEMUXER
655 static const AVClass img2pipe_class = {
656     .class_name = "image2pipe demuxer",
657     .item_name  = av_default_item_name,
658     .option     = ff_img2pipe_options,
659     .version    = LIBAVUTIL_VERSION_INT,
660 };
661 AVInputFormat ff_image2pipe_demuxer = {
662     .name           = "image2pipe",
663     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
664     .priv_data_size = sizeof(VideoDemuxData),
665     .read_header    = ff_img_read_header,
666     .read_packet    = ff_img_read_packet,
667     .priv_class     = &img2pipe_class,
668 };
669 #endif
670
671 static int bmp_probe(const AVProbeData *p)
672 {
673     const uint8_t *b = p->buf;
674     int ihsize;
675
676     if (AV_RB16(b) != 0x424d)
677         return 0;
678
679     ihsize = AV_RL32(b+14);
680     if (ihsize < 12 || ihsize > 255)
681         return 0;
682
683     if (!AV_RN32(b + 6)) {
684         return AVPROBE_SCORE_EXTENSION + 1;
685     }
686     return AVPROBE_SCORE_EXTENSION / 4;
687 }
688
689 static int cri_probe(const AVProbeData *p)
690 {
691     const uint8_t *b = p->buf;
692
693     if (   AV_RL32(b) == 1
694         && AV_RL32(b + 4) == 4
695         && AV_RN32(b + 8) == AV_RN32("DVCC"))
696         return AVPROBE_SCORE_MAX - 1;
697     return 0;
698 }
699
700 static int dds_probe(const AVProbeData *p)
701 {
702     const uint8_t *b = p->buf;
703
704     if (   AV_RB64(b) == 0x444453207c000000
705         && AV_RL32(b +  8)
706         && AV_RL32(b + 12))
707         return AVPROBE_SCORE_MAX - 1;
708     return 0;
709 }
710
711 static int dpx_probe(const AVProbeData *p)
712 {
713     const uint8_t *b = p->buf;
714     int w, h;
715     int is_big = (AV_RN32(b) == AV_RN32("SDPX"));
716
717     if (p->buf_size < 0x304+8)
718         return 0;
719     w = is_big ? AV_RB32(p->buf + 0x304) : AV_RL32(p->buf + 0x304);
720     h = is_big ? AV_RB32(p->buf + 0x308) : AV_RL32(p->buf + 0x308);
721     if (w <= 0 || h <= 0)
722         return 0;
723
724     if (is_big || AV_RN32(b) == AV_RN32("XPDS"))
725         return AVPROBE_SCORE_EXTENSION + 1;
726     return 0;
727 }
728
729 static int exr_probe(const AVProbeData *p)
730 {
731     const uint8_t *b = p->buf;
732
733     if (AV_RL32(b) == 20000630)
734         return AVPROBE_SCORE_EXTENSION + 1;
735     return 0;
736 }
737
738 static int j2k_probe(const AVProbeData *p)
739 {
740     const uint8_t *b = p->buf;
741
742     if (AV_RB64(b) == 0x0000000c6a502020 ||
743         AV_RB32(b) == 0xff4fff51)
744         return AVPROBE_SCORE_EXTENSION + 1;
745     return 0;
746 }
747
748 static int jpeg_probe(const AVProbeData *p)
749 {
750     const uint8_t *b = p->buf;
751     int i, state = SOI;
752
753     if (AV_RB16(b) != 0xFFD8 ||
754         AV_RB32(b) == 0xFFD8FFF7)
755     return 0;
756
757     b += 2;
758     for (i = 0; i < p->buf_size - 3; i++) {
759         int c;
760         if (b[i] != 0xFF)
761             continue;
762         c = b[i + 1];
763         switch (c) {
764         case SOI:
765             return 0;
766         case SOF0:
767         case SOF1:
768         case SOF2:
769         case SOF3:
770         case SOF5:
771         case SOF6:
772         case SOF7:
773             i += AV_RB16(&b[i + 2]) + 1;
774             if (state != SOI)
775                 return 0;
776             state = SOF0;
777             break;
778         case SOS:
779             i += AV_RB16(&b[i + 2]) + 1;
780             if (state != SOF0 && state != SOS)
781                 return 0;
782             state = SOS;
783             break;
784         case EOI:
785             if (state != SOS)
786                 return 0;
787             state = EOI;
788             break;
789         case DQT:
790         case APP0:
791         case APP1:
792         case APP2:
793         case APP3:
794         case APP4:
795         case APP5:
796         case APP6:
797         case APP7:
798         case APP8:
799         case APP9:
800         case APP10:
801         case APP11:
802         case APP12:
803         case APP13:
804         case APP14:
805         case APP15:
806         case COM:
807             i += AV_RB16(&b[i + 2]) + 1;
808             break;
809         default:
810             if (  (c > TEM && c < SOF0)
811                 || c == JPG)
812                 return 0;
813         }
814     }
815
816     if (state == EOI)
817         return AVPROBE_SCORE_EXTENSION + 1;
818     if (state == SOS)
819         return AVPROBE_SCORE_EXTENSION / 2;
820     return AVPROBE_SCORE_EXTENSION / 8 + 1;
821 }
822
823 static int jpegls_probe(const AVProbeData *p)
824 {
825     const uint8_t *b = p->buf;
826
827     if (AV_RB32(b) == 0xffd8fff7)
828          return AVPROBE_SCORE_EXTENSION + 1;
829     return 0;
830 }
831
832 static int pcx_probe(const AVProbeData *p)
833 {
834     const uint8_t *b = p->buf;
835
836     if (   p->buf_size < 128
837         || b[0] != 10
838         || b[1] > 5
839         || b[2] > 1
840         || av_popcount(b[3]) != 1 || b[3] > 8
841         || AV_RL16(&b[4]) > AV_RL16(&b[8])
842         || AV_RL16(&b[6]) > AV_RL16(&b[10])
843         || b[64])
844         return 0;
845     b += 73;
846     while (++b < p->buf + 128)
847         if (*b)
848             return AVPROBE_SCORE_EXTENSION / 4;
849
850     return AVPROBE_SCORE_EXTENSION + 1;
851 }
852
853 static int qdraw_probe(const AVProbeData *p)
854 {
855     const uint8_t *b = p->buf;
856
857     if (   p->buf_size >= 528
858         && (AV_RB64(b + 520) & 0xFFFFFFFFFFFF) == 0x001102ff0c00
859         && AV_RB16(b + 520)
860         && AV_RB16(b + 518))
861         return AVPROBE_SCORE_MAX * 3 / 4;
862     if (   (AV_RB64(b + 8) & 0xFFFFFFFFFFFF) == 0x001102ff0c00
863         && AV_RB16(b + 8)
864         && AV_RB16(b + 6))
865         return AVPROBE_SCORE_EXTENSION / 4;
866     return 0;
867 }
868
869 static int pictor_probe(const AVProbeData *p)
870 {
871     const uint8_t *b = p->buf;
872
873     if (AV_RL16(b) == 0x1234)
874         return AVPROBE_SCORE_EXTENSION / 4;
875     return 0;
876 }
877
878 static int png_probe(const AVProbeData *p)
879 {
880     const uint8_t *b = p->buf;
881
882     if (AV_RB64(b) == 0x89504e470d0a1a0a)
883         return AVPROBE_SCORE_MAX - 1;
884     return 0;
885 }
886
887 static int psd_probe(const AVProbeData *p)
888 {
889     const uint8_t *b = p->buf;
890     int ret = 0;
891     uint16_t color_mode;
892
893     if (AV_RL32(b) == MKTAG('8','B','P','S')) {
894         ret += 1;
895     } else {
896         return 0;
897     }
898
899     if ((b[4] == 0) && (b[5] == 1)) {/* version 1 is PSD, version 2 is PSB */
900         ret += 1;
901     } else {
902         return 0;
903     }
904
905     if ((AV_RL32(b+6) == 0) && (AV_RL16(b+10) == 0))/* reserved must be 0 */
906         ret += 1;
907
908     color_mode = AV_RB16(b+24);
909     if ((color_mode <= 9) && (color_mode != 5) && (color_mode != 6))
910         ret += 1;
911
912     return AVPROBE_SCORE_EXTENSION + ret;
913 }
914
915 static int sgi_probe(const AVProbeData *p)
916 {
917     const uint8_t *b = p->buf;
918
919     if (AV_RB16(b) == 474 &&
920         (b[2] & ~1) == 0 &&
921         (b[3] & ~3) == 0 && b[3] &&
922         (AV_RB16(b + 4) & ~7) == 0 && AV_RB16(b + 4))
923         return AVPROBE_SCORE_EXTENSION + 1;
924     return 0;
925 }
926
927 static int sunrast_probe(const AVProbeData *p)
928 {
929     const uint8_t *b = p->buf;
930
931     if (AV_RB32(b) == 0x59a66a95)
932         return AVPROBE_SCORE_EXTENSION + 1;
933     return 0;
934 }
935
936 static int svg_probe(const AVProbeData *p)
937 {
938     const uint8_t *b = p->buf;
939     const uint8_t *end = p->buf + p->buf_size;
940
941     if (memcmp(p->buf, "<?xml", 5))
942         return 0;
943     while (b < end) {
944         int inc = ff_subtitles_next_line(b);
945         if (!inc)
946             break;
947         b += inc;
948         if (b >= end - 4)
949             return 0;
950         if (!memcmp(b, "<svg", 4))
951             return AVPROBE_SCORE_EXTENSION + 1;
952     }
953     return 0;
954 }
955
956 static int tiff_probe(const AVProbeData *p)
957 {
958     const uint8_t *b = p->buf;
959
960     if (AV_RB32(b) == 0x49492a00 ||
961         AV_RB32(b) == 0x4D4D002a)
962         return AVPROBE_SCORE_EXTENSION + 1;
963     return 0;
964 }
965
966 static int webp_probe(const AVProbeData *p)
967 {
968     const uint8_t *b = p->buf;
969
970     if (AV_RB32(b)     == 0x52494646 &&
971         AV_RB32(b + 8) == 0x57454250)
972         return AVPROBE_SCORE_MAX - 1;
973     return 0;
974 }
975
976 static int pnm_magic_check(const AVProbeData *p, int magic)
977 {
978     const uint8_t *b = p->buf;
979
980     return b[0] == 'P' && b[1] == magic + '0';
981 }
982
983 static inline int pnm_probe(const AVProbeData *p)
984 {
985     const uint8_t *b = p->buf;
986
987     while (b[2] == '\r')
988         b++;
989     if (b[2] == '\n' && (b[3] == '#' || (b[3] >= '0' && b[3] <= '9')))
990         return AVPROBE_SCORE_EXTENSION + 2;
991     return 0;
992 }
993
994 static int pbm_probe(const AVProbeData *p)
995 {
996     return pnm_magic_check(p, 1) || pnm_magic_check(p, 4) ? pnm_probe(p) : 0;
997 }
998
999 static inline int pgmx_probe(const AVProbeData *p)
1000 {
1001     return pnm_magic_check(p, 2) || pnm_magic_check(p, 5) ? pnm_probe(p) : 0;
1002 }
1003
1004 static int pgm_probe(const AVProbeData *p)
1005 {
1006     int ret = pgmx_probe(p);
1007     return ret && !av_match_ext(p->filename, "pgmyuv") ? ret : 0;
1008 }
1009
1010 static int pgmyuv_probe(const AVProbeData *p) // custom FFmpeg format recognized by file extension
1011 {
1012     int ret = pgmx_probe(p);
1013     return ret && av_match_ext(p->filename, "pgmyuv") ? ret : 0;
1014 }
1015
1016 static int pgx_probe(const AVProbeData *p)
1017 {
1018     const uint8_t *b = p->buf;
1019     if (!memcmp(b, "PG ML ", 6))
1020         return AVPROBE_SCORE_EXTENSION + 1;
1021     return 0;
1022 }
1023
1024 static int ppm_probe(const AVProbeData *p)
1025 {
1026     return pnm_magic_check(p, 3) || pnm_magic_check(p, 6) ? pnm_probe(p) : 0;
1027 }
1028
1029 static int pam_probe(const AVProbeData *p)
1030 {
1031     return pnm_magic_check(p, 7) ? pnm_probe(p) : 0;
1032 }
1033
1034 static int xbm_probe(const AVProbeData *p)
1035 {
1036     if (!memcmp(p->buf, "/* XBM X10 format */", 20))
1037         return AVPROBE_SCORE_MAX;
1038
1039     if (!memcmp(p->buf, "#define", 7))
1040         return AVPROBE_SCORE_MAX - 1;
1041     return 0;
1042 }
1043
1044 static int xpm_probe(const AVProbeData *p)
1045 {
1046     const uint8_t *b = p->buf;
1047
1048     if (AV_RB64(b) == 0x2f2a2058504d202a && *(b+8) == '/')
1049         return AVPROBE_SCORE_MAX - 1;
1050     return 0;
1051 }
1052
1053 static int xwd_probe(const AVProbeData *p)
1054 {
1055     const uint8_t *b = p->buf;
1056     unsigned width, bpp, bpad, lsize;
1057
1058     if (   p->buf_size < XWD_HEADER_SIZE
1059         || AV_RB32(b     ) < XWD_HEADER_SIZE                          // header size
1060         || AV_RB32(b +  4) != XWD_VERSION                             // version
1061         || AV_RB32(b +  8) != XWD_Z_PIXMAP                            // format
1062         || AV_RB32(b + 12) > 32 || !AV_RB32(b + 12)                   // depth
1063         || AV_RB32(b + 16) == 0                                       // width
1064         || AV_RB32(b + 20) == 0                                       // height
1065         || AV_RB32(b + 28) > 1                                        // byteorder
1066         || AV_RB32(b + 32) & ~56 || av_popcount(AV_RB32(b + 32)) != 1 // bitmap unit
1067         || AV_RB32(b + 36) > 1                                        // bitorder
1068         || AV_RB32(b + 40) & ~56 || av_popcount(AV_RB32(b + 40)) != 1 // padding
1069         || AV_RB32(b + 44) > 32 || !AV_RB32(b + 44)                   // bpp
1070         || AV_RB32(b + 68) > 256)                                     // colours
1071         return 0;
1072
1073     width = AV_RB32(b + 16);
1074     bpad  = AV_RB32(b + 40);
1075     bpp   = AV_RB32(b + 44);
1076     lsize = AV_RB32(b + 48);
1077     if (lsize < FFALIGN(width * bpp, bpad) >> 3)
1078         return 0;
1079
1080     return AVPROBE_SCORE_MAX / 2 + 1;
1081 }
1082
1083 static int gif_probe(const AVProbeData *p)
1084 {
1085     /* check magick */
1086     if (memcmp(p->buf, gif87a_sig, 6) && memcmp(p->buf, gif89a_sig, 6))
1087         return 0;
1088
1089     /* width or height contains zero? */
1090     if (!AV_RL16(&p->buf[6]) || !AV_RL16(&p->buf[8]))
1091         return 0;
1092
1093     return AVPROBE_SCORE_MAX - 1;
1094 }
1095
1096 static int photocd_probe(const AVProbeData *p)
1097 {
1098     if (!memcmp(p->buf, "PCD_OPA", 7))
1099         return AVPROBE_SCORE_MAX - 1;
1100
1101     if (p->buf_size < 0x807 || memcmp(p->buf + 0x800, "PCD_IPI", 7))
1102         return 0;
1103
1104     return AVPROBE_SCORE_MAX - 1;
1105 }
1106
1107 #define IMAGEAUTO_DEMUXER(imgname, codecid)\
1108 static const AVClass imgname ## _class = {\
1109     .class_name = AV_STRINGIFY(imgname) " demuxer",\
1110     .item_name  = av_default_item_name,\
1111     .option     = ff_img2pipe_options,\
1112     .version    = LIBAVUTIL_VERSION_INT,\
1113 };\
1114 AVInputFormat ff_image_ ## imgname ## _pipe_demuxer = {\
1115     .name           = AV_STRINGIFY(imgname) "_pipe",\
1116     .long_name      = NULL_IF_CONFIG_SMALL("piped " AV_STRINGIFY(imgname) " sequence"),\
1117     .priv_data_size = sizeof(VideoDemuxData),\
1118     .read_probe     = imgname ## _probe,\
1119     .read_header    = ff_img_read_header,\
1120     .read_packet    = ff_img_read_packet,\
1121     .priv_class     = & imgname ## _class,\
1122     .flags          = AVFMT_GENERIC_INDEX, \
1123     .raw_codec_id   = codecid,\
1124 };
1125
1126 IMAGEAUTO_DEMUXER(bmp,     AV_CODEC_ID_BMP)
1127 IMAGEAUTO_DEMUXER(cri,     AV_CODEC_ID_CRI)
1128 IMAGEAUTO_DEMUXER(dds,     AV_CODEC_ID_DDS)
1129 IMAGEAUTO_DEMUXER(dpx,     AV_CODEC_ID_DPX)
1130 IMAGEAUTO_DEMUXER(exr,     AV_CODEC_ID_EXR)
1131 IMAGEAUTO_DEMUXER(gif,     AV_CODEC_ID_GIF)
1132 IMAGEAUTO_DEMUXER(j2k,     AV_CODEC_ID_JPEG2000)
1133 IMAGEAUTO_DEMUXER(jpeg,    AV_CODEC_ID_MJPEG)
1134 IMAGEAUTO_DEMUXER(jpegls,  AV_CODEC_ID_JPEGLS)
1135 IMAGEAUTO_DEMUXER(pam,     AV_CODEC_ID_PAM)
1136 IMAGEAUTO_DEMUXER(pbm,     AV_CODEC_ID_PBM)
1137 IMAGEAUTO_DEMUXER(pcx,     AV_CODEC_ID_PCX)
1138 IMAGEAUTO_DEMUXER(pgm,     AV_CODEC_ID_PGM)
1139 IMAGEAUTO_DEMUXER(pgmyuv,  AV_CODEC_ID_PGMYUV)
1140 IMAGEAUTO_DEMUXER(pgx,     AV_CODEC_ID_PGX)
1141 IMAGEAUTO_DEMUXER(photocd, AV_CODEC_ID_PHOTOCD)
1142 IMAGEAUTO_DEMUXER(pictor,  AV_CODEC_ID_PICTOR)
1143 IMAGEAUTO_DEMUXER(png,     AV_CODEC_ID_PNG)
1144 IMAGEAUTO_DEMUXER(ppm,     AV_CODEC_ID_PPM)
1145 IMAGEAUTO_DEMUXER(psd,     AV_CODEC_ID_PSD)
1146 IMAGEAUTO_DEMUXER(qdraw,   AV_CODEC_ID_QDRAW)
1147 IMAGEAUTO_DEMUXER(sgi,     AV_CODEC_ID_SGI)
1148 IMAGEAUTO_DEMUXER(sunrast, AV_CODEC_ID_SUNRAST)
1149 IMAGEAUTO_DEMUXER(svg,     AV_CODEC_ID_SVG)
1150 IMAGEAUTO_DEMUXER(tiff,    AV_CODEC_ID_TIFF)
1151 IMAGEAUTO_DEMUXER(webp,    AV_CODEC_ID_WEBP)
1152 IMAGEAUTO_DEMUXER(xbm,     AV_CODEC_ID_XBM)
1153 IMAGEAUTO_DEMUXER(xpm,     AV_CODEC_ID_XPM)
1154 IMAGEAUTO_DEMUXER(xwd,     AV_CODEC_ID_XWD)