gif.c 10.3 KB
Newer Older
1
/*
2 3 4
 * Copyright (c) 2000 Fabrice Bellard
 * Copyright (c) 2002 Francois Revol
 * Copyright (c) 2006 Baptiste Coudurier
5
 *
6 7
 * first version by Francois Revol <revol@free.fr>
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

25 26 27 28
/**
 * @file
 * GIF encoder
 * @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 35
#include "avcodec.h"
#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;
44 45
    LZWState *lzw;
    uint8_t *buf;
46
    AVFrame *last_frame;
47
    int flags;
48 49
    uint32_t palette[AVPALETTE_COUNT];  ///< local reference palette for !pal8
    uint8_t *tmpl;                      ///< temporary line buffer
50 51
} GIFContext;

52 53
enum {
    GF_OFFSETTING = 1<<0,
54
    GF_TRANSDIFF  = 1<<1,
55 56
};

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
static int pick_palette_entry(const uint8_t *buf, int linesize, int w, int h)
{
    int histogram[AVPALETTE_COUNT] = {0};
    int x, y, i;

    for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++)
            histogram[buf[x]]++;
        buf += linesize;
    }
    for (i = 0; i < FF_ARRAY_ELEMS(histogram); i++)
        if (!histogram[i])
            return i;
    return -1;
}

73 74
static int gif_image_write_image(AVCodecContext *avctx,
                                 uint8_t **bytestream, uint8_t *end,
75
                                 const uint32_t *palette,
76 77
                                 const uint8_t *buf, const int linesize,
                                 AVPacket *pkt)
78
{
79
    GIFContext *s = avctx->priv_data;
80 81
    int len = 0, height = avctx->height, width = avctx->width, x, y;
    int x_start = 0, y_start = 0, trans = -1;
82 83
    const uint8_t *ptr;

84 85
    /* Crop image */
    // TODO support with palette change
86
    if ((s->flags & GF_OFFSETTING) && s->last_frame && !palette) {
87 88 89 90 91 92
        const uint8_t *ref = s->last_frame->data[0];
        const int ref_linesize = s->last_frame->linesize[0];
        int x_end = avctx->width  - 1,
            y_end = avctx->height - 1;

        /* skip common lines */
93
        while (y_start < y_end) {
94 95 96 97 98 99 100 101 102 103 104 105
            if (memcmp(ref + y_start*ref_linesize, buf + y_start*linesize, width))
                break;
            y_start++;
        }
        while (y_end > y_start) {
            if (memcmp(ref + y_end*ref_linesize, buf + y_end*linesize, width))
                break;
            y_end--;
        }
        height = y_end + 1 - y_start;

        /* skip common columns */
106
        while (x_start < x_end) {
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            int same_column = 1;
            for (y = y_start; y < y_end; y++) {
                if (ref[y*ref_linesize + x_start] != buf[y*linesize + x_start]) {
                    same_column = 0;
                    break;
                }
            }
            if (!same_column)
                break;
            x_start++;
        }
        while (x_end > x_start) {
            int same_column = 1;
            for (y = y_start; y < y_end; y++) {
                if (ref[y*ref_linesize + x_end] != buf[y*linesize + x_end]) {
                    same_column = 0;
                    break;
                }
            }
            if (!same_column)
                break;
            x_end--;
        }
        width = x_end + 1 - x_start;

        av_log(avctx, AV_LOG_DEBUG,"%dx%d image at pos (%d;%d) [area:%dx%d]\n",
               width, height, x_start, y_start, avctx->width, avctx->height);
    }

136
    /* image block */
137
    bytestream_put_byte(bytestream, GIF_IMAGE_SEPARATOR);
138 139 140 141
    bytestream_put_le16(bytestream, x_start);
    bytestream_put_le16(bytestream, y_start);
    bytestream_put_le16(bytestream, width);
    bytestream_put_le16(bytestream, height);
142 143

    if (!palette) {
144
        bytestream_put_byte(bytestream, 0x00); /* flags */
145 146 147 148 149 150 151 152
    } else {
        unsigned i;
        bytestream_put_byte(bytestream, 1<<7 | 0x7); /* flags */
        for (i = 0; i < AVPALETTE_COUNT; i++) {
            const uint32_t v = palette[i];
            bytestream_put_be24(bytestream, v);
        }
    }
153

154 155 156 157 158 159 160 161 162 163 164
    /* TODO: support with palette change (pal8) */
    if ((s->flags & GF_TRANSDIFF) && s->last_frame && !palette) {
        trans = pick_palette_entry(buf + y_start*linesize + x_start,
                                   linesize, width, height);
        if (trans < 0) { // TODO, patch welcome
            av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
        } else {
            uint8_t *pal_exdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
            if (!pal_exdata)
                return AVERROR(ENOMEM);
            memcpy(pal_exdata, s->palette, AVPALETTE_SIZE);
165
            pal_exdata[trans*4 + 3*!HAVE_BIGENDIAN] = 0x00;
166 167 168
        }
    }

169 170
    bytestream_put_byte(bytestream, 0x08);

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 176 177 178 179 180 181 182 183 184 185 186 187 188
    if (trans >= 0) {
        const int ref_linesize = s->last_frame->linesize[0];
        const uint8_t *ref = s->last_frame->data[0] + y_start*ref_linesize + x_start;

        for (y = 0; y < height; y++) {
            memcpy(s->tmpl, ptr, width);
            for (x = 0; x < width; x++)
                if (ref[x] == ptr[x])
                    s->tmpl[x] = trans;
            len += ff_lzw_encode(s->lzw, s->tmpl, width);
            ptr += linesize;
            ref += ref_linesize;
        }
    } else {
189 190 191 192
        for (y = 0; y < height; y++) {
            len += ff_lzw_encode(s->lzw, ptr, width);
            ptr += linesize;
        }
193
    }
