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