FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 "libavutil/intreadwrite.h"
29 #include "libavutil/opt.h"
30 #include "internal.h"
31 #include "libavcodec/gif.h"
32 
33 typedef struct GIFDemuxContext {
34  const AVClass *class;
35  /**
36  * Time span in hundredths of second before
37  * the next frame should be drawn on screen.
38  */
39  int delay;
40  /**
41  * Minimum allowed delay between frames in hundredths of
42  * second. Values below this threshold considered to be
43  * invalid and set to value of default_delay.
44  */
45  int min_delay;
46  int max_delay;
48 
49  /**
50  * loop options
51  */
56 
57 /**
58  * Major web browsers display gifs at ~10-15fps when rate
59  * is not explicitly set or have too low values. We assume default rate to be 10.
60  * Default delay = 100hundredths of second / 10fps = 10hos per frame.
61  */
62 #define GIF_DEFAULT_DELAY 10
63 /**
64  * By default delay values less than this threshold considered to be invalid.
65  */
66 #define GIF_MIN_DELAY 2
67 
68 static int gif_probe(AVProbeData *p)
69 {
70  /* check magick */
71  if (memcmp(p->buf, gif87a_sig, 6) && memcmp(p->buf, gif89a_sig, 6))
72  return 0;
73 
74  /* width or height contains zero? */
75  if (!AV_RL16(&p->buf[6]) || !AV_RL16(&p->buf[8]))
76  return 0;
77 
78  return AVPROBE_SCORE_MAX;
79 }
80 
81 static int resync(AVIOContext *pb)
82 {
83  int i;
84  for (i = 0; i < 6; i++) {
85  int b = avio_r8(pb);
86  if (b != gif87a_sig[i] && b != gif89a_sig[i])
87  i = -(b != 'G');
88  if (avio_feof(pb))
89  return AVERROR_EOF;
90  }
91  return 0;
92 }
93 
95 {
96  GIFDemuxContext *gdc = s->priv_data;
97  AVIOContext *pb = s->pb;
98  AVStream *st;
99  int width, height, ret;
100 
101  if ((ret = resync(pb)) < 0)
102  return ret;
103 
104  gdc->delay = gdc->default_delay;
105  width = avio_rl16(pb);
106  height = avio_rl16(pb);
107 
108  if (width == 0 || height == 0)
109  return AVERROR_INVALIDDATA;
110 
111  st = avformat_new_stream(s, NULL);
112  if (!st)
113  return AVERROR(ENOMEM);
114 
115  /* GIF format operates with time in "hundredths of second",
116  * therefore timebase is 1/100 */
117  avpriv_set_pts_info(st, 64, 1, 100);
120  st->codec->width = width;
121  st->codec->height = height;
122 
123  /* jump to start because gif decoder needs header data too */
124  if (avio_seek(pb, 0, SEEK_SET) != 0)
125  return AVERROR(EIO);
126 
127  return 0;
128 }
129 
131 {
132  int sb_size, ret = 0;
133 
134  while (0x00 != (sb_size = avio_r8(pb))) {
135  if ((ret = avio_skip(pb, sb_size)) < 0)
136  return ret;
137  }
138 
139  return ret;
140 }
141 
143 {
144  GIFDemuxContext *gdc = s->priv_data;
145  AVIOContext *pb = s->pb;
146  int sb_size, ext_label = avio_r8(pb);
147  int ret;
148 
149  if (ext_label == GIF_GCE_EXT_LABEL) {
150  if ((sb_size = avio_r8(pb)) < 4) {
151  av_log(s, AV_LOG_FATAL, "Graphic Control Extension block's size less than 4.\n");
152  return AVERROR_INVALIDDATA;
153  }
154 
155  /* skip packed fields */
156  if ((ret = avio_skip(pb, 1)) < 0)
157  return ret;
158 
159  gdc->delay = avio_rl16(pb);
160 
161  if (gdc->delay < gdc->min_delay)
162  gdc->delay = gdc->default_delay;
163  gdc->delay = FFMIN(gdc->delay, gdc->max_delay);
164 
165  /* skip the rest of the Graphic Control Extension block */
166  if ((ret = avio_skip(pb, sb_size - 3)) < 0 )
167  return ret;
168  } else if (ext_label == GIF_APP_EXT_LABEL) {
169  uint8_t data[256];
170 
171  sb_size = avio_r8(pb);
172  ret = avio_read(pb, data, sb_size);
173  if (ret < 0 || !sb_size)
174  return ret;
175 
176  if (sb_size == strlen(NETSCAPE_EXT_STR)) {
177  sb_size = avio_r8(pb);
178  ret = avio_read(pb, data, sb_size);
179  if (ret < 0 || !sb_size)
180  return ret;
181 
182  if (sb_size == 3 && data[0] == 1) {
183  gdc->total_iter = AV_RL16(data+1);
184 
185  if (gdc->total_iter == 0)
186  gdc->total_iter = -1;
187  }
188  }
189  }
190 
191  if ((ret = gif_skip_subblocks(pb)) < 0)
192  return ret;
193 
194  return 0;
195 }
196 
198 {
199  GIFDemuxContext *gdc = s->priv_data;
200  AVIOContext *pb = s->pb;
201  int packed_fields, block_label, ct_size,
202  keyframe, frame_parsed = 0, ret;
203  int64_t frame_start = avio_tell(pb), frame_end;
204  unsigned char buf[6];
205 
206  if ((ret = avio_read(pb, buf, 6)) == 6) {
207  keyframe = memcmp(buf, gif87a_sig, 6) == 0 ||
208  memcmp(buf, gif89a_sig, 6) == 0;
209  } else if (ret < 0) {
210  return ret;
211  } else {
212  keyframe = 0;
213  }
214 
215  if (keyframe) {
216 parse_keyframe:
217  /* skip 2 bytes of width and 2 of height */
218  if ((ret = avio_skip(pb, 4)) < 0)
219  return ret;
220 
221  packed_fields = avio_r8(pb);
222 
223  /* skip 1 byte of Background Color Index and 1 byte of Pixel Aspect Ratio */
224  if ((ret = avio_skip(pb, 2)) < 0)
225  return ret;
226 
227  /* global color table presence */
228  if (packed_fields & 0x80) {
229  ct_size = 3 * (1 << ((packed_fields & 0x07) + 1));
230 
231  if ((ret = avio_skip(pb, ct_size)) < 0)
232  return ret;
233  }
234  } else {
235  avio_seek(pb, -ret, SEEK_CUR);
236  ret = AVERROR_EOF;
237  }
238 
239  while (GIF_TRAILER != (block_label = avio_r8(pb)) && !avio_feof(pb)) {
240  if (block_label == GIF_EXTENSION_INTRODUCER) {
241  if ((ret = gif_read_ext (s)) < 0 )
242  goto resync;
243  } else if (block_label == GIF_IMAGE_SEPARATOR) {
244  /* skip to last byte of Image Descriptor header */
245  if ((ret = avio_skip(pb, 8)) < 0)
246  return ret;
247 
248  packed_fields = avio_r8(pb);
249 
250  /* local color table presence */
251  if (packed_fields & 0x80) {
252  ct_size = 3 * (1 << ((packed_fields & 0x07) + 1));
253 
254  if ((ret = avio_skip(pb, ct_size)) < 0)
255  return ret;
256  }
257 
258  /* read LZW Minimum Code Size */
259  if (avio_r8(pb) < 1) {
260  av_log(s, AV_LOG_ERROR, "lzw minimum code size must be >= 1\n");
261  goto resync;
262  }
263 
264  if ((ret = gif_skip_subblocks(pb)) < 0)
265  goto resync;
266 
267  frame_end = avio_tell(pb);
268 
269  if (avio_seek(pb, frame_start, SEEK_SET) != frame_start)
270  return AVERROR(EIO);
271 
272  ret = av_get_packet(pb, pkt, frame_end - frame_start);
273  if (ret < 0)
274  return ret;
275 
276  if (keyframe)
277  pkt->flags |= AV_PKT_FLAG_KEY;
278 
279  pkt->stream_index = 0;
280  pkt->duration = gdc->delay;
281 
282  /* Graphic Control Extension's scope is single frame.
283  * Remove its influence. */
284  gdc->delay = gdc->default_delay;
285  frame_parsed = 1;
286 
287  break;
288  } else {
289  av_log(s, AV_LOG_ERROR, "invalid block label\n");
290 resync:
291  if (!keyframe)
292  avio_seek(pb, frame_start, SEEK_SET);
293  if ((ret = resync(pb)) < 0)
294  return ret;
295  frame_start = avio_tell(pb) - 6;
296  keyframe = 1;
297  goto parse_keyframe;
298  }
299  }
300 
301  if ((ret >= 0 && !frame_parsed) || ret == AVERROR_EOF) {
302  /* This might happen when there is no image block
303  * between extension blocks and GIF_TRAILER or EOF */
304  if (!gdc->ignore_loop && (block_label == GIF_TRAILER || avio_feof(pb))
305  && (gdc->total_iter < 0 || ++gdc->iter_count < gdc->total_iter))
306  return avio_seek(pb, 0, SEEK_SET);
307  return AVERROR_EOF;
308  } else
309  return ret;
310 }
311 
312 static const AVOption options[] = {
313  { "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 },
314  { "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 },
315  { "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 },
316  { "ignore_loop" , "ignore loop setting (netscape extension)" , offsetof(GIFDemuxContext, ignore_loop) , AV_OPT_TYPE_INT, {.i64 = 1} , 0, 1, AV_OPT_FLAG_DECODING_PARAM },
317  { NULL },
318 };
319 
320 static const AVClass demuxer_class = {
321  .class_name = "GIF demuxer",
322  .item_name = av_default_item_name,
323  .option = options,
324  .version = LIBAVUTIL_VERSION_INT,
325  .category = AV_CLASS_CATEGORY_DEMUXER,
326 };
327 
329  .name = "gif",
330  .long_name = NULL_IF_CONFIG_SMALL("CompuServe Graphics Interchange Format (GIF)"),
331  .priv_data_size = sizeof(GIFDemuxContext),
336  .priv_class = &demuxer_class,
337 };
#define NULL
Definition: coverity.c:32
static int gif_read_header(AVFormatContext *s)
Definition: gifdec.c:94
const char * s
Definition: avisynth_c.h:631
Bytestream IO Context.
Definition: avio.h:111
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int default_delay
Definition: gifdec.c:47
AVOption.
Definition: opt.h:255
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
static const AVOption options[]
Definition: gifdec.c:312
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4006
const char * b
Definition: vf_curves.c:109
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:203
static const uint8_t gif87a_sig[6]
Definition: gif.h:34
#define GIF_GCE_EXT_LABEL
Definition: gif.h:45
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:276
static AVPacket pkt
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_RL16
Definition: bytestream.h:85
Format I/O context.
Definition: avformat.h:1272
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:72
uint8_t
AVOptions.
int iter_count
Definition: gifdec.c:53
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3672
#define AVERROR_EOF
End of file.
Definition: error.h:55
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:241
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:365
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1180
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:537
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1208
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1168
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:528
static void frame_end(MpegEncContext *s)
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:861
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:450
#define GIF_IMAGE_SEPARATOR
Definition: gif.h:44
static int gif_skip_subblocks(AVIOContext *pb)
Definition: gifdec.c:130
int min_delay
Minimum allowed delay between frames in hundredths of second.
Definition: gifdec.c:45
static const AVClass demuxer_class
Definition: gifdec.c:320
#define FFMIN(a, b)
Definition: common.h:66
int ignore_loop
Definition: gifdec.c:54
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
ret
Definition: avfilter.c:974
int width
picture width / height.
Definition: avcodec.h:1414
#define GIF_APP_EXT_LABEL
Definition: gif.h:46
AVInputFormat ff_gif_demuxer
Definition: gifdec.c:328
#define GIF_EXTENSION_INTRODUCER
Definition: gif.h:43
static int gif_probe(AVProbeData *p)
Definition: gifdec.c:68
static int gif_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: gifdec.c:197
int max_delay
Definition: gifdec.c:46
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:620
Stream structure.
Definition: avformat.h:842
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
enum AVMediaType codec_type
Definition: avcodec.h:1249
static int resync(AVIOContext *pb)
Definition: gifdec.c:81
enum AVCodecID codec_id
Definition: avcodec.h:1258
AVIOContext * pb
I/O context.
Definition: avformat.h:1314
GIF format definitions.
static int frame_start(MpegEncContext *s)
int total_iter
loop options
Definition: gifdec.c:52
void * buf
Definition: avisynth_c.h:553
BYTE int const BYTE int int int height
Definition: avisynth_c.h:676
Describe the class of an AVClass context structure.
Definition: log.h:67
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:473
int delay
Time span in hundredths of second before the next frame should be drawn on screen.
Definition: gifdec.c:39
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:286
#define GIF_TRAILER
Definition: gif.h:42
This structure contains the data a format has to probe a file.
Definition: avformat.h:448
static int gif_read_ext(AVFormatContext *s)
Definition: gifdec.c:142
static int flags
Definition: cpu.c:47
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:460
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:642
Main libavformat public API header.
#define NETSCAPE_EXT_STR
Definition: gif.h:47
static const uint8_t gif89a_sig[6]
Definition: gif.h:35
#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:62
void * priv_data
Format private data.
Definition: avformat.h:1300
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:628
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:170
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:300
int stream_index
Definition: avcodec.h:1164
#define GIF_MIN_DELAY
By default delay values less than this threshold considered to be invalid.
Definition: gifdec.c:66
This structure stores compressed data.
Definition: avcodec.h:1139
static int width