libavcodec/gifdec.c
06d392a7
 /*
  * GIF decoder
406792e7
  * Copyright (c) 2003 Fabrice Bellard
  * Copyright (c) 2006 Baptiste Coudurier
91499f4e
  * Copyright (c) 2012 Vitaliy E Sugrobov
06d392a7
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
7ffe76e5
 #include "libavutil/imgutils.h"
91499f4e
 #include "libavutil/opt.h"
06d392a7
 #include "avcodec.h"
 #include "bytestream.h"
594d4d5d
 #include "internal.h"
ffc5430b
 #include "lzw.h"
005cb97e
 #include "gif.h"
06d392a7
 
91499f4e
 /* This value is intentionally set to "transparent white" color.
  * It is much better to have white background instead of black
  * when gif image converted to format which not support transparency.
  */
 #define GIF_TRANSPARENT_COLOR    0x00ffffff
06d392a7
 
 typedef struct GifState {
91499f4e
     const AVClass *class;
80e9e63c
     AVFrame *frame;
06d392a7
     int screen_width;
     int screen_height;
91499f4e
     int has_global_palette;
06d392a7
     int bits_per_pixel;
91499f4e
     uint32_t bg_color;
06d392a7
     int background_color_index;
     int transparent_color_index;
     int color_resolution;
91499f4e
     /* intermediate buffer for storing color indices
      * obtained from lzw-encoded data stream */
     uint8_t *idx_line;
2152b60f
     int idx_line_size;
06d392a7
 
     /* after the frame is displayed, the disposal method is used */
91499f4e
     int gce_prev_disposal;
06d392a7
     int gce_disposal;
91499f4e
     /* rectangle describing area that must be disposed */
     int gce_l, gce_t, gce_w, gce_h;
     /* depending on disposal method we store either part of the image
      * drawn on the canvas or background color that
      * should be used upon disposal */
     uint32_t * stored_img;
2152b60f
     int stored_img_size;
91499f4e
     int stored_bg_color;
06d392a7
 
3fd60d80
     GetByteContext gb;
ffc5430b
     LZWState *lzw;
06d392a7
 
     /* aux buffers */
91499f4e
     uint32_t global_palette[256];
     uint32_t local_palette[256];
318c5e05
 
3662f787
     AVCodecContext *avctx;
91499f4e
     int keyframe;
46cb6181
     int keyframe_ok;
91499f4e
     int trans_color;    /**< color value that is used instead of transparent color */
06d392a7
 } GifState;
 
3fd60d80
 static void gif_read_palette(GifState *s, uint32_t *pal, int nb)
91499f4e
 {
3fd60d80
     int i;
91499f4e
 
3fd60d80
     for (i = 0; i < nb; i++, pal++)
         *pal = (0xffu << 24) | bytestream2_get_be24u(&s->gb);
91499f4e
 }
 
 static void gif_fill(AVFrame *picture, uint32_t color)
 {
     uint32_t *p = (uint32_t *)picture->data[0];
     uint32_t *p_end = p + (picture->linesize[0] / sizeof(uint32_t)) * picture->height;
 
     for (; p < p_end; p++)
         *p = color;
 }
 
 static void gif_fill_rect(AVFrame *picture, uint32_t color, int l, int t, int w, int h)
 {
     const int linesize = picture->linesize[0] / sizeof(uint32_t);
     const uint32_t *py = (uint32_t *)picture->data[0] + t * linesize;
c004de0b
     const uint32_t *pr, *pb = py + h * linesize;
91499f4e
     uint32_t *px;
 
     for (; py < pb; py += linesize) {
         px = (uint32_t *)py + l;
         pr = px + w;
 
         for (; px < pr; px++)
             *px = color;
     }
 }
 
 static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst,
                               int linesize, int l, int t, int w, int h)
 {
     const int y_start = t * linesize;
f1412c79
     const uint32_t *src_px,
91499f4e
                    *src_py = src + y_start,
                    *dst_py = dst + y_start;
c1035035
     const uint32_t *src_pb = src_py + h * linesize;
91499f4e
     uint32_t *dst_px;
 
     for (; src_py < src_pb; src_py += linesize, dst_py += linesize) {
         src_px = src_py + l;
         dst_px = (uint32_t *)dst_py + l;
 
f1412c79
         memcpy(dst_px, src_px, w * sizeof(uint32_t));
91499f4e
     }
 }
