img2.c 16.7 KB
Newer Older
1 2
/*
 * Image format
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 5
 * Copyright (c) 2004 Michael Niedermayer
 *
6 7 8
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
9 10
 * modify it under the terms of the GNU Lesser General Public
 * 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 15 16 17 18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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 26 27
#include "libavutil/log.h"
#include "libavutil/opt.h"
#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 36 37 38 39
    int img_first;
    int img_last;
    int img_number;
    int img_count;
    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. */
A
Anton Khirnov 已提交
45
    int loop;
46
    int updatefirst;
47 48 49 50 51 52 53 54 55 56
} VideoData;

typedef struct {
    enum CodecID id;
    const char *str;
} IdStrMap;

static const IdStrMap img_tags[] = {
    { CODEC_ID_MJPEG     , "jpeg"},
    { CODEC_ID_MJPEG     , "jpg"},
57
    { CODEC_ID_LJPEG     , "ljpg"},
58
    { CODEC_ID_JPEGLS    , "jls"},
59
    { CODEC_ID_PNG       , "png"},
L
Loren Merritt 已提交
60
    { CODEC_ID_PNG       , "mng"},
61
    { CODEC_ID_PPM       , "ppm"},
C
Carl Eugen Hoyos 已提交
62
    { CODEC_ID_PPM       , "pnm"},
63 64 65 66
    { CODEC_ID_PGM       , "pgm"},
    { CODEC_ID_PGMYUV    , "pgmyuv"},
    { CODEC_ID_PBM       , "pbm"},
    { CODEC_ID_PAM       , "pam"},
67 68 69 70
    { CODEC_ID_MPEG1VIDEO, "mpg1-img"},
    { CODEC_ID_MPEG2VIDEO, "mpg2-img"},
    { CODEC_ID_MPEG4     , "mpg4-img"},
    { CODEC_ID_FFV1      , "ffv1-img"},
M
Michael Niedermayer 已提交
71
    { CODEC_ID_RAWVIDEO  , "y"},
72
    { CODEC_ID_RAWVIDEO  , "raw"},
M
Måns Rullgård 已提交
73
    { CODEC_ID_BMP       , "bmp"},
B
Baptiste Coudurier 已提交
74
    { CODEC_ID_GIF       , "gif"},
75 76
    { CODEC_ID_TARGA     , "tga"},
    { CODEC_ID_TIFF      , "tiff"},
Q
Quoc Cuong Pham 已提交
77
    { CODEC_ID_TIFF      , "tif"},
78
    { CODEC_ID_SGI       , "sgi"},
I
Ivo van Poorten 已提交
79
    { CODEC_ID_PTX       , "ptx"},
I
Ivo van Poorten 已提交
80
    { CODEC_ID_PCX       , "pcx"},
I
Ivo van Poorten 已提交
81 82 83 84 85 86 87
    { CODEC_ID_SUNRAST   , "sun"},
    { CODEC_ID_SUNRAST   , "ras"},
    { CODEC_ID_SUNRAST   , "rs"},
    { CODEC_ID_SUNRAST   , "im1"},
    { CODEC_ID_SUNRAST   , "im8"},
    { CODEC_ID_SUNRAST   , "im24"},
    { CODEC_ID_SUNRAST   , "sunras"},
J
Jean First 已提交
88
    { CODEC_ID_JPEG2000  , "j2c"},
89
    { CODEC_ID_JPEG2000  , "j2k"},
B
Benoit Fouet 已提交
90
    { CODEC_ID_JPEG2000  , "jp2"},
K
Kamil Nowosad 已提交
91
    { CODEC_ID_JPEG2000  , "jpc"},
92
    { CODEC_ID_DPX       , "dpx"},
93
    { CODEC_ID_PICTOR    , "pic"},
94
    { CODEC_ID_NONE      , NULL}
95 96
};

97
static const int sizes[][2] = {
M
Michael Niedermayer 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    { 640, 480 },
    { 720, 480 },
    { 720, 576 },
    { 352, 288 },
    { 352, 240 },
    { 160, 128 },
    { 512, 384 },
    { 640, 352 },
    { 640, 240 },
};

