cinepakenc.c 50.1 KB
Newer Older
Tomas Härdin's avatar
Tomas Härdin committed
1 2 3
/*
 * Cinepak encoder (c) 2011 Tomas Härdin
 * http://titan.codemill.se/~tomhar/cinepakenc.patch
4 5 6
 *
 * Fixes and improvements, vintage decoders compatibility
 *  (c) 2013, 2014 Rl, Aetey Global Technologies AB
Tomas Härdin's avatar
Tomas Härdin committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

26 27 28 29 30 31 32 33 34 35
 * TODO:
 * - optimize: color space conversion, ...
 * - implement options to set the min/max number of strips?
 * MAYBE:
 * - "optimally" split the frame into several non-regular areas
 *   using a separate codebook pair for each area and approximating
 *   the area by several rectangular strips (generally not full width ones)
 *   (use quadtree splitting? a simple fixed-granularity grid?)
 *
 *
36 37 38
 * version 2014-01-23 Rl
 * - added option handling for flexibility
 *
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
 * version 2014-01-21 Rl
 * - believe it or not, now we get even smaller files, with better quality
 *   (which means I missed an optimization earlier :)
 *
 * version 2014-01-20 Rl
 * - made the encoder compatible with vintage decoders
 *   and added some yet unused code for possible future
 *   incremental codebook updates
 * - fixed a small memory leak
 *
 * version 2013-04-28 Rl
 * - bugfixed codebook optimization logic
 *
 * version 2013-02-14 Rl
 * "Valentine's Day" version:
 * - made strip division more robust
 * - minimized bruteforcing the number of strips,
 *   (costs some R/D but speeds up compession a lot), the heuristic
 *   assumption is that score as a function of the number of strips has
 *   one wide minimum which moves slowly, of course not fully true
 * - simplified codebook generation,
 *   the old code was meant for other optimizations than we actually do
 * - optimized the codebook generation / error estimation for MODE_MC
 *
 * version 2013-02-12 Rl
 * - separated codebook training sets, avoided the transfer of wasted bytes,
 *   which yields both better quality and smaller files
 * - now using the correct colorspace (TODO: move conversion to libswscale)
 *
 * version 2013-02-08 Rl
 * - fixes/optimization in multistrip encoding and codebook size choice,
 *   quality/bitrate is now better than that of the binary proprietary encoder
Tomas Härdin's avatar
Tomas Härdin committed
71 72 73 74 75 76
 */

#include "libavutil/intreadwrite.h"
#include "avcodec.h"
#include "libavutil/lfg.h"
#include "elbg.h"
77 78 79
#include "internal.h"

#include "libavutil/avassert.h"
80
#include "libavutil/opt.h"
Tomas Härdin's avatar
Tomas Härdin committed
81 82 83 84 85 86 87 88 89

#define CVID_HEADER_SIZE 10
#define STRIP_HEADER_SIZE 12
#define CHUNK_HEADER_SIZE 4

#define MB_SIZE 4           //4x4 MBs
#define MB_AREA (MB_SIZE*MB_SIZE)

#define VECTOR_MAX 6        //six or four entries per vector depending on format
90
#define CODEBOOK_MAX 256    //size of a codebook
Tomas Härdin's avatar
Tomas Härdin committed
91

92
#define MAX_STRIPS  32      //Note: having fewer choices regarding the number of strips speeds up encoding (obviously)
Tomas Härdin's avatar
Tomas Härdin committed
93
#define MIN_STRIPS  1       //Note: having more strips speeds up encoding the frame (this is less obvious)
94 95 96 97 98 99 100 101
// MAX_STRIPS limits the maximum quality you can reach
//            when you want hight quality on high resolutions,
// MIN_STRIPS limits the minimum efficiently encodable bit rate
//            on low resolutions
// the numbers are only used for brute force optimization for the first frame,
// for the following frames they are adaptively readjusted
// NOTE the decoder in ffmpeg has its own arbitrary limitation on the number
// of strips, currently 32
Tomas Härdin's avatar
Tomas Härdin committed
102 103 104 105 106 107 108 109 110 111 112 113

typedef enum {
    MODE_V1_ONLY = 0,
    MODE_V1_V4,
    MODE_MC,

    MODE_COUNT,
} CinepakMode;

typedef enum {
    ENC_V1,
    ENC_V4,
114 115 116
    ENC_SKIP,

    ENC_UNCERTAIN
Tomas Härdin's avatar
Tomas Härdin committed
117 118 119 120 121
} mb_encoding;

typedef struct {
    int v1_vector;                  //index into v1 codebook
    int v1_error;                   //error when using V1 encoding
122 123
    int v4_vector[4];               //indices into v4 codebooks
    int v4_error;                   //error when using V4 encoding
Tomas Härdin's avatar
Tomas Härdin committed
124 125 126 127 128 129
    int skip_error;                 //error when block is skipped (aka copied from last frame)
    mb_encoding best_encoding;      //last result from calculate_mode_score()
} mb_info;

typedef struct {
    int v1_codebook[CODEBOOK_MAX*VECTOR_MAX];
130 131 132 133
    int v4_codebook[CODEBOOK_MAX*VECTOR_MAX];
    int v1_size;
    int v4_size;
    CinepakMode mode;
Tomas Härdin's avatar
Tomas Härdin committed
134 135 136
} strip_info;

typedef struct {
137
    const AVClass *class;
Tomas Härdin's avatar
Tomas Härdin committed
138
    AVCodecContext *avctx;
139 140 141 142 143 144
    unsigned char *pict_bufs[4], *strip_buf, *frame_buf;
    AVFrame *last_frame;
    AVFrame *best_frame;
    AVFrame *scratch_frame;
    AVFrame *input_frame;
    enum AVPixelFormat pix_fmt;
Tomas Härdin's avatar
Tomas Härdin committed
145
    int w, h;
146
    int frame_buf_size;
Tomas Härdin's avatar
Tomas Härdin committed
147 148 149 150 151 152
    int curframe, keyint;
    AVLFG randctx;
    uint64_t lambda;
    int *codebook_input;
    int *codebook_closest;
    mb_info *mb;                                //MB RD state
153 154
    int min_strips;          //the current limit
    int max_strips;          //the current limit
Tomas Härdin's avatar
Tomas Härdin committed
155 156 157 158
#ifdef CINEPAKENC_DEBUG
    mb_info *best_mb;                           //TODO: remove. only used for printing stats
    int num_v1_mode, num_v4_mode, num_mc_mode;
    int num_v1_encs, num_v4_encs, num_skips;
159
#endif
160 161 162 163 164 165
// options
    int max_extra_cb_iterations;
    int skip_empty_cb;
    int min_min_strips;
    int max_max_strips;
    int strip_number_delta_range;
Tomas Härdin's avatar
Tomas Härdin committed
166 167
} CinepakEncContext;

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
#define OFFSET(x) offsetof(CinepakEncContext, x)
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
    { "max_extra_cb_iterations", "Max extra codebook recalculation passes, more is better and slower", OFFSET(max_extra_cb_iterations), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, VE },
    { "skip_empty_cb", "Avoid wasting bytes, ignore vintage MacOS decoder", OFFSET(skip_empty_cb), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
    { "max_strips", "Limit strips/frame, vintage compatible is 1..3, otherwise the more the better", OFFSET(max_max_strips), AV_OPT_TYPE_INT, { .i64 = 3 }, MIN_STRIPS, MAX_STRIPS, VE },
    { "min_strips", "Enforce min strips/frame, more is worse and faster, must be <= max_strips", OFFSET(min_min_strips), AV_OPT_TYPE_INT, { .i64 = MIN_STRIPS }, MIN_STRIPS, MAX_STRIPS, VE },
    { "strip_number_adaptivity", "How fast the strip number adapts, more is slightly better, much slower", OFFSET(strip_number_delta_range), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_STRIPS-MIN_STRIPS, VE },
    { NULL },
};