06d392a7
 
759001c5
 static int gif_read_image(GifState *s, AVFrame *frame)
06d392a7
 {
4ddb3a6d
     int left, top, width, height, bits_per_pixel, code_size, flags, pw;
3ea60c50
     int is_interleaved, has_local_palette, y, pass, y1, linesize, pal_size, lzwed_len;
91499f4e
     uint32_t *ptr, *pal, *px, *pr, *ptr1;
612ecfbb
     int ret;
91499f4e
     uint8_t *idx;
06d392a7
 
de0cb7f0
     /* At least 9 bytes of Image Descriptor. */
3fd60d80
     if (bytestream2_get_bytes_left(&s->gb) < 9)
de0cb7f0
         return AVERROR_INVALIDDATA;
 
7a88b7a9
     left   = bytestream2_get_le16u(&s->gb);
     top    = bytestream2_get_le16u(&s->gb);
     width  = bytestream2_get_le16u(&s->gb);
3fd60d80
     height = bytestream2_get_le16u(&s->gb);
7a88b7a9
     flags  = bytestream2_get_byteu(&s->gb);
06d392a7
     is_interleaved = flags & 0x40;
     has_local_palette = flags & 0x80;
     bits_per_pixel = (flags & 0x07) + 1;
46353231
 
8f7b022c
     ff_dlog(s->avctx, "image x=%d y=%d w=%d h=%d\n", left, top, width, height);
06d392a7
 
     if (has_local_palette) {
91499f4e
         pal_size = 1 << bits_per_pixel;
 
3fd60d80
         if (bytestream2_get_bytes_left(&s->gb) < pal_size * 3)
91499f4e
             return AVERROR_INVALIDDATA;
 
3fd60d80
         gif_read_palette(s, s->local_palette, pal_size);
91499f4e
         pal = s->local_palette;
06d392a7
     } else {
91499f4e
         if (!s->has_global_palette) {
0c894393
             av_log(s->avctx, AV_LOG_ERROR, "picture doesn't have either global or local palette.\n");
91499f4e
             return AVERROR_INVALIDDATA;
         }
 
         pal = s->global_palette;
     }
 
     if (s->keyframe) {
         if (s->transparent_color_index == -1 && s->has_global_palette) {
             /* transparency wasn't set before the first frame, fill with background color */
80e9e63c
             gif_fill(frame, s->bg_color);
91499f4e
         } else {
             /* otherwise fill with transparent color.
              * this is necessary since by default picture filled with 0x80808080. */
80e9e63c
             gif_fill(frame, s->trans_color);
91499f4e
         }
06d392a7
     }
 
     /* verify that all the image is inside the screen dimensions */
4ddb3a6d
     if (!width || width > s->screen_width || left >= s->screen_width) {
         av_log(s->avctx, AV_LOG_ERROR, "Invalid image width.\n");
0c894393
         return AVERROR_INVALIDDATA;
564ae836
     }
4ddb3a6d
     if (!height || height > s->screen_height || top >= s->screen_height) {
         av_log(s->avctx, AV_LOG_ERROR, "Invalid image height.\n");
286930d3
         return AVERROR_INVALIDDATA;
c453723a
     }
4ddb3a6d
     if (left + width > s->screen_width) {
         /* width must be kept around to avoid lzw vs line desync */
         pw = s->screen_width - left;
         av_log(s->avctx, AV_LOG_WARNING, "Image too wide by %d, truncating.\n",
                left + width - s->screen_width);
     } else {
         pw = width;
     }
     if (top + height > s->screen_height) {
         /* we don't care about the extra invisible lines */
         av_log(s->avctx, AV_LOG_WARNING, "Image too high by %d, truncating.\n",
                top + height - s->screen_height);
         height = s->screen_height - top;
     }
06d392a7
 
91499f4e
     /* process disposal method */
     if (s->gce_prev_disposal == GCE_DISPOSAL_BACKGROUND) {
80e9e63c
         gif_fill_rect(frame, s->stored_bg_color, s->gce_l, s->gce_t, s->gce_w, s->gce_h);
91499f4e
     } else if (s->gce_prev_disposal == GCE_DISPOSAL_RESTORE) {
80e9e63c
         gif_copy_img_rect(s->stored_img, (uint32_t *)frame->data[0],
             frame->linesize[0] / sizeof(uint32_t), s->gce_l, s->gce_t, s->gce_w, s->gce_h);
91499f4e
     }
 
     s->gce_prev_disposal = s->gce_disposal;
 
     if (s->gce_disposal != GCE_DISPOSAL_NONE) {
         s->gce_l = left;  s->gce_t = top;
4ddb3a6d
         s->gce_w = pw;    s->gce_h = height;
91499f4e
 
         if (s->gce_disposal == GCE_DISPOSAL_BACKGROUND) {
522cb6ab
             if (s->transparent_color_index >= 0)
91499f4e
                 s->stored_bg_color = s->trans_color;
             else
                 s->stored_bg_color = s->bg_color;
         } else if (s->gce_disposal == GCE_DISPOSAL_RESTORE) {
80e9e63c
             av_fast_malloc(&s->stored_img, &s->stored_img_size, frame->linesize[0] * frame->height);
2152b60f
             if (!s->stored_img)
                 return AVERROR(ENOMEM);
91499f4e
 
80e9e63c
             gif_copy_img_rect((uint32_t *)frame->data[0], s->stored_img,
4ddb3a6d
                 frame->linesize[0] / sizeof(uint32_t), left, top, pw, height);
91499f4e
         }
47babca8
     }
06d392a7
 
de0cb7f0
     /* Expect at least 2 bytes: 1 for lzw code size and 1 for block size. */
3fd60d80
     if (bytestream2_get_bytes_left(&s->gb) < 2)
de0cb7f0
         return AVERROR_INVALIDDATA;
 
06d392a7
     /* now get the image data */
3fd60d80
     code_size = bytestream2_get_byteu(&s->gb);
     if ((ret = ff_lzw_decode_init(s->lzw, code_size, s->gb.buffer,
                                   bytestream2_get_bytes_left(&s->gb), FF_LZW_GIF)) < 0) {
612ecfbb
         av_log(s->avctx, AV_LOG_ERROR, "LZW init failed\n");
         return ret;
     }
06d392a7
 
     /* read all the image */
80e9e63c
     linesize = frame->linesize[0] / sizeof(uint32_t);
     ptr1 = (uint32_t *)frame->data[0] + top * linesize + left;
06d392a7
     ptr = ptr1;
     pass = 0;
     y1 = 0;
     for (y = 0; y < height; y++) {
745c40a4
         int count = ff_lzw_decode(s->lzw, s->idx_line, width);
         if (count != width) {
             if (count)
                 av_log(s->avctx, AV_LOG_ERROR, "LZW decode failed\n");
91499f4e
             goto decode_tail;
745c40a4
         }
91499f4e
 
4ddb3a6d
         pr = ptr + pw;
91499f4e
 
         for (px = ptr, idx = s->idx_line; px < pr; px++, idx++) {
a3a22c21
             if (*idx != s->transparent_color_index)
                 *px = pal[*idx];
91499f4e
         }
 
06d392a7
         if (is_interleaved) {
             switch(pass) {
             default:
             case 0:
             case 1:
                 y1 += 8;
                 ptr += linesize * 8;
                 break;
             case 2:
                 y1 += 4;
                 ptr += linesize * 4;
                 break;
             case 3:
                 y1 += 2;
                 ptr += linesize * 2;
                 break;
             }
8f145786
             while (y1 >= height) {
0b39ac6f
                 y1  = 4 >> pass;
8f145786
                 ptr = ptr1 + linesize * y1;
                 pass++;
             }
06d392a7
         } else {
             ptr += linesize;
         }
     }
91499f4e
 
  decode_tail:
06d392a7
     /* read the garbage data until end marker is found */
3ea60c50
     lzwed_len = ff_lzw_decode_tail(s->lzw);
     bytestream2_skipu(&s->gb, lzwed_len);
91499f4e
 
     /* Graphic Control Extension's scope is single frame.
      * Remove its influence. */
     s->transparent_color_index = -1;
     s->gce_disposal = GCE_DISPOSAL_NONE;
 
06d392a7
     return 0;
 }
 
 static int gif_read_extension(GifState *s)
 {
3fd60d80
     int ext_code, ext_len, gce_flags, gce_transparent_index;
06d392a7
 
de0cb7f0
     /* There must be at least 2 bytes:
      * 1 for extension label and 1 for extension length. */
3fd60d80
     if (bytestream2_get_bytes_left(&s->gb) < 2)
de0cb7f0
         return AVERROR_INVALIDDATA;
 
3fd60d80
     ext_code = bytestream2_get_byteu(&s->gb);
7a88b7a9
     ext_len  = bytestream2_get_byteu(&s->gb);
46353231
 
8f7b022c
     ff_dlog(s->avctx, "ext_code=0x%x len=%d\n", ext_code, ext_len);
46353231
 
06d392a7
     switch(ext_code) {
c5fe41c7
     case GIF_GCE_EXT_LABEL:
06d392a7
         if (ext_len != 4)
             goto discard_ext;
de0cb7f0
 
         /* We need at least 5 bytes more: 4 is for extension body
          * and 1 for next block size. */
3fd60d80
         if (bytestream2_get_bytes_left(&s->gb) < 5)
de0cb7f0
             return AVERROR_INVALIDDATA;
 
7a88b7a9
         gce_flags    = bytestream2_get_byteu(&s->gb);
3fd60d80
         bytestream2_skipu(&s->gb, 2);    // delay during which the frame is shown
         gce_transparent_index = bytestream2_get_byteu(&s->gb);
06d392a7
         if (gce_flags & 0x01)
             s->transparent_color_index = gce_transparent_index;
         else
             s->transparent_color_index = -1;
         s->gce_disposal = (gce_flags >> 2) & 0x7;
46353231
 
8f7b022c
         ff_dlog(s->avctx, "gce_flags=%x tcolor=%d disposal=%d\n",
91499f4e
                gce_flags,
06d392a7
                s->transparent_color_index, s->gce_disposal);
46353231
 
91499f4e
         if (s->gce_disposal > 3) {
             s->gce_disposal = GCE_DISPOSAL_NONE;
8f7b022c
             ff_dlog(s->avctx, "invalid value in gce_disposal (%d). Using default value of 0.\n", ext_len);
91499f4e
         }
 
3fd60d80
         ext_len = bytestream2_get_byteu(&s->gb);
06d392a7
         break;
     }
 
     /* NOTE: many extension blocks can come after */
  discard_ext:
aaebdce3
     while (ext_len) {
de0cb7f0
         /* There must be at least ext_len bytes and 1 for next block size byte. */
3fd60d80
         if (bytestream2_get_bytes_left(&s->gb) < ext_len + 1)
de0cb7f0
             return AVERROR_INVALIDDATA;
 
3fd60d80
         bytestream2_skipu(&s->gb, ext_len);
         ext_len = bytestream2_get_byteu(&s->gb);
46353231
 
8f7b022c
         ff_dlog(s->avctx, "ext_len1=%d\n", ext_len);
06d392a7
     }
     return 0;
 }
 
 static int gif_read_header1(GifState *s)
 {
     uint8_t sig[6];
a7fb3a96
     int v, n;
91499f4e
     int background_color_index;
06d392a7
 
3fd60d80
     if (bytestream2_get_bytes_left(&s->gb) < 13)
2da5a5ce
         return AVERROR_INVALIDDATA;
7a28b771
 
06d392a7
     /* read gif signature */
3fd60d80
     bytestream2_get_bufferu(&s->gb, sig, 6);
aaebdce3
     if (memcmp(sig, gif87a_sig, 6) &&
         memcmp(sig, gif89a_sig, 6))
2da5a5ce
         return AVERROR_INVALIDDATA;
06d392a7
 
     /* read screen header */
     s->transparent_color_index = -1;
7a88b7a9
     s->screen_width  = bytestream2_get_le16u(&s->gb);
3fd60d80
     s->screen_height = bytestream2_get_le16u(&s->gb);
06d392a7
 
3fd60d80
     v = bytestream2_get_byteu(&s->gb);
06d392a7
     s->color_resolution = ((v & 0x70) >> 4) + 1;
91499f4e
     s->has_global_palette = (v & 0x80);
06d392a7
     s->bits_per_pixel = (v & 0x07) + 1;
3fd60d80
     background_color_index = bytestream2_get_byteu(&s->gb);
     n = bytestream2_get_byteu(&s->gb);
49435d38
     if (n) {
         s->avctx->sample_aspect_ratio.num = n + 15;
         s->avctx->sample_aspect_ratio.den = 64;
     }
46353231
 
8f7b022c
     ff_dlog(s->avctx, "screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",
06d392a7
            s->screen_width, s->screen_height, s->bits_per_pixel,
91499f4e
            s->has_global_palette);
46353231
 
91499f4e
     if (s->has_global_palette) {
         s->background_color_index = background_color_index;
06d392a7
         n = 1 << s->bits_per_pixel;
3fd60d80
         if (bytestream2_get_bytes_left(&s->gb) < n * 3)
2da5a5ce
             return AVERROR_INVALIDDATA;
91499f4e
 
3fd60d80
         gif_read_palette(s, s->global_palette, n);
91499f4e
         s->bg_color = s->global_palette[s->background_color_index];
     } else
         s->background_color_index = -1;
 
06d392a7
     return 0;
 }
 
