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.

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