static int infer_size(int *width_ptr, int *height_ptr, int size)
{
    int i;

113
    for(i=0;i<FF_ARRAY_ELEMS(sizes);i++) {
M
Michael Niedermayer 已提交
114 115 116 117 118 119 120 121
        if ((sizes[i][0] * sizes[i][1]) == size) {
            *width_ptr = sizes[i][0];
            *height_ptr = sizes[i][1];
            return 0;
        }
    }
    return -1;
}
122 123
static enum CodecID av_str2id(const IdStrMap *tags, const char *str)
{
M
10l  
Michael Niedermayer 已提交
124 125 126
    str= strrchr(str, '.');
    if(!str) return CODEC_ID_NONE;
    str++;
127 128

    while (tags->id) {
129
        if (!av_strcasecmp(str, tags->str))
130
            return tags->id;
131 132 133 134 135 136 137

        tags++;
    }
    return CODEC_ID_NONE;
}

/* return -1 if no image found */
138
static int find_image_range(int *pfirst_index, int *plast_index,
139 140 141 142 143 144 145
                            const char *path)
{
    char buf[1024];
    int range, last_index, range1, first_index;

    /* find the first image */
    for(first_index = 0; first_index < 5; first_index++) {
146
        if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){
147
            *pfirst_index =
148
            *plast_index = 1;
149
            if (avio_check(buf, AVIO_FLAG_READ) > 0)
150 151
                return 0;
            return -1;
152
        }
153
        if (avio_check(buf, AVIO_FLAG_READ) > 0)
154 155 156 157
            break;
    }
    if (first_index == 5)
        goto fail;
158

159 160 161 162 163 164 165 166 167
    /* find the last image */
    last_index = first_index;
    for(;;) {
        range = 0;
        for(;;) {
            if (!range)
                range1 = 1;
            else
                range1 = 2 * range;
168 169
            if (av_get_frame_filename(buf, sizeof(buf), path,
                                      last_index + range1) < 0)
170
                goto fail;
171
            if (avio_check(buf, AVIO_FLAG_READ) <= 0)
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
                break;
            range = range1;
            /* just in case... */
            if (range >= (1 << 30))
                goto fail;
        }
        /* we are sure than image last_index + range exists */
        if (!range)
            break;
        last_index += range;
    }
    *pfirst_index = first_index;
    *plast_index = last_index;
    return 0;
 fail:
    return -1;
}


191
static int read_probe(AVProbeData *p)
192
{
193
    if (p->filename && av_str2id(img_tags, p->filename)) {
194 195 196 197 198 199
        if (av_filename_number_test(p->filename))
            return AVPROBE_SCORE_MAX;
        else
            return AVPROBE_SCORE_MAX/2;
    }
    return 0;
200 201
}

202 203 204 205 206 207
enum CodecID ff_guess_image2_codec(const char *filename)
{
    return av_str2id(img_tags, filename);
}

#if FF_API_GUESS_IMG2_CODEC
208 209 210
enum CodecID av_guess_image2_codec(const char *filename){
    return av_str2id(img_tags, filename);
}
211
#endif
212

213
static int read_header(AVFormatContext *s1, AVFormatParameters *ap)
214 215
{
    VideoData *s = s1->priv_data;
216 217
    int first_index, last_index, ret = 0;
    int width = 0, height = 0;
218
    AVStream *st;
219
    enum PixelFormat pix_fmt = PIX_FMT_NONE;
220
    AVRational framerate;
221 222 223

    s1->ctx_flags |= AVFMTCTX_NOHEADER;

224
    st = avformat_new_stream(s1, NULL);
225
    if (!st) {
226
        return AVERROR(ENOMEM);
227 228
    }

229 230 231 232
    if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
        av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
        return AVERROR(EINVAL);
    }
233 234 235 236
    if (s->video_size && (ret = av_parse_video_size(&width, &height, s->video_size)) < 0) {
        av_log(s, AV_LOG_ERROR, "Could not parse video size: %s.\n", s->video_size);
        return ret;
    }
237 238 239 240
    if ((ret = av_parse_video_rate(&framerate, s->framerate)) < 0) {
        av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s->framerate);
        return ret;
    }
241

