]> git.sesse.net Git - ffmpeg/blob - libavcodec/flashsvenc.c
flashsvenc: merge two consecutive if-conditions
[ffmpeg] / libavcodec / flashsvenc.c
1 /*
2  * Flash Screen Video encoder
3  * Copyright (C) 2004 Alex Beregszaszi
4  * Copyright (C) 2006 Benjamin Larsson
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /* Encoding development sponsored by http://fh-campuswien.ac.at */
24
25 /**
26  * @file
27  * Flash Screen Video encoder
28  * @author Alex Beregszaszi
29  * @author Benjamin Larsson
30  */
31
32 /* Bitstream description
33  * The picture is divided into blocks that are zlib-compressed.
34  *
35  * The decoder is fed complete frames, the frameheader contains:
36  *  4 bits of block width
37  * 12 bits of frame width
38  *  4 bits of block height
39  * 12 bits of frame height
40  *
41  * Directly after the header are the compressed blocks. The blocks
42  * have their compressed size represented with 16 bits in the beginning.
43  * If the size = 0 then the block is unchanged from the previous frame.
44  * All blocks are decompressed until the buffer is consumed.
45  *
46  * Encoding ideas: A basic encoder would just use a fixed block size.
47  * Block sizes can be multiples of 16, from 16 to 256. The blocks don't
48  * have to be quadratic. A brute force search with a set of different
49  * block sizes should give a better result than to just use a fixed size.
50  *
51  * TODO:
52  * Don't reencode the frame in brute force mode if the frame is a dupe.
53  * Speed up. Make the difference check faster.
54  */
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <zlib.h>
59
60 #include "avcodec.h"
61 #include "put_bits.h"
62 #include "bytestream.h"
63
64
65 typedef struct FlashSVContext {
66     AVCodecContext *avctx;
67     uint8_t        *previous_frame;
68     AVFrame         frame;
69     int             image_width, image_height;
70     int             block_width, block_height;
71     uint8_t        *tmpblock;
72     uint8_t        *encbuffer;
73     int             block_size;
74     z_stream        zstream;
75     int             last_key_frame;
76 } FlashSVContext;
77
78 static int copy_region_enc(uint8_t *sptr, uint8_t *dptr, int dx, int dy,
79                            int h, int w, int stride, uint8_t *pfptr)
80 {
81     int i, j;
82     uint8_t *nsptr;
83     uint8_t *npfptr;
84     int diff = 0;
85
86     for (i = dx + h; i > dx; i--) {
87         nsptr  = sptr  + i * stride + dy * 3;
88         npfptr = pfptr + i * stride + dy * 3;
89         for (j = 0; j < w * 3; j++) {
90             diff    |= npfptr[j] ^ nsptr[j];
91             dptr[j]  = nsptr[j];
92         }
93         dptr += w * 3;
94     }
95     if (diff)
96         return 1;
97     return 0;
98 }
99
100 static av_cold int flashsv_encode_init(AVCodecContext *avctx)
101 {
102     FlashSVContext *s = avctx->priv_data;
103
104     s->avctx = avctx;
105
106     if (avctx->width > 4095 || avctx->height > 4095) {
107         av_log(avctx, AV_LOG_ERROR,
108                "Input dimensions too large, input must be max 4096x4096 !\n");
109         return AVERROR_INVALIDDATA;
110     }
111
112     // Needed if zlib unused or init aborted before deflateInit
113     memset(&s->zstream, 0, sizeof(z_stream));
114
115     s->last_key_frame = 0;
116
117     s->image_width  = avctx->width;
118     s->image_height = avctx->height;
119
120     s->tmpblock  = av_mallocz(3 * 256 * 256);
121     s->encbuffer = av_mallocz(s->image_width * s->image_height * 3);
122
123     if (!s->tmpblock || !s->encbuffer) {
124         av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");
125         return AVERROR(ENOMEM);
126     }
127
128     return 0;
129 }
130
131
132 static int encode_bitstream(FlashSVContext *s, AVFrame *p, uint8_t *buf,
133                             int buf_size, int block_width, int block_height,
134                             uint8_t *previous_frame, int *I_frame)
135 {
136
137     PutBitContext pb;
138     int h_blocks, v_blocks, h_part, v_part, i, j;
139     int buf_pos, res;
140     int pred_blocks = 0;
141
142     init_put_bits(&pb, buf, buf_size * 8);
143
144     put_bits(&pb,  4, block_width / 16 - 1);
145     put_bits(&pb, 12, s->image_width);
146     put_bits(&pb,  4, block_height / 16 - 1);
147     put_bits(&pb, 12, s->image_height);
148     flush_put_bits(&pb);
149     buf_pos = 4;
150
151     h_blocks = s->image_width  / block_width;
152     h_part   = s->image_width  % block_width;
153     v_blocks = s->image_height / block_height;
154     v_part   = s->image_height % block_height;
155
156     /* loop over all block columns */
157     for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {
158
159         int hp = j * block_height; // horizontal position in frame
160         int hs = (j < v_blocks) ? block_height : v_part; // size of block
161
162         /* loop over all block rows */
163         for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {
164             int wp  = i * block_width; // vertical position in frame
165             int ws  = (i < h_blocks) ? block_width : h_part; // size of block
166             int ret = Z_OK;
167             uint8_t *ptr = buf + buf_pos;
168
169             /* copy the block to the temp buffer before compression
170              * (if it differs from the previous frame's block) */
171             res = copy_region_enc(p->data[0], s->tmpblock,
172                                   s->image_height - (hp + hs + 1),
173                                   wp, hs, ws, p->linesize[0], previous_frame);
174
175             if (res || *I_frame) {
176                 unsigned long zsize = 3 * block_width * block_height;
177                 ret   = compress2(ptr + 2, &zsize, s->tmpblock, 3 * ws * hs, 9);
178
179                 //ret = deflateReset(&s->zstream);
180                 if (ret != Z_OK)
181                     av_log(s->avctx, AV_LOG_ERROR,
182                            "error while compressing block %dx%d\n", i, j);
183
184                 bytestream_put_be16(&ptr, (unsigned int) zsize);
185                 buf_pos += zsize + 2;
186                 av_dlog(avctx, "buf_pos = %d\n", buf_pos);
187             } else {
188                 pred_blocks++;
189                 bytestream_put_be16(&ptr, 0);
190                 buf_pos += 2;
191             }
192         }
193     }
194
195     if (pred_blocks)
196         *I_frame = 0;
197     else
198         *I_frame = 1;
199
200     return buf_pos;
201 }
202
203
204 static int flashsv_encode_frame(AVCodecContext *avctx, uint8_t *buf,
205                                 int buf_size, void *data)
206 {
207     FlashSVContext * const s = avctx->priv_data;
208     AVFrame *pict = data;
209     AVFrame * const p = &s->frame;
210     uint8_t *pfptr;
211     int res;
212     int I_frame = 0;
213     int opt_w = 4, opt_h = 4;
214
215     *p = *pict;
216
217     /* First frame needs to be a keyframe */
218     if (avctx->frame_number == 0) {
219         s->previous_frame = av_mallocz(FFABS(p->linesize[0]) * s->image_height);
220         if (!s->previous_frame) {
221             av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");
222             return AVERROR(ENOMEM);
223         }
224         I_frame = 1;
225     }
226
227     if (p->linesize[0] < 0)
228         pfptr = s->previous_frame - (s->image_height - 1) * p->linesize[0];
229     else
230         pfptr = s->previous_frame;
231
232     /* Check the placement of keyframes */
233     if (avctx->gop_size > 0 &&
234         avctx->frame_number >= s->last_key_frame + avctx->gop_size) {
235         I_frame = 1;
236     }
237
238     if (buf_size < s->image_width * s->image_height * 3) {
239         //Conservative upper bound check for compressed data
240         av_log(avctx, AV_LOG_ERROR, "buf_size %d <  %d\n",
241                buf_size, s->image_width * s->image_height * 3);
242         return -1;
243     }
244
245     res = encode_bitstream(s, p, buf, buf_size, opt_w * 16, opt_h * 16,
246                            pfptr, &I_frame);
247
248     //save the current frame
249     if (p->linesize[0] > 0)
250         memcpy(s->previous_frame, p->data[0], s->image_height * p->linesize[0]);
251     else
252         memcpy(s->previous_frame,
253                p->data[0] + p->linesize[0] * (s->image_height - 1),
254                s->image_height * FFABS(p->linesize[0]));
255
256     //mark the frame type so the muxer can mux it correctly
257     if (I_frame) {
258         p->pict_type      = AV_PICTURE_TYPE_I;
259         p->key_frame      = 1;
260         s->last_key_frame = avctx->frame_number;
261         av_dlog(avctx, "Inserting keyframe at frame %d\n", avctx->frame_number);
262     } else {
263         p->pict_type = AV_PICTURE_TYPE_P;
264         p->key_frame = 0;
265     }
266
267     avctx->coded_frame = p;
268
269     return res;
270 }
271
272 static av_cold int flashsv_encode_end(AVCodecContext *avctx)
273 {
274     FlashSVContext *s = avctx->priv_data;
275
276     deflateEnd(&s->zstream);
277
278     av_free(s->encbuffer);
279     av_free(s->previous_frame);
280     av_free(s->tmpblock);
281
282     return 0;
283 }
284
285 AVCodec ff_flashsv_encoder = {
286     .name           = "flashsv",
287     .type           = AVMEDIA_TYPE_VIDEO,
288     .id             = CODEC_ID_FLASHSV,
289     .priv_data_size = sizeof(FlashSVContext),
290     .init           = flashsv_encode_init,
291     .encode         = flashsv_encode_frame,
292     .close          = flashsv_encode_end,
293     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_BGR24, PIX_FMT_NONE},
294     .long_name      = NULL_IF_CONFIG_SMALL("Flash Screen Video"),
295 };
296