FFmpeg  2.6.9
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules 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;
46  int buf_size;
48  int flags;
49  uint32_t palette[AVPALETTE_COUNT]; ///< local reference palette for !pal8
53  uint8_t *tmpl; ///< temporary line buffer
54 } GIFContext;
55 
56 enum {
57  GF_OFFSETTING = 1<<0,
58  GF_TRANSDIFF = 1<<1,
59 };
60 
61 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
62 {
63  int histogram[AVPALETTE_COUNT] = {0};
64  int x, y, i;
65 
66  for (y = 0; y < h; y++) {
67  for (x = 0; x < w; x++)
68  histogram[buf[x]]++;
69  buf += linesize;
70  }
71  for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
72  if (!histogram[i])
73  return i;
74  return -1;
75 }
76 
78  uint8_t **bytestream, uint8_t *end,
79  const uint32_t *palette,
80  const uint8_t *buf, const int linesize,
81  AVPacket *pkt)
82 {
83  GIFContext *s = avctx->priv_data;
84  int len = 0, height = avctx->height, width = avctx->width, x, y;
85  int x_start = 0, y_start = 0, trans = s->transparent_index;
86  int honor_transparency = (s->flags & GF_TRANSDIFF) && s->last_frame;
87  const uint8_t *ptr;
88 
89  /* Crop image */
90  if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
91  const uint8_t *ref = s->last_frame->data[0];
92  const int ref_linesize = s->last_frame->linesize[0];
93  int x_end = avctx->width - 1,
94  y_end = avctx->height - 1;
95 
96  /* skip common lines */
97  while (y_start < y_end) {
98  if (memcmp(ref + y_start*ref_linesize, buf + y_start*linesize, width))
99  break;
100  y_start++;
101  }
102  while (y_end > y_start) {
103  if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, width))
104  break;
105  y_end--;
106  }
107  height = y_end + 1 - y_start;
108 
109  /* skip common columns */
110  while (x_start < x_end) {
111  int same_column = 1;
112  for (y = y_start; y <= y_end; y++) {
113  if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {
114  same_column = 0;
115  break;
116  }
117  }
118  if (!same_column)
119  break;
120  x_start++;
121  }
122  while (x_end > x_start) {
123  int same_column = 1;
124  for (y = y_start; y <= y_end; y++) {
125  if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
126  same_column = 0;
127  break;
128  }
129  }
130  if (!same_column)
131  break;
132  x_end--;
133  }
134  width = x_end + 1 - x_start;
135 
136  av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
137  width, height, x_start, y_start, avctx->width, avctx->height);
138  }
139 
140  /* image block */
141  bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
142  bytestream_put_le16(bytestream, x_start);
143  bytestream_put_le16(bytestream, y_start);
144  bytestream_put_le16(bytestream, width);
145  bytestream_put_le16(bytestream, height);
146 
147  if (!palette) {
148  bytestream_put_byte(bytestream, 0x00); /* flags */
149  } else {
150  unsigned i;
151  bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */
152  for (i = 0; i < AVPALETTE_COUNT; i++) {
153  const uint32_t v = palette[i];
154  bytestream_put_be24(bytestream, v);
155  }
156  }
157 
158  if (honor_transparency && trans < 0) {
159  trans = pick_palette_entry(buf + y_start*linesize + x_start,
160  linesize, width, height);
161  if (trans < 0) { // TODO, patch welcome
162  av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
163  } else {
164  uint8_t *pal_exdata = s->pal_exdata;
165  if (!pal_exdata)
167  if (!pal_exdata)
168  return AVERROR(ENOMEM);
169  memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);
170  pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;
171  }
172  }
173  if (trans < 0)
174  honor_transparency = 0;
175 
176  bytestream_put_byte(bytestream, 0x08);
177 
178  ff_lzw_encode_init(s->lzw, s->buf, s->buf_size,
179  12, FF_LZW_GIF, put_bits);
180 
181  ptr = buf + y_start*linesize + x_start;
182  if (honor_transparency) {
183  const int ref_linesize = s->last_frame->linesize[0];
184  const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
185 
186  for (y = 0; y < height; y++) {
187  memcpy(s->tmpl, ptr, width);
188  for (x = 0; x < width; x++)
189  if (ref[x] == ptr[x])
190  s->tmpl[x] = trans;
191  len += ff_lzw_encode(s->lzw, s->tmpl, width);
192  ptr += linesize;
193  ref += ref_linesize;
194  }
195  } else {
196  for (y = 0; y < height; y++) {
197  len += ff_lzw_encode(s->lzw, ptr, width);
198  ptr += linesize;
199  }
200  }
202 
203  ptr = s->buf;
204  while (len > 0) {
205  int size = FFMIN(255, len);
206  bytestream_put_byte(bytestream, size);
207  if (end - *bytestream < size)
208  return -1;
209  bytestream_put_buffer(bytestream, ptr, size);
210  ptr += size;
211  len -= size;
212  }
213  bytestream_put_byte(bytestream, 0x00); /* end of image block */
214  return 0;
215 }
216 
218 {
219  GIFContext *s = avctx->priv_data;
220 
221  if (avctx->width > 65535 || avctx->height > 65535) {
222  av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
223  return AVERROR(EINVAL);
224  }
225 
226  avctx->coded_frame = av_frame_alloc();
227  if (!avctx->coded_frame)
228  return AVERROR(ENOMEM);
229 
231  avctx->coded_frame->key_frame = 1;
232 
233  s->transparent_index = -1;
234 
236  s->buf_size = avctx->width*avctx->height*2 + 1000;
237  s->buf = av_malloc(s->buf_size);
238  s->tmpl = av_malloc(avctx->width);
239  if (!s->tmpl || !s->buf || !s->lzw)
240  return AVERROR(ENOMEM);
241 
242  if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
244 
245  return 0;
246 }
247 
248 /* FIXME: duplicated with lavc */
249 static int get_palette_transparency_index(const uint32_t *palette)
250 {
251  int transparent_color_index = -1;
252  unsigned i, smallest_alpha = 0xff;
253 
254  if (!palette)
255  return -1;
256 
257  for (i = 0; i < AVPALETTE_COUNT; i++) {
258  const uint32_t v = palette[i];
259  if (v >> 24 < smallest_alpha) {
260  smallest_alpha = v >> 24;
261  transparent_color_index = i;
262  }
263  }
264  return smallest_alpha < 128 ? transparent_color_index : -1;
265 }
266 
268  const AVFrame *pict, int *got_packet)
269 {
270  GIFContext *s = avctx->priv_data;
271  uint8_t *outbuf_ptr, *end;
272  const uint32_t *palette = NULL;
273  int ret;
274 
275  if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + FF_MIN_BUFFER_SIZE)) < 0)
276  return ret;
277  outbuf_ptr = pkt->data;
278  end = pkt->data + pkt->size;
279 
280  if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
282  if (!pal_exdata)
283  return AVERROR(ENOMEM);
284  memcpy(pal_exdata, pict->data[1], AVPALETTE_SIZE);
285  palette = (uint32_t*)pict->data[1];
286 
287  s->pal_exdata = pal_exdata;
288 
289  /* The first palette with PAL8 will be used as generic palette by the
290  * muxer so we don't need to write it locally in the packet. We store
291  * it as a reference here in case it changes later. */
292  if (!s->palette_loaded) {
293  memcpy(s->palette, palette, AVPALETTE_SIZE);
295  s->palette_loaded = 1;
296  palette = NULL;
297  } else if (!memcmp(s->palette, palette, AVPALETTE_SIZE)) {
298  palette = NULL;
299  }
300  }
301 
302  gif_image_write_image(avctx, &outbuf_ptr, end, palette,
303  pict->data[0], pict->linesize[0], pkt);
304  if (!s->last_frame) {
305  s->last_frame = av_frame_alloc();
306  if (!s->last_frame)
307  return AVERROR(ENOMEM);
308  }
310  ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
311  if (ret < 0)
312  return ret;
313 
314  pkt->size = outbuf_ptr - pkt->data;
315  pkt->flags |= AV_PKT_FLAG_KEY;
316  *got_packet = 1;
317 
318  return 0;
319 }
320 
322 {
323  GIFContext *s = avctx->priv_data;
324 
325  av_frame_free(&avctx->coded_frame);
326 
327  av_freep(&s->lzw);
328  av_freep(&s->buf);
329  s->buf_size = 0;
331  av_freep(&s->tmpl);
332  return 0;
333 }
334 
335 #define OFFSET(x) offsetof(GIFContext, x)
336 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
337 static const AVOption gif_options[] = {
338  { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
339  { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
340  { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
341  { NULL }
342 };
343 
344 static const AVClass gif_class = {
345  .class_name = "GIF encoder",
346  .item_name = av_default_item_name,
347  .option = gif_options,
348  .version = LIBAVUTIL_VERSION_INT,
349 };
350 
352  .name = "gif",
353  .long_name = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
354  .type = AVMEDIA_TYPE_VIDEO,
355  .id = AV_CODEC_ID_GIF,
356  .priv_data_size = sizeof(GIFContext),
358  .encode2 = gif_encode_frame,
359  .close = gif_encode_close,
360  .pix_fmts = (const enum AVPixelFormat[]){
363  },
364  .priv_class = &gif_class,
365 };
#define NULL
Definition: coverity.c:32
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1724
float v
const char * s
Definition: avisynth_c.h:669
This structure describes decoded (raw) audio or video data.
Definition: frame.h:163
AVOption.
Definition: opt.h:255
uint32_t palette[AVPALETTE_COUNT]
local reference palette for !pal8
Definition: gif.c:49
misc image utilities
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:198
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2743
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
static int get_palette_transparency_index(const uint32_t *palette)
Definition: gif.c:249
int size
Definition: avcodec.h:1161
static int gif_encode_close(AVCodecContext *avctx)
Definition: gif.c:321
static const AVClass gif_class
Definition: gif.c:344
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:351
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1442
#define FF_ARRAY_ELEMS(a)
static AVPacket pkt
AVCodec.
Definition: avcodec.h:3173
packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb)
Definition: pixfmt.h:92
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:71
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
if()
Definition: avfilter.c:975
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 PIX_FMT_RGB32 palette
Definition: pixfmt.h:79
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:67
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:278
int buf_size
Definition: gif.c:46
uint8_t * data
Definition: avcodec.h:1160
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:77
ptrdiff_t size
Definition: opengl_enc.c:101
uint8_t * tmpl
temporary line buffer
Definition: gif.c:53
int flags
Definition: gif.c:48
#define av_log(a,...)
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1206
#define FLAGS
Definition: gif.c:336
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:52
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:175
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:180
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:196
Definition: gif.c:42
const char * name
Name of the codec implementation.
Definition: avcodec.h:3180
Libavcodec external API header.
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1166
#define OFFSET(x)
Definition: gif.c:335
#define GIF_IMAGE_SEPARATOR
Definition: gif.h:44
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:234
#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:61
float y
packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb)
Definition: pixfmt.h:95
#define FF_MIN_BUFFER_SIZE
minimum encoding buffer size Used to avoid some checks during header writing.
Definition: avcodec.h:635
ret
Definition: avfilter.c:974
int width
picture width / height.
Definition: avcodec.h:1412
packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb)
Definition: pixfmt.h:90
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:191
GIF format definitions.
main external API structure.
Definition: avcodec.h:1239
static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet)
Definition: gif.c:267
void * buf
Definition: avisynth_c.h:595
BYTE int const BYTE int int int height
Definition: avisynth_c.h:714
Describe the class of an AVClass context structure.
Definition: log.h:66
uint8_t * buf
Definition: gif.c:45
#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:377
static int flags
Definition: cpu.c:47
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:174
LZW decoding routines.
int palette
Definition: v4l.c:60
Y , 8bpp.
Definition: pixfmt.h:76
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))
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
packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb)
Definition: pixfmt.h:93
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:1281
AVFrame * last_frame
Definition: gif.c:47
int len
static av_cold int gif_encode_init(AVCodecContext *avctx)
Definition: gif.c:217
int transparent_index
Definition: gif.c:51
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:229
#define av_freep(p)
int palette_loaded
Definition: gif.c:50
const int ff_lzw_encode_state_size
Definition: lzwenc.c:67
#define HAVE_BIGENDIAN
Definition: config.h:168
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:300
static const AVOption gif_options[]
Definition: gif.c:337
AVPixelFormat
Pixel format.
Definition: pixfmt.h:66
This structure stores compressed data.
Definition: avcodec.h:1137
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:250
static int width
bitstream writer API