A
Anton Khirnov 已提交
242 243 244 245 246
#if FF_API_LOOP_INPUT
    if (s1->loop_input)
        s->loop = s1->loop_input;
#endif

M
Måns Rullgård 已提交
247
    av_strlcpy(s->path, s1->filename, sizeof(s->path));
248 249
    s->img_number = 0;
    s->img_count = 0;
250

251 252 253
    /* find format */
    if (s1->iformat->flags & AVFMT_NOFILE)
        s->is_pipe = 0;
M
Michael Niedermayer 已提交
254
    else{
255
        s->is_pipe = 1;
A
Aurelien Jacobs 已提交
256
        st->need_parsing = AVSTREAM_PARSE_FULL;
M
Michael Niedermayer 已提交
257
    }
258

259
    avpriv_set_pts_info(st, 60, framerate.den, framerate.num);
260

261 262 263
    if (width && height) {
        st->codec->width  = width;
        st->codec->height = height;
M
Michael Niedermayer 已提交
264
    }
265

266 267
    if (!s->is_pipe) {
        if (find_image_range(&first_index, &last_index, s->path) < 0)
268
            return AVERROR(ENOENT);
269 270 271 272 273
        s->img_first = first_index;
        s->img_last = last_index;
        s->img_number = first_index;
        /* compute duration */
        st->start_time = 0;
274
        st->duration = last_index - first_index + 1;
275
    }
276

277
    if(s1->video_codec_id){
278
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
279 280
        st->codec->codec_id = s1->video_codec_id;
    }else if(s1->audio_codec_id){
281
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
282
        st->codec->codec_id = s1->audio_codec_id;
283
    }else{
284
        const char *str= strrchr(s->path, '.');
285
        s->split_planes = str && !av_strcasecmp(str + 1, "y");
286
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
287
        st->codec->codec_id = av_str2id(img_tags, s->path);
M
Michael Niedermayer 已提交
288
        if (st->codec->codec_id == CODEC_ID_LJPEG)
289
            st->codec->codec_id = CODEC_ID_MJPEG;
290
    }
291 292
    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pix_fmt != PIX_FMT_NONE)
        st->codec->pix_fmt = pix_fmt;
293 294 295 296

    return 0;
}

297
static int read_packet(AVFormatContext *s1, AVPacket *pkt)
298 299 300
{
    VideoData *s = s1->priv_data;
    char filename[1024];
M
Michael Niedermayer 已提交
301 302
    int i;
    int size[3]={0}, ret[3]={0};
303
    AVIOContext *f[3];
304
    AVCodecContext *codec= s1->streams[0]->codec;
305 306 307

    if (!s->is_pipe) {
        /* loop over input */
A
Anton Khirnov 已提交
308
        if (s->loop && s->img_number > s->img_last) {
309
            s->img_number = s->img_first;
M
Michael Niedermayer 已提交
310
        }
311 312
        if (s->img_number > s->img_last)
            return AVERROR_EOF;
313 314
        if (av_get_frame_filename(filename, sizeof(filename),
                                  s->path, s->img_number)<0 && s->img_number > 1)
315
            return AVERROR(EIO);
M
Michael Niedermayer 已提交
316
        for(i=0; i<3; i++){
317 318
            if (avio_open2(&f[i], filename, AVIO_FLAG_READ,
                           &s1->interrupt_callback, NULL) < 0) {
319 320
                if(i==1)
                    break;
321
                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename);
322
                return AVERROR(EIO);
323
            }
A
Anton Khirnov 已提交
324
            size[i]= avio_size(f[i]);
325

326
            if(!s->split_planes)
M
Michael Niedermayer 已提交
327 328 329
                break;
            filename[ strlen(filename) - 1 ]= 'U' + i;
        }
330

M
Michael Niedermayer 已提交
331 332
        if(codec->codec_id == CODEC_ID_RAWVIDEO && !codec->width)
            infer_size(&codec->width, &codec->height, size[0]);
333
    } else {
334
        f[0] = s1->pb;
M
Michael Niedermayer 已提交
335
        if (url_feof(f[0]))
336
            return AVERROR(EIO);
M
Michael Niedermayer 已提交
337
        size[0]= 4096;
338 339
    }

