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 uint32_t palette[AVPALETTE_COUNT]; ///< local reference palette for !pal8
57 int transparent_index;
58 uint8_t *tmpl; ///< temporary line buffer
66 static int is_image_translucent(AVCodecContext *avctx,
67 const uint8_t *buf, const int linesize)
69 GIFContext *s = avctx->priv_data;
70 int trans = s->transparent_index;
75 for (int y = 0; y < avctx->height; y++) {
76 for (int x = 0; x < avctx->width; x++) {
77 if (buf[x] == trans) {
87 static int get_palette_transparency_index(const uint32_t *palette)
89 int transparent_color_index = -1;
90 unsigned i, smallest_alpha = 0xff;
95 for (i = 0; i < AVPALETTE_COUNT; i++) {
96 const uint32_t v = palette[i];
97 if (v >> 24 < smallest_alpha) {
98 smallest_alpha = v >> 24;
99 transparent_color_index = i;
102 return smallest_alpha < 128 ? transparent_color_index : -1;
105 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
107 int histogram[AVPALETTE_COUNT] = {0};
110 for (y = 0; y < h; y++) {
111 for (x = 0; x < w; x++)
115 for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
121 static void gif_crop_translucent(AVCodecContext *avctx,
122 const uint8_t *buf, const int linesize,
123 int *width, int *height,
124 int *x_start, int *y_start)
126 GIFContext *s = avctx->priv_data;
127 int trans = s->transparent_index;
130 if ((s->flags & GF_OFFSETTING) && trans >= 0) {
131 const int w = avctx->width;
132 const int h = avctx->height;
137 while (*y_start < y_end) {
139 for (int i = 0; i < w; i++) {
140 if (buf[w * *y_start + i] != trans) {
154 for (int i = 0; i < w; i++) {
155 if (buf[w * y_end + i] != trans) {
166 while (*x_start < x_end) {
168 for (int i = *y_start; i < y_end; i++) {
169 if (buf[w * i + *x_start] != trans) {
182 for (int i = *y_start; i < y_end; i++) {
183 if (buf[w * i + x_end] != trans) {
193 *height = y_end + 1 - *y_start;
194 *width = x_end + 1 - *x_start;
195 av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
196 *width, *height, *x_start, *y_start, avctx->width, avctx->height);
200 static void gif_crop_opaque(AVCodecContext *avctx,
201 const uint32_t *palette,
202 const uint8_t *buf, const int linesize,
203 int *width, int *height, int *x_start, int *y_start)
205 GIFContext *s = avctx->priv_data;
208 if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
209 const uint8_t *ref = s->last_frame->data[0];
210 const int ref_linesize = s->last_frame->linesize[0];
211 int x_end = avctx->width - 1,
212 y_end = avctx->height - 1;
214 /* skip common lines */
215 while (*y_start < y_end) {
216 if (memcmp(ref + *y_start*ref_linesize, buf + *y_start*linesize, *width))
220 while (y_end > *y_start) {
221 if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, *width))
225 *height = y_end + 1 - *y_start;
227 /* skip common columns */
228 while (*x_start < x_end) {
230 for (int y = *y_start; y <= y_end; y++) {
231 if (ref[y*ref_linesize + *x_start] != buf[y*linesize + *x_start]) {
240 while (x_end > *x_start) {
242 for (int y = *y_start; y <= y_end; y++) {
243 if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
252 *width = x_end + 1 - *x_start;
254 av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
255 *width, *height, *x_start, *y_start, avctx->width, avctx->height);
259 static int gif_image_write_image(AVCodecContext *avctx,
260 uint8_t **bytestream, uint8_t *end,
261 const uint32_t *palette,
262 const uint8_t *buf, const int linesize,
265 GIFContext *s = avctx->priv_data;
266 int disposal, len = 0, height = avctx->height, width = avctx->width, x, y;
267 int x_start = 0, y_start = 0, trans = s->transparent_index;
268 int bcid = -1, honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame && !palette;
271 if (!s->is_first_frame && is_image_translucent(avctx, buf, linesize)) {
272 gif_crop_translucent(avctx, buf, linesize, &width, &height, &x_start, &y_start);
273 honor_transparency = 0;
274 disposal = GCE_DISPOSAL_BACKGROUND;
276 gif_crop_opaque(avctx, palette, buf, linesize, &width, &height, &x_start, &y_start);
277 disposal = GCE_DISPOSAL_INPLACE;
280 if (s->is_first_frame) { /* GIF header */
281 const uint32_t *global_palette = palette ? palette : s->palette;
282 const AVRational sar = avctx->sample_aspect_ratio;
285 if (sar.num > 0 && sar.den > 0) {
286 aspect = sar.num * 64LL / sar.den - 15;
287 if (aspect < 0 || aspect > 255)
291 bytestream_put_buffer(bytestream, gif89a_sig, sizeof(gif89a_sig));
292 bytestream_put_le16(bytestream, avctx->width);
293 bytestream_put_le16(bytestream, avctx->height);
295 bcid = get_palette_transparency_index(global_palette);
297 bytestream_put_byte(bytestream, 0xf7); /* flags: global clut, 256 entries */
298 bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid); /* background color index */
299 bytestream_put_byte(bytestream, aspect);
300 for (int i = 0; i < 256; i++) {
301 const uint32_t v = global_palette[i] & 0xffffff;
302 bytestream_put_be24(bytestream, v);
305 s->is_first_frame = 0;
308 if (honor_transparency && trans < 0) {
309 trans = pick_palette_entry(buf + y_start*linesize + x_start,
310 linesize, width, height);
311 if (trans < 0) // TODO, patch welcome
312 av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
316 honor_transparency = 0;
318 bcid = honor_transparency || disposal == GCE_DISPOSAL_BACKGROUND ? trans : get_palette_transparency_index(palette);
320 /* graphic control extension */
321 bytestream_put_byte(bytestream, GIF_EXTENSION_INTRODUCER);
322 bytestream_put_byte(bytestream, GIF_GCE_EXT_LABEL);
323 bytestream_put_byte(bytestream, 0x04); /* block size */
324 bytestream_put_byte(bytestream, disposal<<2 | (bcid >= 0));
325 bytestream_put_le16(bytestream, 5); // default delay
326 bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid);
327 bytestream_put_byte(bytestream, 0x00);
330 bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
331 bytestream_put_le16(bytestream, x_start);
332 bytestream_put_le16(bytestream, y_start);
333 bytestream_put_le16(bytestream, width);
334 bytestream_put_le16(bytestream, height);
337 bytestream_put_byte(bytestream, 0x00); /* flags */
340 bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */
341 for (i = 0; i < AVPALETTE_COUNT; i++) {
342 const uint32_t v = palette[i];
343 bytestream_put_be24(bytestream, v);
347 bytestream_put_byte(bytestream, 0x08);
349 ff_lzw_encode_init(s->lzw, s->buf, s->buf_size,
350 12, FF_LZW_GIF, put_bits);
352 ptr = buf + y_start*linesize + x_start;
353 if (honor_transparency) {
354 const int ref_linesize = s->last_frame->linesize[0];
355 const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
357 for (y = 0; y < height; y++) {
358 memcpy(s->tmpl, ptr, width);
359 for (x = 0; x < width; x++)
360 if (ref[x] == ptr[x])
362 len += ff_lzw_encode(s->lzw, s->tmpl, width);
367 for (y = 0; y < height; y++) {
368 len += ff_lzw_encode(s->lzw, ptr, width);
372 len += ff_lzw_encode_flush(s->lzw, flush_put_bits);
376 int size = FFMIN(255, len);
377 bytestream_put_byte(bytestream, size);
378 if (end - *bytestream < size)
380 bytestream_put_buffer(bytestream, ptr, size);
384 bytestream_put_byte(bytestream, 0x00); /* end of image block */
388 static av_cold int gif_encode_init(AVCodecContext *avctx)
390 GIFContext *s = avctx->priv_data;
392 if (avctx->width > 65535 || avctx->height > 65535) {
393 av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
394 return AVERROR(EINVAL);
397 s->transparent_index = -1;
398 s->is_first_frame = 1;
400 s->lzw = av_mallocz(ff_lzw_encode_state_size);
401 s->buf_size = avctx->width*avctx->height*2 + 1000;
402 s->buf = av_malloc(s->buf_size);
403 s->tmpl = av_malloc(avctx->width);
404 if (!s->tmpl || !s->buf || !s->lzw)
405 return AVERROR(ENOMEM);
407 if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
408 av_assert0(avctx->pix_fmt == AV_PIX_FMT_PAL8);
413 static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
414 const AVFrame *pict, int *got_packet)
416 GIFContext *s = avctx->priv_data;
417 uint8_t *outbuf_ptr, *end;
418 const uint32_t *palette = NULL;
421 if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
423 outbuf_ptr = pkt->data;
424 end = pkt->data + pkt->size;
427 s->is_first_frame = 1;
429 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
430 palette = (uint32_t*)pict->data[1];
432 if (!s->palette_loaded) {
433 memcpy(s->palette, palette, AVPALETTE_SIZE);
434 s->transparent_index = get_palette_transparency_index(palette);
435 s->palette_loaded = 1;
436 } else if (!memcmp(s->palette, palette, AVPALETTE_SIZE)) {
441 gif_image_write_image(avctx, &outbuf_ptr, end, palette,
442 pict->data[0], pict->linesize[0], pkt);
443 if (!s->last_frame && !s->image) {
444 s->last_frame = av_frame_alloc();
446 return AVERROR(ENOMEM);
450 av_frame_unref(s->last_frame);
451 ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
456 pkt->size = outbuf_ptr - pkt->data;
457 if (s->is_first_frame)
458 pkt->flags |= AV_PKT_FLAG_KEY;
464 static int gif_encode_close(AVCodecContext *avctx)
466 GIFContext *s = avctx->priv_data;
471 av_frame_free(&s->last_frame);
476 #define OFFSET(x) offsetof(GIFContext, x)
477 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
478 static const AVOption gif_options[] = {
479 { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
480 { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
481 { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
482 { "gifimage", "enable encoding only images per frame", OFFSET(image), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS, "flags" },
486 static const AVClass gif_class = {
487 .class_name = "GIF encoder",
488 .item_name = av_default_item_name,
489 .option = gif_options,
490 .version = LIBAVUTIL_VERSION_INT,
493 AVCodec ff_gif_encoder = {
495 .long_name = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
496 .type = AVMEDIA_TYPE_VIDEO,
497 .id = AV_CODEC_ID_GIF,
498 .priv_data_size = sizeof(GIFContext),
499 .init = gif_encode_init,
500 .encode2 = gif_encode_frame,
501 .close = gif_encode_close,
502 .pix_fmts = (const enum AVPixelFormat[]){
503 AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE,
504 AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE
506 .priv_class = &gif_class,