img2enc.c 9.35 KB
Newer Older
1 2 3 4 5
/*
 * Image format
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
 * Copyright (c) 2004 Michael Niedermayer
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9 10 11 12
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
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 21 22 23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/intreadwrite.h"
24
#include "libavutil/avassert.h"
25 26
#include "libavutil/avstring.h"
#include "libavutil/log.h"
27
#include "libavutil/opt.h"
28
#include "libavutil/pixdesc.h"
29
#include "libavutil/time_internal.h"
30 31 32
#include "avformat.h"
#include "avio_internal.h"
#include "internal.h"
33
#include "img2.h"
34

35
typedef struct VideoMuxData {
36
    const AVClass *class;  /**< Class for private options. */
37 38
    int img_number;
    int is_pipe;
39
    int split_planes;       /**< use independent file for each Y, U, V plane */
40
    char path[1024];
41 42
    char tmp[4][1024];
    char target[4][1024];
43
    int update;
44
    int use_strftime;
45
    int frame_pts;
46
    const char *muxer;
47
    int use_rename;
48 49 50 51 52
} VideoMuxData;

static int write_header(AVFormatContext *s)
{
    VideoMuxData *img = s->priv_data;
53
    AVStream *st = s->streams[0];
54
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(st->codecpar->format);
55

56
    av_strlcpy(img->path, s->url, sizeof(img->path));
57 58 59 60 61 62 63

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

64
    if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
65
        img->muxer = "gif";
Paras Chadha's avatar
Paras Chadha committed
66 67
    } else if (st->codecpar->codec_id == AV_CODEC_ID_FITS) {
        img->muxer = "fits";
68
    } else if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
69
        const char *str = strrchr(img->path, '.');
70 71 72 73 74 75
        img->split_planes =     str
                             && !av_strcasecmp(str + 1, "y")
                             && s->nb_streams == 1
                             && desc
                             &&(desc->flags & AV_PIX_FMT_FLAG_PLANAR)
                             && desc->nb_components >= 3;
76
    }
77

78 79 80 81 82 83
    return 0;
}

