Coverage Report

Created: 2025-12-31 07:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavformat/apngdec.c
Line
Count
Source
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"
34
#include "libavutil/intreadwrite.h"
35
#include "libavutil/mem.h"
36
#include "libavutil/opt.h"
37
#include "libavcodec/apng.h"
38
#include "libavcodec/png.h"
39
#include "libavcodec/bytestream.h"
40
41
#define DEFAULT_APNG_FPS 15
42
43
typedef struct APNGDemuxContext {
44
    const AVClass *class;
45
46
    int max_fps;
47
    int default_fps;
48
49
    int pkt_duration;
50
51
    int is_key_frame;
52
53
    /*
54
     * loop options
55
     */
56
    int ignore_loop;
57
    uint32_t num_frames;
58
    uint32_t num_play;
59
    uint32_t cur_loop;
60
} APNGDemuxContext;
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
 */
71
static int apng_probe(const AVProbeData *p)
72
942k
{
73
942k
    GetByteContext gb;
74
942k
    int state = 0;
75
942k
    uint32_t len, tag;
76
77
942k
    bytestream2_init(&gb, p->buf, p->buf_size);
78
79
942k
    if (bytestream2_get_be64(&gb) != PNGSIG)
80
937k
        return 0;
81
82
14.1k
    for (;;) {
83
14.1k
        len = bytestream2_get_be32(&gb);
84
14.1k
        if (len > 0x7fffffff)
85
456
            return 0;
86
87
13.7k
        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
13.7k
        if (tag != MKTAG('I', 'D', 'A', 'T') &&
91
13.5k
            len + 4 > bytestream2_get_bytes_left(&gb))
92
4.05k
            return 0;
93
94
9.68k
        switch (tag) {
95
487
        case MKTAG('I', 'H', 'D', 'R'):
96
487
            if (len != 13)
97
15
                return 0;
98
472
            if (av_image_check_size(bytestream2_get_be32(&gb), bytestream2_get_be32(&gb), 0, NULL))
99
103
                return 0;
100
369
            bytestream2_skip(&gb, 9);
101
369
            state++;
102
369
            break;
103
202
        case MKTAG('a', 'c', 'T', 'L'):
104
202
            if (state != 1 ||
105
177
                len != 8 ||
106
149
                bytestream2_get_be32(&gb) == 0) /* 0 is not a valid value for number of frames */
107
61
                return 0;
108
141
            bytestream2_skip(&gb, 8);
109
141
            state++;
110
141
            break;
111
144
        case MKTAG('I', 'D', 'A', 'T'):
112
144
            if (state != 2)
113
30
                return 0;
114
114
            goto end;
115
8.84k
        default:
116
            /* skip other tags */
117
8.84k
            bytestream2_skip(&gb, len + 4);
118
8.84k
            break;
119
9.68k
        }
120
9.68k
    }
121
122
114
end:
123
114
    return AVPROBE_SCORE_MAX;
124
4.83k
}
125
126
static int append_extradata(AVCodecParameters *par, AVIOContext *pb, int len)
127
34.4k
{
128
34.4k
    int previous_size = par->extradata_size;
129
34.4k
    int new_size, ret;
130
34.4k
    uint8_t *new_extradata;
131
132
34.4k
    if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE - previous_size)
133
24
        return AVERROR_INVALIDDATA;
134
135
34.3k
    new_size = previous_size + len;
136
34.3k
    new_extradata = av_realloc(par->extradata, new_size + AV_INPUT_BUFFER_PADDING_SIZE);
137
34.3k
    if (!new_extradata)
138
0
        return AVERROR(ENOMEM);
