3 * Copyright (c) 2014 Benoit Fouet
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * @see https://wiki.mozilla.org/APNG_Specification
26 * @see http://www.w3.org/TR/PNG
30 #include "avio_internal.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/opt.h"
35 #include "libavcodec/apng.h"
36 #include "libavcodec/png.h"
37 #include "libavcodec/bytestream.h"
39 #define DEFAULT_APNG_FPS 15
41 typedef struct APNGDemuxContext {
61 * To be a valid APNG file, we mandate, in this order:
69 static int apng_probe(const AVProbeData *p)
75 bytestream2_init(&gb, p->buf, p->buf_size);
77 if (bytestream2_get_be64(&gb) != PNGSIG)
81 len = bytestream2_get_be32(&gb);
85 tag = bytestream2_get_le32(&gb);
86 /* we don't check IDAT size, as this is the last tag
87 * we check, and it may be larger than the probe buffer */
88 if (tag != MKTAG('I', 'D', 'A', 'T') &&
89 len + 4 > bytestream2_get_bytes_left(&gb))
93 case MKTAG('I', 'H', 'D', 'R'):
96 if (av_image_check_size(bytestream2_get_be32(&gb), bytestream2_get_be32(&gb), 0, NULL))
98 bytestream2_skip(&gb, 9);
101 case MKTAG('a', 'c', 'T', 'L'):
104 bytestream2_get_be32(&gb) == 0) /* 0 is not a valid value for number of frames */
106 bytestream2_skip(&gb, 8);
109 case MKTAG('I', 'D', 'A', 'T'):
114 /* skip other tags */
115 bytestream2_skip(&gb, len + 4);
121 return AVPROBE_SCORE_MAX;
124 static int append_extradata(AVCodecParameters *par, AVIOContext *pb, int len)
126 int previous_size = par->extradata_size;
128 uint8_t *new_extradata;
130 if (previous_size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE - len)
131 return AVERROR_INVALIDDATA;
133 new_size = previous_size + len;
134 new_extradata = av_realloc(par->extradata, new_size + AV_INPUT_BUFFER_PADDING_SIZE);
136 return AVERROR(ENOMEM);
137 memset(new_extradata + new_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
138 par->extradata = new_extradata;
139 par->extradata_size = new_size;
141 if ((ret = avio_read(pb, par->extradata + previous_size, len)) < 0)
144 return previous_size;
147 static int apng_read_header(AVFormatContext *s)
149 APNGDemuxContext *ctx = s->priv_data;
150 AVIOContext *pb = s->pb;
154 int64_t ret = AVERROR_INVALIDDATA;
157 if (avio_rb64(pb) != PNGSIG)
160 /* parse IHDR (must be first chunk) */
163 if (len != 13 || tag != MKTAG('I', 'H', 'D', 'R'))
166 st = avformat_new_stream(s, NULL);
168 return AVERROR(ENOMEM);
170 /* set the timebase to something large enough (1/100,000 of second)
171 * to hopefully cope with all sane frame durations */
172 avpriv_set_pts_info(st, 64, 1, 100000);
173 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
174 st->codecpar->codec_id = AV_CODEC_ID_APNG;
175 st->codecpar->width = avio_rb32(pb);
176 st->codecpar->height = avio_rb32(pb);
177 if ((ret = av_image_check_size(st->codecpar->width, st->codecpar->height, 0, s)) < 0)
180 /* extradata will contain every chunk up to the first fcTL (excluded) */
181 ret = ff_alloc_extradata(st->codecpar, len + 12);
184 AV_WB32(st->codecpar->extradata, len);
185 AV_WL32(st->codecpar->extradata+4, tag);
186 AV_WB32(st->codecpar->extradata+8, st->codecpar->width);
187 AV_WB32(st->codecpar->extradata+12, st->codecpar->height);
188 if ((ret = avio_read(pb, st->codecpar->extradata+16, 9)) < 0)
191 while (!avio_feof(pb)) {
192 if (acTL_found && ctx->num_play != 1) {
193 int64_t size = avio_size(pb);
194 int64_t offset = avio_tell(pb);
198 } else if (offset < 0) {
201 } else if ((ret = ffio_ensure_seekback(pb, size - offset)) < 0) {
202 av_log(s, AV_LOG_WARNING, "Could not ensure seekback, will not loop\n");
206 if ((ctx->num_play == 1 || !acTL_found) &&
207 ((ret = ffio_ensure_seekback(pb, 4 /* len */ + 4 /* tag */)) < 0))
211 if (len > 0x7fffffff) {
212 ret = AVERROR_INVALIDDATA;
218 case MKTAG('a', 'c', 'T', 'L'):
219 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
220 (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
223 ctx->num_frames = AV_RB32(st->codecpar->extradata + ret + 8);
224 ctx->num_play = AV_RB32(st->codecpar->extradata + ret + 12);
225 av_log(s, AV_LOG_DEBUG, "num_frames: %"PRIu32", num_play: %"PRIu32"\n",
226 ctx->num_frames, ctx->num_play);
228 case MKTAG('f', 'c', 'T', 'L'):
230 ret = AVERROR_INVALIDDATA;
233 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
237 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
238 (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
247 static int decode_fctl_chunk(AVFormatContext *s, APNGDemuxContext *ctx, AVPacket *pkt)
249 uint32_t sequence_number, width, height, x_offset, y_offset;
250 uint16_t delay_num, delay_den;
251 uint8_t dispose_op, blend_op;
253 sequence_number = avio_rb32(s->pb);
254 width = avio_rb32(s->pb);
255 height = avio_rb32(s->pb);
256 x_offset = avio_rb32(s->pb);
257 y_offset = avio_rb32(s->pb);
258 delay_num = avio_rb16(s->pb);
259 delay_den = avio_rb16(s->pb);
260 dispose_op = avio_r8(s->pb);
261 blend_op = avio_r8(s->pb);
262 avio_skip(s->pb, 4); /* crc */
264 /* default is hundredths of seconds */
267 if (!delay_num || (ctx->max_fps && delay_den / delay_num > ctx->max_fps)) {
269 delay_den = ctx->default_fps;
271 ctx->pkt_duration = av_rescale_q(delay_num,
272 (AVRational){ 1, delay_den },
273 s->streams[0]->time_base);
275 av_log(s, AV_LOG_DEBUG, "%s: "
276 "sequence_number: %"PRId32", "
278 "height: %"PRIu32", "
279 "x_offset: %"PRIu32", "
280 "y_offset: %"PRIu32", "
281 "delay_num: %"PRIu16", "
282 "delay_den: %"PRIu16", "
296 if (width != s->streams[0]->codecpar->width ||
297 height != s->streams[0]->codecpar->height ||
300 if (sequence_number == 0 ||
301 x_offset >= s->streams[0]->codecpar->width ||
302 width > s->streams[0]->codecpar->width - x_offset ||
303 y_offset >= s->streams[0]->codecpar->height ||
304 height > s->streams[0]->codecpar->height - y_offset)
305 return AVERROR_INVALIDDATA;
306 ctx->is_key_frame = 0;
308 if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS)
309 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
310 ctx->is_key_frame = dispose_op == APNG_DISPOSE_OP_BACKGROUND ||
311 blend_op == APNG_BLEND_OP_SOURCE;
317 static int apng_read_packet(AVFormatContext *s, AVPacket *pkt)
319 APNGDemuxContext *ctx = s->priv_data;
322 AVIOContext *pb = s->pb;
326 * fcTL chunk length, in bytes:
333 * 4 (tag (must be fdAT or IDAT))
335 /* if num_play is not 1, then the seekback is already guaranteed */
336 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 46)) < 0)
346 case MKTAG('f', 'c', 'T', 'L'):
348 return AVERROR_INVALIDDATA;
350 if ((ret = decode_fctl_chunk(s, ctx, pkt)) < 0)
353 /* fcTL must precede fdAT or IDAT */
356 if (len > 0x7fffffff ||
357 tag != MKTAG('f', 'd', 'A', 'T') &&
358 tag != MKTAG('I', 'D', 'A', 'T'))
359 return AVERROR_INVALIDDATA;
361 size = 38 /* fcTL */ + 8 /* len, tag */ + len + 4 /* crc */;
363 return AVERROR(EINVAL);
365 if ((ret = avio_seek(pb, -46, SEEK_CUR)) < 0 ||
366 (ret = av_append_packet(pb, pkt, size)) < 0)
369 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
375 tag != MKTAG('f', 'c', 'T', 'L') &&
376 tag != MKTAG('I', 'E', 'N', 'D')) {
377 if (len > 0x7fffffff)
378 return AVERROR_INVALIDDATA;
379 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
380 (ret = av_append_packet(pb, pkt, len + 12)) < 0)
382 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
387 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
390 if (ctx->is_key_frame)
391 pkt->flags |= AV_PKT_FLAG_KEY;
392 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
393 pkt->duration = ctx->pkt_duration;
395 case MKTAG('I', 'E', 'N', 'D'):
397 if (ctx->ignore_loop || ctx->num_play >= 1 && ctx->cur_loop == ctx->num_play) {
398 avio_seek(pb, -8, SEEK_CUR);
401 if ((ret = avio_seek(pb, s->streams[0]->codecpar->extradata_size + 8, SEEK_SET)) < 0)
405 avpriv_request_sample(s, "In-stream tag=%s (0x%08"PRIX32") len=%"PRIu32,
406 av_fourcc2str(tag), tag, len);
407 avio_skip(pb, len + 4);
410 /* Handle the unsupported yet cases */
411 return AVERROR_PATCHWELCOME;
414 static const AVOption options[] = {
415 { "ignore_loop", "ignore loop setting" , offsetof(APNGDemuxContext, ignore_loop),
416 AV_OPT_TYPE_BOOL, { .i64 = 1 } , 0, 1 , AV_OPT_FLAG_DECODING_PARAM },
417 { "max_fps" , "maximum framerate (0 is no limit)" , offsetof(APNGDemuxContext, max_fps),
418 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
419 { "default_fps", "default framerate (0 is as fast as possible)", offsetof(APNGDemuxContext, default_fps),
420 AV_OPT_TYPE_INT, { .i64 = DEFAULT_APNG_FPS }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
424 static const AVClass demuxer_class = {
425 .class_name = "APNG demuxer",
426 .item_name = av_default_item_name,
428 .version = LIBAVUTIL_VERSION_INT,
429 .category = AV_CLASS_CATEGORY_DEMUXER,
432 AVInputFormat ff_apng_demuxer = {
434 .long_name = NULL_IF_CONFIG_SMALL("Animated Portable Network Graphics"),
435 .priv_data_size = sizeof(APNGDemuxContext),
436 .read_probe = apng_probe,
437 .read_header = apng_read_header,
438 .read_packet = apng_read_packet,
439 .flags = AVFMT_GENERIC_INDEX,
440 .priv_class = &demuxer_class,