static int write_packet(AVFormatContext *s, AVPacket *pkt)
{
    VideoMuxData *img = s->priv_data;
84
    AVIOContext *pb[4];
85
    char filename[1024];
86
    AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
87
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(par->format);
88
    int i;
89
    int nb_renames = 0;
90 91

    if (!img->is_pipe) {
92 93
        if (img->update) {
            av_strlcpy(filename, img->path, sizeof(filename));
94 95
        } else if (img->use_strftime) {
            time_t now0;
96
            struct tm *tm, tmpbuf;
97
            time(&now0);
98
            tm = localtime_r(&now0, &tmpbuf);
99 100 101 102
            if (!strftime(filename, sizeof(filename), img->path, tm)) {
                av_log(s, AV_LOG_ERROR, "Could not get frame filename with strftime\n");
                return AVERROR(EINVAL);
            }
103 104 105 106 107
        } else if (img->frame_pts) {
            if (av_get_frame_filename2(filename, sizeof(filename), img->path, pkt->pts, AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0) {
                av_log(s, AV_LOG_ERROR, "Cannot write filename by pts of the frames.");
                return AVERROR(EINVAL);
            }
108 109
        } else if (av_get_frame_filename2(filename, sizeof(filename), img->path,
                                          img->img_number,
110
                                          AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0 &&
111
                   img->img_number > 1) {
112
            av_log(s, AV_LOG_ERROR,
113
                   "Could not get frame filename number %d from pattern '%s' (either set update or use a pattern like %%03d within the filename pattern)\n",
114
                   img->img_number, img->path);
115
            return AVERROR(EINVAL);
116
        }
117
        for (i = 0; i < 4; i++) {
118 119
            snprintf(img->tmp[i], sizeof(img->tmp[i]), "%s.tmp", filename);
            av_strlcpy(img->target[i], filename, sizeof(img->target[i]));
120
            if (s->io_open(s, &pb[i], img->use_rename ? img->tmp[i] : filename, AVIO_FLAG_WRITE, NULL) < 0) {
121
                av_log(s, AV_LOG_ERROR, "Could not open file : %s\n", img->use_rename ? img->tmp[i] : filename);
122 123 124
                return AVERROR(EIO);
            }

125
            if (!img->split_planes || i+1 >= desc->nb_components)
126
                break;
127
            filename[strlen(filename) - 1] = "UVAx"[i];
128
        }
129 130
        if (img->use_rename)
            nb_renames = i + 1;
131 132 133 134
    } else {
        pb[0] = s->pb;
    }

135
    if (img->split_planes) {
136
        int ysize = par->width * par->height;
137
        int usize = AV_CEIL_RSHIFT(par->width, desc->log2_chroma_w) * AV_CEIL_RSHIFT(par->height, desc->log2_chroma_h);
138
        if (desc->comp[0].depth >= 9) {
139 140 141
            ysize *= 2;
            usize *= 2;
        }
142
        avio_write(pb[0], pkt->data                , ysize);
143 144
        avio_write(pb[1], pkt->data + ysize        , usize);
        avio_write(pb[2], pkt->data + ysize + usize, usize);
145 146
        ff_format_io_close(s, &pb[1]);
        ff_format_io_close(s, &pb[2]);
147 148
        if (desc->nb_components > 3) {
            avio_write(pb[3], pkt->data + ysize + 2*usize, ysize);
149
            ff_format_io_close(s, &pb[3]);
150
        }
151 152 153 154 155 156 157 158
    } else if (img->muxer) {
        int ret;
        AVStream *st;
        AVPacket pkt2 = {0};
        AVFormatContext *fmt = NULL;

        av_assert0(!img->split_planes);

159
        ret = avformat_alloc_output_context2(&fmt, NULL, img->muxer, s->url);
160 161 162 163 164 165 166 167 168 169
        if (ret < 0)
            return ret;
        st = avformat_new_stream(fmt, NULL);
        if (!st) {
            avformat_free_context(fmt);
            return AVERROR(ENOMEM);
        }
        st->id = pkt->stream_index;

        fmt->pb = pb[0];
170
        if ((ret = av_packet_ref(&pkt2, pkt))                             < 0 ||
171
            (ret = avcodec_parameters_copy(st->codecpar, s->streams[0]->codecpar)) < 0 ||
172 173 174
            (ret = avformat_write_header(fmt, NULL))                      < 0 ||
            (ret = av_interleaved_write_frame(fmt, &pkt2))                < 0 ||
            (ret = av_write_trailer(fmt))                                 < 0) {
175
            av_packet_unref(&pkt2);
176 177 178
            avformat_free_context(fmt);
            return ret;
        }
179
        av_packet_unref(&pkt2);
180
        avformat_free_context(fmt);
181
    } else {
182 183 184 185
        avio_write(pb[0], pkt->data, pkt->size);
    }
    avio_flush(pb[0]);
    if (!img->is_pipe) {
186
        ff_format_io_close(s, &pb[0]);
187
        for (i = 0; i < nb_renames; i++) {
188 189 190
            int ret = ff_rename(img->tmp[i], img->target[i], s);
            if (ret < 0)
                return ret;
191
        }
192 193 194 195 196 197
    }

    img->img_number++;
    return 0;
}

198 199 200 201 202 203 204 205 206 207 208
static int query_codec(enum AVCodecID id, int std_compliance)
{
    int i;
    for (i = 0; ff_img_tags[i].id != AV_CODEC_ID_NONE; i++)
        if (ff_img_tags[i].id == id)
            return 1;

    // Anything really can be stored in img2
    return std_compliance < FF_COMPLIANCE_NORMAL;
}

209 210 211
#define OFFSET(x) offsetof(VideoMuxData, x)
#define ENC AV_OPT_FLAG_ENCODING_PARAM
static const AVOption muxoptions[] = {
212
    { "update",       "continuously overwrite one file", OFFSET(update),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0,       1, ENC },
213
    { "start_number", "set first number in the sequence", OFFSET(img_number), AV_OPT_TYPE_INT,  { .i64 = 1 }, 0, INT_MAX, ENC },
214
    { "strftime",     "use strftime for filename", OFFSET(use_strftime),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
215
    { "frame_pts",    "use current frame pts for filename", OFFSET(frame_pts),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
216
    { "atomic_writing", "write files atomically (using temporary files and renames)", OFFSET(use_rename), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
217 218 219
    { NULL },
};

220
#if CONFIG_IMAGE2_MUXER
221 222 223 224 225 226
static const AVClass img2mux_class = {
    .class_name = "image2 muxer",
    .item_name  = av_default_item_name,
    .option     = muxoptions,
    .version    = LIBAVUTIL_VERSION_INT,
};
227

228 229 230
AVOutputFormat ff_image2_muxer = {
    .name           = "image2",
    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
231
    .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
232
                      "ppm,sgi,tga,tif,tiff,jp2,j2c,j2k,xwd,sun,ras,rs,im1,im8,im24,"
233
                      "sunras,xbm,xface,pix,y",
234
    .priv_data_size = sizeof(VideoMuxData),
235
    .video_codec    = AV_CODEC_ID_MJPEG,
236 237
    .write_header   = write_header,
    .write_packet   = write_packet,
238
    .query_codec    = query_codec,
239 240
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE,
    .priv_class     = &img2mux_class,
241 242 243 244 245 246 247
};
#endif
#if CONFIG_IMAGE2PIPE_MUXER
AVOutputFormat ff_image2pipe_muxer = {
    .name           = "image2pipe",
    .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
    .priv_data_size = sizeof(VideoMuxData),
248
    .video_codec    = AV_CODEC_ID_MJPEG,
249 250
    .write_header   = write_header,
    .write_packet   = write_packet,
251
    .query_codec    = query_codec,
252 253 254
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
};
#endif