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