/libavcodec/gifdec.c

http://github.com/FFmpeg/FFmpeg · C · 575 lines · 428 code · 89 blank · 58 comment · 84 complexity · 019bf211bee3919d9de286048a96b488 MD5 · raw file

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