M
Michael Niedermayer 已提交
340
    av_new_packet(pkt, size[0] + size[1] + size[2]);
341
    pkt->stream_index = 0;
342
    pkt->flags |= AV_PKT_FLAG_KEY;
343

M
Michael Niedermayer 已提交
344 345 346
    pkt->size= 0;
    for(i=0; i<3; i++){
        if(size[i]){
347
            ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]);
M
Michael Niedermayer 已提交
348
            if (!s->is_pipe)
349
                avio_close(f[i]);
M
Michael Niedermayer 已提交
350 351 352
            if(ret[i]>0)
                pkt->size += ret[i];
        }
353 354
    }

M
Michael Niedermayer 已提交
355
    if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) {
356
        av_free_packet(pkt);
357
        return AVERROR(EIO); /* signal EOF */
358 359 360 361 362 363 364
    } else {
        s->img_count++;
        s->img_number++;
        return 0;
    }
}

365
#if CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER
366 367 368
/******************************************************/
/* image output */

369
static int write_header(AVFormatContext *s)
370 371
{
    VideoData *img = s->priv_data;
372
    const char *str;
373 374

    img->img_number = 1;
M
Måns Rullgård 已提交
375
    av_strlcpy(img->path, s->filename, sizeof(img->path));
376 377 378 379 380 381

    /* find format */
    if (s->oformat->flags & AVFMT_NOFILE)
        img->is_pipe = 0;
    else
        img->is_pipe = 1;
382

383
    str = strrchr(img->path, '.');
384
    img->split_planes = str && !av_strcasecmp(str + 1, "y");
385 386 387
    return 0;
}

388
static int write_packet(AVFormatContext *s, AVPacket *pkt)
389 390
{
    VideoData *img = s->priv_data;
391
    AVIOContext *pb[3];
392
    char filename[1024];
393
    AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec;
M
Michael Niedermayer 已提交
394
    int i;
395 396

    if (!img->is_pipe) {
397
        if (av_get_frame_filename(filename, sizeof(filename),
398 399 400 401 402
                                  img->path, img->img_number) < 0 && img->img_number>1 && !img->updatefirst) {
            av_log(s, AV_LOG_ERROR,
                   "Could not get frame filename number %d from pattern '%s'\n",
                   img->img_number, img->path);
            return AVERROR(EINVAL);
403
        }
M
Michael Niedermayer 已提交
404
        for(i=0; i<3; i++){
405 406
            if (avio_open2(&pb[i], filename, AVIO_FLAG_WRITE,
                           &s->interrupt_callback, NULL) < 0) {
407
                av_log(s, AV_LOG_ERROR, "Could not open file : %s\n",filename);
408
                return AVERROR(EIO);
409
            }
410

411
            if(!img->split_planes)
M
Michael Niedermayer 已提交
412 413 414
                break;
            filename[ strlen(filename) - 1 ]= 'U' + i;
        }
415
    } else {
416
        pb[0] = s->pb;
417
    }
418

419
    if(img->split_planes){
420
        int ysize = codec->width * codec->height;
421 422 423
        avio_write(pb[0], pkt->data        , ysize);
        avio_write(pb[1], pkt->data + ysize, (pkt->size - ysize)/2);
        avio_write(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2);
424 425
        avio_flush(pb[1]);
        avio_flush(pb[2]);
426 427
        avio_close(pb[1]);
        avio_close(pb[2]);
M
Michael Niedermayer 已提交
428
    }else{
429 430 431 432 433 434
        if(av_str2id(img_tags, s->filename) == CODEC_ID_JPEG2000){
            AVStream *st = s->streams[0];
            if(st->codec->extradata_size > 8 &&
               AV_RL32(st->codec->extradata+4) == MKTAG('j','p','2','h')){
                if(pkt->size < 8 || AV_RL32(pkt->data+4) != MKTAG('j','p','2','c'))
                    goto error;
435
                avio_wb32(pb[0], 12);
436
                ffio_wfourcc(pb[0], "jP  ");
437 438
                avio_wb32(pb[0], 0x0D0A870A); // signature
                avio_wb32(pb[0], 20);
439 440
                ffio_wfourcc(pb[0], "ftyp");
                ffio_wfourcc(pb[0], "jp2 ");
441
                avio_wb32(pb[0], 0);
442
                ffio_wfourcc(pb[0], "jp2 ");
443
                avio_write(pb[0], st->codec->extradata, st->codec->extradata_size);
444 445
            }else if(pkt->size >= 8 && AV_RB32(pkt->data) == 0xFF4FFF51){
                //jpeg2000 codestream
446 447 448 449
            }else if(pkt->size < 8 ||
                     (!st->codec->extradata_size &&
                      AV_RL32(pkt->data+4) != MKTAG('j','P',' ',' '))){ // signature
            error:
450
                av_log(s, AV_LOG_ERROR, "malformed JPEG 2000 codestream %X\n", AV_RB32(pkt->data));
451 452 453
                return -1;
            }
        }
454
        avio_write(pb[0], pkt->data, pkt->size);
M
Michael Niedermayer 已提交
455
    }
456
    avio_flush(pb[0]);
457
    if (!img->is_pipe) {
458
        avio_close(pb[0]);
459 460 461 462 463 464
    }

    img->img_number++;
    return 0;
}

