]> git.sesse.net Git - ffmpeg/blob - libavcodec/gif.c
avcodec/gif: enable encoding single gif image per frame
[ffmpeg] / libavcodec / gif.c
1 /*
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
7  *
8  * first version by Francois Revol <revol@free.fr>
9  *
10  * This file is part of FFmpeg.
11  *
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.
16  *
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.
21  *
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
25  */
26
27 /**
28  * @file
29  * GIF encoder
30  * @see http://www.w3.org/Graphics/GIF/spec-gif89a.txt
31  */
32
33 #define BITSTREAM_WRITER_LE
34 #include "libavutil/opt.h"
35 #include "libavutil/imgutils.h"
36 #include "avcodec.h"
37 #include "bytestream.h"
38 #include "internal.h"
39 #include "lzw.h"
40 #include "gif.h"
41
42 #include "put_bits.h"
43
44 #define DEFAULT_TRANSPARENCY_INDEX 0x1f
45
46 typedef struct GIFContext {
47     const AVClass *class;
48     LZWState *lzw;
49     uint8_t *buf;
50     int buf_size;
51     int is_first_frame;
52     AVFrame *last_frame;
53     int flags;
54     int image;
55     uint32_t palette[AVPALETTE_COUNT];  ///< local reference palette for !pal8
56     int palette_loaded;
57     int transparent_index;
58     uint8_t *tmpl;                      ///< temporary line buffer
59 } GIFContext;
60
61 enum {
62     GF_OFFSETTING = 1<<0,
63     GF_TRANSDIFF  = 1<<1,
64 };
65
66 static int is_image_translucent(AVCodecContext *avctx,
67                                 const uint8_t *buf, const int linesize)
68 {
69     GIFContext *s = avctx->priv_data;
70     int trans = s->transparent_index;
71
72     if (trans < 0)
73         return 0;
74
75     for (int y = 0; y < avctx->height; y++) {
76         for (int x = 0; x < avctx->width; x++) {
77             if (buf[x] == trans) {
78                 return 1;
79             }
80         }
81         buf += linesize;
82     }
83
84     return 0;
85 }
86
87 static int get_palette_transparency_index(const uint32_t *palette)
88 {
89     int transparent_color_index = -1;
90     unsigned i, smallest_alpha = 0xff;
91
92     if (!palette)
93         return -1;
94
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;
100         }
101     }
102     return smallest_alpha < 128 ? transparent_color_index : -1;
103 }
104
105 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
106 {
107     int histogram[AVPALETTE_COUNT] = {0};
108     int x, y, i;
109
110     for (y = 0; y < h; y++) {
111         for (x = 0; x < w; x++)
112             histogram[buf[x]]++;
113         buf += linesize;
114     }
115     for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
116         if (!histogram[i])
117             return i;
118     return -1;
119 }
120
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)
125 {
126     GIFContext *s = avctx->priv_data;
127     int trans = s->transparent_index;
128
129     /* Crop image */
130     if ((s->flags & GF_OFFSETTING) && trans >= 0) {
131         const int w = avctx->width;
132         const int h = avctx->height;
133         int x_end = w - 1,
134             y_end = h - 1;
135
136         // crop top
137         while (*y_start < y_end) {
138             int is_trans = 1;
139             for (int i = 0; i < w; i++) {
140                 if (buf[w * *y_start + i] != trans) {
141                     is_trans = 0;
142                     break;
143                 }
144             }
145
146             if (!is_trans)
147                 break;
148             (*y_start)++;
149         }
150
151         // crop bottom
152         while (y_end < h) {
153             int is_trans = 1;
154             for (int i = 0; i < w; i++) {
155                 if (buf[w * y_end + i] != trans) {
156                     is_trans = 0;
157                     break;
158                 }
159             }
160             if (!is_trans)
161                 break;
162             y_end--;
163         }
164
165         // crop left
166         while (*x_start < x_end) {
167             int is_trans = 1;
168             for (int i = *y_start; i < y_end; i++) {
169                 if (buf[w * i + *x_start] != trans) {
170                     is_trans = 0;
171                     break;
172                 }
173             }
174             if (!is_trans)
175                 break;
176             (*x_start)++;
177         }
178
179         // crop right
180         while (x_end < w) {
181             int is_trans = 1;
182             for (int i = *y_start; i < y_end; i++) {
183                 if (buf[w * i + x_end] != trans) {
184                     is_trans = 0;
185                     break;
186                 }
187             }
188             if (!is_trans)
189                 break;
190             x_end--;
191         }
192
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);
197     }
198 }
199
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)
204 {
205     GIFContext *s = avctx->priv_data;
206
207     /* Crop image */
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;
213
214         /* skip common lines */
215         while (*y_start < y_end) {
216             if (memcmp(ref + *y_start*ref_linesize, buf + *y_start*linesize, *width))
217                 break;
218             (*y_start)++;
219         }
220         while (y_end > *y_start) {
221             if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, *width))
222                 break;
223             y_end--;
224         }
225         *height = y_end + 1 - *y_start;
226
227         /* skip common columns */
228         while (*x_start < x_end) {
229             int same_column = 1;
230             for (int y = *y_start; y <= y_end; y++) {
231                 if (ref[y*ref_linesize + *x_start] != buf[y*linesize + *x_start]) {
232                     same_column = 0;
233                     break;
234                 }
235             }
236             if (!same_column)
237                 break;
238             (*x_start)++;
239         }
240         while (x_end > *x_start) {
241             int same_column = 1;
242             for (int y = *y_start; y <= y_end; y++) {
243                 if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
244                     same_column = 0;
245                     break;
246                 }
247             }
248             if (!same_column)
249                 break;
250             x_end--;
251         }
252         *width = x_end + 1 - *x_start;
253
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);
256     }
257 }
258
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,
263                                  AVPacket *pkt)
264 {
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;
269     const uint8_t *ptr;
270
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;
275     } else {
276         gif_crop_opaque(avctx, palette, buf, linesize, &width, &height, &x_start, &y_start);
277         disposal = GCE_DISPOSAL_INPLACE;
278     }
279
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;
283         int64_t aspect = 0;
284
285         if (sar.num > 0 && sar.den > 0) {
286             aspect = sar.num * 64LL / sar.den - 15;
287             if (aspect < 0 || aspect > 255)
288                 aspect = 0;
289         }
290
291         bytestream_put_buffer(bytestream, gif89a_sig, sizeof(gif89a_sig));
292         bytestream_put_le16(bytestream, avctx->width);
293         bytestream_put_le16(bytestream, avctx->height);
294
295         bcid = get_palette_transparency_index(global_palette);
296
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);
303         }
304
305         s->is_first_frame = 0;
306     }
307
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");
313     }
314
315     if (trans < 0)
316         honor_transparency = 0;
317
318     bcid = honor_transparency || disposal == GCE_DISPOSAL_BACKGROUND ? trans : get_palette_transparency_index(palette);
319
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);
328
329     /* image block */
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);
335
336     if (!palette) {
337         bytestream_put_byte(bytestream, 0x00); /* flags */
338     } else {
339         unsigned i;
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);
344         }
345     }
346
347     bytestream_put_byte(bytestream, 0x08);
348
349     ff_lzw_encode_init(s->lzw, s->buf, s->buf_size,
350                        12, FF_LZW_GIF, put_bits);
351
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;
356
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])
361                     s->tmpl[x] = trans;
362             len += ff_lzw_encode(s->lzw, s->tmpl, width);
363             ptr += linesize;
364             ref += ref_linesize;
365         }
366     } else {
367         for (y = 0; y < height; y++) {
368             len += ff_lzw_encode(s->lzw, ptr, width);
369             ptr += linesize;
370         }
371     }
372     len += ff_lzw_encode_flush(s->lzw, flush_put_bits);
373
374     ptr = s->buf;
375     while (len > 0) {
376         int size = FFMIN(255, len);
377         bytestream_put_byte(bytestream, size);
378         if (end - *bytestream < size)
379             return -1;
380         bytestream_put_buffer(bytestream, ptr, size);
381         ptr += size;
382         len -= size;
383     }
384     bytestream_put_byte(bytestream, 0x00); /* end of image block */
385     return 0;
386 }
387
388 static av_cold int gif_encode_init(AVCodecContext *avctx)
389 {
390     GIFContext *s = avctx->priv_data;
391
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);
395     }
396
397     s->transparent_index = -1;
398     s->is_first_frame = 1;
399
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);
406
407     if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
408         av_assert0(avctx->pix_fmt == AV_PIX_FMT_PAL8);
409
410     return 0;
411 }
412
413 static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
414                             const AVFrame *pict, int *got_packet)
415 {
416     GIFContext *s = avctx->priv_data;
417     uint8_t *outbuf_ptr, *end;
418     const uint32_t *palette = NULL;
419     int ret;
420
421     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
422         return ret;
423     outbuf_ptr = pkt->data;
424     end        = pkt->data + pkt->size;
425
426     if (s->image)
427         s->is_first_frame = 1;
428
429     if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
430         palette = (uint32_t*)pict->data[1];
431
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)) {
437             palette = NULL;
438         }
439     }
440
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();
445         if (!s->last_frame)
446             return AVERROR(ENOMEM);
447     }
448
449     if (!s->image) {
450         av_frame_unref(s->last_frame);
451         ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
452         if (ret < 0)
453             return ret;
454     }
455
456     pkt->size   = outbuf_ptr - pkt->data;
457     if (s->is_first_frame)
458         pkt->flags |= AV_PKT_FLAG_KEY;
459     *got_packet = 1;
460
461     return 0;
462 }
463
464 static int gif_encode_close(AVCodecContext *avctx)
465 {
466     GIFContext *s = avctx->priv_data;
467
468     av_freep(&s->lzw);
469     av_freep(&s->buf);
470     s->buf_size = 0;
471     av_frame_free(&s->last_frame);
472     av_freep(&s->tmpl);
473     return 0;
474 }
475
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" },
483     { NULL }
484 };
485
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,
491 };
492
493 AVCodec ff_gif_encoder = {
494     .name           = "gif",
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
505     },
506     .priv_class     = &gif_class,
507 };