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