FFmpeg
Loading...
Searching...
No Matches
webp_anim_dec.c
Go to the documentation of this file.
1/*
2 * Animated WebP demuxer
3 * Copyright (c) 2020 Pexeso Inc.
4 * Copyright (c) 2026 Ramiro Polla
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file
25 * Animated WebP demuxer.
26 */
27
28#include "avio_internal.h"
29#include "demux.h"
30#include "avformat.h"
31#include "internal.h"
33#include "libavutil/mem.h"
34#include "libavutil/opt.h"
35
36#define VP8X_FLAG_ANIMATION 0x02
37#define VP8X_FLAG_XMP_METADATA 0x04
38#define VP8X_FLAG_EXIF_METADATA 0x08
39#define VP8X_FLAG_ALPHA 0x10
40#define VP8X_FLAG_ICC 0x20
41
42typedef struct WebPAnimDemuxContext {
43 const AVClass *class;
44
45 /**
46 * Minimum allowed delay between frames in milliseconds.
47 * Values below this threshold are considered to be invalid
48 * and set to value of default_delay.
49 */
53
54 /*
55 * loop options
56 */
57 int ignore_loop; ///< ignore loop setting
58 int loop_count; ///< number of times to loop the animation
59 int cur_loop; ///< current loop counter
60
61 /*
62 * variables for the key frame detection
63 */
66
69
72
75
76/**
77 * Major web browsers display WebPs at ~10-15fps when rate is not
78 * explicitly set or have too low values. We assume default rate to be 10.
79 * Default delay = 1000 microseconds / 10fps = 100 milliseconds per frame.
80 */
81#define WEBP_DEFAULT_DELAY 100
82/**
83 * By default delay values less than this threshold considered to be invalid.
84 */
85#define WEBP_MIN_DELAY 10
86
87static int webp_anim_probe(const AVProbeData *p)
88{
89 const uint8_t *b = p->buf;
90
91 if (AV_RL32(b) == MKTAG('R', 'I', 'F', 'F') &&
92 AV_RL32(b + 8) == MKTAG('W', 'E', 'B', 'P') &&
93 AV_RL32(b + 12) == MKTAG('V', 'P', '8', 'X') &&
94 AV_RL32(b + 16) == 10 &&
95 (b[20] & VP8X_FLAG_ANIMATION))
96 return AVPROBE_SCORE_MAX;
97
98 return 0;
99}
100
102{
103 WebPAnimDemuxContext *ctx = s->priv_data;
104 AVIOContext *pb = s->pb;
105 int ret;
106
107 /* Check for signature. */
108 if (avio_rl32(pb) != MKTAG('R', 'I', 'F', 'F'))
109 return AVERROR_INVALIDDATA;
110 avio_skip(pb, 4); /* file size */
111 if (avio_rl32(pb) != MKTAG('W', 'E', 'B', 'P'))
112 return AVERROR_INVALIDDATA;
113
114 /* VP8X must be first chunk */
115 if (avio_rl32(pb) != MKTAG('V', 'P', '8', 'X') ||
116 avio_rl32(pb) != 10 /* chunk size */)
117 return AVERROR_INVALIDDATA;
118 ctx->vp8x_flags = avio_r8(pb);
119 if (!(ctx->vp8x_flags & VP8X_FLAG_ANIMATION))
120 return AVERROR_INVALIDDATA;
121 avio_skip(pb, 3);
122
124 if (!st)
125 return AVERROR(ENOMEM);
126
127 avpriv_set_pts_info(st, 64, 1, 1000);
131 st->codecpar->width = avio_rl24(pb) + 1;
132 st->codecpar->height = avio_rl24(pb) + 1;
133 st->start_time = 0;
134
135 int explode = (s->error_recognition & AV_EF_EXPLODE);
136 int loglevel = explode ? AV_LOG_ERROR : AV_LOG_WARNING;
137 while (1) {
139 uint32_t fourcc = avio_rl32(pb);
140 uint32_t size = avio_rl32(pb);
141
142 av_log(s, AV_LOG_DEBUG, "Chunk %s of size %u at offset %" PRId64 "\n",
144
145 if (size == UINT32_MAX)
146 return AVERROR_INVALIDDATA;
147 size += size & 1;
148
149 if (avio_feof(pb))
150 break;
151
152 switch (fourcc) {
153 case MKTAG('I', 'C', 'C', 'P'):
154 if (ctx->has_iccp) {
155 av_log(s, loglevel, "Extra ICCP chunk found\n");
156 if (explode)
157 return AVERROR_INVALIDDATA;
158 avio_skip(pb, size);
159 } else {
160 if (!(ctx->vp8x_flags & VP8X_FLAG_ICC)) {
161 av_log(s, loglevel,
162 "ICCP chunk present, but ICC Profile bit not set in the VP8X header\n");
163 if (explode)
164 return AVERROR_INVALIDDATA;
165 }
166
170 if (!sd)
171 return AVERROR(ENOMEM);
172 ret = ffio_read_size(pb, sd->data, size);
173 if (ret < 0) {
175 return ret;
176 }
177 ctx->has_iccp = 1;
178 }
179 break;
180 case MKTAG('A', 'N', 'I', 'M'):
181 if (ctx->has_anim) {
182 av_log(s, loglevel, "Extra ANIM chunk found\n");
183 if (explode)
184 return AVERROR_INVALIDDATA;
185 avio_skip(pb, size);
186 } else {
187 if (size != 6)
188 return AVERROR_INVALIDDATA;
189 uint32_t bg_color = avio_rb32(pb);
190 ctx->loop_count = avio_rl16(pb);
191 if (ctx->usebgcolor) {
193 if (!st->codecpar->extradata)
194 return AVERROR(ENOMEM);
195 AV_WB32(st->codecpar->extradata, bg_color);
196 st->codecpar->extradata_size = 4;
197 }
199 "ANIM: background BGRA 0x%08x loop count %d\n",
200 bg_color, ctx->loop_count);
201 ctx->has_anim = 1;
202 }
203 break;
204 case MKTAG('A', 'N', 'M', 'F'):
205 if (!ctx->has_anim) {
206 av_log(s, loglevel,
207 "ANMF chunk present, but no previous ANIM chunk found\n");
208 if (explode)
209 return AVERROR_INVALIDDATA;
210 ctx->loop_count = 1;
211 } else if (!ctx->ignore_loop && ctx->loop_count != 1) {
212 int64_t file_size = avio_size(pb);
213 if (file_size < 0 || offset < 0 ||
214 (ret = ffio_ensure_seekback(pb, file_size - offset)) < 0) {
216 "Could not ensure seekback, will not loop\n");
217 ctx->loop_count = 1;
218 }
219 }
220 ctx->first_anmf_offset = offset;
221 ret = avio_seek(pb, -8, SEEK_CUR);
222 if (ret < 0)
223 return ret;
224 return 0;
225 default:
226 av_log(s, AV_LOG_WARNING, "Skipping chunk: %s\n", av_fourcc2str(fourcc));
227 avio_skip(pb, size);
228 break;
229 }
230 }
231
232 return AVERROR_INVALIDDATA;
233}
234
236{
237 WebPAnimDemuxContext *ctx = s->priv_data;
238 AVIOContext *pb = s->pb;
239 int ret;
240
241 int explode = (s->error_recognition & AV_EF_EXPLODE);
242 int loglevel = explode ? AV_LOG_ERROR : AV_LOG_WARNING;
243 while (1) {
245 uint32_t fourcc = avio_rl32(pb);
246 uint32_t size = avio_rl32(pb);
247
248 if (size == UINT32_MAX)
249 return AVERROR_INVALIDDATA;
250 size += size & 1;
251
252 if (avio_feof(pb)) {
253 if (!ctx->ignore_loop &&
254 (ctx->loop_count == 0 || ++ctx->cur_loop < ctx->loop_count)) {
255 ret = avio_seek(pb, ctx->first_anmf_offset, SEEK_SET);
256 if (ret < 0)
257 return ret;
258 continue;
259 }
260 break;
261 }
262
263 av_log(s, AV_LOG_DEBUG, "Chunk %s of size %u at offset %" PRId64 "\n",
265
266 switch (fourcc) {
267 case MKTAG('A', 'N', 'M', 'F'):
268 if (size < 16)
269 return AVERROR_INVALIDDATA;
270 ret = av_get_packet(pb, pkt, size);
271 if (ret < 0)
272 return ret;
273 pkt->pos = offset;
274 if (offset == ctx->first_anmf_offset)
275 pkt->flags |= AV_PKT_FLAG_KEY;
276 pkt->pts = AV_NOPTS_VALUE;
277 pkt->dts = AV_NOPTS_VALUE;
278 uint32_t duration = AV_RL24(pkt->data + 12);
279 if (duration <= ctx->min_delay)
280 duration = ctx->default_delay;
281 pkt->duration = FFMIN(duration, ctx->max_delay);
282 return ret;
283 case MKTAG('E', 'X', 'I', 'F'):
284 if (offset == ctx->exif_offset) {
285 avio_skip(pb, size);
286 } else if (ctx->exif_offset) {
287 av_log(s, loglevel, "Extra EXIF chunk found\n");
288 if (explode)
289 return AVERROR_INVALIDDATA;
290 avio_skip(pb, size);
291 } else {
292 if (!(ctx->vp8x_flags & VP8X_FLAG_EXIF_METADATA)) {
293 av_log(s, loglevel,
294 "EXIF chunk present, but EXIF bit not set in the VP8X header\n");
295 if (explode)
296 return AVERROR_INVALIDDATA;
297 }
298
299 AVStream *st = s->streams[0];
303 if (!sd)
304 return AVERROR(ENOMEM);
305 ret = ffio_read_size(pb, sd->data, size);
306 if (ret < 0) {
308 return ret;
309 }
310 ctx->exif_offset = offset;
311 }
312 break;
313 case MKTAG('X', 'M', 'P', ' '):
314 if (offset == ctx->xmp_offset) {
315 avio_skip(pb, size);
316 } else if (ctx->xmp_offset) {
317 av_log(s, loglevel, "Extra XMP chunk found\n");
318 if (explode)
319 return AVERROR_INVALIDDATA;
320 avio_skip(pb, size);
321 } else {
322 if (!(ctx->vp8x_flags & VP8X_FLAG_XMP_METADATA)) {
323 av_log(s, loglevel,
324 "XMP chunk present, but XMP bit not set in the VP8X header\n");
325 if (explode)
326 return AVERROR_INVALIDDATA;
327 }
328
329 uint8_t *xmp = av_malloc(size + 1);
330 if (!xmp)
331 return AVERROR(ENOMEM);
332 ret = ffio_read_size(pb, xmp, size);
333 if (ret < 0) {
334 av_free(xmp);
335 return ret;
336 }
337 xmp[size] = '\0';
338 av_dict_set(&s->metadata, "xmp", xmp, AV_DICT_DONT_STRDUP_VAL);
339 ctx->xmp_offset = offset;
340 }
341 break;
342 default:
343 av_log(s, AV_LOG_WARNING, "Skipping chunk: %s\n", av_fourcc2str(fourcc));
344 avio_skip(pb, size);
345 break;
346 }
347 }
348
349 return AVERROR_EOF;
350}
351
352static const AVOption options[] = {
353 { "min_delay", "minimum valid delay between frames (in milliseconds)", offsetof(WebPAnimDemuxContext, min_delay), AV_OPT_TYPE_INT, {.i64 = WEBP_MIN_DELAY}, 0, 1000 * 60, AV_OPT_FLAG_DECODING_PARAM },
354 { "max_webp_delay", "maximum valid delay between frames (in milliseconds)", offsetof(WebPAnimDemuxContext, max_delay), AV_OPT_TYPE_INT, {.i64 = 0xffffff}, 0, 0xffffff, AV_OPT_FLAG_DECODING_PARAM },
355 { "default_delay", "default delay between frames (in milliseconds)", offsetof(WebPAnimDemuxContext, default_delay), AV_OPT_TYPE_INT, {.i64 = WEBP_DEFAULT_DELAY}, 0, 1000 * 60, AV_OPT_FLAG_DECODING_PARAM },
356 { "ignore_loop", "ignore loop setting", offsetof(WebPAnimDemuxContext, ignore_loop), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
357 { "usebgcolor", "use background color from ANIM chunk", offsetof(WebPAnimDemuxContext, usebgcolor), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
358 { NULL },
359};
360
361static const AVClass demuxer_class = {
362 .class_name = "Animated WebP demuxer",
363 .item_name = av_default_item_name,
364 .option = options,
365 .version = LIBAVUTIL_VERSION_INT,
366 .category = AV_CLASS_CATEGORY_DEMUXER,
367};
368
370 .p.name = "webp_anim",
371 .p.long_name = NULL_IF_CONFIG_SMALL("Animated WebP"),
372 .p.flags = AVFMT_GENERIC_INDEX,
373 .p.priv_class = &demuxer_class,
374 .priv_data_size = sizeof(WebPAnimDemuxContext),
378};
const FFInputFormat ff_webp_anim_demuxer
static AVFormatContext * ctx
static const AVClass demuxer_class
Definition apngdec.c:464
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
Main libavformat public API header.
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:485
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition utils.c:98
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition avformat.h:501
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:507
unsigned int avio_rl16(AVIOContext *s)
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
unsigned int avio_rl32(AVIOContext *s)
unsigned int avio_rl24(AVIOContext *s)
unsigned int avio_rb32(AVIOContext *s)
int avio_r8(AVIOContext *s)
Definition aviobuf.c:611
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition aviobuf.c:994
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:674
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
#define s(width, name)
Definition cbs_vp9.c:198
static int read_probe(const AVProbeData *p)
Definition cdg.c:30
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition defs.h:51
static AVPacket * pkt
static int64_t duration
Definition ffplay.c:359
int ret
Definition ffplay.c:391
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:580
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition opt.h:355
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_CODEC_ID_WEBP_ANIM
Definition codec_id.h:326
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
AVPacketSideData * av_packet_side_data_new(AVPacketSideData **psd, int *pnb_sd, enum AVPacketSideDataType type, size_t size, int flags)
Allocate a new packet side data.
Definition packet.c:621
void av_packet_side_data_remove(AVPacketSideData *sd, int *pnb_sd, enum AVPacketSideDataType type)
Remove side data of the given type from a side data array.
Definition packet.c:643
@ AV_PKT_DATA_ICC_PROFILE
ICC profile data consisting of an opaque octet buffer following the format described by ISO 15076-1.
Definition packet.h:271
@ AV_PKT_DATA_EXIF
Extensible image file format metadata.
Definition packet.h:369
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
#define av_fourcc2str(fourcc)
Definition avutil.h:323
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define b
Definition input.c:43
#define AV_RL24(x)
#define AV_WB32(p, v)
#define AV_RL32(p)
unsigned offset
Definition libaomenc.c:763
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
@ AV_CLASS_CATEGORY_DEMUXER
Definition log.h:33
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
Memory handling functions.
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
@ AV_PIX_FMT_ARGB
packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
Definition pixfmt.h:99
Describe the class of an AVClass context structure.
Definition log.h:76
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
int height
The height of the video frame in pixels.
Definition codec_par.h:150
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition codec_par.h:88
int width
The width of the video frame in pixels.
Definition codec_par.h:143
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition codec_par.h:83
Format I/O context.
Definition avformat.h:1401
Bytestream IO Context.
Definition avio.h:160
AVOption.
Definition opt.h:428
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition packet.h:431
uint8_t * data
Definition packet.h:432
This structure stores compressed data.
Definition packet.h:587
This structure contains the data a format has to probe a file.
Definition avformat.h:473
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition avformat.h:817
int cur_loop
current loop counter
int min_delay
Minimum allowed delay between frames in milliseconds.
int loop_count
number of times to loop the animation
int ignore_loop
ignore loop setting
#define av_free(p)
#define av_mallocz(s)
#define av_log(a,...)
int size
uint32_t fourcc
#define VP8X_FLAG_ICC
Definition webp.c:67
#define VP8X_FLAG_EXIF_METADATA
Definition webp.c:65
#define VP8X_FLAG_ANIMATION
Definition webp.c:63
#define VP8X_FLAG_XMP_METADATA
Definition webp.c:64
static int webp_anim_probe(const AVProbeData *p)
#define WEBP_DEFAULT_DELAY
Major web browsers display WebPs at ~10-15fps when rate is not explicitly set or have too low values.
static int webp_anim_read_header(AVFormatContext *s)
static int webp_anim_read_packet(AVFormatContext *s, AVPacket *pkt)
#define WEBP_MIN_DELAY
By default delay values less than this threshold considered to be invalid.