194 195 196 197 198 199 200 201 202 203 204
    len += ff_lzw_encode_flush(s->lzw, flush_put_bits);

    ptr = s->buf;
    while (len > 0) {
        int size = FFMIN(255, len);
        bytestream_put_byte(bytestream, size);
        if (end - *bytestream < size)
            return -1;
        bytestream_put_buffer(bytestream, ptr, size);
        ptr += size;
        len -= size;
205 206 207 208 209
    }
    bytestream_put_byte(bytestream, 0x00); /* end of image block */
    return 0;
}

210
static av_cold int gif_encode_init(AVCodecContext *avctx)
211 212 213
{
    GIFContext *s = avctx->priv_data;

214 215
    if (avctx->width > 65535 || avctx->height > 65535) {
        av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");
216
        return AVERROR(EINVAL);
217 218
    }

219 220 221 222 223 224 225
    avctx->coded_frame = av_frame_alloc();
    if (!avctx->coded_frame)
        return AVERROR(ENOMEM);

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
    avctx->coded_frame->key_frame = 1;

226 227
    s->lzw = av_mallocz(ff_lzw_encode_state_size);
    s->buf = av_malloc(avctx->width*avctx->height*2);
228 229
    s->tmpl = av_malloc(avctx->width);
    if (!s->tmpl || !s->buf || !s->lzw)
230
        return AVERROR(ENOMEM);
231 232 233 234

    if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)
        av_assert0(avctx->pix_fmt == AV_PIX_FMT_PAL8);

235 236 237
    return 0;
}

238 239
static int gif_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                            const AVFrame *pict, int *got_packet)
240 241
{
    GIFContext *s = avctx->priv_data;
242
    uint8_t *outbuf_ptr, *end;
243
    const uint32_t *palette = NULL;
244 245
    int ret;

246
    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*7/5 + FF_MIN_BUFFER_SIZE)) < 0)
247 248 249
        return ret;
    outbuf_ptr = pkt->data;
    end        = pkt->data + pkt->size;
250

251 252 253 254
    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
        uint8_t *pal_exdata = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
        if (!pal_exdata)
            return AVERROR(ENOMEM);
255 256
        memcpy(pal_exdata, pict->data[1], AVPALETTE_SIZE);
        palette = (uint32_t*)pict->data[1];
257
    }
258

259 260
    gif_image_write_image(avctx, &outbuf_ptr, end, palette,
                          pict->data[0], pict->linesize[0], pkt);
261 262 263 264 265 266 267 268 269
    if (!s->last_frame) {
        s->last_frame = av_frame_alloc();
        if (!s->last_frame)
            return AVERROR(ENOMEM);
    }
    av_frame_unref(s->last_frame);
    ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
    if (ret < 0)
        return ret;
270 271 272 273 274 275

    pkt->size   = outbuf_ptr - pkt->data;
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;

    return 0;
276 277
}

278 279 280 281
static int gif_encode_close(AVCodecContext *avctx)
{
    GIFContext *s = avctx->priv_data;

282 283
    av_frame_free(&avctx->coded_frame);

284 285
    av_freep(&s->lzw);
    av_freep(&s->buf);
286
    av_frame_free(&s->last_frame);
287
    av_freep(&s->tmpl);
288 289 290
    return 0;
}

291 292 293
#define OFFSET(x) offsetof(GIFContext, x)
#define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption gif_options[] = {
294
    { "gifflags", "set GIF flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = GF_OFFSETTING|GF_TRANSDIFF}, 0, INT_MAX, FLAGS, "flags" },
295
        { "offsetting", "enable picture offsetting", 0, AV_OPT_TYPE_CONST, {.i64=GF_OFFSETTING}, INT_MIN, INT_MAX, FLAGS, "flags" },
296
        { "transdiff", "enable transparency detection between frames", 0, AV_OPT_TYPE_CONST, {.i64=GF_TRANSDIFF}, INT_MIN, INT_MAX, FLAGS, "flags" },
297 298 299 300 301 302 303 304 305 306
    { NULL }
};

static const AVClass gif_class = {
    .class_name = "GIF encoder",
    .item_name  = av_default_item_name,
    .option     = gif_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

307
AVCodec ff_gif_encoder = {
308
    .name           = "gif",
309
    .long_name      = NULL_IF_CONFIG_SMALL("GIF (Graphics Interchange Format)"),
310
    .type           = AVMEDIA_TYPE_VIDEO,
311
    .id             = AV_CODEC_ID_GIF,
312 313
    .priv_data_size = sizeof(GIFContext),
    .init           = gif_encode_init,
314
    .encode2        = gif_encode_frame,
315
    .close          = gif_encode_close,
316 317 318
    .pix_fmts       = (const enum AVPixelFormat[]){
        AV_PIX_FMT_RGB8, AV_PIX_FMT_BGR8, AV_PIX_FMT_RGB4_BYTE, AV_PIX_FMT_BGR4_BYTE,
        AV_PIX_FMT_GRAY8, AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE
319
    },
320
    .priv_class     = &gif_class,
321
};