FFmpeg
gifdec.c
Go to the documentation of this file.
1 /*
2  * GIF demuxer
3  * Copyright (c) 2012 Vitaliy E Sugrobov
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  * GIF demuxer.
25  */
26 
27 #include "avformat.h"
28 #include "demux.h"
29 #include "libavutil/bprint.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/opt.h"
32 #include "avio_internal.h"
33 #include "internal.h"
34 #include "libavcodec/gif.h"
35 
36 #define GIF_PACKET_SIZE 1024
37 
38 typedef struct GIFDemuxContext {
39  const AVClass *class;
40  /**
41  * Time span in hundredths of second before
42  * the next frame should be drawn on screen.
43  */
44  int delay;
45  /**
46  * Minimum allowed delay between frames in hundredths of
47  * second. Values below this threshold considered to be
48  * invalid and set to value of default_delay.
49  */
50  int min_delay;
51  int max_delay;
53 
54  /**
55  * loop options
56  */
61 
62 /**
63  * Major web browsers display gifs at ~10-15fps when rate
64  * is not explicitly set or have too low values. We assume default rate to be 10.
65  * Default delay = 100hundredths of second / 10fps = 10hos per frame.
66  */
67 #define GIF_DEFAULT_DELAY 10
68 /**
69  * By default delay values less than this threshold considered to be invalid.
70  */
71 #define GIF_MIN_DELAY 2
72 
73 static int gif_probe(const AVProbeData *p)
74 {
75  /* check magick */
76  if (memcmp(p->buf, gif87a_sig, 6) && memcmp(p->buf, gif89a_sig, 6))
77  return 0;
78 
79  /* width or height contains zero? */
80  if (!AV_RL16(&p->buf[6]) || !AV_RL16(&p->buf[8]))
81  return 0;
82 
83  return AVPROBE_SCORE_MAX;
84 }
85 
86 static int resync(AVIOContext *pb)
87 {
88  ffio_ensure_seekback(pb, 13);
89  for (int i = 0; i < 6; i++) {
90  int b = avio_r8(pb);
91  if (b != gif87a_sig[i] && b != gif89a_sig[i])
92  i = -(b != 'G');
93  if (avio_feof(pb))
94  return AVERROR_EOF;
95  }
96  return 0;
97 }
98 
100 {
101  int sb_size, ret = 0;
102 
103  while (0x00 != (sb_size = avio_r8(pb))) {
104  if ((ret = avio_skip(pb, sb_size)) < 0)
105  return ret;
106  }
107 
108  return ret;
109 }
110 
112 {
113  GIFDemuxContext *gdc = s->priv_data;
114  AVIOContext *pb = s->pb;
115  AVStream *st;
116  int type, width, height, ret, n, flags;
117  int64_t nb_frames = 0, duration = 0, pos;
118 
119  if ((ret = resync(pb)) < 0)
120  return ret;
121 
122  pos = avio_tell(pb);
123  gdc->delay = gdc->default_delay;
124  width = avio_rl16(pb);
125  height = avio_rl16(pb);
126  flags = avio_r8(pb);
127  avio_skip(pb, 1);
128  n = avio_r8(pb);
129 
130  if (width == 0 || height == 0)
131  return AVERROR_INVALIDDATA;
132 
133  st = avformat_new_stream(s, NULL);
134  if (!st)
135  return AVERROR(ENOMEM);
136 
137  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
138  goto skip;
139 
140  if (flags & 0x80)
141  avio_skip(pb, 3 * (1 << ((flags & 0x07) + 1)));
142 
143  while ((type = avio_r8(pb)) != GIF_TRAILER) {
144  if (avio_feof(pb))
145  break;
147  int subtype = avio_r8(pb);
148  if (subtype == GIF_COM_EXT_LABEL) {
149  AVBPrint bp;
150  int block_size;
151 
153  while ((block_size = avio_r8(pb)) != 0) {
154  avio_read_to_bprint(pb, &bp, block_size);
155  }
156  av_dict_set(&s->metadata, "comment", bp.str, 0);
157  av_bprint_finalize(&bp, NULL);
158  } else if (subtype == GIF_GCE_EXT_LABEL) {
159  int block_size = avio_r8(pb);
160 
161  if (block_size == 4) {
162  int delay;
163 
164  avio_skip(pb, 1);
165  delay = avio_rl16(pb);
166  delay = delay ? delay : gdc->default_delay;
167  duration += delay;
168  avio_skip(pb, 1);
169  } else {
170  avio_skip(pb, block_size);
171  }
172  gif_skip_subblocks(pb);
173  } else if (subtype == GIF_APP_EXT_LABEL) {
174  uint8_t data[256];
175  int sb_size;
176 
177  sb_size = avio_r8(pb);
178  ret = avio_read(pb, data, sb_size);
179  if (ret < 0 || !sb_size)
180  break;
181 
182  if (sb_size == strlen(NETSCAPE_EXT_STR)) {
183  sb_size = avio_r8(pb);
184  ret = avio_read(pb, data, sb_size);
185  if (ret < 0 || !sb_size)
186  break;
187 
188  if (sb_size == 3 && data[0] == 1) {
189  gdc->total_iter = AV_RL16(data+1);
190  av_log(s, AV_LOG_DEBUG, "Loop count is %d\n", gdc->total_iter);
191 
192  if (gdc->total_iter == 0)
193  gdc->total_iter = -1;
194  }
195  }
196  gif_skip_subblocks(pb);
197  } else {
198  gif_skip_subblocks(pb);
199  }
200  } else if (type == GIF_IMAGE_SEPARATOR) {
201  avio_skip(pb, 8);
202  flags = avio_r8(pb);
203  if (flags & 0x80)
204  avio_skip(pb, 3 * (1 << ((flags & 0x07) + 1)));
205  avio_skip(pb, 1);
206  gif_skip_subblocks(pb);
207  nb_frames++;
208  } else {
209  break;
210  }
211  }
212 
213 skip:
214  /* jump to start because gif decoder needs header data too */
215  if (avio_seek(pb, pos - 6, SEEK_SET) != pos - 6)
216  return AVERROR(EIO);
217 
218  /* GIF format operates with time in "hundredths of second",
219  * therefore timebase is 1/100 */
220  avpriv_set_pts_info(st, 64, 1, 100);
224  st->codecpar->width = width;
225  st->codecpar->height = height;
226  if (nb_frames > 1) {
228  100, duration / nb_frames, INT_MAX);
229  } else if (duration) {
230  st->avg_frame_rate = (AVRational) { 100, duration };
231  }
232  st->start_time = 0;
233  st->duration = duration;
234  st->nb_frames = nb_frames;
235  if (n)
236  st->codecpar->sample_aspect_ratio = av_make_q(n + 15, 64);
237 
238  return 0;
239 }
240 
242 {
243  GIFDemuxContext *gdc = s->priv_data;
244  AVIOContext *pb = s->pb;
245  int ret;
246 
247  if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
248  !gdc->ignore_loop && avio_feof(pb) &&
249  (gdc->total_iter < 0 || (++gdc->iter_count < gdc->total_iter))) {
250  avio_seek(pb, 0, SEEK_SET);
251  }
252  if ((ret = av_new_packet(pkt, GIF_PACKET_SIZE)) < 0)
253  return ret;
254 
255  pkt->pos = avio_tell(pb);
256  pkt->stream_index = 0;
258  if (ret < 0) {
260  return ret;
261  }
263  return ret;
264 }
265 
266 static const AVOption options[] = {
267  { "min_delay" , "minimum valid delay between frames (in hundredths of second)", offsetof(GIFDemuxContext, min_delay) , AV_OPT_TYPE_INT, {.i64 = GIF_MIN_DELAY} , 0, 100 * 60, AV_OPT_FLAG_DECODING_PARAM },
268  { "max_gif_delay", "maximum valid delay between frames (in hundredths of seconds)", offsetof(GIFDemuxContext, max_delay) , AV_OPT_TYPE_INT, {.i64 = 65535} , 0, 65535 , AV_OPT_FLAG_DECODING_PARAM },
269  { "default_delay", "default delay between frames (in hundredths of second)" , offsetof(GIFDemuxContext, default_delay), AV_OPT_TYPE_INT, {.i64 = GIF_DEFAULT_DELAY}, 0, 100 * 60, AV_OPT_FLAG_DECODING_PARAM },
270  { "ignore_loop" , "ignore loop setting (netscape extension)" , offsetof(GIFDemuxContext, ignore_loop) , AV_OPT_TYPE_BOOL,{.i64 = 1} , 0, 1, AV_OPT_FLAG_DECODING_PARAM },
271  { NULL },
272 };
273 
274 static const AVClass demuxer_class = {
275  .class_name = "GIF demuxer",
276  .item_name = av_default_item_name,
277  .option = options,
278  .version = LIBAVUTIL_VERSION_INT,
279  .category = AV_CLASS_CATEGORY_DEMUXER,
280 };
281 
283  .p.name = "gif",
284  .p.long_name = NULL_IF_CONFIG_SMALL("CompuServe Graphics Interchange Format (GIF)"),
285  .p.flags = AVFMT_GENERIC_INDEX,
286  .p.extensions = "gif",
287  .p.priv_class = &demuxer_class,
288  .priv_data_size = sizeof(GIFDemuxContext),
292 };
GIF_MIN_DELAY
#define GIF_MIN_DELAY
By default delay values less than this threshold considered to be invalid.
Definition: gifdec.c:71
options
static const AVOption options[]
Definition: gifdec.c:266
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:427
AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_UNLIMITED
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
GIFDemuxContext
Definition: gifdec.c:38
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:51
gif_read_header
static int gif_read_header(AVFormatContext *s)
Definition: gifdec.c:111
av_bprint_init
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
GIFDemuxContext::default_delay
int default_delay
Definition: gifdec.c:52
GIF_TRAILER
#define GIF_TRAILER
Definition: gif.h:42
AVPacket::data
uint8_t * data
Definition: packet.h:522
ff_gif_demuxer
const FFInputFormat ff_gif_demuxer
Definition: gifdec.c:282
AVOption
AVOption.
Definition: opt.h:346
b
#define b
Definition: input.c:41
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:832
data
const char data[16]
Definition: mxf.c:148
NETSCAPE_EXT_STR
#define NETSCAPE_EXT_STR
Definition: gif.h:48
GIF_GCE_EXT_LABEL
#define GIF_GCE_EXT_LABEL
Definition: gif.h:45
GIFDemuxContext::iter_count
int iter_count
Definition: gifdec.c:58
AVPROBE_SCORE_MAX
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:463
avpriv_set_pts_info
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:853
GIF_COM_EXT_LABEL
#define GIF_COM_EXT_LABEL
Definition: gif.h:46
ffstream
static av_always_inline FFStream * ffstream(AVStream *st)
Definition: internal.h:417
av_shrink_packet
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition: avpacket.c:113
avio_tell
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:494
AVFMT_GENERIC_INDEX
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:480
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:802
av_reduce
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
avio_rl16
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:713
AVRational::num
int num
Numerator.
Definition: rational.h:59
gif89a_sig
static const uint8_t gif89a_sig[6]
Definition: gif.h:35
pkt
AVPacket * pkt
Definition: movenc.c:59
duration
int64_t duration
Definition: movenc.c:64
read_packet
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_read_callback.c:41
width
#define width
intreadwrite.h
s
#define s(width, name)
Definition: cbs_vp9.c:198
GIFDemuxContext::min_delay
int min_delay
Minimum allowed delay between frames in hundredths of second.
Definition: gifdec.c:50
av_new_packet
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:98
avio_read_to_bprint
int avio_read_to_bprint(AVIOContext *h, struct AVBPrint *pb, size_t max_size)
Read contents of h into print buffer, up to max_size bytes, or up to EOF.
Definition: aviobuf.c:1250
AVCodecParameters::sample_aspect_ratio
AVRational sample_aspect_ratio
Video only.
Definition: codec_par.h:144
AVInputFormat::name
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:553
AVProbeData::buf
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:453
AVCodecParameters::width
int width
Video only.
Definition: codec_par.h:134
GIF_IMAGE_SEPARATOR
#define GIF_IMAGE_SEPARATOR
Definition: gif.h:44
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:201
AV_RL16
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_RL16
Definition: bytestream.h:94
AV_CLASS_CATEGORY_DEMUXER
@ AV_CLASS_CATEGORY_DEMUXER
Definition: log.h:33
FFStream::need_parsing
enum AVStreamParseType need_parsing
Definition: internal.h:386
AVFormatContext
Format I/O context.
Definition: avformat.h:1255
internal.h
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:766
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
read_header
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:550
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
NULL
#define NULL
Definition: coverity.c:32
demuxer_class
static const AVClass demuxer_class
Definition: gifdec.c:274
GIFDemuxContext::ignore_loop
int ignore_loop
Definition: gifdec.c:59
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
AVProbeData
This structure contains the data a format has to probe a file.
Definition: avformat.h:451
gif_read_packet
static int gif_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: gifdec.c:241
AVStream::nb_frames
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:804
gif_skip_subblocks
static int gif_skip_subblocks(AVIOContext *pb)
Definition: gifdec.c:99
AVIOContext
Bytestream IO Context.
Definition: avio.h:160
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:106
AVIOContext::seekable
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:261
av_bprint_finalize
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:240
gif.h
av_make_q
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition: rational.h:71
resync
static int resync(AVIOContext *pb)
Definition: gifdec.c:86
FFInputFormat::p
AVInputFormat p
The public AVInputFormat.
Definition: demux.h:41
avio_r8
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:602
height
#define height
GIFDemuxContext::total_iter
int total_iter
loop options
Definition: gifdec.c:57
ffio_ensure_seekback
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition: aviobuf.c:1022
AV_CODEC_ID_GIF
@ AV_CODEC_ID_GIF
Definition: codec_id.h:149
bprint.h
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:255
avio_internal.h
gif87a_sig
static const uint8_t gif87a_sig[6]
Definition: gif.h:34
GIF_PACKET_SIZE
#define GIF_PACKET_SIZE
Definition: gifdec.c:36
AVCodecParameters::height
int height
Definition: codec_par.h:135
GIF_EXTENSION_INTRODUCER
#define GIF_EXTENSION_INTRODUCER
Definition: gif.h:43
demux.h
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:743
avio_seek
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:230
AVClass::class_name
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:71
GIFDemuxContext::max_delay
int max_delay
Definition: gifdec.c:51
pos
unsigned int pos
Definition: spdifenc.c:413
avformat.h
GIFDemuxContext::delay
int delay
Time span in hundredths of second before the next frame should be drawn on screen.
Definition: gifdec.c:44
AVIO_SEEKABLE_NORMAL
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:41
AVRational::den
int den
Denominator.
Definition: rational.h:60
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:235
avio_read
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:611
gif_probe
static int gif_probe(const AVProbeData *p)
Definition: gifdec.c:73
AVSTREAM_PARSE_FULL_RAW
@ AVSTREAM_PARSE_FULL_RAW
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition: avformat.h:597
AVPacket::stream_index
int stream_index
Definition: packet.h:524
avio_skip
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:317
AV_OPT_FLAG_DECODING_PARAM
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition: opt.h:273
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
read_probe
static int read_probe(const AVProbeData *p)
Definition: cdg.c:30
GIF_APP_EXT_LABEL
#define GIF_APP_EXT_LABEL
Definition: gif.h:47
AVCodecParameters::codec_id
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:55
AVPacket
This structure stores compressed data.
Definition: packet.h:499
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Definition: opt.h:251
av_dict_set
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:88
AVPacket::pos
int64_t pos
byte position in stream, -1 if unknown
Definition: packet.h:542
FFInputFormat
Definition: demux.h:37
GIF_DEFAULT_DELAY
#define GIF_DEFAULT_DELAY
Major web browsers display gifs at ~10-15fps when rate is not explicitly set or have too low values.
Definition: gifdec.c:67
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:474
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
AVStream::start_time
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition: avformat.h:792
avio_read_partial
int avio_read_partial(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:683
skip
static void BS_FUNC() skip(BSCTX *bc, unsigned int n)
Skip n bits in the buffer.
Definition: bitstream_template.h:375
avio_feof
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:345