139
34.3k
    memset(new_extradata + new_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
140
34.3k
    par->extradata = new_extradata;
141
34.3k
    par->extradata_size = new_size;
142
143
34.3k
    if ((ret = ffio_read_size(pb, par->extradata + previous_size, len)) < 0)
144
397
        return ret;
145
146
33.9k
    return previous_size;
147
34.3k
}
148
149
static int apng_read_header(AVFormatContext *s)
150
4.41k
{
151
4.41k
    APNGDemuxContext *ctx = s->priv_data;
152
4.41k
    AVIOContext *pb = s->pb;
153
4.41k
    uint32_t len, tag;
154
4.41k
    AVStream *st;
155
4.41k
    int acTL_found = 0;
156
4.41k
    int64_t ret;
157
158
    /* verify PNGSIG */
159
4.41k
    if (avio_rb64(pb) != PNGSIG)
160
203
        return AVERROR_INVALIDDATA;
161
162
    /* parse IHDR (must be first chunk) */
163
4.21k
    len = avio_rb32(pb);
164
4.21k
    tag = avio_rl32(pb);
165
4.21k
    if (len != 13 || tag != MKTAG('I', 'H', 'D', 'R'))
166
103
        return AVERROR_INVALIDDATA;
167
168
4.10k
    st = avformat_new_stream(s, NULL);
169
4.10k
    if (!st)
170
0
        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
4.10k
    avpriv_set_pts_info(st, 64, 1, 100000);
175
4.10k
    st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
176
4.10k
    st->codecpar->codec_id   = AV_CODEC_ID_APNG;
177
4.10k
    st->codecpar->width      = avio_rb32(pb);
178
4.10k
    st->codecpar->height     = avio_rb32(pb);
179
4.10k
    if ((ret = av_image_check_size(st->codecpar->width, st->codecpar->height, 0, s)) < 0)
180
184
        return ret;
181
182
    /* extradata will contain every chunk up to the first fcTL (excluded) */
183
3.92k
    ret = ff_alloc_extradata(st->codecpar, len + 12);
184
3.92k
    if (ret < 0)
185
0
        return ret;
186
3.92k
    AV_WB32(st->codecpar->extradata,    len);
187
3.92k
    AV_WL32(st->codecpar->extradata+4,  tag);
188
3.92k
    AV_WB32(st->codecpar->extradata+8,  st->codecpar->width);
189
3.92k
    AV_WB32(st->codecpar->extradata+12, st->codecpar->height);
190
3.92k
    if ((ret = ffio_read_size(pb, st->codecpar->extradata + 16, 9)) < 0)
191
32
        return ret;
192
193
37.8k
    while (1) {
194
37.8k
        if (acTL_found && ctx->num_play != 1) {
195
20.8k
            int64_t size   = avio_size(pb);
196
20.8k
            int64_t offset = avio_tell(pb);
197
20.8k
            if (size < 0) {
198
59
                return size;
199
20.8k
            } else if (offset < 0) {
200
0
                return offset;
201
20.8k
            } else if ((ret = ffio_ensure_seekback(pb, size - offset)) < 0) {
202
833
                av_log(s, AV_LOG_WARNING, "Could not ensure seekback, will not loop\n");
203
833
                ctx->num_play = 1;
204
833
            }
205
20.8k
        }
206
37.8k
        if ((ctx->num_play == 1 || !acTL_found) &&
207
17.8k
            ((ret = ffio_ensure_seekback(pb, 4 /* len */ + 4 /* tag */)) < 0))
208
0
            return ret;
209
210
37.8k
        len = avio_rb32(pb);
211
37.8k
        if (len > INT_MAX - 12)
212
48
            return AVERROR_INVALIDDATA;
213
214
37.7k
        tag = avio_rl32(pb);
215
37.7k
        switch (tag) {
216
3.90k
        case MKTAG('a', 'c', 'T', 'L'):
217
3.90k
            if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
218
3.89k
                (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
219
58
                return ret;
220
3.84k
            acTL_found = 1;
221
3.84k
            ctx->num_frames = AV_RB32(st->codecpar->extradata + ret + 8);
222
3.84k
            ctx->num_play   = AV_RB32(st->codecpar->extradata + ret + 12);
223
3.84k
            av_log(s, AV_LOG_DEBUG, "num_frames: %"PRIu32", num_play: %"PRIu32"\n",
224
3.84k
                                    ctx->num_frames, ctx->num_play);
225
3.84k
            break;
226
3.20k
        case MKTAG('f', 'c', 'T', 'L'):
227
3.20k
            if (!acTL_found || len != APNG_FCTL_CHUNK_SIZE) {
228
34
                return AVERROR_INVALIDDATA;
229
34
            }
230
3.17k
            if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
231
4
                return ret;
232
3.17k
            return 0;
233
30.6k
        default:
234
30.6k
            if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
235
30.5k
                (ret = append_extradata(st->codecpar, pb, len + 12)) < 0)
236
519
                return ret;
237
37.7k
        }
238
37.7k
    }
239
3.89k
}
240
241
static int decode_fctl_chunk(AVFormatContext *s, APNGDemuxContext *ctx, AVPacket *pkt)
242
89.4k
{
243
89.4k
    uint32_t sequence_number, width, height, x_offset, y_offset;
244
89.4k
    uint16_t delay_num, delay_den;
245
89.4k
    uint8_t dispose_op, blend_op;
246
247
89.4k
    sequence_number = avio_rb32(s->pb);
248
89.4k
    width           = avio_rb32(s->pb);
249
89.4k
    height          = avio_rb32(s->pb);
250
89.4k
    x_offset        = avio_rb32(s->pb);
251
89.4k
    y_offset        = avio_rb32(s->pb);
252
89.4k
    delay_num       = avio_rb16(s->pb);
253
89.4k
    delay_den       = avio_rb16(s->pb);
254
89.4k
    dispose_op      = avio_r8(s->pb);
255
89.4k
    blend_op        = avio_r8(s->pb);
256
89.4k
    avio_skip(s->pb, 4); /* crc */
257
258
    /* default is hundredths of seconds */
259
89.4k
    if (!delay_den)
260
2.60k
        delay_den = 100;
261
89.4k
    if (!delay_num || (ctx->max_fps && delay_den / delay_num > ctx->max_fps)) {
262
2.30k
        delay_num = 1;
263
2.30k
        delay_den = ctx->default_fps;
264
2.30k
    }
265
89.4k
    ctx->pkt_duration = av_rescale_q(delay_num,
266
89.4k
                                     (AVRational){ 1, delay_den },
267
89.4k
                                     s->streams[0]->time_base);
268
269
89.4k
    av_log(s, AV_LOG_DEBUG, "%s: "
270
89.4k
            "sequence_number: %"PRId32", "
271
89.4k
            "width: %"PRIu32", "
272
89.4k
            "height: %"PRIu32", "
273
89.4k
            "x_offset: %"PRIu32", "
274
89.4k
            "y_offset: %"PRIu32", "
275
89.4k
            "delay_num: %"PRIu16", "
276
89.4k
            "delay_den: %"PRIu16", "
277
89.4k
            "dispose_op: %d, "
278
89.4k
            "blend_op: %d\n",
279
89.4k
            __func__,
280
89.4k
            sequence_number,
281
89.4k
            width,
282
89.4k
            height,
283
89.4k
            x_offset,
284
89.4k
            y_offset,
285
89.4k
            delay_num,
286
89.4k
            delay_den,
287
89.4k
            dispose_op,
288
89.4k
            blend_op);
289
290
89.4k
    if (width != s->streams[0]->codecpar->width ||
291
69.3k
        height != s->streams[0]->codecpar->height ||
292
67.8k
        x_offset != 0 ||
293
67.8k
        y_offset != 0) {
294
21.6k
        if (sequence_number == 0 ||
295
21.2k
            x_offset >= s->streams[0]->codecpar->width ||
296
20.9k
            width > s->streams[0]->codecpar->width - x_offset ||
297
20.7k
            y_offset >= s->streams[0]->codecpar->height ||
298
20.6k
            height > s->streams[0]->codecpar->height - y_offset)
299
1.19k
            return AVERROR_INVALIDDATA;
300
20.4k
        ctx->is_key_frame = 0;
301
67.7k
    } else {
302
67.7k
        if (sequence_number == 0 && dispose_op == APNG_DISPOSE_OP_PREVIOUS)
303
13
            dispose_op = APNG_DISPOSE_OP_BACKGROUND;
304
67.7k
        ctx->is_key_frame = dispose_op == APNG_DISPOSE_OP_BACKGROUND ||
305
67.4k
                            blend_op   == APNG_BLEND_OP_SOURCE;
306
67.7k
    }
307
308
88.2k
    return 0;
309
89.4k
}
310
311
static int apng_read_packet(AVFormatContext *s, AVPacket *pkt)
312
92.9k
{
313
92.9k
    APNGDemuxContext *ctx = s->priv_data;
314
92.9k
    int64_t ret;
315
92.9k
    int64_t size;
316
92.9k
    AVIOContext *pb = s->pb;
317
92.9k
    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
92.9k
    if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 46)) < 0)
