flashsvenc.c 8.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Flash Screen Video encoder
 * Copyright (C) 2004 Alex Beregszaszi
 * Copyright (C) 2006 Benjamin Larsson
 *
 * 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
 */

/* Encoding development sponsored by http://fh-campuswien.ac.at */

/**
26
 * @file
27 28 29
 * Flash Screen Video encoder
 * @author Alex Beregszaszi
 * @author Benjamin Larsson
30 31 32 33
 *
 * A description of the bitstream format for Flash Screen Video version 1/2
 * is part of the SWF File Format Specification (version 10), which can be
 * downloaded from http://www.adobe.com/devnet/swf.html.
34 35
 */

36
/*
37 38
 * Encoding ideas: A basic encoder would just use a fixed block size.
 * Block sizes can be multiples of 16, from 16 to 256. The blocks don't
39 40
 * have to be quadratic. A brute force search with a set of different
 * block sizes should give a better result than to just use a fixed size.
41 42 43 44
 *
 * TODO:
 * Don't reencode the frame in brute force mode if the frame is a dupe.
 * Speed up. Make the difference check faster.
45 46 47 48 49 50 51
 */

#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>

#include "avcodec.h"
52
#include "internal.h"
53
#include "put_bits.h"
54 55 56 57 58
#include "bytestream.h"


typedef struct FlashSVContext {
    AVCodecContext *avctx;
59 60 61 62 63 64 65 66
    uint8_t        *previous_frame;
    int             image_width, image_height;
    int             block_width, block_height;
    uint8_t        *tmpblock;
    uint8_t        *encbuffer;
    int             block_size;
    z_stream        zstream;
    int             last_key_frame;
67 68
} FlashSVContext;

69 70 71 72
static int copy_region_enc(uint8_t *sptr, uint8_t *dptr, int dx, int dy,
                           int h, int w, int stride, uint8_t *pfptr)
{
    int i, j;
73 74 75 76
    uint8_t *nsptr;
    uint8_t *npfptr;
    int diff = 0;

77
    for (i = dx + h; i > dx; i--) {
78 79
        nsptr  = sptr  + i * stride + dy * 3;
        npfptr = pfptr + i * stride + dy * 3;
80 81 82
        for (j = 0; j < w * 3; j++) {
            diff    |= npfptr[j] ^ nsptr[j];
            dptr[j]  = nsptr[j];
83
        }
84
        dptr += w * 3;
85 86 87 88 89 90
    }
    if (diff)
        return 1;
    return 0;
}

91 92 93 94 95 96
static av_cold int flashsv_encode_end(AVCodecContext *avctx)
{
    FlashSVContext *s = avctx->priv_data;

    deflateEnd(&s->zstream);

97 98 99
    av_freep(&s->encbuffer);
    av_freep(&s->previous_frame);
    av_freep(&s->tmpblock);
100 101 102 103 104 105

    av_frame_free(&avctx->coded_frame);

    return 0;
}

106
static av_cold int flashsv_encode_init(AVCodecContext *avctx)
107
{
108
    FlashSVContext *s = avctx->priv_data;
109 110 111

    s->avctx = avctx;

112
    if (avctx->width > 4095 || avctx->height > 4095) {
113 114
        av_log(avctx, AV_LOG_ERROR,
               "Input dimensions too large, input must be max 4096x4096 !\n");
115
        return AVERROR_INVALIDDATA;
116 117 118
    }

    // Needed if zlib unused or init aborted before deflateInit
119
    memset(&s->zstream, 0, sizeof(z_stream));
120

121
    s->last_key_frame = 0;
122

123
    s->image_width  = avctx->width;
124 125
    s->image_height = avctx->height;

126 127
    s->tmpblock  = av_mallocz(3 * 256 * 256);
    s->encbuffer = av_mallocz(s->image_width * s->image_height * 3);
128 129 130

    if (!s->tmpblock || !s->encbuffer) {
        av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");
131
        return AVERROR(ENOMEM);
132 133
    }

134 135 136 137 138 139
    avctx->coded_frame = av_frame_alloc();
    if (!avctx->coded_frame) {
        flashsv_encode_end(avctx);
        return AVERROR(ENOMEM);
    }

140 141 142 143
    return 0;
}


