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