]> git.sesse.net Git - ffmpeg/blob - libavformat/img2.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / img2.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/intreadwrite.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/log.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/parseutils.h"
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "internal.h"
32
33 typedef struct {
34     const AVClass *class;  /**< Class for private options. */
35     int img_first;
36     int img_last;
37     int img_number;
38     int img_count;
39     int is_pipe;
40     int split_planes;  /**< use independent file for each Y, U, V plane */
41     char path[1024];
42     char *pixel_format;     /**< Set by a private option. */
43     char *video_size;       /**< Set by a private option. */
44     char *framerate;        /**< Set by a private option. */
45     int loop;
46     int updatefirst;
47 } VideoData;
48
49 typedef struct {
50     enum CodecID id;
51     const char *str;
52 } IdStrMap;
53
54 static const IdStrMap img_tags[] = {
55     { CODEC_ID_MJPEG     , "jpeg"},
56     { CODEC_ID_MJPEG     , "jpg"},
57     { CODEC_ID_MJPEG     , "jps"},
58     { CODEC_ID_LJPEG     , "ljpg"},
59     { CODEC_ID_JPEGLS    , "jls"},
60     { CODEC_ID_PNG       , "png"},
61     { CODEC_ID_PNG       , "pns"},
62     { CODEC_ID_PNG       , "mng"},
63     { CODEC_ID_PPM       , "ppm"},
64     { CODEC_ID_PPM       , "pnm"},
65     { CODEC_ID_PGM       , "pgm"},
66     { CODEC_ID_PGMYUV    , "pgmyuv"},
67     { CODEC_ID_PBM       , "pbm"},
68     { CODEC_ID_PAM       , "pam"},
69     { CODEC_ID_MPEG1VIDEO, "mpg1-img"},
70     { CODEC_ID_MPEG2VIDEO, "mpg2-img"},
71     { CODEC_ID_MPEG4     , "mpg4-img"},
72     { CODEC_ID_FFV1      , "ffv1-img"},
73     { CODEC_ID_RAWVIDEO  , "y"},
74     { CODEC_ID_RAWVIDEO  , "raw"},
75     { CODEC_ID_BMP       , "bmp"},
76     { CODEC_ID_GIF       , "gif"},
77     { CODEC_ID_TARGA     , "tga"},
78     { CODEC_ID_TIFF      , "tiff"},
79     { CODEC_ID_TIFF      , "tif"},
80     { CODEC_ID_SGI       , "sgi"},
81     { CODEC_ID_PTX       , "ptx"},
82     { CODEC_ID_PCX       , "pcx"},
83     { CODEC_ID_SUNRAST   , "sun"},
84     { CODEC_ID_SUNRAST   , "ras"},
85     { CODEC_ID_SUNRAST   , "rs"},
86     { CODEC_ID_SUNRAST   , "im1"},
87     { CODEC_ID_SUNRAST   , "im8"},
88     { CODEC_ID_SUNRAST   , "im24"},
89     { CODEC_ID_SUNRAST   , "sunras"},
90     { CODEC_ID_JPEG2000  , "j2c"},
91     { CODEC_ID_JPEG2000  , "j2k"},
92     { CODEC_ID_JPEG2000  , "jp2"},
93     { CODEC_ID_JPEG2000  , "jpc"},
94     { CODEC_ID_DPX       , "dpx"},
95     { CODEC_ID_PICTOR    , "pic"},
96     { CODEC_ID_XWD       , "xwd"},
97     { CODEC_ID_NONE      , NULL}
98 };
99
100 static const int sizes[][2] = {
101     { 640, 480 },
102     { 720, 480 },
103     { 720, 576 },
104     { 352, 288 },
105     { 352, 240 },
106     { 160, 128 },
107     { 512, 384 },
108     { 640, 352 },
109     { 640, 240 },
110 };
111
112 static int infer_size(int *width_ptr, int *height_ptr, int size)
113 {
114     int i;
115
116     for(i=0;i<FF_ARRAY_ELEMS(sizes);i++) {
117         if ((sizes[i][0] * sizes[i][1]) == size) {
118             *width_ptr = sizes[i][0];
119             *height_ptr = sizes[i][1];
120             return 0;
121         }
122     }
123     return -1;
124 }
125 static enum CodecID av_str2id(const IdStrMap *tags, const char *str)
126 {
127     str= strrchr(str, '.');
128     if(!str) return CODEC_ID_NONE;
129     str++;
130
131     while (tags->id) {
132         if (!av_strcasecmp(str, tags->str))
133             return tags->id;
134
135         tags++;
136     }
137     return CODEC_ID_NONE;
138 }
139
140 /* return -1 if no image found */
141 static int find_image_range(int *pfirst_index, int *plast_index,
142                             const char *path)
143 {
144     char buf[1024];
145     int range, last_index, range1, first_index;
146
147     /* find the first image */
148     for(first_index = 0; first_index < 5; first_index++) {
149         if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
150             *pfirst_index =
151             *plast_index = 1;
152             if (avio_check(buf, AVIO_FLAG_READ) > 0)
153                 return 0;
154             return -1;
155         }
156         if (avio_check(buf, AVIO_FLAG_READ) > 0)
157             break;
158     }
159     if (first_index == 5)
160         goto fail;
161
162     /* find the last image */
163     last_index = first_index;
164     for(;;) {
165         range = 0;
166         for(;;) {
167             if (!range)
168                 range1 = 1;
169             else
170                 range1 = 2 * range;
171             if (av_get_frame_filename(buf, sizeof(buf), path,
172                                       last_index + range1) < 0)
173                 goto fail;
174             if (avio_check(buf, AVIO_FLAG_READ) <= 0)
175                 break;
176             range = range1;
177             /* just in case... */
178             if (range >= (1 << 30))
179                 goto fail;
180         }
181         /* we are sure than image last_index + range exists */
182         if (!range)
183             break;
184         last_index += range;
185     }
186     *pfirst_index = first_index;
187     *plast_index = last_index;
188     return 0;
189  fail:
190     return -1;
191 }
192
193
194 static int read_probe(AVProbeData *p)
195 {
196     if (p->filename && av_str2id(img_tags, p->filename)) {
197         if (av_filename_number_test(p->filename))
198             return AVPROBE_SCORE_MAX;
199         else
200             return AVPROBE_SCORE_MAX/2;
201     }
202     return 0;
203 }
204
205 enum CodecID ff_guess_image2_codec(const char *filename)
206 {
207     return av_str2id(img_tags, filename);
208 }
209
210 static int read_header(AVFormatContext *s1)
211 {
212     VideoData *s = s1->priv_data;
213     int first_index, last_index, ret = 0;
214     int width = 0, height = 0;
215     AVStream *st;
216     enum PixelFormat pix_fmt = PIX_FMT_NONE;
217     AVRational framerate;
218
219     s1->ctx_flags |= AVFMTCTX_NOHEADER;
220
221     st = avformat_new_stream(s1, NULL);
222     if (!st) {
223         return AVERROR(ENOMEM);
224     }
225
226     if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
227         av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
228         return AVERROR(EINVAL);
229     }
230     if (s->video_size && (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
231         av_log(s, AV_LOG_ERROR, "Could not parse video size: %s.\n", s->video_size);
232         return ret;
233     }
234     if ((ret = av_parse_video_rate(&framerate, s->framerate)) < 0) {
235         av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s->framerate);
236         return ret;
237     }
238
239     av_strlcpy(s->path, s1->filename, sizeof(s->path));
240     s->img_number = 0;
241     s->img_count = 0;
242
243     /* find format */
244     if (s1->iformat->flags & AVFMT_NOFILE)
245         s->is_pipe = 0;
246     else{
247         s->is_pipe = 1;
248         st->need_parsing = AVSTREAM_PARSE_FULL;
249     }
250
251     avpriv_set_pts_info(st, 60, framerate.den, framerate.num);
252
253     if (width && height) {
254         st->codec->width  = width;
255         st->codec->height = height;
256     }
257
258     if (!s->is_pipe) {
259         if (find_image_range(&first_index, &last_index, s->path) < 0)
260             return AVERROR(ENOENT);
261         s->img_first = first_index;
262         s->img_last = last_index;
263         s->img_number = first_index;
264         /* compute duration */
265         st->start_time = 0;
266         st->duration = last_index - first_index + 1;
267     }
268
269     if(s1->video_codec_id){
270         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
271         st->codec->codec_id = s1->video_codec_id;
272     }else if(s1->audio_codec_id){
273         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
274         st->codec->codec_id = s1->audio_codec_id;
275     }else{
276         const char *str= strrchr(s->path, '.');
277         s->split_planes = str && !av_strcasecmp(str + 1, "y");
278         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
279         st->codec->codec_id = av_str2id(img_tags, s->path);
280         if (st->codec->codec_id == CODEC_ID_LJPEG)
281             st->codec->codec_id = CODEC_ID_MJPEG;
282     }
283     if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pix_fmt != PIX_FMT_NONE)
284         st->codec->pix_fmt = pix_fmt;
285
286     return 0;
287 }
288
289 static int read_packet(AVFormatContext *s1, AVPacket *pkt)
290 {
291     VideoData *s = s1->priv_data;
292     char filename[1024];
293     int i;
294     int size[3]={0}, ret[3]={0};
295     AVIOContext *f[3];
296     AVCodecContext *codec= s1->streams[0]->codec;
297
298     if (!s->is_pipe) {
299         /* loop over input */
300         if (s->loop && s->img_number > s->img_last) {
301             s->img_number = s->img_first;
302         }
303         if (s->img_number > s->img_last)
304             return AVERROR_EOF;
305         if (av_get_frame_filename(filename, sizeof(filename),
306                                   s->path, s->img_number)<0 && s->img_number > 1)
307             return AVERROR(EIO);
308         for(i=0; i<3; i++){
309             if (avio_open2(&f[i], filename, AVIO_FLAG_READ,
310                            &s1->interrupt_callback, NULL) < 0) {
311                 if(i==1)
312                     break;
313                 av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);
314                 return AVERROR(EIO);
315             }
316             size[i]= avio_size(f[i]);
317
318             if(!s->split_planes)
319                 break;
320             filename[ strlen(filename) - 1 ]= 'U' + i;
321         }
322
323         if(codec->codec_id == CODEC_ID_RAWVIDEO && !codec->width)
324             infer_size(&codec->width, &codec->height, size[0]);
325     } else {
326         f[0] = s1->pb;
327         if (url_feof(f[0]))
328             return AVERROR(EIO);
329         size[0]= 4096;
330     }
331
332     av_new_packet(pkt, size[0] + size[1] + size[2]);
333     pkt->stream_index = 0;
334     pkt->flags |= AV_PKT_FLAG_KEY;
335
336     pkt->size= 0;
337     for(i=0; i<3; i++){
338         if(size[i]){
339             ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);
340             if (!s->is_pipe)
341                 avio_close(f[i]);
342             if(ret[i]>0)
343                 pkt->size += ret[i];
344         }
345     }
346
347     if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {
348         av_free_packet(pkt);
349         return AVERROR(EIO); /* signal EOF */
350     } else {
351         s->img_count++;
352         s->img_number++;
353         return 0;
354     }
355 }
356
357 #if CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER
358 /******************************************************/
359 /* image output */
360
361 static int write_header(AVFormatContext *s)
362 {
363     VideoData *img = s->priv_data;
364     const char *str;
365
366     img->img_number = 1;
367     av_strlcpy(img->path, s->filename, sizeof(img->path));
368
369     /* find format */
370     if (s->oformat->flags & AVFMT_NOFILE)
371         img->is_pipe = 0;
372     else
373         img->is_pipe = 1;
374
375     str = strrchr(img->path, '.');
376     img->split_planes = str && !av_strcasecmp(str + 1, "y");
377     return 0;
378 }
379
380 static int write_packet(AVFormatContext *s, AVPacket *pkt)
381 {
382     VideoData *img = s->priv_data;
383     AVIOContext *pb[3];
384     char filename[1024];
385     AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec;
386     int i;
387
388     if (!img->is_pipe) {
389         if (av_get_frame_filename(filename, sizeof(filename),
390                                   img->path, img->img_number) < 0 && img->img_number>1 && !img->updatefirst) {
391             av_log(s, AV_LOG_ERROR,
392                    "Could not get frame filename number %d from pattern '%s'\n",
393                    img->img_number, img->path);
394             return AVERROR(EINVAL);
395         }
396         for(i=0; i<3; i++){
397             if (avio_open2(&pb[i], filename, AVIO_FLAG_WRITE,
398                            &s->interrupt_callback, NULL) < 0) {
399                 av_log(s, AV_LOG_ERROR, "Could not open file : %s\n",filename);
400                 return AVERROR(EIO);
401             }
402
403             if(!img->split_planes)
404                 break;
405             filename[ strlen(filename) - 1 ]= 'U' + i;
406         }
407     } else {
408         pb[0] = s->pb;
409     }
410
411     if(img->split_planes){
412         int ysize = codec->width * codec->height;
413         avio_write(pb[0], pkt->data        , ysize);
414         avio_write(pb[1], pkt->data + ysize, (pkt->size - ysize)/2);
415         avio_write(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2);
416         avio_flush(pb[1]);
417         avio_flush(pb[2]);
418         avio_close(pb[1]);
419         avio_close(pb[2]);
420     }else{
421         if(av_str2id(img_tags, s->filename) == CODEC_ID_JPEG2000){
422             AVStream *st = s->streams[0];
423             if(st->codec->extradata_size > 8 &&
424                AV_RL32(st->codec->extradata+4) == MKTAG('j','p','2','h')){
425                 if(pkt->size < 8 || AV_RL32(pkt->data+4) != MKTAG('j','p','2','c'))
426                     goto error;
427                 avio_wb32(pb[0], 12);
428                 ffio_wfourcc(pb[0], "jP  ");
429                 avio_wb32(pb[0], 0x0D0A870A); // signature
430                 avio_wb32(pb[0], 20);
431                 ffio_wfourcc(pb[0], "ftyp");
432                 ffio_wfourcc(pb[0], "jp2 ");
433                 avio_wb32(pb[0], 0);
434                 ffio_wfourcc(pb[0], "jp2 ");
435                 avio_write(pb[0], st->codec->extradata, st->codec->extradata_size);
436             }else if(pkt->size >= 8 && AV_RB32(pkt->data) == 0xFF4FFF51){
437                 //jpeg2000 codestream
438             }else if(pkt->size < 8 ||
439                      (!st->codec->extradata_size &&
440                       AV_RL32(pkt->data+4) != MKTAG('j','P',' ',' '))){ // signature
441             error:
442                 av_log(s, AV_LOG_ERROR, "malformed JPEG 2000 codestream %X\n", AV_RB32(pkt->data));
443                 return -1;
444             }
445         }
446         avio_write(pb[0], pkt->data, pkt->size);
447     }
448     avio_flush(pb[0]);
449     if (!img->is_pipe) {
450         avio_close(pb[0]);
451     }
452
453     img->img_number++;
454     return 0;
455 }
456
457 #endif /* CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER */
458
459 #define OFFSET(x) offsetof(VideoData, x)
460 #define DEC AV_OPT_FLAG_DECODING_PARAM
461 #define ENC AV_OPT_FLAG_ENCODING_PARAM
462 static const AVOption options[] = {
463     { "pixel_format", "", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
464     { "video_size",   "", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
465     { "framerate",    "", OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, DEC },
466     { "loop",         "", OFFSET(loop),         AV_OPT_TYPE_INT,    {.dbl = 0},    0, 1, DEC },
467     { NULL },
468 };
469
470 static const AVOption muxoptions[] = {
471     { "updatefirst",  "", OFFSET(updatefirst),  AV_OPT_TYPE_INT,    {.dbl = 0},    0, 1, ENC },
472     { NULL },
473 };
474
475 /* input */
476 #if CONFIG_IMAGE2_DEMUXER
477 static const AVClass img2_class = {
478     .class_name = "image2 demuxer",
479     .item_name  = av_default_item_name,
480     .option     = options,
481     .version    = LIBAVUTIL_VERSION_INT,
482 };
483 AVInputFormat ff_image2_demuxer = {
484     .name           = "image2",
485     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
486     .priv_data_size = sizeof(VideoData),
487     .read_probe     = read_probe,
488     .read_header    = read_header,
489     .read_packet    = read_packet,
490     .flags          = AVFMT_NOFILE,
491     .priv_class     = &img2_class,
492 };
493 #endif
494 #if CONFIG_IMAGE2PIPE_DEMUXER
495 static const AVClass img2pipe_class = {
496     .class_name = "image2pipe demuxer",
497     .item_name  = av_default_item_name,
498     .option     = options,
499     .version    = LIBAVUTIL_VERSION_INT,
500 };
501 AVInputFormat ff_image2pipe_demuxer = {
502     .name           = "image2pipe",
503     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
504     .priv_data_size = sizeof(VideoData),
505     .read_header    = read_header,
506     .read_packet    = read_packet,
507     .priv_class     = &img2pipe_class,
508 };
509 #endif
510
511 /* output */
512 #if CONFIG_IMAGE2_MUXER
513 static const AVClass img2mux_class = {
514     .class_name = "image2 muxer",
515     .item_name  = av_default_item_name,
516     .option     = muxoptions,
517     .version    = LIBAVUTIL_VERSION_INT,
518 };
519 AVOutputFormat ff_image2_muxer = {
520     .name           = "image2",
521     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
522     .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
523                       "ppm,sgi,tga,tif,tiff,jp2,j2c,xwd",
524     .priv_data_size = sizeof(VideoData),
525     .video_codec    = CODEC_ID_MJPEG,
526     .write_header   = write_header,
527     .write_packet   = write_packet,
528     .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE,
529     .priv_class     = &img2mux_class,
530 };
531 #endif
532 #if CONFIG_IMAGE2PIPE_MUXER
533 AVOutputFormat ff_image2pipe_muxer = {
534     .name           = "image2pipe",
535     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
536     .priv_data_size = sizeof(VideoData),
537     .video_codec    = CODEC_ID_MJPEG,
538     .write_header   = write_header,
539     .write_packet   = write_packet,
540     .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
541 };
542 #endif