759001c5
 static int gif_parse_next_image(GifState *s, AVFrame *frame)
06d392a7
 {
1f3e56b6
     while (bytestream2_get_bytes_left(&s->gb) > 0) {
3fd60d80
         int code = bytestream2_get_byte(&s->gb);
048ffb9b
         int ret;
46353231
 
afdfff48
         av_log(s->avctx, AV_LOG_DEBUG, "code=%02x '%c'\n", code, code);
46353231
 
06d392a7
         switch (code) {
c5fe41c7
         case GIF_IMAGE_SEPARATOR:
759001c5
             return gif_read_image(s, frame);
c5fe41c7
         case GIF_EXTENSION_INTRODUCER:
             if ((ret = gif_read_extension(s)) < 0)
                 return ret;
06d392a7
             break;
c5fe41c7
         case GIF_TRAILER:
94cebc56
             /* end of image */
285128ee
             return AVERROR_EOF;
06d392a7
         default:
c5fe41c7
             /* erroneous block label */
             return AVERROR_INVALIDDATA;
06d392a7
         }
     }
c5fe41c7
     return AVERROR_EOF;
06d392a7
 }
 
98a6fff9
 static av_cold int gif_decode_init(AVCodecContext *avctx)
06d392a7
 {
     GifState *s = avctx->priv_data;
 
318c5e05
     s->avctx = avctx;
 
91499f4e
     avctx->pix_fmt = AV_PIX_FMT_RGB32;
80e9e63c
     s->frame = av_frame_alloc();
     if (!s->frame)
         return AVERROR(ENOMEM);
ffc5430b
     ff_lzw_decode_open(&s->lzw);
06d392a7
     return 0;
 }
 
