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