465
#endif /* CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER */
466

467 468
#define OFFSET(x) offsetof(VideoData, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
469
#define ENC AV_OPT_FLAG_ENCODING_PARAM
470
static const AVOption options[] = {
471 472 473 474
    { "pixel_format", "", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
    { "video_size",   "", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
    { "framerate",    "", OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0, DEC },
    { "loop",         "", OFFSET(loop),         AV_OPT_TYPE_INT,    {.dbl = 0},    0, 1, DEC },
475 476 477
    { NULL },
};

478 479 480 481 482
static const AVOption muxoptions[] = {
    { "updatefirst",  "", OFFSET(updatefirst),  AV_OPT_TYPE_INT,    {.dbl = 0},    0, 1, ENC },
    { NULL },
};

483 484
/* input */
#if CONFIG_IMAGE2_DEMUXER
485 486 487 488 489 490
static const AVClass img2_class = {
    .class_name = "image2 demuxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};
491
AVInputFormat ff_image2_demuxer = {
492 493
    .name           = "image2",
    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
494
    .priv_data_size = sizeof(VideoData),
495 496 497 498
    .read_probe     = read_probe,
    .read_header    = read_header,
    .read_packet    = read_packet,
    .flags          = AVFMT_NOFILE,
499
    .priv_class     = &img2_class,
500
};
501
#endif
502
#if CONFIG_IMAGE2PIPE_DEMUXER
503 504 505 506 507 508
static const AVClass img2pipe_class = {
    .class_name = "image2pipe demuxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};
509
AVInputFormat ff_image2pipe_demuxer = {
510 511
    .name           = "image2pipe",
    .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
512
    .priv_data_size = sizeof(VideoData),
513 514
    .read_header    = read_header,
    .read_packet    = read_packet,
515
    .priv_class     = &img2pipe_class,
516
};
517
#endif
518 519

/* output */
520
#if CONFIG_IMAGE2_MUXER
521 522 523 524 525 526
static const AVClass img2mux_class = {
    .class_name = "image2 muxer",
    .item_name  = av_default_item_name,
    .option     = muxoptions,
    .version    = LIBAVUTIL_VERSION_INT,
};
527
AVOutputFormat ff_image2_muxer = {
528 529
    .name           = "image2",
    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
530
    .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
J
Jean First 已提交
531
                      "ppm,sgi,tga,tif,tiff,jp2,j2c",
532
    .priv_data_size = sizeof(VideoData),
533 534 535
    .video_codec    = CODEC_ID_MJPEG,
    .write_header   = write_header,
    .write_packet   = write_packet,
536 537
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE,
    .priv_class     = &img2mux_class,
538
};
539
#endif
540
#if CONFIG_IMAGE2PIPE_MUXER
541
AVOutputFormat ff_image2pipe_muxer = {
542 543
    .name           = "image2pipe",
    .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
544
    .priv_data_size = sizeof(VideoData),
545 546 547 548
    .video_codec    = CODEC_ID_MJPEG,
    .write_header   = write_header,
    .write_packet   = write_packet,
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
549
};
550
#endif