FFmpeg
Loading...
Searching...
No Matches
apngdec.c
Go to the documentation of this file.
1/*
2 * APNG demuxer
3 * Copyright (c) 2014 Benoit Fouet
4 *
5 * This file is part of FFmpeg.
6 *
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.
11 *
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.
16 *
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
20 */
21
22/**
23 * @file
24 * APNG demuxer.
25 * @see https://wiki.mozilla.org/APNG_Specification
26 * @see http://www.w3.org/TR/PNG
27 */
28
29#include "avformat.h"
30#include "avio_internal.h"
31#include "demux.h"
32#include "internal.h"
33#include "libavutil/imgutils.h"
35#include "libavutil/mem.h"
36#include "libavutil/opt.h"
37#include "libavcodec/apng.h"
38#include "libavcodec/png.h"
40
41#define DEFAULT_APNG_FPS 15
42
43typedef struct APNGDemuxContext {
44 const AVClass *class;
45
48
50
52
53 /*
54 * loop options
55 */
57 uint32_t num_frames;
58 uint32_t num_play;
59 uint32_t cur_loop;
61
62/*
63 * To be a valid APNG file, we mandate, in this order:
64 * PNGSIG
65 * IHDR
66 * ...
67 * acTL
68 * ...
69 * IDAT
70 */
71static int apng_probe(const AVProbeData *p)
72{
74 int state = 0;
75 uint32_t len, tag;
76
77 bytestream2_init(&gb, p->buf, p->buf_size);
78
79 if (bytestream2_get_be64(&gb) != PNGSIG)
80 return 0;
81
82 for (;;) {
83 len = bytestream2_get_be32(&gb);
84 if (len > 0x7fffffff)
85 return 0;
86
87 tag = bytestream2_get_le32(&gb);
88 /* we don't check IDAT size, as this is the last tag
89 * we check, and it may be larger than the probe buffer */
90 if (tag != MKTAG('I', 'D', 'A', 'T') &&
92 return 0;
93
94 switch (tag) {
95 case MKTAG('I', 'H', 'D', 'R'):
96 if (len != 13)
97 return 0;
98 if (av_image_check_size(bytestream2_get_be32(&gb), bytestream2_get_be32(&gb), 0, NULL))
99 return 0;
100 bytestream2_skip(&gb, 9);
101 state++;
102 break;
103 case MKTAG('a', 'c', 'T', 'L'):
104 if (state != 1 ||
105 len != 8 ||
106 bytestream2_get_be32(&gb) == 0) /* 0 is not a valid value for number of frames */
107 return 0;
108 bytestream2_skip(&gb, 8);
109 state++;
110 break;
111 case MKTAG('I', 'D', 'A', 'T'):
112 if (state != 2)
113 return 0;
114 goto end;
115 default:
116 /* skip other tags */
117 bytestream2_skip(&gb, len + 4);
118 break;
119 }
120 }
121
122end:
123 return AVPROBE_SCORE_MAX;
124}
125
127{
128 int previous_size = par->extradata_size;
129 int new_size, ret;
130 uint8_t *new_extradata;
131
132 if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE - previous_size)
133 return AVERROR_INVALIDDATA;
134
135 new_size = previous_size + len;
136 new_extradata = av_realloc(par->extradata, new_size + AV_INPUT_BUFFER_PADDING_SIZE);
137 if (!new_extradata)
138 return AVERROR(ENOMEM);
139 memset(new_extradata + new_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
140 par->extradata = new_extradata;
141 par->extradata_size = new_size;
142
143 if ((ret = ffio_read_size(pb, par->extradata + previous_size, len)) < 0)
144 return ret;
145
146 return previous_size;
147}
148
150{
151 APNGDemuxContext *ctx = s->priv_data;
152 AVIOContext *pb = s->pb;
153 uint32_t len, tag;
154 AVStream *st;
155 int acTL_found = 0;
156 int64_t ret;
157
158 /* verify PNGSIG */
159 if (avio_rb64(pb) != PNGSIG)
160 return AVERROR_INVALIDDATA;
161
162 /* parse IHDR (must be first chunk) */
163 len = avio_rb32(pb);
164 tag = avio_rl32(pb);
165 if (len != 13 || tag != MKTAG('I', 'H', 'D', 'R'))
166 return AVERROR_INVALIDDATA;
167
169 if (!st)
170 return AVERROR(ENOMEM);
171
172 /* set the timebase to something large enough (1/100,000 of second)
173 * to hopefully cope with all sane frame durations */
174 avpriv_set_pts_info(st, 64, 1, 100000);
177 st->codecpar->width = avio_rb32(pb);
178 st->codecpar->height = avio_rb32(pb);
179 if ((ret = av_image_check_size(st->codecpar->width, st->codecpar->height, 0, s)) < 0)
180 return ret;
181
182 /* extradata will contain every chunk up to the first fcTL (excluded) */
183 ret = ff_alloc_extradata(st->codecpar, len + 12);
184 if (ret < 0)
185 return ret;
187 AV_WL32(st->codecpar->extradata+4, tag);
190 if ((ret = ffio_read_size(pb, st->codecpar->extradata + 16, 9)) < 0)
191 return ret;
192
193 while (1) {
194 if (acTL_found && ctx->num_play != 1) {
195 int64_t size = avio_size(pb);
197 if (size < 0 || offset < 0 ||
198 (ret = ffio_ensure_seekback(pb, size - offset)) < 0) {
199 av_log(s, AV_LOG_WARNING, "Could not ensure seekback, will not loop\n");
200 ctx->num_play = 1;
201 }
202 }
203 if ((ctx->num_play == 1 || !acTL_found) &&
204 ((ret = ffio_ensure_seekback(pb, 4 /* len */ + 4 /* tag */)) < 0))
205 return ret;
206
207 len = avio_rb32(pb);
208 if (len > INT_MAX - 12)
209 return AVERROR_INVALIDDATA;
210
211 tag = avio_rl32(pb);
212 switch (tag) {
213 case MKTAG('a', 'c', 'T', 'L'):
214 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
215 (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
216 return ret;
217 acTL_found = 1;
218 ctx->num_frames = AV_RB32(st->codecpar->extradata + ret + 8);
219 ctx->num_play = AV_RB32(st->codecpar->extradata + ret + 12);
220 av_log(s, AV_LOG_DEBUG, "num_frames: %"PRIu32", num_play: %"PRIu32"\n",
221 ctx->num_frames, ctx->num_play);
222 break;
223 case MKTAG('f', 'c', 'T', 'L'):
224 if (!acTL_found || len != APNG_FCTL_CHUNK_SIZE) {
225 return AVERROR_INVALIDDATA;
226 }
227 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
228 return ret;
229 return 0;
230 default:
231 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
232 (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
233 return ret;
234 }
235 }
236}
237
239{
240 uint32_t sequence_number, width, height, x_offset, y_offset;
241 uint16_t delay_num, delay_den;
242 uint8_t dispose_op, blend_op;
243
244 sequence_number = avio_rb32(s->pb);
245 width = avio_rb32(s->pb);
246 height = avio_rb32(s->pb);
247 x_offset = avio_rb32(s->pb);
248 y_offset = avio_rb32(s->pb);
249 delay_num = avio_rb16(s->pb);
250 delay_den = avio_rb16(s->pb);
251 dispose_op = avio_r8(s->pb);
252 blend_op = avio_r8(s->pb);
253 avio_skip(s->pb, 4); /* crc */
254
255 /* default is hundredths of seconds */
256 if (!delay_den)
257 delay_den = 100;
258 if (!delay_num || (ctx->max_fps && delay_den / delay_num > ctx->max_fps)) {
259 delay_num = 1;
260 delay_den = ctx->default_fps;
261 }
262 ctx->pkt_duration = av_rescale_q(delay_num,
263 (AVRational){ 1, delay_den },
264 s->streams[0]->time_base);
265
266 av_log(s, AV_LOG_DEBUG, "%s: "
267 "sequence_number: %"PRId32", "
268 "width: %"PRIu32", "
269 "height: %"PRIu32", "
270 "x_offset: %"PRIu32", "
271 "y_offset: %"PRIu32", "
272 "delay_num: %"PRIu16", "
273 "delay_den: %"PRIu16", "
274 "dispose_op: %d, "
275 "blend_op: %d\n",
276 __func__,
277 sequence_number,
278 width,
279 height,
280 x_offset,
281 y_offset,
282 delay_num,
283 delay_den,
284 dispose_op,
285 blend_op);
286
287 if (width != s->streams[0]->codecpar->width ||
288 height != s->streams[0]->codecpar->height ||
289 x_offset != 0 ||
290 y_offset != 0) {
291 if (sequence_number == 0 ||
292 x_offset >= s->streams[0]->codecpar->width ||
293 width > s->streams[0]->codecpar->width - x_offset ||
294 y_offset >= s->streams[0]->codecpar->height ||
295 height > s->streams[0]->codecpar->height - y_offset)
296 return AVERROR_INVALIDDATA;
297 ctx->is_key_frame = 0;
298 } else {
299 if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS)
300 dispose_op = APNG_DISPOSE_OP_BACKGROUND;
301 ctx->is_key_frame = dispose_op == APNG_DISPOSE_OP_BACKGROUND ||
302 blend_op == APNG_BLEND_OP_SOURCE;
303 }
304
305 return 0;
306}
307
309{
310 APNGDemuxContext *ctx = s->priv_data;
311 int64_t ret;
313 AVIOContext *pb = s->pb;
314 uint32_t len, tag;
315
316 /*
317 * fcTL chunk length, in bytes:
318 * 4 (length)
319 * 4 (tag)
320 * 26 (actual chunk)
321 * 4 (crc) bytes
322 * and needed next:
323 * 4 (length)
324 * 4 (tag (must be fdAT or IDAT))
325 */
326 /* if num_play is not 1, then the seekback is already guaranteed */
327 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 46)) < 0)
328 return ret;
329
330 len = avio_rb32(pb);
331 tag = avio_rl32(pb);
332
333 if (avio_feof(pb))
334 return AVERROR_EOF;
335
336 switch (tag) {
337 case MKTAG('f', 'c', 'T', 'L'):
339 return AVERROR_INVALIDDATA;
340
341 if ((ret = decode_fctl_chunk(s, ctx)) < 0)
342 return ret;
343
344 /* fcTL may be followed by other chunks before fdAT or IDAT */
345 len = avio_rb32(pb);
346 tag = avio_rl32(pb);
347 if (len > 0x7fffffff)
348 return AVERROR_INVALIDDATA;
349
350 /* check for empty frame */
351 if (tag == MKTAG('f', 'c', 'T', 'L') ||
352 tag == MKTAG('I', 'E', 'N', 'D'))
353 return AVERROR_INVALIDDATA;
354
355 size = 38 /* fcTL */ + 8 /* len, tag */ + len + 4 /* crc */;
356 if (size > INT_MAX)
357 return AVERROR(EINVAL);
358
359 if ((ret = avio_seek(pb, -46, SEEK_CUR)) < 0 ||
360 (ret = av_append_packet(pb, pkt, size)) < 0)
361 return ret;
362
363 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
364 return ret;
365
366 len = avio_rb32(pb);
367 tag = avio_rl32(pb);
368 while (tag &&
369 tag != MKTAG('f', 'c', 'T', 'L') &&
370 tag != MKTAG('I', 'E', 'N', 'D')) {
371 if (len > 0x7fffffff)
372 return AVERROR_INVALIDDATA;
373 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
374 (ret = av_append_packet(pb, pkt, len + 12)) < 0)
375 return ret;
376 if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
377 return ret;
378 len = avio_rb32(pb);
379 tag = avio_rl32(pb);
380 }
381 if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
382 return ret;
383
384 if (ctx->is_key_frame)
385 pkt->flags |= AV_PKT_FLAG_KEY;
386 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
387 pkt->duration = ctx->pkt_duration;
388 return ret;
389 case MKTAG('I', 'E', 'N', 'D'):
390 ctx->cur_loop++;
391 if (ctx->ignore_loop || ctx->num_play >= 1 && ctx->cur_loop == ctx->num_play) {
392 avio_seek(pb, -8, SEEK_CUR);
393 return AVERROR_EOF;
394 }
395 if ((ret = avio_seek(pb, s->streams[0]->codecpar->extradata_size + 8, SEEK_SET)) < 0)
396 return ret;
397 return 0;
398 default:
399 avpriv_request_sample(s, "In-stream tag=%s (0x%08"PRIX32") len=%"PRIu32,
401 avio_skip(pb, len + 4);
402 }
403
404 /* Handle the unsupported yet cases */
406}
407
408static const AVOption options[] = {
409 { "ignore_loop", "ignore loop setting" , offsetof(APNGDemuxContext, ignore_loop),
410 AV_OPT_TYPE_BOOL, { .i64 = 1 } , 0, 1 , AV_OPT_FLAG_DECODING_PARAM },
411 { "max_fps" , "maximum framerate (0 is no limit)" , offsetof(APNGDemuxContext, max_fps),
412 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
413 { "default_fps", "default framerate (0 is as fast as possible)", offsetof(APNGDemuxContext, default_fps),
415 { NULL },
416};
417
418static const AVClass demuxer_class = {
419 .class_name = "APNG demuxer",
420 .item_name = av_default_item_name,
421 .option = options,
422 .version = LIBAVUTIL_VERSION_INT,
423 .category = AV_CLASS_CATEGORY_DEMUXER,
424};
425
427 .p.name = "apng",
428 .p.long_name = NULL_IF_CONFIG_SMALL("Animated Portable Network Graphics"),
429 .p.flags = AVFMT_GENERIC_INDEX,
430 .p.priv_class = &demuxer_class,
431 .priv_data_size = sizeof(APNGDemuxContext),
435};
const FFInputFormat ff_apng_demuxer
Definition apngdec.c:426
static AVFormatContext * ctx
APNG common header.
#define APNG_FCTL_CHUNK_SIZE
Definition apng.h:42
@ APNG_DISPOSE_OP_BACKGROUND
Definition apng.h:32
@ APNG_DISPOSE_OP_PREVIOUS
Definition apng.h:33
@ APNG_BLEND_OP_SOURCE
Definition apng.h:37
static int apng_read_header(AVFormatContext *s)
Definition apngdec.c:149
static int decode_fctl_chunk(AVFormatContext *s, APNGDemuxContext *ctx)
Definition apngdec.c:238
static int apng_probe(const AVProbeData *p)
Definition apngdec.c:71
static const AVClass demuxer_class
Definition apngdec.c:418
static int append_extradata(AVCodecParameters *par, AVIOContext *pb, int len)
Definition apngdec.c:126
static int apng_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition apngdec.c:308
#define DEFAULT_APNG_FPS
Definition apngdec.c:41
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:834
Main libavformat public API header.
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
Read data and append it to the current content of the AVPacket.
Definition utils.c:114
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:483
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition avformat.h:499
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
uint64_t avio_rb64(AVIOContext *s)
Definition aviobuf.c:911
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
unsigned int avio_rb16(AVIOContext *s)
Definition aviobuf.c:749
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:494
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
unsigned int avio_rl32(AVIOContext *s)
Definition aviobuf.c:733
unsigned int avio_rb32(AVIOContext *s)
Definition aviobuf.c:764
int avio_r8(AVIOContext *s)
Definition aviobuf.c:606
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition aviobuf.c:1026
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:665
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
static av_always_inline int bytestream2_get_bytes_left(const GetByteContext *g)
Definition bytestream.h:158
static av_always_inline void bytestream2_init(GetByteContext *g, const uint8_t *buf, int buf_size)
Definition bytestream.h:137
static av_always_inline void bytestream2_skip(GetByteContext *g, unsigned int size)
Definition bytestream.h:168
#define s(width, name)
Definition cbs_vp9.c:198
static int read_probe(const AVProbeData *p)
Definition cdg.c:30
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static AVPacket * pkt
static struct @346255127015250356166251341105367306144006377143 state
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:578
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition opt.h:355
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_CODEC_ID_APNG
Definition codec_id.h:260
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
#define av_fourcc2str(fourcc)
Definition avutil.h:323
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
Check if the given dimension of an image is valid, meaning that all bytes of the image can be address...
Definition imgutils.c:318
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
misc image utilities
#define AV_WB32(p, v)
#define AV_WL32(p, v)
#define AV_RB32(p)
unsigned offset
Definition libaomenc.c:763
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0.
Definition utils.c:237
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
@ AV_CLASS_CATEGORY_DEMUXER
Definition log.h:33
#define MKTAG(a, b, c, d)
Definition macros.h:55
Memory handling functions.
uint32_t tag
Definition movenc.c:2087
#define av_realloc(p, s)
Definition ops_static.c:54
AVOptions.
#define PNGSIG
Definition png.h:49
uint32_t num_frames
Definition apngdec.c:57
uint32_t num_play
Definition apngdec.c:58
uint32_t cur_loop
Definition apngdec.c:59
Describe the class of an AVClass context structure.
Definition log.h:76
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
int height
The height of the video frame in pixels.
Definition codec_par.h:150
int width
The width of the video frame in pixels.
Definition codec_par.h:143
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
Format I/O context.
Definition avformat.h:1333
Bytestream IO Context.
Definition avio.h:160
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
This structure contains the data a format has to probe a file.
Definition avformat.h:471
Rational number (pair of numerator and denominator).
Definition rational.h:58
Stream structure.
Definition avformat.h:766
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:789
#define avpriv_request_sample(...)
#define av_log(a,...)
#define height
Definition dsp.h:89
#define width
Definition dsp.h:89
int size
int len