fc1152de
 static int gif_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
06d392a7
 {
     GifState *s = avctx->priv_data;
     int ret;
 
3fd60d80
     bytestream2_init(&s->gb, avpkt->data, avpkt->size);
 
80e9e63c
     s->frame->pts     = avpkt->pts;
3f9137c5
 #if FF_API_PKT_PTS
 FF_DISABLE_DEPRECATION_WARNINGS
80e9e63c
     s->frame->pkt_pts = avpkt->pts;
3f9137c5
 FF_ENABLE_DEPRECATION_WARNINGS
 #endif
80e9e63c
     s->frame->pkt_dts = avpkt->dts;
     av_frame_set_pkt_duration(s->frame, avpkt->duration);
91499f4e
 
3fd60d80
     if (avpkt->size >= 6) {
         s->keyframe = memcmp(avpkt->data, gif87a_sig, 6) == 0 ||
                       memcmp(avpkt->data, gif89a_sig, 6) == 0;
91499f4e
     } else {
         s->keyframe = 0;
     }
06d392a7
 
91499f4e
     if (s->keyframe) {
46cb6181
         s->keyframe_ok = 0;
d23b8462
         s->gce_prev_disposal = GCE_DISPOSAL_NONE;
91499f4e
         if ((ret = gif_read_header1(s)) < 0)
             return ret;
 
e6b9d71a
         if ((ret = ff_set_dimensions(avctx, s->screen_width, s->screen_height)) < 0)
91499f4e
             return ret;
 
80e9e63c
         av_frame_unref(s->frame);
1ec94b0f
         if ((ret = ff_get_buffer(avctx, s->frame, 0)) < 0)
91499f4e
             return ret;
 
51c7af9d
         av_fast_malloc(&s->idx_line, &s->idx_line_size, s->screen_width);
         if (!s->idx_line)
             return AVERROR(ENOMEM);
 
80e9e63c
         s->frame->pict_type = AV_PICTURE_TYPE_I;
         s->frame->key_frame = 1;
46cb6181
         s->keyframe_ok = 1;
91499f4e
     } else {
46cb6181
         if (!s->keyframe_ok) {
             av_log(avctx, AV_LOG_ERROR, "cannot decode frame without keyframe\n");
             return AVERROR_INVALIDDATA;
         }
 
1ec94b0f
         if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)
91499f4e
             return ret;
 
80e9e63c
         s->frame->pict_type = AV_PICTURE_TYPE_P;
         s->frame->key_frame = 0;
d54d396d
     }
