img2enc.c 8.92 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
    const char *muxer;
46
    int use_rename;
47 48 49 50 51
} VideoMuxData;

static int write_header(AVFormatContext *s)
{
    VideoMuxData *img = s->priv_data;
52
    AVStream *st = s->streams[0];
53
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(st->codecpar->format);
54 55 56 57 58 59 60 61 62

    av_strlcpy(img->path, s->filename, sizeof(img->path));

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

63
    if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
64
        img->muxer = "gif";
65
    } else if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
66
        const char *str = strrchr(img->path, '.');
67 68 69 70 71 72
        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;
73
    }
74

75 76 77 78 79 80
    return 0;
}

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

    if (!img->is_pipe) {
89 90
        if (img->update) {
            av_strlcpy(filename, img->path, sizeof(filename));
91 92
        } else if (img->use_strftime) {
            time_t now0;
93
            struct tm *tm, tmpbuf;
94
            time(&now0);
95
            tm = localtime_r(&now0, &tmpbuf);
96 97 98 99
            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);
            }
100 101
        } else if (av_get_frame_filename(filename, sizeof(filename), img->path, img->img_number) < 0 &&
                   img->img_number > 1) {
102
            av_log(s, AV_LOG_ERROR,
Michael Niedermayer's avatar
Michael Niedermayer committed
103
                   "Could not get frame filename number %d from pattern '%s' (either set updatefirst or use a pattern like %%03d within the filename pattern)\n",
104
                   img->img_number, img->path);
105
            return AVERROR(EINVAL);
106
        }
107
        for (i = 0; i < 4; i++) {
108 109
            snprintf(img->tmp[i], sizeof(img->tmp[i]), "%s.tmp", filename);
            av_strlcpy(img->target[i], filename, sizeof(img->target[i]));
110
            if (s->io_open(s, &pb[i], img->use_rename ? img->tmp[i] : filename, AVIO_FLAG_WRITE, NULL) < 0) {
111
                av_log(s, AV_LOG_ERROR, "Could not open file : %s\n", img->use_rename ? img->tmp[i] : filename);
112 113 114
                return AVERROR(EIO);
            }

115
            if (!img->split_planes || i+1 >= desc->nb_components)
116
                break;
117
            filename[strlen(filename) - 1] = "UVAx"[i];
118
        }
119 120
        if (img->use_rename)
            nb_renames = i + 1;
121 122 123 124
    } else {
        pb[0] = s->pb;
    }

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

        av_assert0(!img->split_planes);

        ret = avformat_alloc_output_context2(&fmt, NULL, img->muxer, s->filename);
        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];
        if ((ret = av_copy_packet(&pkt2, pkt))                            < 0 ||
            (ret = av_dup_packet(&pkt2))                                  < 0 ||
162
            (ret = avcodec_parameters_copy(st->codecpar, s->streams[0]->codecpar)) < 0 ||
163 164 165
            (ret = avformat_write_header(fmt, NULL))                      < 0 ||
            (ret = av_interleaved_write_frame(fmt, &pkt2))                < 0 ||
            (ret = av_write_trailer(fmt))                                 < 0) {
166
            av_packet_unref(&pkt2);
167 168 169
            avformat_free_context(fmt);
            return ret;
        }
170
        av_packet_unref(&pkt2);
171
        avformat_free_context(fmt);
172
    } else {
173 174 175 176
        avio_write(pb[0], pkt->data, pkt->size);
    }
    avio_flush(pb[0]);
    if (!img->is_pipe) {
177
        ff_format_io_close(s, &pb[0]);
178
        for (i = 0; i < nb_renames; i++) {
179 180 181
            int ret = ff_rename(img->tmp[i], img->target[i], s);
            if (ret < 0)
                return ret;
182
        }
183 184 185 186 187 188
    }

    img->img_number++;
    return 0;
}

189 190 191 192 193 194 195 196 197 198 199
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;
}

200 201 202
#define OFFSET(x) offsetof(VideoMuxData, x)
#define ENC AV_OPT_FLAG_ENCODING_PARAM
static const AVOption muxoptions[] = {
203 204
    { "updatefirst",  "continuously overwrite one file", OFFSET(update),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0,       1, ENC },
    { "update",       "continuously overwrite one file", OFFSET(update),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0,       1, ENC },
205
    { "start_number", "set first number in the sequence", OFFSET(img_number), AV_OPT_TYPE_INT,  { .i64 = 1 }, 0, INT_MAX, ENC },
206
    { "strftime",     "use strftime for filename", OFFSET(use_strftime),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
207
    { "atomic_writing", "write files atomically (using temporary files and renames)", OFFSET(use_rename), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
208 209 210
    { NULL },
};

211
#if CONFIG_IMAGE2_MUXER
212 213 214 215 216 217
static const AVClass img2mux_class = {
    .class_name = "image2 muxer",
    .item_name  = av_default_item_name,
    .option     = muxoptions,
    .version    = LIBAVUTIL_VERSION_INT,
};
218

219 220 221
AVOutputFormat ff_image2_muxer = {
    .name           = "image2",
    .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
222
    .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
223
                      "ppm,sgi,tga,tif,tiff,jp2,j2c,j2k,xwd,sun,ras,rs,im1,im8,im24,"
224
                      "sunras,xbm,xface,pix,y",
225
    .priv_data_size = sizeof(VideoMuxData),
226
    .video_codec    = AV_CODEC_ID_MJPEG,
227 228
    .write_header   = write_header,
    .write_packet   = write_packet,
229
    .query_codec    = query_codec,
230 231
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE,
    .priv_class     = &img2mux_class,
232 233 234 235 236 237 238
};
#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),
239
    .video_codec    = AV_CODEC_ID_MJPEG,
240 241
    .write_header   = write_header,
    .write_packet   = write_packet,
242
    .query_codec    = query_codec,
243 244 245
    .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
};
#endif