You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

545 lines
17KB

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