FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
gif.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2000 Fabrice Bellard
3  * Copyright (c) 2002 Francois Revol
4  * Copyright (c) 2006 Baptiste Coudurier
5  *
6  * first version by Francois Revol <revol@free.fr>
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24 
25 /**
26  * @file
27  * GIF encoder
28  * @see http://www.w3.org/Graphics/GIF/spec-gif89a.txt
29  */
30 
31 #define BITSTREAM_WRITER_LE
32 #include "libavutil/opt.h"
33 #include "libavutil/imgutils.h"
34 #include "avcodec.h"
35 #include "bytestream.h"
36 #include "internal.h"
37 #include "lzw.h"
38 #include "gif.h"
39 
40 #include "put_bits.h"
41 
42 typedef struct GIFContext {
43  const AVClass *class;
47  int flags;
48  uint32_t palette[AVPALETTE_COUNT]; ///< local reference palette for !pal8
52  uint8_t *tmpl; ///< temporary line buffer
53 } GIFContext;
54 
55 enum {
56  GF_OFFSETTING = 1<<0,
57  GF_TRANSDIFF = 1<<1,
58 };
59 
60 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
61 {
62  int histogram[AVPALETTE_COUNT] = {0};
63  int x, y, i;
64 
65  for (y = 0; y < h; y++) {
66  for (x = 0; x < w; x++)
67  histogram[buf[x]]++;
68  buf += linesize;
69  }
70  for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
71  if (!histogram[i])
72  return i;
73  return -1;
74 }
75 
77  uint8_t **bytestream, uint8_t *end,
78  const uint32_t *palette,
79  const uint8_t *buf, const int linesize,
80  AVPacket *pkt)
81 {
82  GIFContext *s = avctx->priv_data;
83  int len = 0, height = avctx->height, width = avctx->width, x, y;
84  int x_start = 0, y_start = 0, trans = s->transparent_index;
85  int honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame;
86  const uint8_t *ptr;
87 
88  /* Crop image */
89  if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
90  const uint8_t *ref = s->last_frame->data[0];
91  const int ref_linesize = s->last_frame->linesize[0];
92  int x_end = avctx->width - 1,
93  y_end = avctx->height - 1;
94 
95  /* skip common lines */
96  while (y_start < y_end) {
97  if (memcmp(ref + y_start*ref_linesize, buf + y_start*linesize, width))
98  break;
99  y_start++;
100  }
101  while (y_end > y_start) {
102  if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, width))
103  break;
104  y_end--;
105  }
106  height = y_end + 1 - y_start;
107 
108  /* skip common columns */
109  while (x_start < x_end) {
110  int same_column = 1;
111  for (y = y_start; y <= y_end; y++) {
112  if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {
113  same_column = 0;
114  break;
115  }
116  }
117  if (!same_column)
118  break;
119  x_start++;
120  }
121  while (x_end > x_start) {
122  int same_column = 1;
123  for (y = y_start; y <= y_end; y++) {
124  if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
125  same_column = 0;
126  break;
127  }
128  }
129  if (!same_column)
130  break;
131  x_end--;
132  }
133  width = x_end + 1 - x_start;
134 
135  av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
136  width, height, x_start, y_start, avctx->width, avctx->height);
137  }
138 
139  /* image block */
140  bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
141  bytestream_put_le16(bytestream, x_start);
142  bytestream_put_le16(bytestream, y_start);
143  bytestream_put_le16(bytestream, width);
144  bytestream_put_le16(bytestream, height);
145 
146  if (!palette) {
147  bytestream_put_byte(bytestream, 0x00); /* flags */
148  } else {
149  unsigned i;
150  bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */
151  for (i = 0; i < AVPALETTE_COUNT; i++) {
152  const uint32_t v = palette[i];
153  bytestream_put_be24(bytestream, v);
154  }
155  }
156 
157  if (honor_transparency && trans < 0) {
158  trans = pick_palette_entry(buf + y_start*linesize + x_start,
159  linesize, width, height);
160  if (trans < 0) { // TODO, patch welcome
161  av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
162  } else {
163  uint8_t *pal_exdata = s->pal_exdata;
164  if (!pal_exdata)
166  if (!pal_exdata)
167  return AVERROR(ENOMEM);
168  memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);
169  pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;
170  }
171  }
172  if (trans < 0)
173  honor_transparency = 0;
174 
175  bytestream_put_byte(bytestream, 0x08);
176 
177  ff_lzw_encode_init(s->lzw, s->buf, 2 * width * height,
178  12, FF_LZW_GIF, put_bits);
179 
180  ptr = buf + y_start*linesize + x_start;
181  if (honor_transparency) {
182  const int ref_linesize = s->last_frame->linesize[0];
183  const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
184 
185  for (y = 0; y < height; y++) {
186  memcpy(s->tmpl, ptr, width);
187  for (x = 0; x < width; x++)
188  if (ref[x] == ptr[x])
189  s->tmpl[x] = trans;
190  len += ff_lzw_encode(s->lzw, s->tmpl, width);
191  ptr += linesize;
192  ref += ref_linesize;
193  }
194  } else {
195  for (y = 0; y < height; y++) {
196  len += ff_lzw_encode(s->lzw, ptr, width);
197  ptr += linesize;
198  }
199  }
201 
202  ptr = s->buf;
203  while (len > 0) {
204  int size = FFMIN(255, len);
205  bytestream_put_byte(bytestream, size);
206  if (end - *bytestream < size)
207  return -1;
208  bytestream_put_buffer(bytestream, ptr, size);
209  ptr += size;
210  len -= size;
211  }
212  bytestream_put_byte(bytestream, 0x00); /* end of image block */
213  return 0;
214 }
215 
217 {
218  GIFContext *s = avctx->priv_data;
219 
220  if (avctx->width > 65535 || avctx->height > 65535) {
221  av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
222  return AVERROR(EINVAL);
223  }
224 #if FF_API_CODED_FRAME
227  avctx->coded_frame->key_frame = 1;
229 #endif
230 
231  s->transparent_index = -1;
232 
234  s->buf = av_malloc(avctx->width*avctx->height*2);
235  s->tmpl = av_malloc(avctx->width);
236  if (!s->tmpl || !s->buf || !s->lzw)
237  return AVERROR(ENOMEM);
238 
239  if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
241 
242  return 0;
243 }
244 
245 /* FIXME: duplicated with lavc */
246 static int get_palette_transparency_index(const uint32_t *palette)
247 {
248  int transparent_color_index = -1;
249  unsigned i, smallest_alpha = 0xff;
250 
251  if (!palette)
252  return -1;
253 
254  for (i = 0; i < AVPALETTE_COUNT; i++) {
255  const uint32_t v = palette[i];
256  if (v >> 24 < smallest_alpha) {
257  smallest_alpha = v >> 24;
258  transparent_color_index = i;
259  }
260  }
261  return smallest_alpha < 128 ? transparent_color_index : -1;
262 }
263 
265  const AVFrame *pict, int *got_packet)
266 {
267  GIFContext *s = avctx->priv_data;
268  uint8_t *outbuf_ptr, *end;
269  const uint32_t *palette = NULL;
270  int ret;
271 
272  if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
273  return ret;
274  outbuf_ptr = pkt->data;
275  end = pkt->data + pkt->size;
276 
277  if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
279  if (!pal_exdata)
280  return AVERROR(ENOMEM);
281  memcpy(pal_exdata, pict->data[1], AVPALETTE_SIZE);
282  palette = (uint32_t*)pict->data[1];
283 
284  s->pal_exdata = pal_exdata;
285 
286  /* The first palette with PAL8 will be used as generic palette by the
287  * muxer so we don't need to write it locally in the packet. We store
288  * it as a reference here in case it changes later. */
289  if (!s->palette_loaded) {
290  memcpy(s->palette, palette, AVPALETTE_SIZE);
292  s->palette_loaded = 1;
293  palette = NULL;
294  } else if (!memcmp(s->palette, palette, AVPALETTE_SIZE)) {
295  palette = NULL;
296  }
297  }
298 
299  gif_image_write_image(avctx, &outbuf_ptr, end, palette,
300  pict->data[0], pict->linesize[0], pkt);
301  if (!s->last_frame) {
302  s->last_frame = av_frame_alloc();
303  if (!s->last_frame)
304  return AVERROR(ENOMEM);
305  }
307  ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
308  if (ret < 0)
309  return ret;
310 
311  pkt->size = outbuf_ptr - pkt->data;
312  pkt->flags |= AV_PKT_FLAG_KEY;
313  *got_packet = 1;
314 
315  return 0;
316 }
317 
319 {
320  GIFContext *s = avctx->priv_data;
321 
322  av_freep(&s->lzw);
323  av_freep(&s->buf);
325  av_freep(&s->tmpl);
326  return 0;
327 }
328 
329 #define OFFSET(x) offsetof(GIFContext, x)
330 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
331 static const AVOption gif_options[] = {
332  { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
333  { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
334  { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
335  { NULL }
336 };
337 
338 static const AVClass gif_class = {
339  .class_name = "GIF encoder",
340  .item_name = av_default_item_name,
341  .option = gif_options,
342  .version = LIBAVUTIL_VERSION_INT,
343 };
344 
346  .name = "gif",
347  .long_name = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
348  .type = AVMEDIA_TYPE_VIDEO,
349  .id = AV_CODEC_ID_GIF,
350  .priv_data_size = sizeof(GIFContext),
352  .encode2 = gif_encode_frame,
353  .close = gif_encode_close,
354  .pix_fmts = (const enum AVPixelFormat[]){
357  },
358  .priv_class = &gif_class,
359 };
#define NULL
Definition: coverity.c:32
float v
const char * s
Definition: avisynth_c.h:631
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
AVOption.
Definition: opt.h:255
uint32_t palette[AVPALETTE_COUNT]
local reference palette for !pal8
Definition: gif.c:48
misc image utilities
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:167
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
static int get_palette_transparency_index(const uint32_t *palette)
Definition: gif.c:246
int size
Definition: avcodec.h:1424
static int gif_encode_close(AVCodecContext *avctx)
Definition: gif.c:318
static const AVClass gif_class
Definition: gif.c:338
int ff_lzw_encode(struct LZWEncodeState *s, const uint8_t *inbuf, int insize)
LZW main compress function.
Definition: lzwenc.c:227
AVCodec ff_gif_encoder
Definition: gif.c:345
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1722
static AVPacket pkt
AVCodec.
Definition: avcodec.h:3472
packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb)
Definition: pixfmt.h:87
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
uint8_t
#define av_cold
Definition: attributes.h:74
#define av_malloc(s)
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:135
8 bit with AV_PIX_FMT_RGB32 palette
Definition: pixfmt.h:74
AVOptions.
int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt)
Definition: imgutils.c:152
#define AVPALETTE_SIZE
Definition: pixfmt.h:33
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
Definition: frame.c:365
uint8_t * data
Definition: avcodec.h:1423
static int gif_image_write_image(AVCodecContext *avctx, uint8_t **bytestream, uint8_t *end, const uint32_t *palette, const uint8_t *buf, const int linesize, AVPacket *pkt)
Definition: gif.c:76
ptrdiff_t size
Definition: opengl_enc.c:101
uint8_t * tmpl
temporary line buffer
Definition: gif.c:52
int flags
Definition: gif.c:47
#define AV_INPUT_BUFFER_MIN_SIZE
minimum encoding buffer size Used to avoid some checks during header writing.
Definition: avcodec.h:643
#define av_log(a,...)
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1469
#define FLAGS
Definition: gif.c:330
int ff_lzw_encode_flush(struct LZWEncodeState *s, void(*lzw_flush_put_bits)(struct PutBitContext *))
Definition: lzw.c:46
uint8_t * pal_exdata
Definition: gif.c:51
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
LZWState * lzw
Definition: gif.c:44
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:148
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
Definition: gif.c:42
const char * name
Name of the codec implementation.
Definition: avcodec.h:3479
Libavcodec external API header.
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1429
#define OFFSET(x)
Definition: gif.c:329
#define GIF_IMAGE_SEPARATOR
Definition: gif.h:44
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:242
#define FFMIN(a, b)
Definition: common.h:81
Definition: lzw.h:38
static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
Definition: gif.c:60
float y
packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb)
Definition: pixfmt.h:90
int width
picture width / height.
Definition: avcodec.h:1681
#define FF_ARRAY_ELEMS(a)
packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb)
Definition: pixfmt.h:85
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:199
GIF format definitions.
main external API structure.
Definition: avcodec.h:1502
static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet)
Definition: gif.c:264
void * buf
Definition: avisynth_c.h:553
BYTE int const BYTE int int int height
Definition: avisynth_c.h:676
Describe the class of an AVClass context structure.
Definition: log.h:67
uint8_t * buf
Definition: gif.c:45
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1782
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:209
#define AVPALETTE_COUNT
Definition: pixfmt.h:34
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:464
static int flags
Definition: cpu.c:47
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
LZW decoding routines.
int palette
Definition: v4l.c:61
Y , 8bpp.
Definition: pixfmt.h:71
void ff_lzw_encode_init(struct LZWEncodeState *s, uint8_t *outbuf, int outsize, int maxbits, enum FF_LZW_MODES mode, void(*lzw_put_bits)(struct PutBitContext *, int, unsigned int))
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:79
common internal api header.
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition: put_bits.h:101
if(ret< 0)
Definition: vf_mcdeint.c:280
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:3024
packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb)
Definition: pixfmt.h:88
static av_always_inline void bytestream_put_buffer(uint8_t **b, const uint8_t *src, unsigned int size)
Definition: bytestream.h:368
void * priv_data
Definition: avcodec.h:1544
AVFrame * last_frame
Definition: gif.c:46
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:80
int len
static av_cold int gif_encode_init(AVCodecContext *avctx)
Definition: gif.c:216
int transparent_index
Definition: gif.c:50
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:237
#define av_freep(p)
int palette_loaded
Definition: gif.c:49
const int ff_lzw_encode_state_size
Definition: lzwenc.c:67
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:299
static const AVOption gif_options[]
Definition: gif.c:331
AVPixelFormat
Pixel format.
Definition: pixfmt.h:61
This structure stores compressed data.
Definition: avcodec.h:1400
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:252
static int width
bitstream writer API