91499f4e
 
80e9e63c
     ret = gif_parse_next_image(s, s->frame);
06d392a7
     if (ret < 0)
         return ret;
285128ee
 
80e9e63c
     if ((ret = av_frame_ref(data, s->frame)) < 0)
         return ret;
285128ee
     *got_frame = 1;
06d392a7
 
1f3e56b6
     return bytestream2_tell(&s->gb);
06d392a7
 }
 
98a6fff9
 static av_cold int gif_decode_close(AVCodecContext *avctx)
d54d396d
 {
     GifState *s = avctx->priv_data;
 
ffc5430b
     ff_lzw_decode_close(&s->lzw);
80e9e63c
     av_frame_free(&s->frame);
91499f4e
     av_freep(&s->idx_line);
     av_freep(&s->stored_img);
 
d54d396d
     return 0;
 }
 
91499f4e
 static const AVOption options[] = {
     { "trans_color", "color value (ARGB) that is used instead of transparent color",
       offsetof(GifState, trans_color), AV_OPT_TYPE_INT,
       {.i64 = GIF_TRANSPARENT_COLOR}, 0, 0xffffffff,
       AV_OPT_FLAG_DECODING_PARAM|AV_OPT_FLAG_VIDEO_PARAM },
     { NULL },
 };
 
 static const AVClass decoder_class = {
     .class_name = "gif decoder",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
     .category   = AV_CLASS_CATEGORY_DECODER,
 };
 
e7e2df27
 AVCodec ff_gif_decoder = {
ec6402b7
     .name           = "gif",
b2bed932
     .long_name      = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
ec6402b7
     .type           = AVMEDIA_TYPE_VIDEO,
36ef5369
     .id             = AV_CODEC_ID_GIF,
ec6402b7
     .priv_data_size = sizeof(GifState),
     .init           = gif_decode_init,
     .close          = gif_decode_close,
     .decode         = gif_decode_frame,
def97856
     .capabilities   = AV_CODEC_CAP_DR1,
91499f4e
     .priv_class     = &decoder_class,
06d392a7
 };