144
static int encode_bitstream(FlashSVContext *s, const AVFrame *p, uint8_t *buf,
145 146 147
                            int buf_size, int block_width, int block_height,
                            uint8_t *previous_frame, int *I_frame)
{
148 149 150 151 152 153

    PutBitContext pb;
    int h_blocks, v_blocks, h_part, v_part, i, j;
    int buf_pos, res;
    int pred_blocks = 0;

154
    init_put_bits(&pb, buf, buf_size);
155

156
    put_bits(&pb,  4, block_width / 16 - 1);
157
    put_bits(&pb, 12, s->image_width);
158
    put_bits(&pb,  4, block_height / 16 - 1);
159 160
    put_bits(&pb, 12, s->image_height);
    flush_put_bits(&pb);
161
    buf_pos = 4;
162

163 164
    h_blocks = s->image_width  / block_width;
    h_part   = s->image_width  % block_width;
165
    v_blocks = s->image_height / block_height;
166
    v_part   = s->image_height % block_height;
167 168

    /* loop over all block columns */
169
    for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {
170

171 172
        int y_pos = j * block_height; // vertical position in frame
        int cur_blk_height = (j < v_blocks) ? block_height : v_part;
173 174

        /* loop over all block rows */
175
        for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {
176 177
            int x_pos = i * block_width; // horizontal position in frame
            int cur_blk_width = (i < h_blocks) ? block_width : h_part;
178
            int ret = Z_OK;
179
            uint8_t *ptr = buf + buf_pos;
180

181 182 183
            /* copy the block to the temp buffer before compression
             * (if it differs from the previous frame's block) */
            res = copy_region_enc(p->data[0], s->tmpblock,
184 185 186
                                  s->image_height - (y_pos + cur_blk_height + 1),
                                  x_pos, cur_blk_height, cur_blk_width,
                                  p->linesize[0], previous_frame);
187 188

            if (res || *I_frame) {
189
                unsigned long zsize = 3 * block_width * block_height;
190 191
                ret = compress2(ptr + 2, &zsize, s->tmpblock,
                                3 * cur_blk_width * cur_blk_height, 9);
192

193
                //ret = deflateReset(&s->zstream);
194
                if (ret != Z_OK)
195 196
                    av_log(s->avctx, AV_LOG_ERROR,
                           "error while compressing block %dx%d\n", i, j);
197

198
                bytestream_put_be16(&ptr, zsize);
199
                buf_pos += zsize + 2;
200
                ff_dlog(s->avctx, "buf_pos = %d\n", buf_pos);
201 202
            } else {
                pred_blocks++;
203
                bytestream_put_be16(&ptr, 0);
204
                buf_pos += 2;
205 206 207 208 209 210 211 212 213 214 215 216 217
            }
        }
    }

    if (pred_blocks)
        *I_frame = 0;
    else
        *I_frame = 1;

    return buf_pos;
}


218 219
static int flashsv_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *pict, int *got_packet)
220
{
221
    FlashSVContext * const s = avctx->priv_data;
222
    const AVFrame * const p = pict;
223
    uint8_t *pfptr;
224 225
    int res;
    int I_frame = 0;
226
    int opt_w = 4, opt_h = 4;
227

228
    /* First frame needs to be a keyframe */
229
    if (avctx->frame_number == 0) {
230
        s->previous_frame = av_mallocz(FFABS(p->linesize[0]) * s->image_height);
231 232
        if (!s->previous_frame) {
            av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");
233
            return AVERROR(ENOMEM);
234 235 236 237
        }
        I_frame = 1;
    }

238
    if (p->linesize[0] < 0)
239
        pfptr = s->previous_frame - (s->image_height - 1) * p->linesize[0];
240 241 242
    else
        pfptr = s->previous_frame;

243
    /* Check the placement of keyframes */
244 245 246
    if (avctx->gop_size > 0 &&
        avctx->frame_number >= s->last_key_frame + avctx->gop_size) {
        I_frame = 1;
247 248
    }

249
    if ((res = ff_alloc_packet2(avctx, pkt, s->image_width * s->image_height * 3)) < 0)
250
        return res;
251

252 253
    pkt->size = encode_bitstream(s, p, pkt->data, pkt->size, opt_w * 16, opt_h * 16,
                                 pfptr, &I_frame);
254

255
    //save the current frame
256 257
    if (p->linesize[0] > 0)
        memcpy(s->previous_frame, p->data[0], s->image_height * p->linesize[0]);
258
    else
259 260
        memcpy(s->previous_frame,
               p->data[0] + p->linesize[0] * (s->image_height - 1),
261
               s->image_height * FFABS(p->linesize[0]));
262 263 264

    //mark the frame type so the muxer can mux it correctly
    if (I_frame) {
265 266
        avctx->coded_frame->pict_type      = AV_PICTURE_TYPE_I;
        avctx->coded_frame->key_frame      = 1;
267
        s->last_key_frame = avctx->frame_number;
268
        ff_dlog(avctx, "Inserting keyframe at frame %d\n", avctx->frame_number);
269
    } else {
270 271
        avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
        avctx->coded_frame->key_frame = 0;
272 273
    }

274
    if (avctx->coded_frame->key_frame)
275 276 277 278
        pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;

    return 0;
279 280
}

281
AVCodec ff_flashsv_encoder = {
282
    .name           = "flashsv",
283
    .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video"),
284
    .type           = AVMEDIA_TYPE_VIDEO,
285
    .id             = AV_CODEC_ID_FLASHSV,
286 287
    .priv_data_size = sizeof(FlashSVContext),
    .init           = flashsv_encode_init,
288
    .encode2        = flashsv_encode_frame,
289
    .close          = flashsv_encode_end,
290
    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_BGR24, AV_PIX_FMT_NONE },
291
};