331
0
        return ret;
332
333
92.9k
    len = avio_rb32(pb);
334
92.9k
    tag = avio_rl32(pb);
335
336
92.9k
    if (avio_feof(pb))
337
1.98k
        return AVERROR_EOF;
338
339
90.9k
    switch (tag) {
340
89.5k
    case MKTAG('f', 'c', 'T', 'L'):
341
89.5k
        if (len != APNG_FCTL_CHUNK_SIZE)
342
184
            return AVERROR_INVALIDDATA;
343
344
89.4k
        if ((ret = decode_fctl_chunk(s, ctx, pkt)) < 0)
345
1.19k
            return ret;
346
347
        /* fcTL may be followed by other chunks before fdAT or IDAT */
348
88.2k
        len = avio_rb32(pb);
349
88.2k
        tag = avio_rl32(pb);
350
88.2k
        if (len > 0x7fffffff)
351
54
            return AVERROR_INVALIDDATA;
352
353
        /* check for empty frame */
354
88.1k
        if (tag == MKTAG('f', 'c', 'T', 'L') ||
355
88.1k
            tag == MKTAG('I', 'E', 'N', 'D'))
356
7
            return AVERROR_INVALIDDATA;
357
358
88.1k
        size = 38 /* fcTL */ + 8 /* len, tag */ + len + 4 /* crc */;
359
88.1k
        if (size > INT_MAX)
360
5
            return AVERROR(EINVAL);
361
362
88.1k
        if ((ret = avio_seek(pb, -46, SEEK_CUR)) < 0 ||
363
87.9k
            (ret = av_append_packet(pb, pkt, size)) < 0)
364
425
            return ret;
365
366
87.7k
        if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
367
0
            return ret;
368
369
87.7k
        len = avio_rb32(pb);
370
87.7k
        tag = avio_rl32(pb);
371
95.6k
        while (tag &&
372
94.1k
               tag != MKTAG('f', 'c', 'T', 'L') &&
373
7.99k
               tag != MKTAG('I', 'E', 'N', 'D')) {
374
7.98k
            if (len > 0x7fffffff)
375
71
                return AVERROR_INVALIDDATA;
376
7.91k
            if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 ||
377
7.90k
                (ret = av_append_packet(pb, pkt, len + 12)) < 0)
378
35
                return ret;
379
7.88k
            if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0)
