]> git.sesse.net Git - ffmpeg/blob - libavcodec/gifdec.c
Prepare gif decoder for use in conjunction with gif demuxer.
[ffmpeg] / libavcodec / gifdec.c
1 /*
2  * GIF decoder
3  * Copyright (c) 2003 Fabrice Bellard
4  * Copyright (c) 2006 Baptiste Coudurier
5  * Copyright (c) 2012 Vitaliy E Sugrobov
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 //#define DEBUG
25
26 #include "libavutil/imgutils.h"
27 #include "libavutil/opt.h"
28 #include "avcodec.h"
29 #include "bytestream.h"
30 #include "lzw.h"
31
32 #define GCE_DISPOSAL_NONE       0
33 #define GCE_DISPOSAL_INPLACE    1
34 #define GCE_DISPOSAL_BACKGROUND 2
35 #define GCE_DISPOSAL_RESTORE    3
36 #define GIF_TRAILER                 0x3b
37 #define GIF_EXTENSION_INTRODUCER    0x21
38 #define GIF_IMAGE_SEPARATOR         0x2c
39 #define GIF_GCE_EXT_LABEL           0xf9
40 /* This value is intentionally set to "transparent white" color.
41  * It is much better to have white background instead of black
42  * when gif image converted to format which not support transparency.
43  */
44 #define GIF_TRANSPARENT_COLOR    0x00ffffff
45
46 typedef struct GifState {
47     const AVClass *class;
48     AVFrame picture;
49     int screen_width;
50     int screen_height;
51     int has_global_palette;
52     int bits_per_pixel;
53     uint32_t bg_color;
54     int background_color_index;
55     int transparent_color_index;
56     int color_resolution;
57     /* intermediate buffer for storing color indices
58      * obtained from lzw-encoded data stream */
59     uint8_t *idx_line;
60
61     /* after the frame is displayed, the disposal method is used */
62     int gce_prev_disposal;
63     int gce_disposal;
64     /* rectangle describing area that must be disposed */
65     int gce_l, gce_t, gce_w, gce_h;
66     /* depending on disposal method we store either part of the image
67      * drawn on the canvas or background color that
68      * should be used upon disposal */
69     uint32_t * stored_img;
70     int stored_bg_color;
71
72     /* LZW compatible decoder */
73     const uint8_t *bytestream;
74     const uint8_t *bytestream_end;
75     LZWState *lzw;
76
77     /* aux buffers */
78     uint32_t global_palette[256];
79     uint32_t local_palette[256];
80
81     AVCodecContext *avctx;
82     int keyframe;
83     int trans_color;    /**< color value that is used instead of transparent color */
84 } GifState;
85
86 static const uint8_t gif87a_sig[6] = "GIF87a";
87 static const uint8_t gif89a_sig[6] = "GIF89a";
88 static void gif_read_palette(const uint8_t **buf, uint32_t *pal, int nb)
89 {
90     const uint8_t *pal_end = *buf + nb * 3;
91
92     for (; *buf < pal_end; *buf += 3, pal++)
93         *pal = (0xffu << 24) | AV_RB24(*buf);
94 }
95
96 static void gif_fill(AVFrame *picture, uint32_t color)
97 {
98     uint32_t *p = (uint32_t *)picture->data[0];
99     uint32_t *p_end = p + (picture->linesize[0] / sizeof(uint32_t)) * picture->height;
100
101     for (; p < p_end; p++)
102         *p = color;
103 }
104
105 static void gif_fill_rect(AVFrame *picture, uint32_t color, int l, int t, int w, int h)
106 {
107     const int linesize = picture->linesize[0] / sizeof(uint32_t);
108     const uint32_t *py = (uint32_t *)picture->data[0] + t * linesize;
109     const uint32_t *pr, *pb = py + (t + h) * linesize;
110     uint32_t *px;
111
112     for (; py < pb; py += linesize) {
113         px = (uint32_t *)py + l;
114         pr = px + w;
115
116         for (; px < pr; px++)
117             *px = color;
118     }
119 }
120
121 static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst,
122                               int linesize, int l, int t, int w, int h)
123 {
124     const int y_start = t * linesize;
125     const uint32_t *src_px, *src_pr,
126                    *src_py = src + y_start,
127                    *dst_py = dst + y_start;
128     const uint32_t *src_pb = src_py + (t + h) * linesize;
129     uint32_t *dst_px;
130
131     for (; src_py < src_pb; src_py += linesize, dst_py += linesize) {
132         src_px = src_py + l;
133         dst_px = (uint32_t *)dst_py + l;
134         src_pr = src_px + w;
135
136         for (; src_px < src_pr; src_px++, dst_px++)
137             *dst_px = *src_px;
138     }
139 }
140
141 static int gif_read_image(GifState *s)
142 {
143     int left, top, width, height, bits_per_pixel, code_size, flags;
144     int is_interleaved, has_local_palette, y, pass, y1, linesize, pal_size;
145     uint32_t *ptr, *pal, *px, *pr, *ptr1;
146     int ret;
147     uint8_t *idx;
148
149     left = bytestream_get_le16(&s->bytestream);
150     top = bytestream_get_le16(&s->bytestream);
151     width = bytestream_get_le16(&s->bytestream);
152     height = bytestream_get_le16(&s->bytestream);
153     flags = bytestream_get_byte(&s->bytestream);
154     is_interleaved = flags & 0x40;
155     has_local_palette = flags & 0x80;
156     bits_per_pixel = (flags & 0x07) + 1;
157
158     av_dlog(s->avctx, "image x=%d y=%d w=%d h=%d\n", left, top, width, height);
159
160     if (has_local_palette) {
161         pal_size = 1 << bits_per_pixel;
162
163         if (s->bytestream_end < s->bytestream + pal_size * 3)
164             return AVERROR_INVALIDDATA;
165
166         gif_read_palette(&s->bytestream, s->local_palette, pal_size);
167         pal = s->local_palette;
168     } else {
169         if (!s->has_global_palette) {
170             av_log(s->avctx, AV_LOG_FATAL, "picture doesn't have either global or local palette.\n");
171             return AVERROR_INVALIDDATA;
172         }
173
174         pal = s->global_palette;
175     }
176
177     if (s->keyframe) {
178         if (s->transparent_color_index == -1 && s->has_global_palette) {
179             /* transparency wasn't set before the first frame, fill with background color */
180             gif_fill(&s->picture, s->bg_color);
181         } else {
182             /* otherwise fill with transparent color.
183              * this is necessary since by default picture filled with 0x80808080. */
184             gif_fill(&s->picture, s->trans_color);
185         }
186     }
187
188     /* verify that all the image is inside the screen dimensions */
189     if (left + width > s->screen_width ||
190         top + height > s->screen_height)
191         return AVERROR(EINVAL);
192
193     /* process disposal method */
194     if (s->gce_prev_disposal == GCE_DISPOSAL_BACKGROUND) {
195         gif_fill_rect(&s->picture, s->stored_bg_color, s->gce_l, s->gce_t, s->gce_w, s->gce_h);
196     } else if (s->gce_prev_disposal == GCE_DISPOSAL_RESTORE) {
197         gif_copy_img_rect(s->stored_img, (uint32_t *)s->picture.data[0],
198             s->picture.linesize[0] / sizeof(uint32_t), s->gce_l, s->gce_t, s->gce_w, s->gce_h);
199     }
200
201     s->gce_prev_disposal = s->gce_disposal;
202
203     if (s->gce_disposal != GCE_DISPOSAL_NONE) {
204         s->gce_l = left;  s->gce_t = top;
205         s->gce_w = width; s->gce_h = height;
206
207         if (s->gce_disposal == GCE_DISPOSAL_BACKGROUND) {
208             if (s->background_color_index == s->transparent_color_index)
209                 s->stored_bg_color = s->trans_color;
210             else
211                 s->stored_bg_color = s->bg_color;
212         } else if (s->gce_disposal == GCE_DISPOSAL_RESTORE) {
213             if (!s->stored_img) {
214                 s->stored_img = av_malloc(s->picture.linesize[0] * s->picture.height);
215
216                 if (!s->stored_img)
217                     return AVERROR(ENOMEM);
218             }
219
220             gif_copy_img_rect((uint32_t *)s->picture.data[0], s->stored_img,
221                 s->picture.linesize[0] / sizeof(uint32_t), left, top, width, height);
222         }
223     }
224
225     /* now get the image data */
226     code_size = bytestream_get_byte(&s->bytestream);
227     if ((ret = ff_lzw_decode_init(s->lzw, code_size, s->bytestream,
228                        s->bytestream_end - s->bytestream, FF_LZW_GIF)) < 0) {
229         av_log(s->avctx, AV_LOG_ERROR, "LZW init failed\n");
230         return ret;
231     }
232
233     /* read all the image */
234     linesize = s->picture.linesize[0] / sizeof(uint32_t);
235     ptr1 = (uint32_t *)s->picture.data[0] + top * linesize + left;
236     ptr = ptr1;
237     pass = 0;
238     y1 = 0;
239     for (y = 0; y < height; y++) {
240         if (ff_lzw_decode(s->lzw, s->idx_line, width) == 0)
241             goto decode_tail;
242
243         pr = ptr + width;
244
245         for (px = ptr, idx = s->idx_line; px < pr; px++, idx++) {
246             if (*idx != s->transparent_color_index)
247                 *px = pal[*idx];
248         }
249
250         if (is_interleaved) {
251             switch(pass) {
252             default:
253             case 0:
254             case 1:
255                 y1 += 8;
256                 ptr += linesize * 8;
257                 if (y1 >= height) {
258                     y1 = pass ? 2 : 4;
259                     ptr = ptr1 + linesize * y1;
260                     pass++;
261                 }
262                 break;
263             case 2:
264                 y1 += 4;
265                 ptr += linesize * 4;
266                 if (y1 >= height) {
267                     y1 = 1;
268                     ptr = ptr1 + linesize;
269                     pass++;
270                 }
271                 break;
272             case 3:
273                 y1 += 2;
274                 ptr += linesize * 2;
275                 break;
276             }
277         } else {
278             ptr += linesize;
279         }
280     }
281
282  decode_tail:
283     /* read the garbage data until end marker is found */
284     ff_lzw_decode_tail(s->lzw);
285     s->bytestream = ff_lzw_cur_ptr(s->lzw);
286
287     /* Graphic Control Extension's scope is single frame.
288      * Remove its influence. */
289     s->transparent_color_index = -1;
290     s->gce_disposal = GCE_DISPOSAL_NONE;
291
292     return 0;
293 }
294
295 static int gif_read_extension(GifState *s)
296 {
297     int ext_code, ext_len, i, gce_flags, gce_transparent_index;
298
299     /* extension */
300     ext_code = bytestream_get_byte(&s->bytestream);
301     ext_len = bytestream_get_byte(&s->bytestream);
302
303     av_dlog(s->avctx, "ext_code=0x%x len=%d\n", ext_code, ext_len);
304
305     switch(ext_code) {
306     case GIF_GCE_EXT_LABEL:
307         if (ext_len != 4)
308             goto discard_ext;
309         s->transparent_color_index = -1;
310         gce_flags = bytestream_get_byte(&s->bytestream);
311         bytestream_get_le16(&s->bytestream);    // delay during which the frame is shown
312         gce_transparent_index = bytestream_get_byte(&s->bytestream);
313         if (gce_flags & 0x01)
314             s->transparent_color_index = gce_transparent_index;
315         else
316             s->transparent_color_index = -1;
317         s->gce_disposal = (gce_flags >> 2) & 0x7;
318
319         av_dlog(s->avctx, "gce_flags=%x tcolor=%d disposal=%d\n",
320                gce_flags,
321                s->transparent_color_index, s->gce_disposal);
322
323         if (s->gce_disposal > 3) {
324             s->gce_disposal = GCE_DISPOSAL_NONE;
325             av_dlog(s->avctx, "invalid value in gce_disposal (%d). Using default value of 0.\n", ext_len);
326         }
327
328         ext_len = bytestream_get_byte(&s->bytestream);
329         break;
330     }
331
332     /* NOTE: many extension blocks can come after */
333  discard_ext:
334     while (ext_len != 0) {
335         for (i = 0; i < ext_len; i++)
336             bytestream_get_byte(&s->bytestream);
337         ext_len = bytestream_get_byte(&s->bytestream);
338
339         av_dlog(s->avctx, "ext_len1=%d\n", ext_len);
340     }
341     return 0;
342 }
343
344 static int gif_read_header1(GifState *s)
345 {
346     uint8_t sig[6];
347     int v, n;
348     int background_color_index;
349
350     if (s->bytestream_end < s->bytestream + 13)
351         return AVERROR_INVALIDDATA;
352
353     /* read gif signature */
354     bytestream_get_buffer(&s->bytestream, sig, 6);
355     if (memcmp(sig, gif87a_sig, 6) != 0 &&
356         memcmp(sig, gif89a_sig, 6) != 0)
357         return AVERROR_INVALIDDATA;
358
359     /* read screen header */
360     s->transparent_color_index = -1;
361     s->screen_width = bytestream_get_le16(&s->bytestream);
362     s->screen_height = bytestream_get_le16(&s->bytestream);
363     if(   (unsigned)s->screen_width  > 32767
364        || (unsigned)s->screen_height > 32767){
365         av_log(s->avctx, AV_LOG_ERROR, "picture size too large\n");
366         return AVERROR_INVALIDDATA;
367     }
368
369     s->idx_line = av_malloc(s->screen_width);
370     if (!s->idx_line)
371         return AVERROR(ENOMEM);
372
373     v = bytestream_get_byte(&s->bytestream);
374     s->color_resolution = ((v & 0x70) >> 4) + 1;
375     s->has_global_palette = (v & 0x80);
376     s->bits_per_pixel = (v & 0x07) + 1;
377     background_color_index = bytestream_get_byte(&s->bytestream);
378     bytestream_get_byte(&s->bytestream);                /* ignored */
379
380     av_dlog(s->avctx, "screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",
381            s->screen_width, s->screen_height, s->bits_per_pixel,
382            s->has_global_palette);
383
384     if (s->has_global_palette) {
385         s->background_color_index = background_color_index;
386         n = 1 << s->bits_per_pixel;
387         if (s->bytestream_end < s->bytestream + n * 3)
388             return AVERROR_INVALIDDATA;
389
390         gif_read_palette(&s->bytestream, s->global_palette, n);
391         s->bg_color = s->global_palette[s->background_color_index];
392     } else
393         s->background_color_index = -1;
394
395     return 0;
396 }
397
398 static int gif_parse_next_image(GifState *s, int *got_picture)
399 {
400     int ret;
401     *got_picture = sizeof(AVPicture);
402     while (s->bytestream < s->bytestream_end) {
403         int code = bytestream_get_byte(&s->bytestream);
404
405         av_dlog(s->avctx, "code=%02x '%c'\n", code, code);
406
407         switch (code) {
408         case GIF_IMAGE_SEPARATOR:
409             return gif_read_image(s);
410         case GIF_EXTENSION_INTRODUCER:
411             if ((ret = gif_read_extension(s)) < 0)
412                 return ret;
413             break;
414         case GIF_TRAILER:
415             /* end of image */
416             *got_picture = 0;
417             return 0;
418         default:
419             /* erroneous block label */
420             return AVERROR_INVALIDDATA;
421         }
422     }
423     return AVERROR_EOF;
424 }
425
426 static av_cold int gif_decode_init(AVCodecContext *avctx)
427 {
428     GifState *s = avctx->priv_data;
429
430     s->avctx = avctx;
431
432     avctx->pix_fmt = AV_PIX_FMT_RGB32;
433     avcodec_get_frame_defaults(&s->picture);
434     avctx->coded_frame= &s->picture;
435     s->picture.data[0] = NULL;
436     ff_lzw_decode_open(&s->lzw);
437     return 0;
438 }
439
440 static int gif_decode_frame(AVCodecContext *avctx, void *data, int *got_picture, AVPacket *avpkt)
441 {
442     const uint8_t *buf = avpkt->data;
443     int buf_size = avpkt->size;
444     GifState *s = avctx->priv_data;
445     AVFrame *picture = data;
446     int ret;
447
448     s->picture.pts          = avpkt->pts;
449     s->picture.pkt_pts      = avpkt->pts;
450     s->picture.pkt_dts      = avpkt->dts;
451     s->picture.pkt_duration = avpkt->duration;
452
453     s->bytestream = buf;
454     s->bytestream_end = buf + buf_size;
455
456     if (buf_size >= 6) {
457         s->keyframe = memcmp(s->bytestream, gif87a_sig, 6) == 0 ||
458                       memcmp(s->bytestream, gif89a_sig, 6) == 0;
459     } else {
460         s->keyframe = 0;
461     }
462
463     if (s->keyframe) {
464         if ((ret = gif_read_header1(s)) < 0)
465             return ret;
466
467         if ((ret = av_image_check_size(s->screen_width, s->screen_height, 0, avctx)) < 0)
468             return ret;
469         avcodec_set_dimensions(avctx, s->screen_width, s->screen_height);
470
471         if (s->picture.data[0])
472             avctx->release_buffer(avctx, &s->picture);
473
474         if ((ret = avctx->get_buffer(avctx, &s->picture)) < 0) {
475             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
476             return ret;
477         }
478
479         s->picture.pict_type = AV_PICTURE_TYPE_I;
480         s->picture.key_frame = 1;
481     } else {
482         if ((ret = avctx->reget_buffer(avctx, &s->picture)) < 0) {
483             av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
484             return ret;
485         }
486
487         s->picture.pict_type = AV_PICTURE_TYPE_P;
488         s->picture.key_frame = 0;
489     }
490
491     ret = gif_parse_next_image(s, got_picture);
492     if (ret < 0)
493         return ret;
494     else if (*got_picture)
495         *picture = s->picture;
496
497     return s->bytestream - buf;
498 }
499
500 static av_cold int gif_decode_close(AVCodecContext *avctx)
501 {
502     GifState *s = avctx->priv_data;
503
504     ff_lzw_decode_close(&s->lzw);
505     if(s->picture.data[0])
506         avctx->release_buffer(avctx, &s->picture);
507
508     av_freep(&s->idx_line);
509     av_freep(&s->stored_img);
510
511     return 0;
512 }
513
514 static const AVOption options[] = {
515     { "trans_color", "color value (ARGB) that is used instead of transparent color",
516       offsetof(GifState, trans_color), AV_OPT_TYPE_INT,
517       {.i64 = GIF_TRANSPARENT_COLOR}, 0, 0xffffffff,
518       AV_OPT_FLAG_DECODING_PARAM|AV_OPT_FLAG_VIDEO_PARAM },
519     { NULL },
520 };
521
522 static const AVClass decoder_class = {
523     .class_name = "gif decoder",
524     .item_name  = av_default_item_name,
525     .option     = options,
526     .version    = LIBAVUTIL_VERSION_INT,
527     .category   = AV_CLASS_CATEGORY_DECODER,
528 };
529
530 AVCodec ff_gif_decoder = {
531     .name           = "gif",
532     .type           = AVMEDIA_TYPE_VIDEO,
533     .id             = AV_CODEC_ID_GIF,
534     .priv_data_size = sizeof(GifState),
535     .init           = gif_decode_init,
536     .close          = gif_decode_close,
537     .decode         = gif_decode_frame,
538     .capabilities   = CODEC_CAP_DR1,
539     .long_name      = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
540     .priv_class     = &decoder_class,
541 };