FFmpeg  2.1.1
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 {
43  const AVClass *class;
47  int flags;
48  uint32_t palette[AVPALETTE_COUNT]; ///< local reference palette for !pal8
49  uint8_t *tmpl; ///< temporary line buffer
50 } GIFContext;
51 
52 enum {
53  GF_OFFSETTING = 1<<0,
54  GF_TRANSDIFF = 1<<1,
55 };
56 
57 static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
58 {
59  int histogram[AVPALETTE_COUNT] = {0};
60  int x, y, i;
61 
62  for (y = 0; y < h; y++) {
63  for (x = 0; x < w; x++)
64  histogram[buf[x]]++;
65  buf += linesize;
66  }
67  for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
68  if (!histogram[i])
69  return i;
70  return -1;
71 }
72 
74  uint8_t **bytestream, uint8_t *end,
75  const uint32_t *palette,
76  const uint8_t *buf, const int linesize,
77  AVPacket *pkt)
78 {
79  GIFContext *s = avctx->priv_data;
80  int len = 0, height = avctx->height, width = avctx->width, x, y;
81  int x_start = 0, y_start = 0, trans = -1;
82  const uint8_t *ptr;
83 
84  /* Crop image */
85  // TODO support with palette change
86  if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
87  const uint8_t *ref = s->last_frame->data[0];
88  const int ref_linesize = s->last_frame->linesize[0];
89  int x_end = avctx->width - 1,
90  y_end = avctx->height - 1;
91 
92  /* skip common lines */
93  while (y_start < y_end) {
94  if (memcmp(ref + y_start*ref_linesize, buf + y_start*linesize, width))
95  break;
96  y_start++;
97  }
98  while (y_end > y_start) {
99  if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, width))
100  break;
101  y_end--;
102  }
103  height = y_end + 1 - y_start;
104 
105  /* skip common columns */
106  while (x_start < x_end) {
107  int same_column = 1;
108  for (y = y_start; y < y_end; y++) {
109  if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {
110  same_column = 0;
111  break;
112  }
113  }
114  if (!same_column)
115  break;
116  x_start++;
117  }
118  while (x_end > x_start) {
119  int same_column = 1;
120  for (y = y_start; y < y_end; y++) {
121  if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
122  same_column = 0;
123  break;
124  }
125  }
126  if (!same_column)
127  break;
128  x_end--;
129  }
130  width = x_end + 1 - x_start;
131 
132  av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
133  width, height, x_start, y_start, avctx->width, avctx->height);
134  }
135 
136  /* image block */
137  bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
138  bytestream_put_le16(bytestream, x_start);
139  bytestream_put_le16(bytestream, y_start);
140  bytestream_put_le16(bytestream, width);
141  bytestream_put_le16(bytestream, height);
142 
143  if (!palette) {
144  bytestream_put_byte(bytestream, 0x00); /* flags */
145  } else {
146  unsigned i;
147  bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */
148  for (i = 0; i < AVPALETTE_COUNT; i++) {
149  const uint32_t v = palette[i];
150  bytestream_put_be24(bytestream, v);
151  }
152  }
153 
154  /* TODO: support with palette change (pal8) */
155  if ((s->flags & GF_TRANSDIFF) && s->last_frame && !palette) {
156  trans = pick_palette_entry(buf + y_start*linesize + x_start,
157  linesize, width, height);
158  if (trans < 0) { // TODO, patch welcome
159  av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
160  } else {
162  if (!pal_exdata)
163  return AVERROR(ENOMEM);
164  memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);
165  pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;
166  }
167  }
168 
169  bytestream_put_byte(bytestream, 0x08);
170 
171  ff_lzw_encode_init(s->lzw, s->buf, 2 * width * height,
172  12, FF_LZW_GIF, put_bits);
173 
174  ptr = buf + y_start*linesize + x_start;
175  if (trans >= 0) {
176  const int ref_linesize = s->last_frame->linesize[0];
177  const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;
178 
179  for (y = 0; y < height; y++) {
180  memcpy(s->tmpl, ptr, width);
181  for (x = 0; x < width; x++)
182  if (ref[x] == ptr[x])
183  s->tmpl[x] = trans;
184  len += ff_lzw_encode(s->lzw, s->tmpl, width);
185  ptr += linesize;
186  ref += ref_linesize;
187  }
188  } else {
189  for (y = 0; y < height; y++) {
190  len += ff_lzw_encode(s->lzw, ptr, width);
191  ptr += linesize;
192  }
193  }
195 
196  ptr = s->buf;
197  while (len > 0) {
198  int size = FFMIN(255, len);
199  bytestream_put_byte(bytestream, size);
200  if (end - *bytestream < size)
201  return -1;
202  bytestream_put_buffer(bytestream, ptr, size);
203  ptr += size;
204  len -= size;
205  }
206  bytestream_put_byte(bytestream, 0x00); /* end of image block */
207  return 0;
208 }
209 
211 {
212  GIFContext *s = avctx->priv_data;
213 
214  if (avctx->width > 65535 || avctx->height > 65535) {
215  av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
216  return AVERROR(EINVAL);
217  }
218 
220  s->buf = av_malloc(avctx->width*avctx->height*2);
221  s->tmpl = av_malloc(avctx->width);
222  if (!s->tmpl || !s->buf || !s->lzw)
223  return AVERROR(ENOMEM);
224 
225  if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
227 
228  return 0;
229 }
230 
232  const AVFrame *pict, int *got_packet)
233 {
234  GIFContext *s = avctx->priv_data;
235  AVFrame *const p = (AVFrame *)pict;
236  uint8_t *outbuf_ptr, *end;
237  const uint32_t *palette = NULL;
238  int ret;
239 
240  if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + FF_MIN_BUFFER_SIZE)) < 0)
241  return ret;
242  outbuf_ptr = pkt->data;
243  end = pkt->data + pkt->size;
244 
246  p->key_frame = 1;
247 
248  if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
250  if (!pal_exdata)
251  return AVERROR(ENOMEM);
252  memcpy(pal_exdata, p->data[1], AVPALETTE_SIZE);
253  palette = (uint32_t*)p->data[1];
254  }
255 
256  gif_image_write_image(avctx, &outbuf_ptr, end, palette,
257  pict->data[0], pict->linesize[0], pkt);
258  if (!s->last_frame) {
259  s->last_frame = av_frame_alloc();
260  if (!s->last_frame)
261  return AVERROR(ENOMEM);
262  }
264  ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
265  if (ret < 0)
266  return ret;
267 
268  pkt->size = outbuf_ptr - pkt->data;
269  pkt->flags |= AV_PKT_FLAG_KEY;
270  *got_packet = 1;
271 
272  return 0;
273 }
274 
276 {
277  GIFContext *s = avctx->priv_data;
278 
279  av_freep(&s->lzw);
280  av_freep(&s->buf);
282  av_freep(&s->tmpl);
283  return 0;
284 }
285 
286 #define OFFSET(x) offsetof(GIFContext, x)
287 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
288 static const AVOption gif_options[] = {
289  { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
290  { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
291  { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
292  { NULL }
293 };
294 
295 static const AVClass gif_class = {
296  .class_name = "GIF encoder",
297  .item_name = av_default_item_name,
298  .option = gif_options,
299  .version = LIBAVUTIL_VERSION_INT,
300 };
301 
303  .name = "gif",
304  .long_name = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
305  .type = AVMEDIA_TYPE_VIDEO,
306  .id = AV_CODEC_ID_GIF,
307  .priv_data_size = sizeof(GIFContext),
309  .encode2 = gif_encode_frame,
311  .pix_fmts = (const enum AVPixelFormat[]){
314  },
315  .priv_class = &gif_class,
316 };
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1500
float v
const char * s
Definition: avisynth_c.h:668
int size
This structure describes decoded (raw) audio or video data.
Definition: frame.h:96
AVOption.
Definition: opt.h:253
uint32_t palette[AVPALETTE_COUNT]
local reference palette for !pal8
Definition: gif.c:48
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:160
#define LIBAVUTIL_VERSION_INT
Definition: avcodec.h:820
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
int size
Definition: avcodec.h:1064
static int gif_encode_close(AVCodecContext *avctx)
Definition: gif.c:275
static const AVClass gif_class
Definition: gif.c:295
int ff_lzw_encode(struct LZWEncodeState *s, const uint8_t *inbuf, int insize)
LZW main compress function.
Definition: lzwenc.c:226
AVCodec ff_gif_encoder
Definition: gif.c:302
void av_log(void *avcl, int level, const char *fmt,...) av_printf_format(3
Send the specified message to the log if the level is less than or equal to the current av_log_level...
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1342
packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb)
Definition: avcodec.h:4553
Pixel format.
Definition: avcodec.h:4533
AVCodec.
Definition: avcodec.h:2922
#define av_cold
Definition: avcodec.h:653
Y , 8bpp.
Definition: avcodec.h:4542
void av_freep(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:234
const char * av_default_item_name(void *ctx)
Return the context name.
Definition: log.c:145
uint8_t
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:55
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:67
const char * name
Name of the codec implementation.
Definition: avcodec.h:2929
int av_frame_ref(AVFrame *dst, AVFrame *src)
Setup a new reference to the data described by a given frame.
Definition: frame.c:247
packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb)
Definition: avcodec.h:4556
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:73
uint8_t * tmpl
temporary line buffer
Definition: gif.c:49
int flags
Definition: gif.c:47
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1113
#define FLAGS
Definition: gif.c:287
int ff_lzw_encode_flush(struct LZWEncodeState *s, void(*lzw_flush_put_bits)(struct PutBitContext *))
Definition: lzw.c:45
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: avcodec.h:4147
LZWState * lzw
Definition: gif.c:44
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:151
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:110
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: avcodec.h:4168
Definition: gif.c:42
int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt)
Definition: imgutils.c:150
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:123
#define AVPALETTE_COUNT
Definition: avcodec.h:4500
Libavcodec external API header.
AVPixelFormat
Pixel format.
Definition: pixfmt.h:66
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:298
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1069
#define OFFSET(x)
Definition: gif.c:286
#define GIF_IMAGE_SEPARATOR
Definition: gif.h:44
#define FF_ARRAY_ELEMS(a)
Definition: avcodec.h:929
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:167
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:351
Definition: lzw.h:38
static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
Definition: gif.c:57
float y
#define FF_MIN_BUFFER_SIZE
minimum encoding buffer size Used to avoid some checks during header writing.
Definition: avcodec.h:587
ret
Definition: avfilter.c:961
int width
picture width / height.
Definition: avcodec.h:1314
void * av_malloc(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:73
#define AVPALETTE_SIZE
Definition: avcodec.h:4499
#define FFMIN(a, b)
Definition: avcodec.h:925
packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb)
Definition: avcodec.h:4555
static int width
Definition: utils.c:158
GIF format definitions.
main external API structure.
Definition: avcodec.h:1146
static void close(AVCodecParserContext *s)
Definition: h264_parser.c:538
static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet)
Definition: gif.c:231
void * buf
Definition: avisynth_c.h:594
BYTE int const BYTE int int int height
Definition: avisynth_c.h:713
Describe the class of an AVClass context structure.
Definition: log.h:50
uint8_t * data
Definition: avcodec.h:1063
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:124
uint8_t * buf
Definition: gif.c:45
void * priv_data
Definition: avcodec.h:1182
static int flags
Definition: cpu.c:45
LZW decoding routines.
int palette
Definition: v4l.c:60
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:89
static av_always_inline void bytestream_put_buffer(uint8_t **b, const uint8_t *src, unsigned int size)
Definition: bytestream.h:340
AVFrame * last_frame
Definition: gif.c:46
int len
static av_cold int gif_encode_init(AVCodecContext *avctx)
Definition: gif.c:210
int key_frame
1 -&gt; keyframe, 0-&gt; not
Definition: frame.h:162
#define AVERROR(e)
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
const int ff_lzw_encode_state_size
Definition: lzwenc.c:66
static AVPacket pkt
Definition: demuxing.c:52
#define HAVE_BIGENDIAN
Definition: config.h:122
8 bit with PIX_FMT_RGB32 palette
Definition: avcodec.h:4545
static const AVOption gif_options[]
Definition: gif.c:288
packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb)
Definition: avcodec.h:4558
This structure stores compressed data.
Definition: avcodec.h:1040
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:107
void * av_mallocz(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:241
bitstream writer API