]> git.sesse.net Git - ffmpeg/blob - libavcodec/zmbvenc.c
avcodec: Constify AVCodecs
[ffmpeg] / libavcodec / zmbvenc.c
1 /*
2  * Zip Motion Blocks Video (ZMBV) encoder
3  * Copyright (c) 2006 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Zip Motion Blocks Video encoder
25  */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "libavutil/common.h"
31 #include "libavutil/intreadwrite.h"
32 #include "avcodec.h"
33 #include "internal.h"
34
35 #include <zlib.h>
36
37 /* Frame header flags */
38 #define ZMBV_KEYFRAME 1
39 #define ZMBV_DELTAPAL 2
40
41 /* Motion block width/height (maximum allowed value is 255)
42  * Note: histogram datatype in block_cmp() must be big enough to hold values
43  * up to (4 * ZMBV_BLOCK * ZMBV_BLOCK)
44  */
45 #define ZMBV_BLOCK 16
46
47 /* Keyframe header format values */
48 enum ZmbvFormat {
49     ZMBV_FMT_NONE  = 0,
50     ZMBV_FMT_1BPP  = 1,
51     ZMBV_FMT_2BPP  = 2,
52     ZMBV_FMT_4BPP  = 3,
53     ZMBV_FMT_8BPP  = 4,
54     ZMBV_FMT_15BPP = 5,
55     ZMBV_FMT_16BPP = 6,
56     ZMBV_FMT_24BPP = 7,
57     ZMBV_FMT_32BPP = 8
58 };
59
60 /**
61  * Encoder context
62  */
63 typedef struct ZmbvEncContext {
64     AVCodecContext *avctx;
65
66     int lrange, urange;
67     uint8_t *comp_buf, *work_buf;
68     uint8_t pal[768];
69     uint32_t pal2[256]; //for quick comparisons
70     uint8_t *prev, *prev_buf;
71     int pstride;
72     int comp_size;
73     int keyint, curfrm;
74     int bypp;
75     enum ZmbvFormat fmt;
76     z_stream zstream;
77
78     int score_tab[ZMBV_BLOCK * ZMBV_BLOCK * 4 + 1];
79 } ZmbvEncContext;
80
81
82 /** Block comparing function
83  * XXX should be optimized and moved to DSPContext
84  */
85 static inline int block_cmp(ZmbvEncContext *c, uint8_t *src, int stride,
86                             uint8_t *src2, int stride2, int bw, int bh,
87                             int *xored)
88 {
89     int sum = 0;
90     int i, j;
91     uint16_t histogram[256] = {0};
92     int bw_bytes = bw * c->bypp;
93
94     /* Build frequency histogram of byte values for src[] ^ src2[] */
95     for(j = 0; j < bh; j++){
96         for(i = 0; i < bw_bytes; i++){
97             int t = src[i] ^ src2[i];
98             histogram[t]++;
99         }
100         src += stride;
101         src2 += stride2;
102     }
103
104     /* If not all the xored values were 0, then the blocks are different */
105     *xored = (histogram[0] < bw_bytes * bh);
106
107     /* Exit early if blocks are equal */
108     if (!*xored) return 0;
109
110     /* Sum the entropy of all values */
111     for(i = 0; i < 256; i++)
112         sum += c->score_tab[histogram[i]];
113
114     return sum;
115 }
116
117 /** Motion estimation function
118  * TODO make better ME decisions
119  */
120 static int zmbv_me(ZmbvEncContext *c, uint8_t *src, int sstride, uint8_t *prev,
121                    int pstride, int x, int y, int *mx, int *my, int *xored)
122 {
123     int dx, dy, txored, tv, bv, bw, bh;
124     int mx0, my0;
125
126     mx0 = *mx;
127     my0 = *my;
128     bw = FFMIN(ZMBV_BLOCK, c->avctx->width - x);
129     bh = FFMIN(ZMBV_BLOCK, c->avctx->height - y);
130
131     /* Try (0,0) */
132     bv = block_cmp(c, src, sstride, prev, pstride, bw, bh, xored);
133     *mx = *my = 0;
134     if(!bv) return 0;
135
136     /* Try previous block's MV (if not 0,0) */
137     if (mx0 || my0){
138         tv = block_cmp(c, src, sstride, prev + mx0 * c->bypp + my0 * pstride, pstride, bw, bh, &txored);
139         if(tv < bv){
140             bv = tv;
141             *mx = mx0;
142             *my = my0;
143             *xored = txored;
144             if(!bv) return 0;
145         }
146     }
147
148     /* Try other MVs from top-to-bottom, left-to-right */
149     for(dy = -c->lrange; dy <= c->urange; dy++){
150         for(dx = -c->lrange; dx <= c->urange; dx++){
151             if(!dx && !dy) continue; // we already tested this block
152             if(dx == mx0 && dy == my0) continue; // this one too
153             tv = block_cmp(c, src, sstride, prev + dx * c->bypp + dy * pstride, pstride, bw, bh, &txored);
154             if(tv < bv){
155                  bv = tv;
156                  *mx = dx;
157                  *my = dy;
158                  *xored = txored;
159                  if(!bv) return 0;
160              }
161          }
162     }
163     return bv;
164 }
165
166 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
167                         const AVFrame *pict, int *got_packet)
168 {
169     ZmbvEncContext * const c = avctx->priv_data;
170     const AVFrame * const p = pict;
171     uint8_t *src, *prev, *buf;
172     uint32_t *palptr;
173     int keyframe, chpal;
174     int fl;
175     int work_size = 0, pkt_size;
176     int bw, bh;
177     int i, j, ret;
178
179     keyframe = !c->curfrm;
180     c->curfrm++;
181     if(c->curfrm == c->keyint)
182         c->curfrm = 0;
183
184     palptr = (avctx->pix_fmt == AV_PIX_FMT_PAL8) ? (uint32_t *)p->data[1] : NULL;
185     chpal = !keyframe && palptr && memcmp(palptr, c->pal2, 1024);
186
187     src = p->data[0];
188     prev = c->prev;
189     if(chpal){
190         uint8_t tpal[3];
191         for(i = 0; i < 256; i++){
192             AV_WB24(tpal, palptr[i]);
193             c->work_buf[work_size++] = tpal[0] ^ c->pal[i * 3 + 0];
194             c->work_buf[work_size++] = tpal[1] ^ c->pal[i * 3 + 1];
195             c->work_buf[work_size++] = tpal[2] ^ c->pal[i * 3 + 2];
196             c->pal[i * 3 + 0] = tpal[0];
197             c->pal[i * 3 + 1] = tpal[1];
198             c->pal[i * 3 + 2] = tpal[2];
199         }
200         memcpy(c->pal2, palptr, 1024);
201     }
202     if(keyframe){
203         if (palptr){
204             for(i = 0; i < 256; i++){
205                 AV_WB24(c->pal+(i*3), palptr[i]);
206             }
207             memcpy(c->work_buf, c->pal, 768);
208             memcpy(c->pal2, palptr, 1024);
209             work_size = 768;
210         }
211         for(i = 0; i < avctx->height; i++){
212             memcpy(c->work_buf + work_size, src, avctx->width * c->bypp);
213             src += p->linesize[0];
214             work_size += avctx->width * c->bypp;
215         }
216     }else{
217         int x, y, bh2, bw2, xored;
218         uint8_t *tsrc, *tprev;
219         uint8_t *mv;
220         int mx = 0, my = 0;
221
222         bw = (avctx->width + ZMBV_BLOCK - 1) / ZMBV_BLOCK;
223         bh = (avctx->height + ZMBV_BLOCK - 1) / ZMBV_BLOCK;
224         mv = c->work_buf + work_size;
225         memset(c->work_buf + work_size, 0, (bw * bh * 2 + 3) & ~3);
226         work_size += (bw * bh * 2 + 3) & ~3;
227         /* for now just XOR'ing */
228         for(y = 0; y < avctx->height; y += ZMBV_BLOCK) {
229             bh2 = FFMIN(avctx->height - y, ZMBV_BLOCK);
230             for(x = 0; x < avctx->width; x += ZMBV_BLOCK, mv += 2) {
231                 bw2 = FFMIN(avctx->width - x, ZMBV_BLOCK);
232
233                 tsrc = src + x * c->bypp;
234                 tprev = prev + x * c->bypp;
235
236                 zmbv_me(c, tsrc, p->linesize[0], tprev, c->pstride, x, y, &mx, &my, &xored);
237                 mv[0] = (mx * 2) | !!xored;
238                 mv[1] = my * 2;
239                 tprev += mx * c->bypp + my * c->pstride;
240                 if(xored){
241                     for(j = 0; j < bh2; j++){
242                         for(i = 0; i < bw2 * c->bypp; i++)
243                             c->work_buf[work_size++] = tsrc[i] ^ tprev[i];
244                         tsrc += p->linesize[0];
245                         tprev += c->pstride;
246                     }
247                 }
248             }
249             src += p->linesize[0] * ZMBV_BLOCK;
250             prev += c->pstride * ZMBV_BLOCK;
251         }
252     }
253     /* save the previous frame */
254     src = p->data[0];
255     prev = c->prev;
256     for(i = 0; i < avctx->height; i++){
257         memcpy(prev, src, avctx->width * c->bypp);
258         prev += c->pstride;
259         src += p->linesize[0];
260     }
261
262     if (keyframe)
263         deflateReset(&c->zstream);
264
265     c->zstream.next_in = c->work_buf;
266     c->zstream.avail_in = work_size;
267     c->zstream.total_in = 0;
268
269     c->zstream.next_out = c->comp_buf;
270     c->zstream.avail_out = c->comp_size;
271     c->zstream.total_out = 0;
272     if(deflate(&c->zstream, Z_SYNC_FLUSH) != Z_OK){
273         av_log(avctx, AV_LOG_ERROR, "Error compressing data\n");
274         return -1;
275     }
276
277     pkt_size = c->zstream.total_out + 1 + 6*keyframe;
278     if ((ret = ff_alloc_packet2(avctx, pkt, pkt_size, 0)) < 0)
279         return ret;
280     buf = pkt->data;
281
282     fl = (keyframe ? ZMBV_KEYFRAME : 0) | (chpal ? ZMBV_DELTAPAL : 0);
283     *buf++ = fl;
284     if (keyframe) {
285         *buf++ = 0; // hi ver
286         *buf++ = 1; // lo ver
287         *buf++ = 1; // comp
288         *buf++ = c->fmt; // format
289         *buf++ = ZMBV_BLOCK; // block width
290         *buf++ = ZMBV_BLOCK; // block height
291     }
292     memcpy(buf, c->comp_buf, c->zstream.total_out);
293
294     pkt->flags |= AV_PKT_FLAG_KEY*keyframe;
295     *got_packet = 1;
296
297     return 0;
298 }
299
300 static av_cold int encode_end(AVCodecContext *avctx)
301 {
302     ZmbvEncContext * const c = avctx->priv_data;
303
304     av_freep(&c->comp_buf);
305     av_freep(&c->work_buf);
306
307     deflateEnd(&c->zstream);
308     av_freep(&c->prev_buf);
309
310     return 0;
311 }
312
313 /**
314  * Init zmbv encoder
315  */
316 static av_cold int encode_init(AVCodecContext *avctx)
317 {
318     ZmbvEncContext * const c = avctx->priv_data;
319     int zret; // Zlib return code
320     int i;
321     int lvl = 9;
322     int prev_size, prev_offset;
323
324     switch (avctx->pix_fmt) {
325     case AV_PIX_FMT_PAL8:
326         c->fmt = ZMBV_FMT_8BPP;
327         c->bypp = 1;
328         break;
329     case AV_PIX_FMT_RGB555LE:
330         c->fmt = ZMBV_FMT_15BPP;
331         c->bypp = 2;
332         break;
333     case AV_PIX_FMT_RGB565LE:
334         c->fmt = ZMBV_FMT_16BPP;
335         c->bypp = 2;
336         break;
337 #ifdef ZMBV_ENABLE_24BPP
338     case AV_PIX_FMT_BGR24:
339         c->fmt = ZMBV_FMT_24BPP;
340         c->bypp = 3;
341         break;
342 #endif //ZMBV_ENABLE_24BPP
343     case AV_PIX_FMT_BGR0:
344         c->fmt = ZMBV_FMT_32BPP;
345         c->bypp = 4;
346         break;
347     default:
348         av_log(avctx, AV_LOG_INFO, "unsupported pixel format\n");
349         return AVERROR(EINVAL);
350     }
351
352     /* Entropy-based score tables for comparing blocks.
353      * Suitable for blocks up to (ZMBV_BLOCK * ZMBV_BLOCK) bytes.
354      * Scores are nonnegative, lower is better.
355      */
356     for(i = 1; i <= ZMBV_BLOCK * ZMBV_BLOCK * c->bypp; i++)
357         c->score_tab[i] = -i * log2(i / (double)(ZMBV_BLOCK * ZMBV_BLOCK * c->bypp)) * 256;
358
359     c->avctx = avctx;
360
361     c->curfrm = 0;
362     c->keyint = avctx->keyint_min;
363
364     /* Motion estimation range: maximum distance is -64..63 */
365     c->lrange = c->urange = 8;
366     if(avctx->me_range > 0){
367         c->lrange = FFMIN(avctx->me_range, 64);
368         c->urange = FFMIN(avctx->me_range, 63);
369     }
370
371     if(avctx->compression_level >= 0)
372         lvl = avctx->compression_level;
373     if(lvl < 0 || lvl > 9){
374         av_log(avctx, AV_LOG_ERROR, "Compression level should be 0-9, not %i\n", lvl);
375         return AVERROR(EINVAL);
376     }
377
378     // Needed if zlib unused or init aborted before deflateInit
379     memset(&c->zstream, 0, sizeof(z_stream));
380     c->comp_size = avctx->width * c->bypp * avctx->height + 1024 +
381         ((avctx->width + ZMBV_BLOCK - 1) / ZMBV_BLOCK) * ((avctx->height + ZMBV_BLOCK - 1) / ZMBV_BLOCK) * 2 + 4;
382     if (!(c->work_buf = av_malloc(c->comp_size))) {
383         av_log(avctx, AV_LOG_ERROR, "Can't allocate work buffer.\n");
384         return AVERROR(ENOMEM);
385     }
386     /* Conservative upper bound taken from zlib v1.2.1 source via lcl.c */
387     c->comp_size = c->comp_size + ((c->comp_size + 7) >> 3) +
388                            ((c->comp_size + 63) >> 6) + 11;
389
390     /* Allocate compression buffer */
391     if (!(c->comp_buf = av_malloc(c->comp_size))) {
392         av_log(avctx, AV_LOG_ERROR, "Can't allocate compression buffer.\n");
393         return AVERROR(ENOMEM);
394     }
395
396     /* Allocate prev buffer - pad around the image to allow out-of-edge ME:
397      * - The image should be padded with `lrange` rows before and `urange` rows
398      *   after.
399      * - The stride should be padded with `lrange` pixels, then rounded up to a
400      *   multiple of 16 bytes.
401      * - The first row should also be padded with `lrange` pixels before, then
402      *   aligned up to a multiple of 16 bytes.
403      */
404     c->pstride = FFALIGN((avctx->width + c->lrange) * c->bypp, 16);
405     prev_size = FFALIGN(c->lrange * c->bypp, 16) + c->pstride * (c->lrange + avctx->height + c->urange);
406     prev_offset = FFALIGN(c->lrange * c->bypp, 16) + c->pstride * c->lrange;
407     if (!(c->prev_buf = av_mallocz(prev_size))) {
408         av_log(avctx, AV_LOG_ERROR, "Can't allocate picture.\n");
409         return AVERROR(ENOMEM);
410     }
411     c->prev = c->prev_buf + prev_offset;
412
413     c->zstream.zalloc = Z_NULL;
414     c->zstream.zfree = Z_NULL;
415     c->zstream.opaque = Z_NULL;
416     zret = deflateInit(&c->zstream, lvl);
417     if (zret != Z_OK) {
418         av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
419         return -1;
420     }
421
422     return 0;
423 }
424
425 const AVCodec ff_zmbv_encoder = {
426     .name           = "zmbv",
427     .long_name      = NULL_IF_CONFIG_SMALL("Zip Motion Blocks Video"),
428     .type           = AVMEDIA_TYPE_VIDEO,
429     .id             = AV_CODEC_ID_ZMBV,
430     .priv_data_size = sizeof(ZmbvEncContext),
431     .init           = encode_init,
432     .encode2        = encode_frame,
433     .close          = encode_end,
434     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_PAL8,
435                                                      AV_PIX_FMT_RGB555LE,
436                                                      AV_PIX_FMT_RGB565LE,
437 #ifdef ZMBV_ENABLE_24BPP
438                                                      AV_PIX_FMT_BGR24,
439 #endif //ZMBV_ENABLE_24BPP
440                                                      AV_PIX_FMT_BGR0,
441                                                      AV_PIX_FMT_NONE },
442 };