380
0
                return ret;
381
7.88k
            len = avio_rb32(pb);
382
7.88k
            tag = avio_rl32(pb);
383
7.88k
        }
384
87.6k
        if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0)
385
471
            return ret;
386
387
87.1k
        if (ctx->is_key_frame)
388
66.9k
            pkt->flags |= AV_PKT_FLAG_KEY;
389
87.1k
        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
390
87.1k
        pkt->duration = ctx->pkt_duration;
391
87.1k
        return ret;
392
15
    case MKTAG('I', 'E', 'N', 'D'):
393
15
        ctx->cur_loop++;
394
15
        if (ctx->ignore_loop || ctx->num_play >= 1 && ctx->cur_loop == ctx->num_play) {
395
15
            avio_seek(pb, -8, SEEK_CUR);
396
15
            return AVERROR_EOF;
397
15
        }
398
0
        if ((ret = avio_seek(pb, s->streams[0]->codecpar->extradata_size + 8, SEEK_SET)) < 0)
399
0
            return ret;
400
0
        return 0;
401
1.35k
    default:
402
1.35k
        avpriv_request_sample(s, "In-stream tag=%s (0x%08"PRIX32") len=%"PRIu32,
403
1.35k
                              av_fourcc2str(tag), tag, len);
404
1.35k
        avio_skip(pb, len + 4);
405
90.9k
    }
406
407
    /* Handle the unsupported yet cases */
408
1.35k
    return AVERROR_PATCHWELCOME;
409
90.9k
}
410
411
static const AVOption options[] = {
412
    { "ignore_loop", "ignore loop setting"                         , offsetof(APNGDemuxContext, ignore_loop),
413
      AV_OPT_TYPE_BOOL, { .i64 = 1 }              , 0, 1      , AV_OPT_FLAG_DECODING_PARAM },
414
    { "max_fps"    , "maximum framerate (0 is no limit)"           , offsetof(APNGDemuxContext, max_fps),
415
      AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
416
    { "default_fps", "default framerate (0 is as fast as possible)", offsetof(APNGDemuxContext, default_fps),
417
      AV_OPT_TYPE_INT, { .i64 = DEFAULT_APNG_FPS }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
418
    { NULL },
419
};
420
421
static const AVClass demuxer_class = {
422
    .class_name = "APNG demuxer",
423
    .item_name  = av_default_item_name,
424
    .option     = options,
425
    .version    = LIBAVUTIL_VERSION_INT,
426
    .category   = AV_CLASS_CATEGORY_DEMUXER,
427
};
428
429
const FFInputFormat ff_apng_demuxer = {
430
    .p.name         = "apng",
431
    .p.long_name    = NULL_IF_CONFIG_SMALL("Animated Portable Network Graphics"),
432
    .p.flags        = AVFMT_GENERIC_INDEX,
433
    .p.priv_class   = &demuxer_class,
434
    .priv_data_size = sizeof(APNGDemuxContext),
435
    .read_probe     = apng_probe,
436
    .read_header    = apng_read_header,
437
    .read_packet    = apng_read_packet,
438
};