]> git.sesse.net Git - ffmpeg/blob - libavformat/apngdec.c
Merge commit '277ff7f5dc134f1c2dfc4ea0ef3540340482e3d2'
[ffmpeg] / libavformat / apngdec.c
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  * Not supported (yet):
29  *     - streams with chunks other than fcTL / fdAT / IEND after the first fcTL
30  *     - streams with multiple fdAT chunks after an fcTL one
31  */
32
33 #include "avformat.h"
34 #include "avio_internal.h"
35 #include "internal.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/png.h"
40 #include "libavcodec/bytestream.h"
41
42 #define DEFAULT_APNG_FPS 15
43
44 typedef struct APNGDemuxContext {
45     const AVClass *class;
46
47     int max_fps;
48     int default_fps;
49
50     int is_key_frame;
51
52     /*
53      * loop options
54      */
55     int ignore_loop;
56     uint32_t num_frames;
57     uint32_t num_play;
58     uint32_t cur_loop;
59 } APNGDemuxContext;
60
61 /*
62  * To be a valid APNG file, we mandate, in this order:
63  *     PNGSIG
64  *     IHDR
65  *     ...
66  *     acTL
67  *     ...
68  *     IDAT
69  */
70 static int apng_probe(AVProbeData *p)
71 {
72     GetByteContext gb;
73     int state = 0;
74     uint32_t len, tag;
75
76     bytestream2_init(&gb, p->buf, p->buf_size);
77
78     if (bytestream2_get_be64(&gb) != PNGSIG)
79         return 0;
80
81     for (;;) {
82         len = bytestream2_get_be32(&gb);
83         if (len > 0x7fffffff)
84             return 0;
85
86         tag = bytestream2_get_le32(&gb);
87         /* we don't check IDAT size, as this is the last tag
88          * we check, and it may be larger than the probe buffer */
89         if (tag != MKTAG('I', 'D', 'A', 'T') &&
90             len > bytestream2_get_bytes_left(&gb))
91             return 0;
92
93         switch (tag) {
94         case MKTAG('I', 'H', 'D', 'R'):
95             if (len != 13)
96                 return 0;
97             if (av_image_check_size(bytestream2_get_be32(&gb), bytestream2_get_be32(&gb), 0, NULL))
98                 return 0;
99             bytestream2_skip(&gb, 9);
100             state++;
101             break;
102         case MKTAG('a', 'c', 'T', 'L'):
103             if (state != 1 ||
104                 len != 8 ||
105                 bytestream2_get_be32(&gb) == 0) /* 0 is not a valid value for number of frames */
106                 return 0;
107             bytestream2_skip(&gb, 8);
108             state++;
109             break;
110         case MKTAG('I', 'D', 'A', 'T'):
111             if (state != 2)
112                 return 0;
113             goto end;
114         default:
115             /* skip other tags */
116             bytestream2_skip(&gb, len + 4);
117             break;
118         }
119     }
120
121 end:
122     return AVPROBE_SCORE_MAX;
123 }
124
125 static int append_extradata(AVCodecContext *s, AVIOContext *pb, int len)
126 {
127     int previous_size = s->extradata_size;
128     int new_size, ret;
129     uint8_t *new_extradata;
130
131     if (previous_size > INT_MAX - len)
132         return AVERROR_INVALIDDATA;
133
134     new_size = previous_size + len;
135     new_extradata = av_realloc(s->extradata, new_size + FF_INPUT_BUFFER_PADDING_SIZE);
136     if (!new_extradata)
137         return AVERROR(ENOMEM);
138     s->extradata = new_extradata;
139     s->extradata_size = new_size;
140
141     if ((ret = avio_read(pb, s->extradata + previous_size, len)) < 0)
142         return ret;
143
144     return previous_size;
145 }
146
147 static int apng_read_header(AVFormatContext *s)
148 {
149     APNGDemuxContext *ctx = s->priv_data;
150     AVIOContext *pb = s->pb;
151     uint32_t len, tag;
152     AVStream *st;
153     int ret = AVERROR_INVALIDDATA, acTL_found = 0;
154
155     /* verify PNGSIG */
156     if (avio_rb64(pb) != PNGSIG)
157         return ret;
158
159     /* parse IHDR (must be first chunk) */
160     len = avio_rb32(pb);
161     tag = avio_rl32(pb);
162     if (len != 13 || tag != MKTAG('I', 'H', 'D', 'R'))
163         return ret;
164
165     st = avformat_new_stream(s, NULL);
166     if (!st)
167         return AVERROR(ENOMEM);
168
169     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
170     st->codec->codec_id   = AV_CODEC_ID_APNG;
171     st->codec->width      = avio_rb32(pb);
172     st->codec->height     = avio_rb32(pb);
173     if ((ret = av_image_check_size(st->codec->width, st->codec->height, 0, s)) < 0)
174         return ret;
175
176     /* extradata will contain every chunk up to the first fcTL (excluded) */
177     st->codec->extradata = av_malloc(len + 12 + FF_INPUT_BUFFER_PADDING_SIZE);
178     if (!st->codec->extradata)
179         return AVERROR(ENOMEM);
180     st->codec->extradata_size = len + 12;
181     AV_WB32(st->codec->extradata,    len);
182     AV_WL32(st->codec->extradata+4,  tag);
183     AV_WB32(st->codec->extradata+8,  st->codec->width);
184     AV_WB32(st->codec->extradata+12, st->codec->height);
185     if ((ret = avio_read(pb, st->codec->extradata+16, 9)) < 0)
186         goto fail;
187
188     while (!avio_feof(pb)) {
189         if (acTL_found && ctx->num_play != 1) {
190             int64_t size   = avio_size(pb);
191             int64_t offset = avio_tell(pb);
192             if (size < 0) {
193                 ret = size;
194                 goto fail;
195             } else if (offset < 0) {
196                 ret = offset;
197                 goto fail;
198             } else if ((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             goto fail;
206
207         len = avio_rb32(pb);
208         if (len > 0x7fffffff) {
209             ret = AVERROR_INVALIDDATA;
210             goto fail;
211         }
212
213         tag = avio_rl32(pb);
214         switch (tag) {
215         case MKTAG('a', 'c', 'T', 'L'):
216             if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
217                 (ret = append_extradata(st->codec, pb, len + 12)) < 0)
218                 goto fail;
219             acTL_found = 1;
220             ctx->num_frames = AV_RB32(st->codec->extradata + ret + 8);
221             ctx->num_play   = AV_RB32(st->codec->extradata + ret + 12);
222             av_log(s, AV_LOG_DEBUG, "num_frames: %"PRIu32", num_play: %"PRIu32"\n",
223                                     ctx->num_frames, ctx->num_play);
224             break;
225         case MKTAG('f', 'c', 'T', 'L'):
226             if (!acTL_found) {
227                ret = AVERROR_INVALIDDATA;
228                goto fail;
229             }
230             if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
231                 goto fail;
232             return 0;
233         default:
234             if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
235                 (ret = append_extradata(st->codec, pb, len + 12)) < 0)
236                 goto fail;
237         }
238     }
239
240 fail:
241     if (st->codec->extradata_size) {
242         av_freep(&st->codec->extradata);
243         st->codec->extradata_size = 0;
244     }
245     return ret;
246 }
247
248 static int decode_fctl_chunk(AVFormatContext *s, APNGDemuxContext *ctx, AVPacket *pkt)
249 {
250     uint32_t sequence_number, width, height, x_offset, y_offset;
251     uint16_t delay_num, delay_den;
252     uint8_t dispose_op, blend_op;
253
254     sequence_number = avio_rb32(s->pb);
255     width           = avio_rb32(s->pb);
256     height          = avio_rb32(s->pb);
257     x_offset        = avio_rb32(s->pb);
258     y_offset        = avio_rb32(s->pb);
259     delay_num       = avio_rb16(s->pb);
260     delay_den       = avio_rb16(s->pb);
261     dispose_op      = avio_r8(s->pb);
262     blend_op        = avio_r8(s->pb);
263     avio_skip(s->pb, 4); /* crc */
264
265     /* default is hundredths of seconds */
266     if (!delay_den)
267         delay_den = 100;
268     if (!delay_num || delay_den / delay_num > ctx->max_fps) {
269         delay_num = 1;
270         delay_den = ctx->default_fps;
271     }
272     s->streams[0]->r_frame_rate.num = delay_den;
273     s->streams[0]->r_frame_rate.den = delay_num;
274     pkt->duration = 1;
275
276     av_log(s, AV_LOG_DEBUG, "%s: "
277             "sequence_number: %"PRId32", "
278             "width: %"PRIu32", "
279             "height: %"PRIu32", "
280             "x_offset: %"PRIu32", "
281             "y_offset: %"PRIu32", "
282             "delay_num: %"PRIu16", "
283             "delay_den: %"PRIu16", "
284             "dispose_op: %d, "
285             "blend_op: %d\n",
286             __FUNCTION__,
287             sequence_number,
288             width,
289             height,
290             x_offset,
291             y_offset,
292             delay_num,
293             delay_den,
294             dispose_op,
295             blend_op);
296
297     if (width != s->streams[0]->codec->width ||
298         height != s->streams[0]->codec->height ||
299         x_offset != 0 ||
300         y_offset != 0) {
301         if (sequence_number == 0)
302             return AVERROR_INVALIDDATA;
303         ctx->is_key_frame = 0;
304     } else {
305         ctx->is_key_frame = 1;
306     }
307
308     return 0;
309 }
310
311 static int apng_read_packet(AVFormatContext *s, AVPacket *pkt)
312 {
313     APNGDemuxContext *ctx = s->priv_data;
314     int ret;
315     int64_t size;
316     AVIOContext *pb = s->pb;
317     uint32_t len, tag;
318
319     /*
320      * fcTL chunk length, in bytes:
321      *  4 (length)
322      *  4 (tag)
323      * 26 (actual chunk)
324      *  4 (crc) bytes
325      * and needed next:
326      *  4 (length)
327      *  4 (tag (must be fdAT or IDAT))
328      *
329      *  TODO: support multiple fdAT following an fcTL
330      */
331     /* if num_play is not 1, then the seekback is already guaranteed */
332     if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 46)) < 0)
333         return ret;
334
335     len = avio_rb32(pb);
336     tag = avio_rl32(pb);
337     switch (tag) {
338     case MKTAG('f', 'c', 'T', 'L'):
339         if (len != 26)
340             return AVERROR_INVALIDDATA;
341
342         if ((ret = decode_fctl_chunk(s, ctx, pkt)) < 0)
343             return ret;
344
345         /* fcTL must precede fdAT or IDAT */
346         len = avio_rb32(pb);
347         tag = avio_rl32(pb);
348         if (len > 0x7fffffff ||
349             tag != MKTAG('f', 'd', 'A', 'T') &&
350             tag != MKTAG('I', 'D', 'A', 'T'))
351             return AVERROR_INVALIDDATA;
352
353         if ((ret = avio_seek(pb, -46, SEEK_CUR)) < 0)
354             return ret;
355
356         size = 38 /* fcTL */ + 8 /* len, tag */ + len + 4 /* crc */;
357         if (size > INT_MAX)
358             return AVERROR(EINVAL);
359
360         if ((ret = av_get_packet(pb, pkt, size)) < 0)
361             return ret;
362         if (ctx->is_key_frame)
363             pkt->flags |= AV_PKT_FLAG_KEY;
364         return ret;
365     case MKTAG('I', 'E', 'N', 'D'):
366         ctx->cur_loop++;
367         if (ctx->ignore_loop || ctx->num_play >= 1 && ctx->cur_loop == ctx->num_play) {
368             avio_seek(pb, -8, SEEK_CUR);
369             return AVERROR_EOF;
370         }
371         if ((ret = avio_seek(pb, s->streams[0]->codec->extradata_size + 8, SEEK_SET)) < 0)
372             return ret;
373         return 0;
374     default:
375         {
376         char tag_buf[5];
377
378         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag);
379         avpriv_request_sample(s, "In-stream tag=%s (0x%08X) len=%"PRIu32, tag_buf, tag, len);
380         avio_skip(pb, len + 4);
381         }
382     }
383
384     /* Handle the unsupported yet cases */
385     return AVERROR_PATCHWELCOME;
386 }
387
388 static const AVOption options[] = {
389     { "ignore_loop", "ignore loop setting"                         , offsetof(APNGDemuxContext, ignore_loop),
390       AV_OPT_TYPE_INT, { .i64 = 1 }               , 0, 1      , AV_OPT_FLAG_DECODING_PARAM },
391     { "max_fps"    , "maximum framerate (0 is no limit)"           , offsetof(APNGDemuxContext, max_fps),
392       AV_OPT_TYPE_INT, { .i64 = DEFAULT_APNG_FPS }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
393     { "default_fps", "default framerate (0 is as fast as possible)", offsetof(APNGDemuxContext, default_fps),
394       AV_OPT_TYPE_INT, { .i64 = DEFAULT_APNG_FPS }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
395     { NULL },
396 };
397
398 static const AVClass demuxer_class = {
399     .class_name = "APNG demuxer",
400     .item_name  = av_default_item_name,
401     .option     = options,
402     .version    = LIBAVUTIL_VERSION_INT,
403     .category   = AV_CLASS_CATEGORY_DEMUXER,
404 };
405
406 AVInputFormat ff_apng_demuxer = {
407     .name           = "apng",
408     .long_name      = NULL_IF_CONFIG_SMALL("Animated Portable Network Graphics"),
409     .priv_data_size = sizeof(APNGDemuxContext),
410     .read_probe     = apng_probe,
411     .read_header    = apng_read_header,
412     .read_packet    = apng_read_packet,
413     .flags          = AVFMT_GENERIC_INDEX,
414     .priv_class     = &demuxer_class,
415 };