]> git.sesse.net Git - ffmpeg/blob - libavformat/img2enc.c
avformat/img2enc: factorize writing fully muxed file
[ffmpeg] / libavformat / img2enc.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/avassert.h"
25 #include "libavutil/avstring.h"
26 #include "libavutil/log.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/time_internal.h"
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "internal.h"
33 #include "img2.h"
34
35 typedef struct VideoMuxData {
36     const AVClass *class;  /**< Class for private options. */
37     int img_number;
38     int is_pipe;
39     int split_planes;       /**< use independent file for each Y, U, V plane */
40     char path[1024];
41     char tmp[4][1024];
42     char target[4][1024];
43     int update;
44     int use_strftime;
45     int frame_pts;
46     const char *muxer;
47     int use_rename;
48 } VideoMuxData;
49
50 static int write_header(AVFormatContext *s)
51 {
52     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     /* find format */
59     if (s->oformat->flags & AVFMT_NOFILE)
60         img->is_pipe = 0;
61     else
62         img->is_pipe = 1;
63
64     if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
65         img->muxer = "gif";
66     } else if (st->codecpar->codec_id == AV_CODEC_ID_FITS) {
67         img->muxer = "fits";
68     } else if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
69         const char *str = strrchr(img->path, '.');
70         img->split_planes =     str
71                              && !av_strcasecmp(str + 1, "y")
72                              && s->nb_streams == 1
73                              && desc
74                              &&(desc->flags & AV_PIX_FMT_FLAG_PLANAR)
75                              && desc->nb_components >= 3;
76     }
77
78     return 0;
79 }
80
81 static int write_muxed_file(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
82 {
83     VideoMuxData *img = s->priv_data;
84     AVCodecParameters *par = s->streams[0]->codecpar;
85     AVStream *st;
86     AVPacket pkt2 = {0};
87     AVFormatContext *fmt = NULL;
88     int ret;
89
90     /* URL is not used directly as we are overriding the IO context later. */
91     ret = avformat_alloc_output_context2(&fmt, NULL, img->muxer, s->url);
92     if (ret < 0)
93         return ret;
94     st = avformat_new_stream(fmt, NULL);
95     if (!st) {
96         avformat_free_context(fmt);
97         return AVERROR(ENOMEM);
98     }
99     st->id = pkt->stream_index;
100
101     fmt->pb = pb;
102     if ((ret = av_packet_ref(&pkt2, pkt))                      < 0 ||
103         (ret = avcodec_parameters_copy(st->codecpar, par))     < 0 ||
104         (ret = avformat_write_header(fmt, NULL))               < 0 ||
105         (ret = av_interleaved_write_frame(fmt, &pkt2))         < 0 ||
106         (ret = av_write_trailer(fmt))                          < 0) {
107         av_packet_unref(&pkt2);
108         avformat_free_context(fmt);
109         return ret;
110     }
111     av_packet_unref(&pkt2);
112     avformat_free_context(fmt);
113     return 0;
114 }
115
116 static int write_packet(AVFormatContext *s, AVPacket *pkt)
117 {
118     VideoMuxData *img = s->priv_data;
119     AVIOContext *pb[4];
120     char filename[1024];
121     AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
122     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(par->format);
123     int ret, i;
124     int nb_renames = 0;
125
126     if (!img->is_pipe) {
127         if (img->update) {
128             av_strlcpy(filename, img->path, sizeof(filename));
129         } else if (img->use_strftime) {
130             time_t now0;
131             struct tm *tm, tmpbuf;
132             time(&now0);
133             tm = localtime_r(&now0, &tmpbuf);
134             if (!strftime(filename, sizeof(filename), img->path, tm)) {
135                 av_log(s, AV_LOG_ERROR, "Could not get frame filename with strftime\n");
136                 return AVERROR(EINVAL);
137             }
138         } else if (img->frame_pts) {
139             if (av_get_frame_filename2(filename, sizeof(filename), img->path, pkt->pts, AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0) {
140                 av_log(s, AV_LOG_ERROR, "Cannot write filename by pts of the frames.");
141                 return AVERROR(EINVAL);
142             }
143         } else if (av_get_frame_filename2(filename, sizeof(filename), img->path,
144                                           img->img_number,
145                                           AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0 &&
146                    img->img_number > 1) {
147             av_log(s, AV_LOG_ERROR,
148                    "Could not get frame filename number %d from pattern '%s'. "
149                    "Use '-frames:v 1' for a single image, or '-update' option, or use a pattern such as %%03d within the filename.\n",
150                    img->img_number, img->path);
151             return AVERROR(EINVAL);
152         }
153         for (i = 0; i < 4; i++) {
154             snprintf(img->tmp[i], sizeof(img->tmp[i]), "%s.tmp", filename);
155             av_strlcpy(img->target[i], filename, sizeof(img->target[i]));
156             if (s->io_open(s, &pb[i], img->use_rename ? img->tmp[i] : filename, AVIO_FLAG_WRITE, NULL) < 0) {
157                 av_log(s, AV_LOG_ERROR, "Could not open file : %s\n", img->use_rename ? img->tmp[i] : filename);
158                 return AVERROR(EIO);
159             }
160
161             if (!img->split_planes || i+1 >= desc->nb_components)
162                 break;
163             filename[strlen(filename) - 1] = "UVAx"[i];
164         }
165         if (img->use_rename)
166             nb_renames = i + 1;
167     } else {
168         pb[0] = s->pb;
169     }
170
171     if (img->split_planes) {
172         int ysize = par->width * par->height;
173         int usize = AV_CEIL_RSHIFT(par->width, desc->log2_chroma_w) * AV_CEIL_RSHIFT(par->height, desc->log2_chroma_h);
174         if (desc->comp[0].depth >= 9) {
175             ysize *= 2;
176             usize *= 2;
177         }
178         avio_write(pb[0], pkt->data                , ysize);
179         avio_write(pb[1], pkt->data + ysize        , usize);
180         avio_write(pb[2], pkt->data + ysize + usize, usize);
181         ff_format_io_close(s, &pb[1]);
182         ff_format_io_close(s, &pb[2]);
183         if (desc->nb_components > 3) {
184             avio_write(pb[3], pkt->data + ysize + 2*usize, ysize);
185             ff_format_io_close(s, &pb[3]);
186         }
187     } else if (img->muxer) {
188         ret = write_muxed_file(s, pb[0], pkt);
189         if (ret < 0)
190             return ret;
191     } else {
192         avio_write(pb[0], pkt->data, pkt->size);
193     }
194     avio_flush(pb[0]);
195     if (!img->is_pipe) {
196         ff_format_io_close(s, &pb[0]);
197         for (i = 0; i < nb_renames; i++) {
198             int ret = ff_rename(img->tmp[i], img->target[i], s);
199             if (ret < 0)
200                 return ret;
201         }
202     }
203
204     img->img_number++;
205     return 0;
206 }
207
208 static int query_codec(enum AVCodecID id, int std_compliance)
209 {
210     int i;
211     for (i = 0; ff_img_tags[i].id != AV_CODEC_ID_NONE; i++)
212         if (ff_img_tags[i].id == id)
213             return 1;
214
215     // Anything really can be stored in img2
216     return std_compliance < FF_COMPLIANCE_NORMAL;
217 }
218
219 #define OFFSET(x) offsetof(VideoMuxData, x)
220 #define ENC AV_OPT_FLAG_ENCODING_PARAM
221 static const AVOption muxoptions[] = {
222     { "update",       "continuously overwrite one file", OFFSET(update),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0,       1, ENC },
223     { "start_number", "set first number in the sequence", OFFSET(img_number), AV_OPT_TYPE_INT,  { .i64 = 1 }, 0, INT_MAX, ENC },
224     { "strftime",     "use strftime for filename", OFFSET(use_strftime),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
225     { "frame_pts",    "use current frame pts for filename", OFFSET(frame_pts),  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
226     { "atomic_writing", "write files atomically (using temporary files and renames)", OFFSET(use_rename), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
227     { NULL },
228 };
229
230 #if CONFIG_IMAGE2_MUXER
231 static const AVClass img2mux_class = {
232     .class_name = "image2 muxer",
233     .item_name  = av_default_item_name,
234     .option     = muxoptions,
235     .version    = LIBAVUTIL_VERSION_INT,
236 };
237
238 AVOutputFormat ff_image2_muxer = {
239     .name           = "image2",
240     .long_name      = NULL_IF_CONFIG_SMALL("image2 sequence"),
241     .extensions     = "bmp,dpx,jls,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,"
242                       "ppm,sgi,tga,tif,tiff,jp2,j2c,j2k,xwd,sun,ras,rs,im1,im8,im24,"
243                       "sunras,xbm,xface,pix,y",
244     .priv_data_size = sizeof(VideoMuxData),
245     .video_codec    = AV_CODEC_ID_MJPEG,
246     .write_header   = write_header,
247     .write_packet   = write_packet,
248     .query_codec    = query_codec,
249     .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE,
250     .priv_class     = &img2mux_class,
251 };
252 #endif
253 #if CONFIG_IMAGE2PIPE_MUXER
254 AVOutputFormat ff_image2pipe_muxer = {
255     .name           = "image2pipe",
256     .long_name      = NULL_IF_CONFIG_SMALL("piped image2 sequence"),
257     .priv_data_size = sizeof(VideoMuxData),
258     .video_codec    = AV_CODEC_ID_MJPEG,
259     .write_header   = write_header,
260     .write_packet   = write_packet,
261     .query_codec    = query_codec,
262     .flags          = AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS
263 };
264 #endif