2 * Cinepak encoder (c) 2011 Tomas Härdin
3 * http://titan.codemill.se/~tomhar/cinepakenc.patch
5 * Fixes and improvements, vintage decoders compatibility
6 * (c) 2013, 2014 Rl, Aetey Global Technologies AB
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
29 * - optimize: color space conversion (move conversion to libswscale), ...
31 * - "optimally" split the frame into several non-regular areas
32 * using a separate codebook pair for each area and approximating
33 * the area by several rectangular strips (generally not full width ones)
34 * (use quadtree splitting? a simple fixed-granularity grid?)
39 #include "libavutil/avassert.h"
40 #include "libavutil/common.h"
41 #include "libavutil/internal.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/lfg.h"
44 #include "libavutil/opt.h"
50 #define CVID_HEADER_SIZE 10
51 #define STRIP_HEADER_SIZE 12
52 #define CHUNK_HEADER_SIZE 4
54 #define MB_SIZE 4 //4x4 MBs
55 #define MB_AREA (MB_SIZE * MB_SIZE)
57 #define VECTOR_MAX 6 // six or four entries per vector depending on format
58 #define CODEBOOK_MAX 256 // size of a codebook
60 #define MAX_STRIPS 32 // Note: having fewer choices regarding the number of strips speeds up encoding (obviously)
61 #define MIN_STRIPS 1 // Note: having more strips speeds up encoding the frame (this is less obvious)
62 // MAX_STRIPS limits the maximum quality you can reach
63 // when you want high quality on high resolutions,
64 // MIN_STRIPS limits the minimum efficiently encodable bit rate
66 // the numbers are only used for brute force optimization for the first frame,
67 // for the following frames they are adaptively readjusted
68 // NOTE the decoder in ffmpeg has its own arbitrary limitation on the number
69 // of strips, currently 32
71 typedef enum CinepakMode {
79 typedef enum mb_encoding {
87 typedef struct mb_info {
88 int v1_vector; // index into v1 codebook
89 int v1_error; // error when using V1 encoding
90 int v4_vector[4]; // indices into v4 codebook
91 int v4_error; // error when using V4 encoding
92 int skip_error; // error when block is skipped (aka copied from last frame)
93 mb_encoding best_encoding; // last result from calculate_mode_score()
96 typedef struct strip_info {
97 int v1_codebook[CODEBOOK_MAX * VECTOR_MAX];
98 int v4_codebook[CODEBOOK_MAX * VECTOR_MAX];
104 typedef struct CinepakEncContext {
105 const AVClass *class;
106 AVCodecContext *avctx;
107 unsigned char *pict_bufs[4], *strip_buf, *frame_buf;
110 AVFrame *scratch_frame;
111 AVFrame *input_frame;
112 enum AVPixelFormat pix_fmt;
115 int curframe, keyint;
119 int *codebook_closest;
120 mb_info *mb; // MB RD state
121 int min_strips; // the current limit
122 int max_strips; // the current limit
124 int max_extra_cb_iterations;
128 int strip_number_delta_range;
131 #define OFFSET(x) offsetof(CinepakEncContext, x)
132 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
133 static const AVOption options[] = {
134 { "max_extra_cb_iterations", "Max extra codebook recalculation passes, more is better and slower",
135 OFFSET(max_extra_cb_iterations), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, VE },
136 { "skip_empty_cb", "Avoid wasting bytes, ignore vintage MacOS decoder",
137 OFFSET(skip_empty_cb), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
138 { "max_strips", "Limit strips/frame, vintage compatible is 1..3, otherwise the more the better",
139 OFFSET(max_max_strips), AV_OPT_TYPE_INT, { .i64 = 3 }, MIN_STRIPS, MAX_STRIPS, VE },
140 { "min_strips", "Enforce min strips/frame, more is worse and faster, must be <= max_strips",
141 OFFSET(min_min_strips), AV_OPT_TYPE_INT, { .i64 = MIN_STRIPS }, MIN_STRIPS, MAX_STRIPS, VE },
142 { "strip_number_adaptivity", "How fast the strip number adapts, more is slightly better, much slower",
143 OFFSET(strip_number_delta_range), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_STRIPS - MIN_STRIPS, VE },
147 static const AVClass cinepak_class = {
148 .class_name = "cinepak",
149 .item_name = av_default_item_name,
151 .version = LIBAVUTIL_VERSION_INT,
154 static av_cold int cinepak_encode_init(AVCodecContext *avctx)
156 CinepakEncContext *s = avctx->priv_data;
157 int x, mb_count, strip_buf_size, frame_buf_size;
159 if (avctx->width & 3 || avctx->height & 3) {
160 av_log(avctx, AV_LOG_ERROR, "width and height must be multiples of four (got %ix%i)\n",
161 avctx->width, avctx->height);
162 return AVERROR(EINVAL);
165 if (s->min_min_strips > s->max_max_strips) {
166 av_log(avctx, AV_LOG_ERROR, "minimum number of strips must not exceed maximum (got %i and %i)\n",
167 s->min_min_strips, s->max_max_strips);
168 return AVERROR(EINVAL);
171 if (!(s->last_frame = av_frame_alloc()))
172 return AVERROR(ENOMEM);
173 if (!(s->best_frame = av_frame_alloc()))
175 if (!(s->scratch_frame = av_frame_alloc()))
177 if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
178 if (!(s->input_frame = av_frame_alloc()))
181 if (!(s->codebook_input = av_malloc_array((avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2, sizeof(*s->codebook_input))))
184 if (!(s->codebook_closest = av_malloc_array((avctx->width * avctx->height) >> 2, sizeof(*s->codebook_closest))))
187 for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
188 if (!(s->pict_bufs[x] = av_malloc((avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2)))
191 mb_count = avctx->width * avctx->height / MB_AREA;
193 // the largest possible chunk is 0x31 with all MBs encoded in V4 mode
194 // and full codebooks being replaced in INTER mode,
195 // which is 34 bits per MB
196 // and 2*256 extra flag bits per strip
197 strip_buf_size = STRIP_HEADER_SIZE + 3 * CHUNK_HEADER_SIZE + 2 * VECTOR_MAX * CODEBOOK_MAX + 4 * (mb_count + (mb_count + 15) / 16) + (2 * CODEBOOK_MAX) / 8;
199 frame_buf_size = CVID_HEADER_SIZE + s->max_max_strips * strip_buf_size;
201 if (!(s->strip_buf = av_malloc(strip_buf_size)))
204 if (!(s->frame_buf = av_malloc(frame_buf_size)))
207 if (!(s->mb = av_malloc_array(mb_count, sizeof(mb_info))))
210 av_lfg_init(&s->randctx, 1);
213 s->h = avctx->height;
214 s->frame_buf_size = frame_buf_size;
216 s->keyint = avctx->keyint_min;
217 s->pix_fmt = avctx->pix_fmt;
220 s->last_frame->data[0] = s->pict_bufs[0];
221 s->last_frame->linesize[0] = s->w;
222 s->best_frame->data[0] = s->pict_bufs[1];
223 s->best_frame->linesize[0] = s->w;
224 s->scratch_frame->data[0] = s->pict_bufs[2];
225 s->scratch_frame->linesize[0] = s->w;
227 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
228 s->last_frame->data[1] = s->last_frame->data[0] + s->w * s->h;
229 s->last_frame->data[2] = s->last_frame->data[1] + ((s->w * s->h) >> 2);
230 s->last_frame->linesize[1] =
231 s->last_frame->linesize[2] = s->w >> 1;
233 s->best_frame->data[1] = s->best_frame->data[0] + s->w * s->h;
234 s->best_frame->data[2] = s->best_frame->data[1] + ((s->w * s->h) >> 2);
235 s->best_frame->linesize[1] =
236 s->best_frame->linesize[2] = s->w >> 1;
238 s->scratch_frame->data[1] = s->scratch_frame->data[0] + s->w * s->h;
239 s->scratch_frame->data[2] = s->scratch_frame->data[1] + ((s->w * s->h) >> 2);
240 s->scratch_frame->linesize[1] =
241 s->scratch_frame->linesize[2] = s->w >> 1;
243 s->input_frame->data[0] = s->pict_bufs[3];
244 s->input_frame->linesize[0] = s->w;
245 s->input_frame->data[1] = s->input_frame->data[0] + s->w * s->h;
246 s->input_frame->data[2] = s->input_frame->data[1] + ((s->w * s->h) >> 2);
247 s->input_frame->linesize[1] =
248 s->input_frame->linesize[2] = s->w >> 1;
251 s->min_strips = s->min_min_strips;
252 s->max_strips = s->max_max_strips;
257 av_frame_free(&s->last_frame);
258 av_frame_free(&s->best_frame);
259 av_frame_free(&s->scratch_frame);
260 if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
261 av_frame_free(&s->input_frame);
262 av_freep(&s->codebook_input);
263 av_freep(&s->codebook_closest);
264 av_freep(&s->strip_buf);
265 av_freep(&s->frame_buf);
268 for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
269 av_freep(&s->pict_bufs[x]);
271 return AVERROR(ENOMEM);
274 static int64_t calculate_mode_score(CinepakEncContext *s, int h,
275 strip_info *info, int report,
276 int *training_set_v1_shrunk,
277 int *training_set_v4_shrunk)
279 // score = FF_LAMBDA_SCALE * error + lambda * bits
281 int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
282 int mb_count = s->w * h / MB_AREA;
284 int64_t score1, score2, score3;
285 int64_t ret = s->lambda * ((info->v1_size ? CHUNK_HEADER_SIZE + info->v1_size * entry_size : 0) +
286 (info->v4_size ? CHUNK_HEADER_SIZE + info->v4_size * entry_size : 0) +
287 CHUNK_HEADER_SIZE) << 3;
289 switch (info->mode) {
292 ret += s->lambda * 8 * mb_count;
294 // while calculating we assume all blocks are ENC_V1
295 for (x = 0; x < mb_count; x++) {
297 ret += FF_LAMBDA_SCALE * mb->v1_error;
298 // this function is never called for report in MODE_V1_ONLY
300 mb->best_encoding = ENC_V1;
305 // 9 or 33 bits per MB
307 // no moves between the corresponding training sets are allowed
308 *training_set_v1_shrunk = *training_set_v4_shrunk = 0;
309 for (x = 0; x < mb_count; x++) {
312 if (mb->best_encoding == ENC_V1)
313 score1 = s->lambda * 9 + FF_LAMBDA_SCALE * (mberr = mb->v1_error);
315 score1 = s->lambda * 33 + FF_LAMBDA_SCALE * (mberr = mb->v4_error);
318 } else { // find best mode per block
319 for (x = 0; x < mb_count; x++) {
321 score1 = s->lambda * 9 + FF_LAMBDA_SCALE * mb->v1_error;
322 score2 = s->lambda * 33 + FF_LAMBDA_SCALE * mb->v4_error;
324 if (score1 <= score2) {
326 mb->best_encoding = ENC_V1;
329 mb->best_encoding = ENC_V4;
336 // 1, 10 or 34 bits per MB
338 int v1_shrunk = 0, v4_shrunk = 0;
339 for (x = 0; x < mb_count; x++) {
341 // it is OK to move blocks to ENC_SKIP here
342 // but not to any codebook encoding!
343 score1 = s->lambda * 1 + FF_LAMBDA_SCALE * mb->skip_error;
344 if (mb->best_encoding == ENC_SKIP) {
346 } else if (mb->best_encoding == ENC_V1) {
347 if ((score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error) >= score1) {
348 mb->best_encoding = ENC_SKIP;
355 if ((score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error) >= score1) {
356 mb->best_encoding = ENC_SKIP;
364 *training_set_v1_shrunk = v1_shrunk;
365 *training_set_v4_shrunk = v4_shrunk;
366 } else { // find best mode per block
367 for (x = 0; x < mb_count; x++) {
369 score1 = s->lambda * 1 + FF_LAMBDA_SCALE * mb->skip_error;
370 score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error;
371 score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error;
373 if (score1 <= score2 && score1 <= score3) {
375 mb->best_encoding = ENC_SKIP;
376 } else if (score2 <= score3) {
378 mb->best_encoding = ENC_V1;
381 mb->best_encoding = ENC_V4;
392 static int write_chunk_header(unsigned char *buf, int chunk_type, int chunk_size)
395 AV_WB24(&buf[1], chunk_size + CHUNK_HEADER_SIZE);
396 return CHUNK_HEADER_SIZE;
399 static int encode_codebook(CinepakEncContext *s, int *codebook, int size,
400 int chunk_type_yuv, int chunk_type_gray,
403 int x, y, ret, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
404 int incremental_codebook_replacement_mode = 0; // hardcoded here,
405 // the compiler should notice that this is a constant -- rl
407 ret = write_chunk_header(buf,
408 s->pix_fmt == AV_PIX_FMT_RGB24 ?
409 chunk_type_yuv + (incremental_codebook_replacement_mode ? 1 : 0) :
410 chunk_type_gray + (incremental_codebook_replacement_mode ? 1 : 0),
412 (incremental_codebook_replacement_mode ? (size + 31) / 32 * 4 : 0));
414 // we do codebook encoding according to the "intra" mode
415 // but we keep the "dead" code for reference in case we will want
416 // to use incremental codebook updates (which actually would give us
417 // "kind of" motion compensation, especially in 1 strip/frame case) -- rl
418 // (of course, the code will be not useful as-is)
419 if (incremental_codebook_replacement_mode) {
422 for (x = 0; x < size; x++) {
428 flags = ((flags >> 1) | 0x80000000);
429 for (y = 0; y < entry_size; y++)
430 buf[ret++] = codebook[y + x * entry_size] ^ (y >= 4 ? 0x80 : 0);
431 if ((flags & 0xffffffff) == 0xffffffff) {
432 AV_WB32(&buf[flagsind], flags);
437 AV_WB32(&buf[flagsind], flags);
439 for (x = 0; x < size; x++)
440 for (y = 0; y < entry_size; y++)
441 buf[ret++] = codebook[y + x * entry_size] ^ (y >= 4 ? 0x80 : 0);
446 // sets out to the sub picture starting at (x,y) in in
447 static void get_sub_picture(CinepakEncContext *s, int x, int y,
448 uint8_t * in_data[4], int in_linesize[4],
449 uint8_t *out_data[4], int out_linesize[4])
451 out_data[0] = in_data[0] + x + y * in_linesize[0];
452 out_linesize[0] = in_linesize[0];
454 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
455 out_data[1] = in_data[1] + (x >> 1) + (y >> 1) * in_linesize[1];
456 out_linesize[1] = in_linesize[1];
458 out_data[2] = in_data[2] + (x >> 1) + (y >> 1) * in_linesize[2];
459 out_linesize[2] = in_linesize[2];
463 // decodes the V1 vector in mb into the 4x4 MB pointed to by data
464 static void decode_v1_vector(CinepakEncContext *s, uint8_t *data[4],
465 int linesize[4], int v1_vector, strip_info *info)
467 int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
471 data[0][ linesize[0]] =
472 data[0][1 + linesize[0]] = info->v1_codebook[v1_vector * entry_size];
476 data[0][2 + linesize[0]] =
477 data[0][3 + linesize[0]] = info->v1_codebook[v1_vector * entry_size + 1];
479 data[0][ 2 * linesize[0]] =
480 data[0][1 + 2 * linesize[0]] =
481 data[0][ 3 * linesize[0]] =
482 data[0][1 + 3 * linesize[0]] = info->v1_codebook[v1_vector * entry_size + 2];
484 data[0][2 + 2 * linesize[0]] =
485 data[0][3 + 2 * linesize[0]] =
486 data[0][2 + 3 * linesize[0]] =
487 data[0][3 + 3 * linesize[0]] = info->v1_codebook[v1_vector * entry_size + 3];
489 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
492 data[1][ linesize[1]] =
493 data[1][1 + linesize[1]] = info->v1_codebook[v1_vector * entry_size + 4];
497 data[2][ linesize[2]] =
498 data[2][1 + linesize[2]] = info->v1_codebook[v1_vector * entry_size + 5];
502 // decodes the V4 vectors in mb into the 4x4 MB pointed to by data
503 static void decode_v4_vector(CinepakEncContext *s, uint8_t *data[4],
504 int linesize[4], int *v4_vector, strip_info *info)
506 int i, x, y, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
508 for (i = y = 0; y < 4; y += 2) {
509 for (x = 0; x < 4; x += 2, i++) {
510 data[0][x + y * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size];
511 data[0][x + 1 + y * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 1];
512 data[0][x + (y + 1) * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 2];
513 data[0][x + 1 + (y + 1) * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 3];
515 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
516 data[1][(x >> 1) + (y >> 1) * linesize[1]] = info->v4_codebook[v4_vector[i] * entry_size + 4];
517 data[2][(x >> 1) + (y >> 1) * linesize[2]] = info->v4_codebook[v4_vector[i] * entry_size + 5];
523 static void copy_mb(CinepakEncContext *s,
524 uint8_t *a_data[4], int a_linesize[4],
525 uint8_t *b_data[4], int b_linesize[4])
529 for (y = 0; y < MB_SIZE; y++)
530 memcpy(a_data[0] + y * a_linesize[0], b_data[0] + y * b_linesize[0],
533 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
534 for (p = 1; p <= 2; p++)
535 for (y = 0; y < MB_SIZE / 2; y++)
536 memcpy(a_data[p] + y * a_linesize[p],
537 b_data[p] + y * b_linesize[p],
542 static int encode_mode(CinepakEncContext *s, int h,
543 uint8_t *scratch_data[4], int scratch_linesize[4],
544 uint8_t *last_data[4], int last_linesize[4],
545 strip_info *info, unsigned char *buf)
547 int x, y, z, flags, bits, temp_size, header_ofs, ret = 0, mb_count = s->w * h / MB_AREA;
548 int needs_extra_bit, should_write_temp;
549 unsigned char temp[64]; // 32/2 = 16 V4 blocks at 4 B each -> 64 B
551 uint8_t *sub_scratch_data[4] = { 0 }, *sub_last_data[4] = { 0 };
552 int sub_scratch_linesize[4] = { 0 }, sub_last_linesize[4] = { 0 };
555 ////// MacOS vintage decoder compatibility dictates the presence of
556 ////// the codebook chunk even when the codebook is empty - pretty dumb...
557 ////// and also the certain order of the codebook chunks -- rl
558 if (info->v4_size || !s->skip_empty_cb)
559 ret += encode_codebook(s, info->v4_codebook, info->v4_size, 0x20, 0x24, buf + ret);
561 if (info->v1_size || !s->skip_empty_cb)
562 ret += encode_codebook(s, info->v1_codebook, info->v1_size, 0x22, 0x26, buf + ret);
564 // update scratch picture
565 for (z = y = 0; y < h; y += MB_SIZE)
566 for (x = 0; x < s->w; x += MB_SIZE, z++) {
569 get_sub_picture(s, x, y, scratch_data, scratch_linesize,
570 sub_scratch_data, sub_scratch_linesize);
572 if (info->mode == MODE_MC && mb->best_encoding == ENC_SKIP) {
573 get_sub_picture(s, x, y, last_data, last_linesize,
574 sub_last_data, sub_last_linesize);
575 copy_mb(s, sub_scratch_data, sub_scratch_linesize,
576 sub_last_data, sub_last_linesize);
577 } else if (info->mode == MODE_V1_ONLY || mb->best_encoding == ENC_V1)
578 decode_v1_vector(s, sub_scratch_data, sub_scratch_linesize,
579 mb->v1_vector, info);
581 decode_v4_vector(s, sub_scratch_data, sub_scratch_linesize,
582 mb->v4_vector, info);
585 switch (info->mode) {
587 ret += write_chunk_header(buf + ret, 0x32, mb_count);
589 for (x = 0; x < mb_count; x++)
590 buf[ret++] = s->mb[x].v1_vector;
594 // remember header position
596 ret += CHUNK_HEADER_SIZE;
598 for (x = 0; x < mb_count; x += 32) {
600 for (y = x; y < FFMIN(x + 32, mb_count); y++)
601 if (s->mb[y].best_encoding == ENC_V4)
602 flags |= 1 << (31 - y + x);
604 AV_WB32(&buf[ret], flags);
607 for (y = x; y < FFMIN(x + 32, mb_count); y++) {
610 if (mb->best_encoding == ENC_V1)
611 buf[ret++] = mb->v1_vector;
613 for (z = 0; z < 4; z++)
614 buf[ret++] = mb->v4_vector[z];
618 write_chunk_header(buf + header_ofs, 0x30, ret - header_ofs - CHUNK_HEADER_SIZE);
622 // remember header position
624 ret += CHUNK_HEADER_SIZE;
625 flags = bits = temp_size = 0;
627 for (x = 0; x < mb_count; x++) {
629 flags |= (mb->best_encoding != ENC_SKIP) << (31 - bits++);
631 should_write_temp = 0;
633 if (mb->best_encoding != ENC_SKIP) {
635 flags |= (mb->best_encoding == ENC_V4) << (31 - bits++);
641 AV_WB32(&buf[ret], flags);
645 if (mb->best_encoding == ENC_SKIP || needs_extra_bit) {
646 memcpy(&buf[ret], temp, temp_size);
650 should_write_temp = 1;
653 if (needs_extra_bit) {
654 flags = (mb->best_encoding == ENC_V4) << 31;
658 if (mb->best_encoding == ENC_V1)
659 temp[temp_size++] = mb->v1_vector;
660 else if (mb->best_encoding == ENC_V4)
661 for (z = 0; z < 4; z++)
662 temp[temp_size++] = mb->v4_vector[z];
664 if (should_write_temp) {
665 memcpy(&buf[ret], temp, temp_size);
672 AV_WB32(&buf[ret], flags);
674 memcpy(&buf[ret], temp, temp_size);
678 write_chunk_header(buf + header_ofs, 0x31, ret - header_ofs - CHUNK_HEADER_SIZE);
686 // computes distortion of 4x4 MB in b compared to a
687 static int compute_mb_distortion(CinepakEncContext *s,
688 uint8_t *a_data[4], int a_linesize[4],
689 uint8_t *b_data[4], int b_linesize[4])
691 int x, y, p, d, ret = 0;
693 for (y = 0; y < MB_SIZE; y++)
694 for (x = 0; x < MB_SIZE; x++) {
695 d = a_data[0][x + y * a_linesize[0]] - b_data[0][x + y * b_linesize[0]];
699 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
700 for (p = 1; p <= 2; p++) {
701 for (y = 0; y < MB_SIZE / 2; y++)
702 for (x = 0; x < MB_SIZE / 2; x++) {
703 d = a_data[p][x + y * a_linesize[p]] - b_data[p][x + y * b_linesize[p]];
712 // return the possibly adjusted size of the codebook
713 #define CERTAIN(x) ((x) != ENC_UNCERTAIN)
714 static int quantize(CinepakEncContext *s, int h, uint8_t *data[4],
715 int linesize[4], int v1mode, strip_info *info,
716 mb_encoding encoding)
718 int x, y, i, j, k, x2, y2, x3, y3, plane, shift, mbn;
719 int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
720 int *codebook = v1mode ? info->v1_codebook : info->v4_codebook;
721 int size = v1mode ? info->v1_size : info->v4_size;
722 int64_t total_error = 0;
723 uint8_t vq_pict_buf[(MB_AREA * 3) / 2];
724 uint8_t *sub_data[4], *vq_data[4];
725 int sub_linesize[4], vq_linesize[4];
727 for (mbn = i = y = 0; y < h; y += MB_SIZE) {
728 for (x = 0; x < s->w; x += MB_SIZE, ++mbn) {
731 if (CERTAIN(encoding)) {
732 // use for the training only the blocks known to be to be encoded [sic:-]
733 if (s->mb[mbn].best_encoding != encoding)
737 base = s->codebook_input + i * entry_size;
740 for (j = y2 = 0; y2 < entry_size; y2 += 2)
741 for (x2 = 0; x2 < 4; x2 += 2, j++) {
742 plane = y2 < 4 ? 0 : 1 + (x2 >> 1);
743 shift = y2 < 4 ? 0 : 1;
746 base[j] = (data[plane][((x + x3) >> shift) + ((y + y3) >> shift) * linesize[plane]] +
747 data[plane][((x + x3) >> shift) + 1 + ((y + y3) >> shift) * linesize[plane]] +
748 data[plane][((x + x3) >> shift) + (((y + y3) >> shift) + 1) * linesize[plane]] +
749 data[plane][((x + x3) >> shift) + 1 + (((y + y3) >> shift) + 1) * linesize[plane]]) >> 2;
753 for (j = y2 = 0; y2 < MB_SIZE; y2 += 2) {
754 for (x2 = 0; x2 < MB_SIZE; x2 += 2)
755 for (k = 0; k < entry_size; k++, j++) {
756 plane = k >= 4 ? k - 3 : 0;
762 x3 = x + x2 + (k & 1);
763 y3 = y + y2 + (k >> 1);
766 base[j] = data[plane][x3 + y3 * linesize[plane]];
774 if (i == 0) // empty training set, nothing to do
779 avpriv_init_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
780 avpriv_do_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
782 // set up vq_data, which contains a single MB
783 vq_data[0] = vq_pict_buf;
784 vq_linesize[0] = MB_SIZE;
785 vq_data[1] = &vq_pict_buf[MB_AREA];
786 vq_data[2] = vq_data[1] + (MB_AREA >> 2);
788 vq_linesize[2] = MB_SIZE >> 1;
791 for (i = j = y = 0; y < h; y += MB_SIZE)
792 for (x = 0; x < s->w; x += MB_SIZE, j++) {
793 mb_info *mb = &s->mb[j];
794 // skip uninteresting blocks if we know their preferred encoding
795 if (CERTAIN(encoding) && mb->best_encoding != encoding)
798 // point sub_data to current MB
799 get_sub_picture(s, x, y, data, linesize, sub_data, sub_linesize);
802 mb->v1_vector = s->codebook_closest[i];
804 // fill in vq_data with V1 data
805 decode_v1_vector(s, vq_data, vq_linesize, mb->v1_vector, info);
807 mb->v1_error = compute_mb_distortion(s, sub_data, sub_linesize,
808 vq_data, vq_linesize);
809 total_error += mb->v1_error;
811 for (k = 0; k < 4; k++)
812 mb->v4_vector[k] = s->codebook_closest[i + k];
814 // fill in vq_data with V4 data
815 decode_v4_vector(s, vq_data, vq_linesize, mb->v4_vector, info);
817 mb->v4_error = compute_mb_distortion(s, sub_data, sub_linesize,
818 vq_data, vq_linesize);
819 total_error += mb->v4_error;
823 // check that we did it right in the beginning of the function
824 av_assert0(i >= size); // training set is no smaller than the codebook
829 static void calculate_skip_errors(CinepakEncContext *s, int h,
830 uint8_t *last_data[4], int last_linesize[4],
831 uint8_t *data[4], int linesize[4],
835 uint8_t *sub_last_data [4], *sub_pict_data [4];
836 int sub_last_linesize[4], sub_pict_linesize[4];
838 for (i = y = 0; y < h; y += MB_SIZE)
839 for (x = 0; x < s->w; x += MB_SIZE, i++) {
840 get_sub_picture(s, x, y, last_data, last_linesize,
841 sub_last_data, sub_last_linesize);
842 get_sub_picture(s, x, y, data, linesize,
843 sub_pict_data, sub_pict_linesize);
845 s->mb[i].skip_error =
846 compute_mb_distortion(s,
847 sub_last_data, sub_last_linesize,
848 sub_pict_data, sub_pict_linesize);
852 static void write_strip_header(CinepakEncContext *s, int y, int h, int keyframe,
853 unsigned char *buf, int strip_size)
855 // actually we are exclusively using intra strip coding (how much can we win
856 // otherwise? how to choose which part of a codebook to update?),
857 // keyframes are different only because we disallow ENC_SKIP on them -- rl
858 // (besides, the logic here used to be inverted: )
859 // buf[0] = keyframe ? 0x11: 0x10;
860 buf[0] = keyframe ? 0x10 : 0x11;
861 AV_WB24(&buf[1], strip_size + STRIP_HEADER_SIZE);
862 // AV_WB16(&buf[4], y); /* using absolute y values works -- rl */
863 AV_WB16(&buf[4], 0); /* using relative values works as well -- rl */
865 // AV_WB16(&buf[8], y + h); /* using absolute y values works -- rl */
866 AV_WB16(&buf[8], h); /* using relative values works as well -- rl */
867 AV_WB16(&buf[10], s->w);
870 static int rd_strip(CinepakEncContext *s, int y, int h, int keyframe,
871 uint8_t *last_data[4], int last_linesize[4],
872 uint8_t *data[4], int linesize[4],
873 uint8_t *scratch_data[4], int scratch_linesize[4],
874 unsigned char *buf, int64_t *best_score)
879 // for codebook optimization:
880 int v1enough, v1_size, v4enough, v4_size;
881 int new_v1_size, new_v4_size;
882 int v1shrunk, v4shrunk;
885 calculate_skip_errors(s, h, last_data, last_linesize, data, linesize,
888 // try some powers of 4 for the size of the codebooks
889 // constraint the v4 codebook to be no bigger than v1 one,
890 // (and no less than v1_size/4)
891 // thus making v1 preferable and possibly losing small details? should be ok
892 #define SMALLEST_CODEBOOK 1
893 for (v1enough = 0, v1_size = SMALLEST_CODEBOOK; v1_size <= CODEBOOK_MAX && !v1enough; v1_size <<= 2) {
894 for (v4enough = 0, v4_size = 0; v4_size <= v1_size && !v4enough; v4_size = v4_size ? v4_size << 2 : v1_size >= SMALLEST_CODEBOOK << 2 ? v1_size >> 2 : SMALLEST_CODEBOOK) {
897 for (mode = 0; mode < MODE_COUNT; mode++) {
898 // don't allow MODE_MC in intra frames
899 if (keyframe && mode == MODE_MC)
902 if (mode == MODE_V1_ONLY) {
903 info.v1_size = v1_size;
904 // the size may shrink even before optimizations if the input is short:
905 info.v1_size = quantize(s, h, data, linesize, 1,
906 &info, ENC_UNCERTAIN);
907 if (info.v1_size < v1_size)
908 // too few eligible blocks, no sense in trying bigger sizes
912 } else { // mode != MODE_V1_ONLY
913 // if v4 codebook is empty then only allow V1-only mode
917 if (mode == MODE_V1_V4) {
918 info.v4_size = v4_size;
919 info.v4_size = quantize(s, h, data, linesize, 0,
920 &info, ENC_UNCERTAIN);
921 if (info.v4_size < v4_size)
922 // too few eligible blocks, no sense in trying bigger sizes
928 // choose the best encoding per block, based on current experience
929 score = calculate_mode_score(s, h, &info, 0,
930 &v1shrunk, &v4shrunk);
932 if (mode != MODE_V1_ONLY) {
933 int extra_iterations_limit = s->max_extra_cb_iterations;
934 // recompute the codebooks, omitting the extra blocks
935 // we assume we _may_ come here with more blocks to encode than before
936 info.v1_size = v1_size;
937 new_v1_size = quantize(s, h, data, linesize, 1, &info, ENC_V1);
938 if (new_v1_size < info.v1_size)
939 info.v1_size = new_v1_size;
940 // we assume we _may_ come here with more blocks to encode than before
941 info.v4_size = v4_size;
942 new_v4_size = quantize(s, h, data, linesize, 0, &info, ENC_V4);
943 if (new_v4_size < info.v4_size)
944 info.v4_size = new_v4_size;
945 // calculate the resulting score
946 // (do not move blocks to codebook encodings now, as some blocks may have
947 // got bigger errors despite a smaller training set - but we do not
948 // ever grow the training sets back)
950 score = calculate_mode_score(s, h, &info, 1,
951 &v1shrunk, &v4shrunk);
952 // do we have a reason to reiterate? if so, have we reached the limit?
953 if ((!v1shrunk && !v4shrunk) || !extra_iterations_limit--)
955 // recompute the codebooks, omitting the extra blocks
957 info.v1_size = v1_size;
958 new_v1_size = quantize(s, h, data, linesize, 1, &info, ENC_V1);
959 if (new_v1_size < info.v1_size)
960 info.v1_size = new_v1_size;
963 info.v4_size = v4_size;
964 new_v4_size = quantize(s, h, data, linesize, 0, &info, ENC_V4);
965 if (new_v4_size < info.v4_size)
966 info.v4_size = new_v4_size;
971 if (best_size == 0 || score < *best_score) {
973 best_size = encode_mode(s, h,
974 scratch_data, scratch_linesize,
975 last_data, last_linesize, &info,
976 s->strip_buf + STRIP_HEADER_SIZE);
978 write_strip_header(s, y, h, keyframe, s->strip_buf, best_size);
984 best_size += STRIP_HEADER_SIZE;
985 memcpy(buf, s->strip_buf, best_size);
990 static int write_cvid_header(CinepakEncContext *s, unsigned char *buf,
991 int num_strips, int data_size, int isakeyframe)
993 buf[0] = isakeyframe ? 0 : 1;
994 AV_WB24(&buf[1], data_size + CVID_HEADER_SIZE);
995 AV_WB16(&buf[4], s->w);
996 AV_WB16(&buf[6], s->h);
997 AV_WB16(&buf[8], num_strips);
999 return CVID_HEADER_SIZE;
1002 static int rd_frame(CinepakEncContext *s, const AVFrame *frame,
1003 int isakeyframe, unsigned char *buf, int buf_size)
1005 int num_strips, strip, i, y, nexty, size, temp_size, best_size;
1006 uint8_t *last_data [4], *data [4], *scratch_data [4];
1007 int last_linesize[4], linesize[4], scratch_linesize[4];
1008 int64_t best_score = 0, score, score_temp;
1011 if (s->pix_fmt == AV_PIX_FMT_RGB24) {
1013 // build a copy of the given frame in the correct colorspace
1014 for (y = 0; y < s->h; y += 2)
1015 for (x = 0; x < s->w; x += 2) {
1017 int32_t r, g, b, rr, gg, bb;
1018 ir[0] = frame->data[0] + x * 3 + y * frame->linesize[0];
1019 ir[1] = ir[0] + frame->linesize[0];
1020 get_sub_picture(s, x, y,
1021 s->input_frame->data, s->input_frame->linesize,
1022 scratch_data, scratch_linesize);
1024 for (i = 0; i < 4; ++i) {
1028 rr = ir[i2][i1 * 3 + 0];
1029 gg = ir[i2][i1 * 3 + 1];
1030 bb = ir[i2][i1 * 3 + 2];
1034 // using fixed point arithmetic for portable repeatability, scaling by 2^23
1036 // rr = 0.2857 * rr + 0.5714 * gg + 0.1429 * bb;
1037 rr = (2396625 * rr + 4793251 * gg + 1198732 * bb) >> 23;
1042 scratch_data[0][i1 + i2 * scratch_linesize[0]] = rr;
1044 // let us scale down as late as possible
1045 // r /= 4; g /= 4; b /= 4;
1047 // rr = -0.1429 * r - 0.2857 * g + 0.4286 * b;
1048 rr = (-299683 * r - 599156 * g + 898839 * b) >> 23;
1053 scratch_data[1][0] = rr + 128; // quantize needs unsigned
1055 // rr = 0.3571 * r - 0.2857 * g - 0.0714 * b;
1056 rr = (748893 * r - 599156 * g - 149737 * b) >> 23;
1061 scratch_data[2][0] = rr + 128; // quantize needs unsigned
1065 // would be nice but quite certainly incompatible with vintage players:
1066 // support encoding zero strips (meaning skip the whole frame)
1067 for (num_strips = s->min_strips; num_strips <= s->max_strips && num_strips <= s->h / MB_SIZE; num_strips++) {
1071 for (y = 0, strip = 1; y < s->h; strip++, y = nexty) {
1074 nexty = strip * s->h / num_strips; // <= s->h
1075 // make nexty the next multiple of 4 if not already there
1077 nexty += 4 - (nexty & 3);
1079 strip_height = nexty - y;
1080 if (strip_height <= 0) { // can this ever happen?
1081 av_log(s->avctx, AV_LOG_INFO, "skipping zero height strip %i of %i\n", strip, num_strips);
1085 if (s->pix_fmt == AV_PIX_FMT_RGB24)
1086 get_sub_picture(s, 0, y,
1087 s->input_frame->data, s->input_frame->linesize,
1090 get_sub_picture(s, 0, y,
1091 (uint8_t **)frame->data, (int *)frame->linesize,
1093 get_sub_picture(s, 0, y,
1094 s->last_frame->data, s->last_frame->linesize,
1095 last_data, last_linesize);
1096 get_sub_picture(s, 0, y,
1097 s->scratch_frame->data, s->scratch_frame->linesize,
1098 scratch_data, scratch_linesize);
1100 if ((temp_size = rd_strip(s, y, strip_height, isakeyframe,
1101 last_data, last_linesize, data, linesize,
1102 scratch_data, scratch_linesize,
1103 s->frame_buf + size + CVID_HEADER_SIZE,
1107 score += score_temp;
1111 if (best_score == 0 || score < best_score) {
1113 best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size, isakeyframe);
1115 FFSWAP(AVFrame *, s->best_frame, s->scratch_frame);
1116 memcpy(buf, s->frame_buf, best_size);
1117 best_nstrips = num_strips;
1119 // avoid trying too many strip numbers without a real reason
1120 // (this makes the processing of the very first frame faster)
1121 if (num_strips - best_nstrips > 4)
1125 // let the number of strips slowly adapt to the changes in the contents,
1126 // compared to full bruteforcing every time this will occasionally lead
1127 // to some r/d performance loss but makes encoding up to several times faster
1128 if (!s->strip_number_delta_range) {
1129 if (best_nstrips == s->max_strips) { // let us try to step up
1130 s->max_strips = best_nstrips + 1;
1131 if (s->max_strips >= s->max_max_strips)
1132 s->max_strips = s->max_max_strips;
1133 } else { // try to step down
1134 s->max_strips = best_nstrips;
1136 s->min_strips = s->max_strips - 1;
1137 if (s->min_strips < s->min_min_strips)
1138 s->min_strips = s->min_min_strips;
1140 s->max_strips = best_nstrips + s->strip_number_delta_range;
1141 if (s->max_strips >= s->max_max_strips)
1142 s->max_strips = s->max_max_strips;
1143 s->min_strips = best_nstrips - s->strip_number_delta_range;
1144 if (s->min_strips < s->min_min_strips)
1145 s->min_strips = s->min_min_strips;
1151 static int cinepak_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1152 const AVFrame *frame, int *got_packet)
1154 CinepakEncContext *s = avctx->priv_data;
1157 s->lambda = frame->quality ? frame->quality - 1 : 2 * FF_LAMBDA_SCALE;
1159 if ((ret = ff_alloc_packet2(avctx, pkt, s->frame_buf_size, 0)) < 0)
1161 ret = rd_frame(s, frame, (s->curframe == 0), pkt->data, s->frame_buf_size);
1163 if (s->curframe == 0)
1164 pkt->flags |= AV_PKT_FLAG_KEY;
1167 FFSWAP(AVFrame *, s->last_frame, s->best_frame);
1169 if (++s->curframe >= s->keyint)
1175 static av_cold int cinepak_encode_end(AVCodecContext *avctx)
1177 CinepakEncContext *s = avctx->priv_data;
1180 av_frame_free(&s->last_frame);
1181 av_frame_free(&s->best_frame);
1182 av_frame_free(&s->scratch_frame);
1183 if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
1184 av_frame_free(&s->input_frame);
1185 av_freep(&s->codebook_input);
1186 av_freep(&s->codebook_closest);
1187 av_freep(&s->strip_buf);
1188 av_freep(&s->frame_buf);
1191 for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
1192 av_freep(&s->pict_bufs[x]);
1197 AVCodec ff_cinepak_encoder = {
1199 .long_name = NULL_IF_CONFIG_SMALL("Cinepak"),
1200 .type = AVMEDIA_TYPE_VIDEO,
1201 .id = AV_CODEC_ID_CINEPAK,
1202 .priv_data_size = sizeof(CinepakEncContext),
1203 .init = cinepak_encode_init,
1204 .encode2 = cinepak_encode_frame,
1205 .close = cinepak_encode_end,
1206 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_RGB24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE },
1207 .priv_class = &cinepak_class,