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