2 * Copyright (c) 2000 Fabrice Bellard
3 * Copyright (c) 2002 Francois Revol
4 * Copyright (c) 2006 Baptiste Coudurier
5 * Copyright (c) 2018 Bjorn Roche
6 * Copyright (c) 2018 Paul B Mahol
8 * first version by Francois Revol <revol@free.fr>
10 * This file is part of FFmpeg.
12 * FFmpeg is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * FFmpeg is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with FFmpeg; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 * @see http://www.w3.org/Graphics/GIF/spec-gif89a.txt
33 #define BITSTREAM_WRITER_LE
34 #include "libavutil/opt.h"
35 #include "libavutil/imgutils.h"
37 #include "bytestream.h"
44 #define DEFAULT_TRANSPARENCY_INDEX 0x1f
46 typedef struct GIFContext {
55 int use_global_palette;
56 uint32_t palette[AVPALETTE_COUNT]; ///< local reference palette for !pal8
58 int transparent_index;
59 uint8_t *tmpl; ///< temporary line buffer
67 static void shrink_palette(const uint32_t *src, uint8_t *map,
68 uint32_t *dst, size_t *palette_count)
70 size_t colors_seen = 0;
72 for (size_t i = 0; i < AVPALETTE_COUNT; i++) {
74 for (size_t c = 0; c < colors_seen; c++) {
75 if (src[i] == dst[c]) {
81 dst[colors_seen] = src[i];
87 *palette_count = colors_seen;
90 static void remap_frame_to_palette(const uint8_t *src, int src_linesize,
91 uint8_t *dst, int dst_linesize,
92 int w, int h, uint8_t *map)
94 for (int i = 0; i < h; i++)
95 for (int j = 0; j < w; j++)
96 dst[i * dst_linesize + j] = map[src[i * src_linesize + j]];
99 static int is_image_translucent(AVCodecContext *avctx,
100 const uint8_t *buf, const int linesize)
102 GIFContext *s = avctx->priv_data;
103 int trans = s->transparent_index;
108 for (int y = 0; y < avctx->height; y++) {
109 for (int x = 0; x < avctx->width; x++) {
110 if (buf[x] == trans) {
120 static int get_palette_transparency_index(const uint32_t *palette)
122 int transparent_color_index = -1;
123 unsigned i, smallest_alpha = 0xff;
128 for (i = 0; i < AVPALETTE_COUNT; i++) {
129 const uint32_t v = palette[i];
130 if (v >> 24 < smallest_alpha) {
131 smallest_alpha = v >> 24;
132 transparent_color_index = i;
135 return smallest_alpha < 128 ? transparent_color_index : -1;
138 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
140 int histogram[AVPALETTE_COUNT] = {0};
143 for (y = 0; y < h; y++) {
144 for (x = 0; x < w; x++)
148 for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
154 static void gif_crop_translucent(AVCodecContext *avctx,
155 const uint8_t *buf, const int linesize,
156 int *width, int *height,
157 int *x_start, int *y_start)
159 GIFContext *s = avctx->priv_data;
160 int trans = s->transparent_index;
163 if ((s->flags & GF_OFFSETTING) && trans >= 0) {
164 const int w = avctx->width;
165 const int h = avctx->height;
170 while (*y_start < y_end) {
172 for (int i = 0; i < w; i++) {
173 if (buf[linesize * *y_start + i] != trans) {
185 while (y_end > *y_start) {
187 for (int i = 0; i < w; i++) {
188 if (buf[linesize * y_end + i] != trans) {
199 while (*x_start < x_end) {
201 for (int i = *y_start; i < y_end; i++) {
202 if (buf[linesize * i + *x_start] != trans) {
213 while (x_end > *x_start) {
215 for (int i = *y_start; i < y_end; i++) {
216 if (buf[linesize * i + x_end] != trans) {
226 *height = y_end + 1 - *y_start;
227 *width = x_end + 1 - *x_start;
228 av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
229 *width, *height, *x_start, *y_start, avctx->width, avctx->height);
233 static void gif_crop_opaque(AVCodecContext *avctx,
234 const uint32_t *palette,
235 const uint8_t *buf, const int linesize,
236 int *width, int *height, int *x_start, int *y_start)
238 GIFContext *s = avctx->priv_data;
241 if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
242 const uint8_t *ref = s->last_frame->data[0];
243 const int ref_linesize = s->last_frame->linesize[0];
244 int x_end = avctx->width - 1,
245 y_end = avctx->height - 1;
247 /* skip common lines */
248 while (*y_start < y_end) {
249 if (memcmp(ref + *y_start*ref_linesize, buf + *y_start*linesize, *width))
253 while (y_end > *y_start) {
254 if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, *width))
258 *height = y_end + 1 - *y_start;
260 /* skip common columns */
261 while (*x_start < x_end) {
263 for (int y = *y_start; y <= y_end; y++) {
264 if (ref[y*ref_linesize + *x_start] != buf[y*linesize + *x_start]) {
273 while (x_end > *x_start) {
275 for (int y = *y_start; y <= y_end; y++) {
276 if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
285 *width = x_end + 1 - *x_start;
287 av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
288 *width, *height, *x_start, *y_start, avctx->width, avctx->height);
292 static int gif_image_write_image(AVCodecContext *avctx,
293 uint8_t **bytestream, uint8_t *end,
294 const uint32_t *palette,
295 const uint8_t *buf, const int linesize,
298 GIFContext *s = avctx->priv_data;
299 int disposal, len = 0, height = avctx->height, width = avctx->width, x, y;
300 int x_start = 0, y_start = 0, trans = s->transparent_index;
301 int bcid = -1, honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame && !palette;
303 uint32_t shrunk_palette[AVPALETTE_COUNT];
304 uint8_t map[AVPALETTE_COUNT] = { 0 };
305 size_t shrunk_palette_count = 0;
308 * We memset to 0xff instead of 0x00 so that the transparency detection
309 * doesn't pick anything after the palette entries as the transparency
310 * index, and because GIF89a requires us to always write a power-of-2
311 * number of palette entries.
313 memset(shrunk_palette, 0xff, AVPALETTE_SIZE);
315 if (!s->image && is_image_translucent(avctx, buf, linesize)) {
316 gif_crop_translucent(avctx, buf, linesize, &width, &height, &x_start, &y_start);
317 honor_transparency = 0;
318 disposal = GCE_DISPOSAL_BACKGROUND;
320 gif_crop_opaque(avctx, palette, buf, linesize, &width, &height, &x_start, &y_start);
321 disposal = GCE_DISPOSAL_INPLACE;
324 if (s->image || !avctx->frame_number) { /* GIF header */
325 const uint32_t *global_palette = palette ? palette : s->palette;
326 const AVRational sar = avctx->sample_aspect_ratio;
329 if (sar.num > 0 && sar.den > 0) {
330 aspect = sar.num * 64LL / sar.den - 15;
331 if (aspect < 0 || aspect > 255)
335 bytestream_put_buffer(bytestream, gif89a_sig, sizeof(gif89a_sig));
336 bytestream_put_le16(bytestream, avctx->width);
337 bytestream_put_le16(bytestream, avctx->height);
339 bcid = get_palette_transparency_index(global_palette);
341 bytestream_put_byte(bytestream, ((uint8_t) s->use_global_palette << 7) | 0x70 | (s->use_global_palette ? 7 : 0)); /* flags: global clut, 256 entries */
342 bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid); /* background color index */
343 bytestream_put_byte(bytestream, aspect);
344 if (s->use_global_palette) {
345 for (int i = 0; i < 256; i++) {
346 const uint32_t v = global_palette[i] & 0xffffff;
347 bytestream_put_be24(bytestream, v);
352 if (honor_transparency && trans < 0) {
353 trans = pick_palette_entry(buf + y_start*linesize + x_start,
354 linesize, width, height);
355 if (trans < 0) // TODO, patch welcome
356 av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
360 honor_transparency = 0;
362 if (palette || !s->use_global_palette) {
363 const uint32_t *pal = palette ? palette : s->palette;
364 shrink_palette(pal, map, shrunk_palette, &shrunk_palette_count);
367 bcid = honor_transparency || disposal == GCE_DISPOSAL_BACKGROUND ? trans : get_palette_transparency_index(palette);
369 /* graphic control extension */
370 bytestream_put_byte(bytestream, GIF_EXTENSION_INTRODUCER);
371 bytestream_put_byte(bytestream, GIF_GCE_EXT_LABEL);
372 bytestream_put_byte(bytestream, 0x04); /* block size */
373 bytestream_put_byte(bytestream, disposal<<2 | (bcid >= 0));
374 bytestream_put_le16(bytestream, 5); // default delay
375 bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : (shrunk_palette_count ? map[bcid] : bcid));
376 bytestream_put_byte(bytestream, 0x00);
379 bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
380 bytestream_put_le16(bytestream, x_start);
381 bytestream_put_le16(bytestream, y_start);
382 bytestream_put_le16(bytestream, width);
383 bytestream_put_le16(bytestream, height);
385 if (palette || !s->use_global_palette) {
386 unsigned pow2_count = av_log2(shrunk_palette_count - 1);
389 bytestream_put_byte(bytestream, 1<<7 | pow2_count); /* flags */
390 for (i = 0; i < 1 << (pow2_count + 1); i++) {
391 const uint32_t v = shrunk_palette[i];
392 bytestream_put_be24(bytestream, v);
395 bytestream_put_byte(bytestream, 0x00); /* flags */
398 bytestream_put_byte(bytestream, 0x08);
400 ff_lzw_encode_init(s->lzw, s->buf, s->buf_size,
403 if (shrunk_palette_count) {
404 if (!s->shrunk_buf) {
405 s->shrunk_buf = av_malloc(avctx->height * linesize);
406 if (!s->shrunk_buf) {
407 av_log(avctx, AV_LOG_ERROR, "Could not allocated remapped frame buffer.\n");
408 return AVERROR(ENOMEM);
411 remap_frame_to_palette(buf, linesize, s->shrunk_buf, linesize, avctx->width, avctx->height, map);
412 ptr = s->shrunk_buf + y_start*linesize + x_start;
414 ptr = buf + y_start*linesize + x_start;
416 if (honor_transparency) {
417 const int ref_linesize = s->last_frame->linesize[0];
418 const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
420 for (y = 0; y < height; y++) {
421 memcpy(s->tmpl, ptr, width);
422 for (x = 0; x < width; x++)
423 if (ref[x] == ptr[x])
425 len += ff_lzw_encode(s->lzw, s->tmpl, width);
430 for (y = 0; y < height; y++) {
431 len += ff_lzw_encode(s->lzw, ptr, width);
435 len += ff_lzw_encode_flush(s->lzw);
439 int size = FFMIN(255, len);
440 bytestream_put_byte(bytestream, size);
441 if (end - *bytestream < size)
443 bytestream_put_buffer(bytestream, ptr, size);
447 bytestream_put_byte(bytestream, 0x00); /* end of image block */
451 static av_cold int gif_encode_init(AVCodecContext *avctx)
453 GIFContext *s = avctx->priv_data;
455 if (avctx->width > 65535 || avctx->height > 65535) {
456 av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
457 return AVERROR(EINVAL);
460 s->transparent_index = -1;
462 s->lzw = av_mallocz(ff_lzw_encode_state_size);
463 s->buf_size = avctx->width*avctx->height*2 + 1000;
464 s->buf = av_malloc(s->buf_size);
465 s->tmpl = av_malloc(avctx->width);
466 if (!s->tmpl || !s->buf || !s->lzw)
467 return AVERROR(ENOMEM);
469 if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
470 av_assert0(avctx->pix_fmt == AV_PIX_FMT_PAL8);
475 static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
476 const AVFrame *pict, int *got_packet)
478 GIFContext *s = avctx->priv_data;
479 uint8_t *outbuf_ptr, *end;
480 const uint32_t *palette = NULL;
483 if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
485 outbuf_ptr = pkt->data;
486 end = pkt->data + pkt->size;
488 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
489 palette = (uint32_t*)pict->data[1];
491 if (!s->palette_loaded) {
492 memcpy(s->palette, palette, AVPALETTE_SIZE);
493 s->transparent_index = get_palette_transparency_index(palette);
494 s->palette_loaded = 1;
495 } else if (!memcmp(s->palette, palette, AVPALETTE_SIZE)) {
500 gif_image_write_image(avctx, &outbuf_ptr, end, palette,
501 pict->data[0], pict->linesize[0], pkt);
502 if (!s->last_frame && !s->image) {
503 s->last_frame = av_frame_alloc();
505 return AVERROR(ENOMEM);
509 av_frame_unref(s->last_frame);
510 ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
515 pkt->size = outbuf_ptr - pkt->data;
516 if (s->image || !avctx->frame_number)
517 pkt->flags |= AV_PKT_FLAG_KEY;
523 static int gif_encode_close(AVCodecContext *avctx)
525 GIFContext *s = avctx->priv_data;
529 av_freep(&s->shrunk_buf);
531 av_frame_free(&s->last_frame);
536 #define OFFSET(x) offsetof(GIFContext, x)
537 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
538 static const AVOption gif_options[] = {
539 { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
540 { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
541 { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
542 { "gifimage", "enable encoding only images per frame", OFFSET(image), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
543 { "global_palette", "write a palette to the global gif header where feasible", OFFSET(use_global_palette), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS },
547 static const AVClass gif_class = {
548 .class_name = "GIF encoder",
549 .item_name = av_default_item_name,
550 .option = gif_options,
551 .version = LIBAVUTIL_VERSION_INT,
554 AVCodec ff_gif_encoder = {
556 .long_name = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
557 .type = AVMEDIA_TYPE_VIDEO,
558 .id = AV_CODEC_ID_GIF,
559 .priv_data_size = sizeof(GIFContext),
560 .init = gif_encode_init,
561 .encode2 = gif_encode_frame,
562 .close = gif_encode_close,
563 .pix_fmts = (const enum AVPixelFormat[]){
564 AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE,
565 AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE
567 .priv_class = &gif_class,
568 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,