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