static const AVClass cinepak_class = {
    .class_name = "cinepak",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

Tomas Härdin's avatar
Tomas Härdin committed
186 187 188 189 190 191 192 193 194 195 196
static av_cold int cinepak_encode_init(AVCodecContext *avctx)
{
    CinepakEncContext *s = avctx->priv_data;
    int x, mb_count, strip_buf_size, frame_buf_size;

    if (avctx->width & 3 || avctx->height & 3) {
        av_log(avctx, AV_LOG_ERROR, "width and height must be multiples of four (got %ix%i)\n",
                avctx->width, avctx->height);
        return AVERROR(EINVAL);
    }

197 198 199 200 201 202
    if (s->min_min_strips > s->max_max_strips) {
        av_log(avctx, AV_LOG_ERROR, "minimal number of strips can not exceed maximal (got %i and %i)\n",
                s->min_min_strips, s->max_max_strips);
        return AVERROR(EINVAL);
    }

203
    if (!(s->last_frame = av_frame_alloc()))
Tomas Härdin's avatar
Tomas Härdin committed
204
        return AVERROR(ENOMEM);
205 206 207 208 209 210 211 212 213 214
    if (!(s->best_frame = av_frame_alloc()))
        goto enomem;
    if (!(s->scratch_frame = av_frame_alloc()))
        goto enomem;
    if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
        if (!(s->input_frame = av_frame_alloc()))
            goto enomem;

    if (!(s->codebook_input = av_malloc(sizeof(int) * (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2)))
        goto enomem;
Tomas Härdin's avatar
Tomas Härdin committed
215 216 217 218

    if (!(s->codebook_closest = av_malloc(sizeof(int) * (avctx->width * avctx->height) >> 2)))
        goto enomem;

219 220
    for(x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
        if(!(s->pict_bufs[x] = av_malloc((avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2)))
Tomas Härdin's avatar
Tomas Härdin committed
221 222 223 224
            goto enomem;

    mb_count = avctx->width * avctx->height / MB_AREA;

225 226 227 228 229
    //the largest possible chunk is 0x31 with all MBs encoded in V4 mode
    //and full codebooks being replaced in INTER mode,
    // which is 34 bits per MB
    //and 2*256 extra flag bits per strip
    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;
Tomas Härdin's avatar
Tomas Härdin committed
230

231
    frame_buf_size = CVID_HEADER_SIZE + s->max_max_strips * strip_buf_size;
Tomas Härdin's avatar
Tomas Härdin committed
232 233 234 235 236 237 238

    if (!(s->strip_buf = av_malloc(strip_buf_size)))
        goto enomem;

    if (!(s->frame_buf = av_malloc(frame_buf_size)))
        goto enomem;

239
    if (!(s->mb = av_malloc_array(mb_count, sizeof(mb_info))))
Tomas Härdin's avatar
Tomas Härdin committed
240 241 242
        goto enomem;

#ifdef CINEPAKENC_DEBUG
243
    if (!(s->best_mb = av_malloc_array(mb_count, sizeof(mb_info))))
Tomas Härdin's avatar
Tomas Härdin committed
244 245 246 247 248 249 250
        goto enomem;
#endif

    av_lfg_init(&s->randctx, 1);
    s->avctx = avctx;
    s->w = avctx->width;
    s->h = avctx->height;
251
    s->frame_buf_size = frame_buf_size;
Tomas Härdin's avatar
Tomas Härdin committed
252 253 254 255 256
    s->curframe = 0;
    s->keyint = avctx->keyint_min;
    s->pix_fmt = avctx->pix_fmt;

    //set up AVFrames
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    s->last_frame->data[0]        = s->pict_bufs[0];
    s->last_frame->linesize[0]    = s->w;
    s->best_frame->data[0]        = s->pict_bufs[1];
    s->best_frame->linesize[0]    = s->w;
    s->scratch_frame->data[0]     = s->pict_bufs[2];
    s->scratch_frame->linesize[0] = s->w;

    if (s->pix_fmt == AV_PIX_FMT_RGB24) {
        s->last_frame->data[1]        = s->last_frame->data[0] + s->w * s->h;
        s->last_frame->data[2]        = s->last_frame->data[1] + ((s->w * s->h) >> 2);
        s->last_frame->linesize[1]    = s->last_frame->linesize[2] = s->w >> 1;

        s->best_frame->data[1]        = s->best_frame->data[0] + s->w * s->h;
        s->best_frame->data[2]        = s->best_frame->data[1] + ((s->w * s->h) >> 2);
        s->best_frame->linesize[1]    = s->best_frame->linesize[2] = s->w >> 1;

        s->scratch_frame->data[1]     = s->scratch_frame->data[0] + s->w * s->h;
        s->scratch_frame->data[2]     = s->scratch_frame->data[1] + ((s->w * s->h) >> 2);
        s->scratch_frame->linesize[1] = s->scratch_frame->linesize[2] = s->w >> 1;

        s->input_frame->data[0]       = s->pict_bufs[3];
        s->input_frame->linesize[0]   = s->w;
        s->input_frame->data[1]       = s->input_frame->data[0] + s->w * s->h;
        s->input_frame->data[2]       = s->input_frame->data[1] + ((s->w * s->h) >> 2);
        s->input_frame->linesize[1]   = s->input_frame->linesize[2] = s->w >> 1;
Tomas Härdin's avatar
Tomas Härdin committed
282 283
    }

284 285
    s->min_strips = s->min_min_strips;
    s->max_strips = s->max_max_strips;
286 287

#ifdef CINEPAKENC_DEBUG
Tomas Härdin's avatar
Tomas Härdin committed
288
    s->num_v1_mode = s->num_v4_mode = s->num_mc_mode = s->num_v1_encs = s->num_v4_encs = s->num_skips = 0;
289
#endif
Tomas Härdin's avatar
Tomas Härdin committed
290 291 292 293

    return 0;

enomem:
294 295 296 297 298 299 300 301 302 303
    av_frame_free(&s->last_frame);
    av_frame_free(&s->best_frame);
    av_frame_free(&s->scratch_frame);
    if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
        av_frame_free(&s->input_frame);
    av_freep(&s->codebook_input);
    av_freep(&s->codebook_closest);
    av_freep(&s->strip_buf);
    av_freep(&s->frame_buf);
    av_freep(&s->mb);
Tomas Härdin's avatar
Tomas Härdin committed
304
#ifdef CINEPAKENC_DEBUG
305
    av_freep(&s->best_mb);
Tomas Härdin's avatar
Tomas Härdin committed
306 307
#endif

308 309
    for(x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
        av_freep(&s->pict_bufs[x]);
Tomas Härdin's avatar
Tomas Härdin committed
310 311 312 313

    return AVERROR(ENOMEM);
}

314 315 316 317 318
static int64_t calculate_mode_score(CinepakEncContext *s, int h, strip_info *info, int report, int *training_set_v1_shrunk, int *training_set_v4_shrunk
#ifdef CINEPAK_REPORT_SERR
, int64_t *serr
#endif
)
Tomas Härdin's avatar
Tomas Härdin committed
319 320 321
{
    //score = FF_LAMBDA_SCALE * error + lambda * bits
    int x;
322
    int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
323 324 325
    int mb_count = s->w * h / MB_AREA;
    mb_info *mb;
    int64_t score1, score2, score3;
326 327
    int64_t ret = s->lambda * ((info->v1_size ? CHUNK_HEADER_SIZE + info->v1_size * entry_size : 0) +
                   (info->v4_size ? CHUNK_HEADER_SIZE + info->v4_size * entry_size : 0) +
Tomas Härdin's avatar
Tomas Härdin committed
328 329
                   CHUNK_HEADER_SIZE) << 3;

330
    //av_log(s->avctx, AV_LOG_INFO, "sizes %3i %3i -> %9"PRId64" score mb_count %i", info->v1_size, info->v4_size, ret, mb_count);
331 332 333 334

#ifdef CINEPAK_REPORT_SERR
    *serr = 0;
#endif
Tomas Härdin's avatar
Tomas Härdin committed
335

336
    switch(info->mode) {
Tomas Härdin's avatar
Tomas Härdin committed
337 338 339 340
    case MODE_V1_ONLY:
        //one byte per MB
        ret += s->lambda * 8 * mb_count;

341
// while calculating we assume all blocks are ENC_V1
Tomas Härdin's avatar
Tomas Härdin committed
342 343 344
        for(x = 0; x < mb_count; x++) {
            mb = &s->mb[x];
            ret += FF_LAMBDA_SCALE * mb->v1_error;
345 346 347 348 349
#ifdef CINEPAK_REPORT_SERR
            *serr += mb->v1_error;
#endif
// this function is never called for report in MODE_V1_ONLY
//            if(!report)
Tomas Härdin's avatar
Tomas Härdin committed
350 351 352 353 354 355
            mb->best_encoding = ENC_V1;
        }

        break;
    case MODE_V1_V4:
        //9 or 33 bits per MB
356 357 358 359 360 361 362 363 364 365
        if(report) {
// no moves between the corresponding training sets are allowed
            *training_set_v1_shrunk = *training_set_v4_shrunk = 0;
            for(x = 0; x < mb_count; x++) {
                int mberr;
                mb = &s->mb[x];
                if(mb->best_encoding == ENC_V1)
                    score1 = s->lambda * 9  + FF_LAMBDA_SCALE * (mberr=mb->v1_error);
                else
                    score1 = s->lambda * 33 + FF_LAMBDA_SCALE * (mberr=mb->v4_error);
Tomas Härdin's avatar
Tomas Härdin committed
366
                ret += score1;
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
#ifdef CINEPAK_REPORT_SERR
                *serr += mberr;
#endif
            }
        } else { // find best mode per block
            for(x = 0; x < mb_count; x++) {
                mb = &s->mb[x];
                score1 = s->lambda * 9  + FF_LAMBDA_SCALE * mb->v1_error;
                score2 = s->lambda * 33 + FF_LAMBDA_SCALE * mb->v4_error;

                if(score1 <= score2) {
                    ret += score1;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->v1_error;
#endif
                    mb->best_encoding = ENC_V1;
                } else {
                    ret += score2;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->v4_error;
#endif
                    mb->best_encoding = ENC_V4;
                }
Tomas Härdin's avatar
Tomas Härdin committed
390 391 392 393 394 395
            }
        }

        break;
    case MODE_MC:
        //1, 10 or 34 bits per MB
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        if(report) {
            int v1_shrunk = 0, v4_shrunk = 0;
            for(x = 0; x < mb_count; x++) {
                mb = &s->mb[x];
// it is OK to move blocks to ENC_SKIP here
// but not to any codebook encoding!
                score1 = s->lambda * 1  + FF_LAMBDA_SCALE * mb->skip_error;
                if(mb->best_encoding == ENC_SKIP) {
                    ret += score1;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->skip_error;
#endif
                } else if(mb->best_encoding == ENC_V1) {
                    if((score2=s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error) >= score1) {
                        mb->best_encoding = ENC_SKIP;
                        ++v1_shrunk;
                        ret += score1;
#ifdef CINEPAK_REPORT_SERR
                        *serr += mb->skip_error;
#endif
                    } else {
                        ret += score2;
#ifdef CINEPAK_REPORT_SERR
                        *serr += mb->v1_error;
#endif
                    }
                } else {
                    if((score3=s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error) >= score1) {
                        mb->best_encoding = ENC_SKIP;
                        ++v4_shrunk;
                        ret += score1;
#ifdef CINEPAK_REPORT_SERR
                        *serr += mb->skip_error;
#endif
                    } else {
                        ret += score3;
#ifdef CINEPAK_REPORT_SERR
                        *serr += mb->v4_error;
#endif
                    }
                }
            }
            *training_set_v1_shrunk = v1_shrunk;
            *training_set_v4_shrunk = v4_shrunk;
        } else { // find best mode per block
            for(x = 0; x < mb_count; x++) {
                mb = &s->mb[x];
                score1 = s->lambda * 1  + FF_LAMBDA_SCALE * mb->skip_error;
                score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error;
                score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error;

                if(score1 <= score2 && score1 <= score3) {
                    ret += score1;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->skip_error;
#endif
                    mb->best_encoding = ENC_SKIP;
                } else if(score2 <= score3) {
                    ret += score2;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->v1_error;
#endif
                    mb->best_encoding = ENC_V1;
                } else {
                    ret += score3;
#ifdef CINEPAK_REPORT_SERR
                    *serr += mb->v4_error;
#endif
                    mb->best_encoding = ENC_V4;
                }
Tomas Härdin's avatar
Tomas Härdin committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            }
        }

        break;
    }

    return ret;
}

static int write_chunk_header(unsigned char *buf, int chunk_type, int chunk_size)
{
    buf[0] = chunk_type;
    AV_WB24(&buf[1], chunk_size + CHUNK_HEADER_SIZE);
    return CHUNK_HEADER_SIZE;
}

static int encode_codebook(CinepakEncContext *s, int *codebook, int size, int chunk_type_yuv, int chunk_type_gray, unsigned char *buf)
{
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    int x, y, ret, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
    int incremental_codebook_replacement_mode = 0; // hardcoded here,
                // the compiler should notice that this is a constant -- rl

    ret = write_chunk_header(buf,
          s->pix_fmt == AV_PIX_FMT_RGB24 ?
           chunk_type_yuv+(incremental_codebook_replacement_mode?1:0) :
           chunk_type_gray+(incremental_codebook_replacement_mode?1:0),
          entry_size * size
           + (incremental_codebook_replacement_mode?(size+31)/32*4:0) );

// we do codebook encoding according to the "intra" mode
// but we keep the "dead" code for reference in case we will want
// to use incremental codebook updates (which actually would give us
// "kind of" motion compensation, especially in 1 strip/frame case) -- rl
// (of course, the code will be not useful as-is)
    if(incremental_codebook_replacement_mode) {
        int flags = 0;
        int flagsind;
        for(x = 0; x < size; x++) {
            if(flags == 0) {
                flagsind = ret;
                ret += 4;
                flags = 0x80000000;
            } else
                flags = ((flags>>1) | 0x80000000);
            for(y = 0; y < entry_size; y++)
                buf[ret++] = codebook[y + x*entry_size] ^ (y >= 4 ? 0x80 : 0);
            if((flags&0xffffffff) == 0xffffffff) {
                AV_WB32(&buf[flagsind], flags);
                flags = 0;
            }
        }
        if(flags)
            AV_WB32(&buf[flagsind], flags);
    } else
        for(x = 0; x < size; x++)
            for(y = 0; y < entry_size; y++)
                buf[ret++] = codebook[y + x*entry_size] ^ (y >= 4 ? 0x80 : 0);
Tomas Härdin's avatar
Tomas Härdin committed
523 524 525 526 527 528 529 530 531 532

    return ret;
}

//sets out to the sub picture starting at (x,y) in in
static void get_sub_picture(CinepakEncContext *s, int x, int y, AVPicture *in, AVPicture *out)
{
    out->data[0] = in->data[0] + x + y * in->linesize[0];
    out->linesize[0] = in->linesize[0];

533
    if(s->pix_fmt == AV_PIX_FMT_RGB24) {
Tomas Härdin's avatar
Tomas Härdin committed
534 535 536 537 538 539 540 541 542
        out->data[1] = in->data[1] + (x >> 1) + (y >> 1) * in->linesize[1];
        out->linesize[1] = in->linesize[1];

        out->data[2] = in->data[2] + (x >> 1) + (y >> 1) * in->linesize[2];
        out->linesize[2] = in->linesize[2];
    }
}

//decodes the V1 vector in mb into the 4x4 MB pointed to by sub_pict
543
static void decode_v1_vector(CinepakEncContext *s, AVPicture *sub_pict, int v1_vector, strip_info *info)
Tomas Härdin's avatar
Tomas Härdin committed
544
{
545
    int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
546 547 548 549

    sub_pict->data[0][0] =
            sub_pict->data[0][1] =
            sub_pict->data[0][    sub_pict->linesize[0]] =
550
            sub_pict->data[0][1+  sub_pict->linesize[0]] = info->v1_codebook[v1_vector*entry_size];
Tomas Härdin's avatar
Tomas Härdin committed
551 552 553 554

    sub_pict->data[0][2] =
            sub_pict->data[0][3] =
            sub_pict->data[0][2+  sub_pict->linesize[0]] =
555
            sub_pict->data[0][3+  sub_pict->linesize[0]] = info->v1_codebook[v1_vector*entry_size+1];
Tomas Härdin's avatar
Tomas Härdin committed
556 557 558 559

    sub_pict->data[0][2*sub_pict->linesize[0]] =
            sub_pict->data[0][1+2*sub_pict->linesize[0]] =
            sub_pict->data[0][  3*sub_pict->linesize[0]] =
560
            sub_pict->data[0][1+3*sub_pict->linesize[0]] = info->v1_codebook[v1_vector*entry_size+2];
Tomas Härdin's avatar
Tomas Härdin committed
561 562 563 564

    sub_pict->data[0][2+2*sub_pict->linesize[0]] =
            sub_pict->data[0][3+2*sub_pict->linesize[0]] =
            sub_pict->data[0][2+3*sub_pict->linesize[0]] =
565
            sub_pict->data[0][3+3*sub_pict->linesize[0]] = info->v1_codebook[v1_vector*entry_size+3];
Tomas Härdin's avatar
Tomas Härdin committed
566

567
    if(s->pix_fmt == AV_PIX_FMT_RGB24) {
Tomas Härdin's avatar
Tomas Härdin committed
568 569 570
        sub_pict->data[1][0] =
            sub_pict->data[1][1] =
            sub_pict->data[1][    sub_pict->linesize[1]] =
571
            sub_pict->data[1][1+  sub_pict->linesize[1]] = info->v1_codebook[v1_vector*entry_size+4];
Tomas Härdin's avatar
Tomas Härdin committed
572 573 574 575

        sub_pict->data[2][0] =
            sub_pict->data[2][1] =
            sub_pict->data[2][    sub_pict->linesize[2]] =
576
            sub_pict->data[2][1+  sub_pict->linesize[2]] = info->v1_codebook[v1_vector*entry_size+5];
Tomas Härdin's avatar
Tomas Härdin committed
577 578 579 580 581 582
    }
}

//decodes the V4 vectors in mb into the 4x4 MB pointed to by sub_pict
static void decode_v4_vector(CinepakEncContext *s, AVPicture *sub_pict, int *v4_vector, strip_info *info)
{
583
    int i, x, y, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
584 585 586 587 588 589 590 591

    for(i = y = 0; y < 4; y += 2) {
        for(x = 0; x < 4; x += 2, i++) {
            sub_pict->data[0][x   +     y*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size];
            sub_pict->data[0][x+1 +     y*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+1];
            sub_pict->data[0][x   + (y+1)*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+2];
            sub_pict->data[0][x+1 + (y+1)*sub_pict->linesize[0]] = info->v4_codebook[v4_vector[i]*entry_size+3];

592
            if(s->pix_fmt == AV_PIX_FMT_RGB24) {
Tomas Härdin's avatar
Tomas Härdin committed
593 594 595 596 597 598 599
                sub_pict->data[1][(x>>1) + (y>>1)*sub_pict->linesize[1]] = info->v4_codebook[v4_vector[i]*entry_size+4];
                sub_pict->data[2][(x>>1) + (y>>1)*sub_pict->linesize[2]] = info->v4_codebook[v4_vector[i]*entry_size+5];
            }
        }
    }
}

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
static void copy_mb(CinepakEncContext *s, AVPicture *a, AVPicture *b)
{
    int y, p;

    for(y = 0; y < MB_SIZE; y++) {
        memcpy(a->data[0]+y*a->linesize[0], b->data[0]+y*b->linesize[0],
               MB_SIZE);
    }

    if(s->pix_fmt == AV_PIX_FMT_RGB24) {
        for(p = 1; p <= 2; p++) {
            for(y = 0; y < MB_SIZE/2; y++) {
                memcpy(a->data[p] + y*a->linesize[p],
                       b->data[p] + y*b->linesize[p],
                       MB_SIZE/2);
            }
        }
    }
}

static int encode_mode(CinepakEncContext *s, int h, AVPicture *scratch_pict, AVPicture *last_pict, strip_info *info, unsigned char *buf)
Tomas Härdin's avatar
Tomas Härdin committed
621 622 623 624 625
{
    int x, y, z, flags, bits, temp_size, header_ofs, ret = 0, mb_count = s->w * h / MB_AREA;
    int needs_extra_bit, should_write_temp;
    unsigned char temp[64]; //32/2 = 16 V4 blocks at 4 B each -> 64 B
    mb_info *mb;
626
    AVPicture sub_scratch = {{0}}, sub_last = {{0}};
Tomas Härdin's avatar
Tomas Härdin committed
627 628

    //encode codebooks
629 630 631
////// MacOS vintage decoder compatibility dictates the presence of
////// the codebook chunk even when the codebook is empty - pretty dumb...
////// and also the certain order of the codebook chunks -- rl
632
    if(info->v4_size || !s->skip_empty_cb)
633
        ret += encode_codebook(s, info->v4_codebook, info->v4_size, 0x20, 0x24, buf + ret);
Tomas Härdin's avatar
Tomas Härdin committed
634

635
    if(info->v1_size || !s->skip_empty_cb)
636
        ret += encode_codebook(s, info->v1_codebook, info->v1_size, 0x22, 0x26, buf + ret);
Tomas Härdin's avatar
Tomas Härdin committed
637 638 639 640 641 642 643 644

    //update scratch picture
    for(z = y = 0; y < h; y += MB_SIZE) {
        for(x = 0; x < s->w; x += MB_SIZE, z++) {
            mb = &s->mb[z];

            get_sub_picture(s, x, y, scratch_pict, &sub_scratch);

645 646 647 648 649 650 651
            if(info->mode == MODE_MC && mb->best_encoding == ENC_SKIP) {
                get_sub_picture(s, x, y, last_pict, &sub_last);
                copy_mb(s, &sub_scratch, &sub_last);
            } else if(info->mode == MODE_V1_ONLY || mb->best_encoding == ENC_V1)
                decode_v1_vector(s, &sub_scratch, mb->v1_vector, info);
            else
                decode_v4_vector(s, &sub_scratch, mb->v4_vector, info);
Tomas Härdin's avatar
Tomas Härdin committed
652 653 654
        }
    }

655
    switch(info->mode) {
Tomas Härdin's avatar
Tomas Härdin committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    case MODE_V1_ONLY:
        //av_log(s->avctx, AV_LOG_INFO, "mb_count = %i\n", mb_count);
        ret += write_chunk_header(buf + ret, 0x32, mb_count);

        for(x = 0; x < mb_count; x++)
            buf[ret++] = s->mb[x].v1_vector;

        break;
    case MODE_V1_V4:
        //remember header position
        header_ofs = ret;
        ret += CHUNK_HEADER_SIZE;

        for(x = 0; x < mb_count; x += 32) {
            flags = 0;
            for(y = x; y < FFMIN(x+32, mb_count); y++)
                if(s->mb[y].best_encoding == ENC_V4)
                    flags |= 1 << (31 - y + x);

            AV_WB32(&buf[ret], flags);
            ret += 4;

            for(y = x; y < FFMIN(x+32, mb_count); y++) {
                mb = &s->mb[y];

                if(mb->best_encoding == ENC_V1)
                    buf[ret++] = mb->v1_vector;
                else
                    for(z = 0; z < 4; z++)
685
                        buf[ret++] = mb->v4_vector[z];
Tomas Härdin's avatar
Tomas Härdin committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
            }
        }

        write_chunk_header(buf + header_ofs, 0x30, ret - header_ofs - CHUNK_HEADER_SIZE);

        break;
    case MODE_MC:
        //remember header position
        header_ofs = ret;
        ret += CHUNK_HEADER_SIZE;
        flags = bits = temp_size = 0;

        for(x = 0; x < mb_count; x++) {
            mb = &s->mb[x];
            flags |= (mb->best_encoding != ENC_SKIP) << (31 - bits++);
            needs_extra_bit = 0;
            should_write_temp = 0;

            if(mb->best_encoding != ENC_SKIP) {
                if(bits < 32)
                    flags |= (mb->best_encoding == ENC_V4) << (31 - bits++);
                else
                    needs_extra_bit = 1;
            }

            if(bits == 32) {
                AV_WB32(&buf[ret], flags);
                ret += 4;
                flags = bits = 0;

                if(mb->best_encoding == ENC_SKIP || needs_extra_bit) {
                    memcpy(&buf[ret], temp, temp_size);
                    ret += temp_size;
                    temp_size = 0;
                } else
                    should_write_temp = 1;
            }

            if(needs_extra_bit) {
                flags = (mb->best_encoding == ENC_V4) << 31;
                bits = 1;
            }

            if(mb->best_encoding == ENC_V1)
                temp[temp_size++] = mb->v1_vector;
            else if(mb->best_encoding == ENC_V4)
                for(z = 0; z < 4; z++)
733
                    temp[temp_size++] = mb->v4_vector[z];
Tomas Härdin's avatar
Tomas Härdin committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

            if(should_write_temp) {
                memcpy(&buf[ret], temp, temp_size);
                ret += temp_size;
                temp_size = 0;
            }
        }

        if(bits > 0) {
            AV_WB32(&buf[ret], flags);
            ret += 4;
            memcpy(&buf[ret], temp, temp_size);
            ret += temp_size;
        }

        write_chunk_header(buf + header_ofs, 0x31, ret - header_ofs - CHUNK_HEADER_SIZE);

        break;
    }

    return ret;
}

//computes distortion of 4x4 MB in b compared to a
static int compute_mb_distortion(CinepakEncContext *s, AVPicture *a, AVPicture *b)
{
    int x, y, p, d, ret = 0;

    for(y = 0; y < MB_SIZE; y++) {
        for(x = 0; x < MB_SIZE; x++) {
            d = a->data[0][x + y*a->linesize[0]] - b->data[0][x + y*b->linesize[0]];
            ret += d*d;
        }
    }

769
    if(s->pix_fmt == AV_PIX_FMT_RGB24) {
Tomas Härdin's avatar
Tomas Härdin committed
770 771 772 773 774 775 776 777 778 779 780 781 782
        for(p = 1; p <= 2; p++) {
            for(y = 0; y < MB_SIZE/2; y++) {
                for(x = 0; x < MB_SIZE/2; x++) {
                    d = a->data[p][x + y*a->linesize[p]] - b->data[p][x + y*b->linesize[p]];
                    ret += d*d;
                }
            }
        }
    }

    return ret;
}

783 784 785 786 787
// return the possibly adjusted size of the codebook
#define CERTAIN(x) ((x)!=ENC_UNCERTAIN)
static int quantize(CinepakEncContext *s, int h, AVPicture *pict,
                    int v1mode, strip_info *info,
                    mb_encoding encoding)
Tomas Härdin's avatar
Tomas Härdin committed
788
{
789 790
    int x, y, i, j, k, x2, y2, x3, y3, plane, shift, mbn;
    int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
791
    int *codebook = v1mode ? info->v1_codebook : info->v4_codebook;
792
    int size = v1mode ? info->v1_size : info->v4_size;
Tomas Härdin's avatar
Tomas Härdin committed
793 794 795 796
    int64_t total_error = 0;
    uint8_t vq_pict_buf[(MB_AREA*3)/2];
    AVPicture sub_pict, vq_pict;

797 798 799
    for(mbn = i = y = 0; y < h; y += MB_SIZE) {
        for(x = 0; x < s->w; x += MB_SIZE, ++mbn) {
            int *base;
Tomas Härdin's avatar
Tomas Härdin committed
800

801 802 803 804 805 806
            if(CERTAIN(encoding)) {
// use for the training only the blocks known to be to be encoded [sic:-]
               if(s->mb[mbn].best_encoding != encoding) continue;
            }

            base = s->codebook_input + i*entry_size;
Tomas Härdin's avatar
Tomas Härdin committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
            if(v1mode) {
                //subsample
                for(j = y2 = 0; y2 < entry_size; y2 += 2) {
                    for(x2 = 0; x2 < 4; x2 += 2, j++) {
                        plane = y2 < 4 ? 0 : 1 + (x2 >> 1);
                        shift = y2 < 4 ? 0 : 1;
                        x3 = shift ? 0 : x2;
                        y3 = shift ? 0 : y2;
                        base[j] = (pict->data[plane][((x+x3) >> shift) +      ((y+y3) >> shift)      * pict->linesize[plane]] +
                                   pict->data[plane][((x+x3) >> shift) + 1 +  ((y+y3) >> shift)      * pict->linesize[plane]] +
                                   pict->data[plane][((x+x3) >> shift) +     (((y+y3) >> shift) + 1) * pict->linesize[plane]] +
                                   pict->data[plane][((x+x3) >> shift) + 1 + (((y+y3) >> shift) + 1) * pict->linesize[plane]]) >> 2;
                    }
                }
            } else {
                //copy
                for(j = y2 = 0; y2 < MB_SIZE; y2 += 2) {
                    for(x2 = 0; x2 < MB_SIZE; x2 += 2) {
                        for(k = 0; k < entry_size; k++, j++) {
                            plane = k >= 4 ? k - 3 : 0;

                            if(k >= 4) {
                                x3 = (x+x2) >> 1;
                                y3 = (y+y2) >> 1;
                            } else {
                                x3 = x + x2 + (k & 1);
                                y3 = y + y2 + (k >> 1);
                            }

                            base[j] = pict->data[plane][x3 + y3*pict->linesize[plane]];
                        }
                    }
                }
            }
841
            i += v1mode ? 1 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
842 843
        }
    }
844 845 846 847 848 849 850 851 852 853
//    if(i < mbn*(v1mode ? 1 : 4)) {
//        av_log(s->avctx, AV_LOG_INFO, "reducing training set for %s from %i to %i (encoding %i)\n", v1mode?"v1":"v4", mbn*(v1mode ? 1 : 4), i, encoding);
//    }

    if(i == 0) // empty training set, nothing to do
        return 0;
    if(i < size) {
        //av_log(s->avctx, (CERTAIN(encoding) ? AV_LOG_ERROR : AV_LOG_INFO), "WOULD WASTE: %s cbsize %i bigger than training set size %i (encoding %i)\n", v1mode?"v1":"v4", size, i, encoding);
        size = i;
    }
Tomas Härdin's avatar
Tomas Härdin committed
854

855 856
    avpriv_init_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
    avpriv_do_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
Tomas Härdin's avatar
Tomas Härdin committed
857 858 859 860 861 862 863 864 865 866

    //setup vq_pict, which contains a single MB
    vq_pict.data[0] = vq_pict_buf;
    vq_pict.linesize[0] = MB_SIZE;
    vq_pict.data[1] = &vq_pict_buf[MB_AREA];
    vq_pict.data[2] = vq_pict.data[1] + (MB_AREA >> 2);
    vq_pict.linesize[1] = vq_pict.linesize[2] = MB_SIZE >> 1;

    //copy indices
    for(i = j = y = 0; y < h; y += MB_SIZE) {
867
        for(x = 0; x < s->w; x += MB_SIZE, j++) {
Tomas Härdin's avatar
Tomas Härdin committed
868
            mb_info *mb = &s->mb[j];
869 870 871
// skip uninteresting blocks if we know their preferred encoding
            if(CERTAIN(encoding) && mb->best_encoding != encoding)
                continue;
Tomas Härdin's avatar
Tomas Härdin committed
872 873 874 875 876 877 878 879

            //point sub_pict to current MB
            get_sub_picture(s, x, y, pict, &sub_pict);

            if(v1mode) {
                mb->v1_vector = s->codebook_closest[i];

                //fill in vq_pict with V1 data
880
                decode_v1_vector(s, &vq_pict, mb->v1_vector, info);
Tomas Härdin's avatar
Tomas Härdin committed
881 882 883 884 885

                mb->v1_error = compute_mb_distortion(s, &sub_pict, &vq_pict);
                total_error += mb->v1_error;
            } else {
                for(k = 0; k < 4; k++)
886
                    mb->v4_vector[k] = s->codebook_closest[i+k];
Tomas Härdin's avatar
Tomas Härdin committed
887 888

                //fill in vq_pict with V4 data
889
                decode_v4_vector(s, &vq_pict, mb->v4_vector, info);
Tomas Härdin's avatar
Tomas Härdin committed
890

891 892
                mb->v4_error = compute_mb_distortion(s, &sub_pict, &vq_pict);
                total_error += mb->v4_error;
Tomas Härdin's avatar
Tomas Härdin committed
893
            }
894
            i += v1mode ? 1 : 4;
Tomas Härdin's avatar
Tomas Härdin committed
895 896
        }
    }
897 898
// check that we did it right in the beginning of the function
    av_assert0(i >= size); // training set is no smaller than the codebook
Tomas Härdin's avatar
Tomas Härdin committed
899

900
    //av_log(s->avctx, AV_LOG_INFO, "isv1 %i size= %i i= %i error %"PRId64"\n", v1mode, size, i, total_error);
Tomas Härdin's avatar
Tomas Härdin committed
901

902
    return size;
Tomas Härdin's avatar
Tomas Härdin committed
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
}

static void calculate_skip_errors(CinepakEncContext *s, int h, AVPicture *last_pict, AVPicture *pict, strip_info *info)
{
    int x, y, i;
    AVPicture sub_last, sub_pict;

    for(i = y = 0; y < h; y += MB_SIZE) {
        for(x = 0; x < s->w; x += MB_SIZE, i++) {
            get_sub_picture(s, x, y, last_pict, &sub_last);
            get_sub_picture(s, x, y, pict,      &sub_pict);

            s->mb[i].skip_error = compute_mb_distortion(s, &sub_last, &sub_pict);
        }
    }
}

static void write_strip_header(CinepakEncContext *s, int y, int h, int keyframe, unsigned char *buf, int strip_size)
{
922 923 924 925 926 927
// actually we are exclusively using intra strip coding (how much can we win
// otherwise? how to choose which part of a codebook to update?),
// keyframes are different only because we disallow ENC_SKIP on them -- rl
// (besides, the logic here used to be inverted: )
//    buf[0] = keyframe ? 0x11: 0x10;
    buf[0] = keyframe ? 0x10: 0x11;
Tomas Härdin's avatar
Tomas Härdin committed
928
    AV_WB24(&buf[1], strip_size + STRIP_HEADER_SIZE);
929 930
//    AV_WB16(&buf[4], y); /* using absolute y values works -- rl */
    AV_WB16(&buf[4], 0); /* using relative values works as well -- rl */
Tomas Härdin's avatar
Tomas Härdin committed
931
    AV_WB16(&buf[6], 0);
932 933
//    AV_WB16(&buf[8], y+h); /* using absolute y values works -- rl */
    AV_WB16(&buf[8], h); /* using relative values works as well -- rl */
Tomas Härdin's avatar
Tomas Härdin committed
934
    AV_WB16(&buf[10], s->w);
935
    //av_log(s->avctx, AV_LOG_INFO, "write_strip_header() %x keyframe=%d\n", buf[0], keyframe);
Tomas Härdin's avatar
Tomas Härdin committed
936 937
}

938 939 940 941 942
static int rd_strip(CinepakEncContext *s, int y, int h, int keyframe, AVPicture *last_pict, AVPicture *pict, AVPicture *scratch_pict, unsigned char *buf, int64_t *best_score
#ifdef CINEPAK_REPORT_SERR
, int64_t *best_serr
#endif
)
Tomas Härdin's avatar
Tomas Härdin committed
943 944
{
    int64_t score = 0;
945 946 947 948
#ifdef CINEPAK_REPORT_SERR
    int64_t serr;
#endif
    int best_size = 0;
Tomas Härdin's avatar
Tomas Härdin committed
949
    strip_info info;
950 951 952 953
// for codebook optimization:
    int v1enough, v1_size, v4enough, v4_size;
    int new_v1_size, new_v4_size;
    int v1shrunk, v4shrunk;
Tomas Härdin's avatar
Tomas Härdin committed
954 955 956 957

    if(!keyframe)
        calculate_skip_errors(s, h, last_pict, pict, &info);

958 959 960 961 962 963 964
    //try some powers of 4 for the size of the codebooks
    //constraint the v4 codebook to be no bigger than v1 one,
    //(and no less than v1_size/4)
    //thus making v1 preferable and possibly losing small details? should be ok
#define SMALLEST_CODEBOOK 1
    for(v1enough = 0, v1_size = SMALLEST_CODEBOOK; v1_size <= CODEBOOK_MAX && !v1enough; v1_size <<= 2) {
        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) {
Tomas Härdin's avatar
Tomas Härdin committed
965 966
            //try all modes
            for(CinepakMode mode = 0; mode < MODE_COUNT; mode++) {
967
                //don't allow MODE_MC in intra frames
Tomas Härdin's avatar
Tomas Härdin committed
968 969 970
                if(keyframe && mode == MODE_MC)
                    continue;

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
                if(mode == MODE_V1_ONLY) {
                    info.v1_size = v1_size;
// the size may shrink even before optimizations if the input is short:
                    info.v1_size = quantize(s, h, pict, 1, &info, ENC_UNCERTAIN);
                    if(info.v1_size < v1_size)
// too few eligible blocks, no sense in trying bigger sizes
                        v1enough = 1;

                    info.v4_size = 0;
                } else { // mode != MODE_V1_ONLY
                    // if v4 codebook is empty then only allow V1-only mode
                    if(!v4_size)
                        continue;

                    if(mode == MODE_V1_V4) {
                        info.v4_size = v4_size;
                        info.v4_size = quantize(s, h, pict, 0, &info, ENC_UNCERTAIN);
                        if(info.v4_size < v4_size)
// too few eligible blocks, no sense in trying bigger sizes
                            v4enough = 1;
                    }
                }
Tomas Härdin's avatar
Tomas Härdin committed
993

994 995 996 997 998 999 1000 1001 1002 1003
                info.mode = mode;
// choose the best encoding per block, based on current experience
                score = calculate_mode_score(s, h, &info, 0,
                                             &v1shrunk, &v4shrunk
#ifdef CINEPAK_REPORT_SERR
, &serr
#endif
);

                if(mode != MODE_V1_ONLY){
1004
                    int extra_iterations_limit = s->max_extra_cb_iterations;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
// recompute the codebooks, omitting the extra blocks
// we assume we _may_ come here with more blocks to encode than before
                    info.v1_size = v1_size;
                    new_v1_size = quantize(s, h, pict, 1, &info, ENC_V1);
                    if(new_v1_size < info.v1_size){
                        //av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: cut v1 codebook to %i entries\n", mode, v1_size, v4_size, new_v1_size);
                        info.v1_size = new_v1_size;
                    }
// we assume we _may_ come here with more blocks to encode than before
                    info.v4_size = v4_size;
                    new_v4_size = quantize(s, h, pict, 0, &info, ENC_V4);
                    if(new_v4_size < info.v4_size) {
                        //av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: cut v4 codebook to %i entries at first iteration\n", mode, v1_size, v4_size, new_v4_size);
                        info.v4_size = new_v4_size;
                    }
// calculate the resulting score
// (do not move blocks to codebook encodings now, as some blocks may have
// got bigger errors despite a smaller training set - but we do not
// ever grow the training sets back)
                    for(;;) {
                        score = calculate_mode_score(s, h, &info, 1,
                                                     &v1shrunk, &v4shrunk
#ifdef CINEPAK_REPORT_SERR
, &serr
#endif
);
1031 1032
// do we have a reason to reiterate? if so, have we reached the limit?
                        if((!v1shrunk && !v4shrunk) || !extra_iterations_limit--) break;
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
// recompute the codebooks, omitting the extra blocks
                        if(v1shrunk) {
                            info.v1_size = v1_size;
                            new_v1_size = quantize(s, h, pict, 1, &info, ENC_V1);
                            if(new_v1_size < info.v1_size){
                                //av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: cut v1 codebook to %i entries\n", mode, v1_size, v4_size, new_v1_size);
                                info.v1_size = new_v1_size;
                            }
                        }
                        if(v4shrunk) {
                            info.v4_size = v4_size;
                            new_v4_size = quantize(s, h, pict, 0, &info, ENC_V4);
                            if(new_v4_size < info.v4_size) {
                                //av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: cut v4 codebook to %i entries\n", mode, v1_size, v4_size, new_v4_size);
                                info.v4_size = new_v4_size;
                            }
                        }
                    }
                }
Tomas Härdin's avatar
Tomas Härdin committed
1052

1053
                //av_log(s->avctx, AV_LOG_INFO, "%3i %3i score = %"PRId64"\n", v1_size, v4_size, score);
Tomas Härdin's avatar
Tomas Härdin committed
1054 1055

                if(best_size == 0 || score < *best_score) {
1056

Tomas Härdin's avatar
Tomas Härdin committed
1057
                    *best_score = score;
1058 1059 1060 1061
#ifdef CINEPAK_REPORT_SERR
                    *best_serr = serr;
#endif
                    best_size = encode_mode(s, h, scratch_pict, last_pict, &info, s->strip_buf + STRIP_HEADER_SIZE);
Tomas Härdin's avatar
Tomas Härdin committed
1062

1063
                    //av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: %18"PRId64" %i B", mode, info.v1_size, info.v4_size, score, best_size);
1064 1065
                    //av_log(s->avctx, AV_LOG_INFO, "\n");
#ifdef CINEPAK_REPORT_SERR
1066
                    av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: %18"PRId64" %i B\n", mode, v1_size, v4_size, serr, best_size);
1067
#endif
Tomas Härdin's avatar
Tomas Härdin committed
1068 1069 1070 1071 1072 1073 1074 1075

#ifdef CINEPAKENC_DEBUG
                    //save MB encoding choices
                    memcpy(s->best_mb, s->mb, mb_count*sizeof(mb_info));
#endif

                    //memcpy(strip_temp + STRIP_HEADER_SIZE, strip_temp, best_size);
                    write_strip_header(s, y, h, keyframe, s->strip_buf, best_size);
1076

Tomas Härdin's avatar
Tomas Härdin committed
1077 1078 1079 1080 1081 1082 1083
                }
            }
        }
    }

#ifdef CINEPAKENC_DEBUG
    //gather stats. this will only work properly of MAX_STRIPS == 1
1084
    if(best_info.mode == MODE_V1_ONLY) {
Tomas Härdin's avatar
Tomas Härdin committed
1085 1086 1087
        s->num_v1_mode++;
        s->num_v1_encs += s->w*h/MB_AREA;
    } else {
1088
        if(best_info.mode == MODE_V1_V4)
Tomas Härdin's avatar
Tomas Härdin committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
            s->num_v4_mode++;
        else
            s->num_mc_mode++;

        int x;
        for(x = 0; x < s->w*h/MB_AREA; x++)
            if(s->best_mb[x].best_encoding == ENC_V1)
                s->num_v1_encs++;
            else if(s->best_mb[x].best_encoding == ENC_V4)
                s->num_v4_encs++;
            else
                s->num_skips++;
    }
#endif

    best_size += STRIP_HEADER_SIZE;
    memcpy(buf, s->strip_buf, best_size);

    return best_size;
}

1110
static int write_cvid_header(CinepakEncContext *s, unsigned char *buf, int num_strips, int data_size, int isakeyframe)
Tomas Härdin's avatar
Tomas Härdin committed
1111
{
1112
    buf[0] = isakeyframe ? 0 : 1;
Tomas Härdin's avatar
Tomas Härdin committed
1113 1114 1115 1116 1117 1118 1119 1120
    AV_WB24(&buf[1], data_size + CVID_HEADER_SIZE);
    AV_WB16(&buf[4], s->w);
    AV_WB16(&buf[6], s->h);
    AV_WB16(&buf[8], num_strips);

    return CVID_HEADER_SIZE;
}

1121
static int rd_frame(CinepakEncContext *s, const AVFrame *frame, int isakeyframe, unsigned char *buf, int buf_size)
Tomas Härdin's avatar
Tomas Härdin committed
1122
{
1123
    int num_strips, strip, i, y, nexty, size, temp_size;
Tomas Härdin's avatar
Tomas Härdin committed
1124 1125
    AVPicture last_pict, pict, scratch_pict;
    int64_t best_score = 0, score, score_temp;
1126 1127 1128
#ifdef CINEPAK_REPORT_SERR
    int64_t best_serr = 0, serr, serr_temp;
#endif
Tomas Härdin's avatar
Tomas Härdin committed
1129

1130
    int best_nstrips = -1, best_size = -1; // mark as uninitialzed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

    if(s->pix_fmt == AV_PIX_FMT_RGB24) {
        int x;
// build a copy of the given frame in the correct colorspace
        for(y = 0; y < s->h; y += 2) {
            for(x = 0; x < s->w; x += 2) {
                uint8_t *ir[2]; int32_t r, g, b, rr, gg, bb;
                ir[0] = ((AVPicture*)frame)->data[0] + x*3 + y*((AVPicture*)frame)->linesize[0];
                ir[1] = ir[0] + ((AVPicture*)frame)->linesize[0];
                get_sub_picture(s, x, y, (AVPicture*)s->input_frame, &scratch_pict);
                r = g = b = 0;
                for(i=0; i<4; ++i) {
                    int i1, i2;
                    i1 = (i&1); i2 = (i>=2);
                    rr = ir[i2][i1*3+0];
                    gg = ir[i2][i1*3+1];
                    bb = ir[i2][i1*3+2];
                    r += rr; g += gg; b += bb;
// using fixed point arithmetic for portable repeatability, scaling by 2^23
// "Y"
//                    rr = 0.2857*rr + 0.5714*gg + 0.1429*bb;
                    rr = (2396625*rr + 4793251*gg + 1198732*bb) >> 23;
                    if(      rr <   0) rr =   0;
                    else if (rr > 255) rr = 255;
                    scratch_pict.data[0][i1 + i2*scratch_pict.linesize[0]] = rr;
                }
// let us scale down as late as possible
//                r /= 4; g /= 4; b /= 4;
// "U"
//                rr = -0.1429*r - 0.2857*g + 0.4286*b;
                rr = (-299683*r - 599156*g + 898839*b) >> 23;
                if(      rr < -128) rr = -128;
                else if (rr >  127) rr =  127;
                scratch_pict.data[1][0] = rr + 128; // quantize needs unsigned
// "V"
//                rr = 0.3571*r - 0.2857*g - 0.0714*b;
                rr = (748893*r - 599156*g - 149737*b) >> 23;
                if(      rr < -128) rr = -128;
                else if (rr >  127) rr =  127;
                scratch_pict.data[2][0] = rr + 128; // quantize needs unsigned
            }
        }
    }

    //would be nice but quite certainly incompatible with vintage players:
    // support encoding zero strips (meaning skip the whole frame)
    for(num_strips = s->min_strips; num_strips <= s->max_strips && num_strips <= s->h / MB_SIZE; num_strips++) {
Tomas Härdin's avatar
Tomas Härdin committed
1178 1179
        score = 0;
        size = 0;
1180 1181 1182 1183 1184 1185
#ifdef CINEPAK_REPORT_SERR
        serr = 0;
#endif

        for(y = 0, strip = 1; y < s->h; strip++, y = nexty) {
            int strip_height;
Tomas Härdin's avatar
Tomas Härdin committed
1186

1187 1188 1189 1190
            nexty = strip * s->h / num_strips; // <= s->h
            //make nexty the next multiple of 4 if not already there
            if(nexty & 3)
                nexty += 4 - (nexty & 3);
Tomas Härdin's avatar
Tomas Härdin committed
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
            strip_height = nexty - y;
            if(strip_height <= 0) { // can this ever happen?
                av_log(s->avctx, AV_LOG_INFO, "skipping zero height strip %i of %i\n", strip, num_strips);
                continue;
            }

            if(s->pix_fmt == AV_PIX_FMT_RGB24)
                get_sub_picture(s, 0, y, (AVPicture*)s->input_frame,    &pict);
            else
                get_sub_picture(s, 0, y, (AVPicture*)frame,              &pict);
            get_sub_picture(s, 0, y, (AVPicture*)s->last_frame,    &last_pict);
            get_sub_picture(s, 0, y, (AVPicture*)s->scratch_frame, &scratch_pict);
Tomas Härdin's avatar
Tomas Härdin committed
1204

1205 1206 1207 1208 1209
            if((temp_size = rd_strip(s, y, strip_height, isakeyframe, &last_pict, &pict, &scratch_pict, s->frame_buf + size + CVID_HEADER_SIZE, &score_temp
#ifdef CINEPAK_REPORT_SERR
, &serr_temp
#endif
)) < 0)
Tomas Härdin's avatar
Tomas Härdin committed
1210 1211 1212
                return temp_size;

            score += score_temp;
1213 1214 1215
#ifdef CINEPAK_REPORT_SERR
            serr += serr_temp;
#endif
Tomas Härdin's avatar
Tomas Härdin committed
1216
            size += temp_size;
1217 1218
            //av_log(s->avctx, AV_LOG_INFO, "strip %d, isakeyframe=%d", strip, isakeyframe);
            //av_log(s->avctx, AV_LOG_INFO, "\n");
Tomas Härdin's avatar
Tomas Härdin committed
1219 1220 1221 1222
        }

        if(best_score == 0 || score < best_score) {
            best_score = score;
1223 1224 1225 1226
#ifdef CINEPAK_REPORT_SERR
            best_serr = serr;
#endif
            best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size, isakeyframe);
1227
            //av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12"PRId64", %i B\n", num_strips, score, best_size);
1228
#ifdef CINEPAK_REPORT_SERR
1229
            av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12"PRId64", %i B\n", num_strips, serr, best_size);
1230
#endif
Tomas Härdin's avatar
Tomas Härdin committed
1231

1232 1233 1234
            FFSWAP(AVFrame *, s->best_frame, s->scratch_frame);
            memcpy(buf, s->frame_buf, best_size);
            best_nstrips = num_strips;
Tomas Härdin's avatar
Tomas Härdin committed
1235
        }
1236 1237 1238 1239
// avoid trying too many strip numbers without a real reason
// (this makes the processing of the very first frame faster)
        if(num_strips - best_nstrips > 4)
            break;
Tomas Härdin's avatar
Tomas Härdin committed
1240 1241
    }

1242 1243
    av_assert0(best_nstrips >= 0 && best_size >= 0);

1244 1245 1246
// let the number of strips slowly adapt to the changes in the contents,
// compared to full bruteforcing every time this will occasionally lead
// to some r/d performance loss but makes encoding up to several times faster
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    if(!s->strip_number_delta_range) {
        if(best_nstrips == s->max_strips) { // let us try to step up
            s->max_strips = best_nstrips + 1;
            if(s->max_strips >= s->max_max_strips)
                s->max_strips = s->max_max_strips;
        } else { // try to step down
            s->max_strips = best_nstrips;
        }
        s->min_strips = s->max_strips - 1;
        if(s->min_strips < s->min_min_strips)
            s->min_strips = s->min_min_strips;
    } else {
        s->max_strips = best_nstrips + s->strip_number_delta_range;
        if(s->max_strips >= s->max_max_strips)
            s->max_strips = s->max_max_strips;
        s->min_strips = best_nstrips - s->strip_number_delta_range;
        if(s->min_strips < s->min_min_strips)
            s->min_strips = s->min_min_strips;
1265
    }
Tomas Härdin's avatar
Tomas Härdin committed
1266 1267 1268 1269

    return best_size;
}

1270 1271
static int cinepak_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *frame, int *got_packet)
Tomas Härdin's avatar
Tomas Härdin committed
1272 1273 1274 1275 1276 1277
{
    CinepakEncContext *s = avctx->priv_data;
    int ret;

    s->lambda = frame->quality ? frame->quality - 1 : 2 * FF_LAMBDA_SCALE;

1278
    if ((ret = ff_alloc_packet2(avctx, pkt, s->frame_buf_size, 0)) < 0)
1279 1280 1281 1282 1283 1284
        return ret;
    ret = rd_frame(s, frame, (s->curframe == 0), pkt->data, s->frame_buf_size);
    pkt->size = ret;
    if (s->curframe == 0)
        pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
Tomas Härdin's avatar
Tomas Härdin committed
1285

1286
    FFSWAP(AVFrame *, s->last_frame, s->best_frame);
Tomas Härdin's avatar
Tomas Härdin committed
1287 1288 1289 1290

    if (++s->curframe >= s->keyint)
        s->curframe = 0;

1291
    return 0;
Tomas Härdin's avatar
Tomas Härdin committed
1292 1293 1294 1295 1296 1297 1298
}

static av_cold int cinepak_encode_end(AVCodecContext *avctx)
{
    CinepakEncContext *s = avctx->priv_data;
    int x;

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    av_frame_free(&s->last_frame);
    av_frame_free(&s->best_frame);
    av_frame_free(&s->scratch_frame);
    if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
        av_frame_free(&s->input_frame);
    av_freep(&s->codebook_input);
    av_freep(&s->codebook_closest);
    av_freep(&s->strip_buf);
    av_freep(&s->frame_buf);
    av_freep(&s->mb);
Tomas Härdin's avatar
Tomas Härdin committed
1309
#ifdef CINEPAKENC_DEBUG
1310
    av_freep(&s->best_mb);
Tomas Härdin's avatar
Tomas Härdin committed
1311 1312
#endif

1313 1314
    for(x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
        av_freep(&s->pict_bufs[x]);
Tomas Härdin's avatar
Tomas Härdin committed
1315

1316
#ifdef CINEPAKENC_DEBUG
Tomas Härdin's avatar
Tomas Härdin committed
1317 1318
    av_log(avctx, AV_LOG_INFO, "strip coding stats: %i V1 mode, %i V4 mode, %i MC mode (%i V1 encs, %i V4 encs, %i skips)\n",
        s->num_v1_mode, s->num_v4_mode, s->num_mc_mode, s->num_v1_encs, s->num_v4_encs, s->num_skips);
1319
#endif
Tomas Härdin's avatar
Tomas Härdin committed
1320 1321 1322 1323 1324

    return 0;
}

AVCodec ff_cinepak_encoder = {
1325 1326 1327 1328 1329 1330 1331 1332 1333
    .name           = "cinepak",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_CINEPAK,
    .priv_data_size = sizeof(CinepakEncContext),
    .init           = cinepak_encode_init,
    .encode2        = cinepak_encode_frame,
    .close          = cinepak_encode_end,
    .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_RGB24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE},
    .long_name      = NULL_IF_CONFIG_SMALL("Cinepak / CVID"),
1334
    .priv_class     = &cinepak_class,
Tomas Härdin's avatar
Tomas Härdin committed
1335
};