dnxhdenc.c 39.4 KB
Newer Older
1 2 3
/*
 * VC3/DNxHD encoder
 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4
 * Copyright (c) 2011 MirriAd Ltd
5 6
 *
 * VC-3 encoder funded by the British Broadcasting Corporation
7
 * 10 bit support added by MirriAd Ltd, Joseph Artsimovich <joseph@mirriad.com>
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

26
#include "libavutil/attributes.h"
27
#include "libavutil/internal.h"
28
#include "libavutil/opt.h"
29
#include "libavutil/timer.h"
30

31 32
#include "avcodec.h"
#include "dsputil.h"
33
#include "internal.h"
34
#include "mpegvideo.h"
35
#include "dnxhdenc.h"
36

37

38 39 40 41
// The largest value that will not lead to overflow for 10bit samples.
#define DNX10BIT_QMAT_SHIFT 18
#define RC_VARIANCE 1 // use variance or ssd for fast rc
#define LAMBDA_FRAC_BITS 10
42

43 44 45 46 47
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
    { "nitris_compat", "encode with Avid Nitris compatibility",
        offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
    { NULL }
48
};
49

50
static const AVClass dnxhd_class = {
51 52 53 54 55
    .class_name = "dnxhd",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};
56

57
static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block,
58
                                          const uint8_t *pixels,
59
                                          ptrdiff_t line_size)
60 61 62
{
    int i;
    for (i = 0; i < 4; i++) {
63 64 65 66 67 68 69 70 71 72
        block[0] = pixels[0];
        block[1] = pixels[1];
        block[2] = pixels[2];
        block[3] = pixels[3];
        block[4] = pixels[4];
        block[5] = pixels[5];
        block[6] = pixels[6];
        block[7] = pixels[7];
        pixels  += line_size;
        block   += 8;
73
    }
74 75 76 77
    memcpy(block,      block -  8, sizeof(*block) * 8);
    memcpy(block +  8, block - 16, sizeof(*block) * 8);
    memcpy(block + 16, block - 24, sizeof(*block) * 8);
    memcpy(block + 24, block - 32, sizeof(*block) * 8);
78 79
}

80
static av_always_inline
81
void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block,
82
                                    const uint8_t *pixels,
83
                                    ptrdiff_t line_size)
84 85
{
    int i;
86
    const uint16_t* pixels16 = (const uint16_t*)pixels;
87
    line_size >>= 1;
88 89

    for (i = 0; i < 4; i++) {
90 91 92 93 94 95
        block[0] = pixels16[0]; block[1] = pixels16[1];
        block[2] = pixels16[2]; block[3] = pixels16[3];
        block[4] = pixels16[4]; block[5] = pixels16[5];
        block[6] = pixels16[6]; block[7] = pixels16[7];
        pixels16 += line_size;
        block += 8;
96
    }
97 98 99 100
    memcpy(block,      block -  8, sizeof(*block) * 8);
    memcpy(block +  8, block - 16, sizeof(*block) * 8);
    memcpy(block + 16, block - 24, sizeof(*block) * 8);
    memcpy(block + 24, block - 32, sizeof(*block) * 8);
101 102
}

Diego Biurrun's avatar
Diego Biurrun committed
103
static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
104 105 106
                                    int n, int qscale, int *overflow)
{
    const uint8_t *scantable= ctx->intra_scantable.scantable;
107
    const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
108
    int last_non_zero = 0;
109
    int i;
110 111 112 113 114 115

    ctx->dsp.fdct(block);

    // Divide by 4 with rounding, to compensate scaling of DCT coefficients
    block[0] = (block[0] + 2) >> 2;

116
    for (i = 1; i < 64; ++i) {
117 118 119 120 121 122 123 124 125 126 127 128
        int j = scantable[i];
        int sign = block[j] >> 31;
        int level = (block[j] ^ sign) - sign;
        level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
        block[j] = (level ^ sign) - sign;
        if (level)
            last_non_zero = i;
    }

    return last_non_zero;
}

129
static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
130
{
131
    int i, j, level, run;
132 133 134 135 136 137 138 139 140 141 142 143 144
    int max_level = 1 << (ctx->cid_table->bit_depth + 2);

    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes,
                      max_level * 4 * sizeof(*ctx->vlc_codes), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits,
                      max_level * 4 * sizeof(*ctx->vlc_bits), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes,
                      63 * 2, fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits,
                      63, fail);

    ctx->vlc_codes += max_level * 2;
    ctx->vlc_bits  += max_level * 2;
145 146
    for (level = -max_level; level < max_level; level++) {
        for (run = 0; run < 2; run++) {
147
            int index = (level << 1) | run;
148 149 150 151
            int sign, offset = 0, alevel = level;

            MASK_ABS(sign, alevel);
            if (alevel > 64) {
152 153
                offset  = (alevel - 1) >> 6;
                alevel -= offset << 6;
154 155
            }
            for (j = 0; j < 257; j++) {
156
                if (ctx->cid_table->ac_level[j] >> 1 == alevel &&
157 158
                    (!offset || (ctx->cid_table->ac_flags[j] & 1) && offset) &&
                    (!run    || (ctx->cid_table->ac_flags[j] & 2) && run)) {
159
                    av_assert1(!ctx->vlc_codes[index]);
160
                    if (alevel) {
161 162 163
                        ctx->vlc_codes[index] =
                            (ctx->cid_table->ac_codes[j] << 1) | (sign & 1);
                        ctx->vlc_bits[index] = ctx->cid_table->ac_bits[j] + 1;
164
                    } else {
165
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
166
                        ctx->vlc_bits[index]  = ctx->cid_table->ac_bits[j];
167 168 169 170
                    }
                    break;
                }
            }
171
            av_assert0(!alevel || j < 257);
172
            if (offset) {
173 174 175
                ctx->vlc_codes[index] =
                    (ctx->vlc_codes[index] << ctx->cid_table->index_bits) | offset;
                ctx->vlc_bits[index] += ctx->cid_table->index_bits;
176 177
            }
        }
178 179 180
    }
    for (i = 0; i < 62; i++) {
        int run = ctx->cid_table->run[i];
181
        av_assert0(run < 63);
182
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
183
        ctx->run_bits[run]  = ctx->cid_table->run_bits[i];
184 185
    }
    return 0;
186
fail:
187
    return AVERROR(ENOMEM);
188 189
}

190
static av_cold int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
191 192
{
    // init first elem to 1 to avoid div by 0 in convert_matrix
193
    uint16_t weight_matrix[64] = { 1, }; // convert_matrix needs uint16_t*
194
    int qscale, i;
195 196
    const uint8_t *luma_weight_table   = ctx->cid_table->luma_weight;
    const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
197

198 199 200 201 202 203 204 205 206 207
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l,
                      (ctx->m.avctx->qmax + 1) * 64 * sizeof(int), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c,
                      (ctx->m.avctx->qmax + 1) * 64 * sizeof(int), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16,
                      (ctx->m.avctx->qmax + 1) * 64 * 2 * sizeof(uint16_t),
                      fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16,
                      (ctx->m.avctx->qmax + 1) * 64 * 2 * sizeof(uint16_t),
                      fail);
208

209 210 211 212 213
    if (ctx->cid_table->bit_depth == 8) {
        for (i = 1; i < 64; i++) {
            int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
            weight_matrix[j] = ctx->cid_table->luma_weight[i];
        }
214 215 216
        ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16,
                          weight_matrix, ctx->m.intra_quant_bias, 1,
                          ctx->m.avctx->qmax, 1);
217 218 219 220
        for (i = 1; i < 64; i++) {
            int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
            weight_matrix[j] = ctx->cid_table->chroma_weight[i];
        }
221 222 223
        ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16,
                          weight_matrix, ctx->m.intra_quant_bias, 1,
                          ctx->m.avctx->qmax, 1);
224 225 226

        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 0; i < 64; i++) {
227 228 229 230 231 232
                ctx->qmatrix_l[qscale][i]      <<= 2;
                ctx->qmatrix_c[qscale][i]      <<= 2;
                ctx->qmatrix_l16[qscale][0][i] <<= 2;
                ctx->qmatrix_l16[qscale][1][i] <<= 2;
                ctx->qmatrix_c16[qscale][0][i] <<= 2;
                ctx->qmatrix_c16[qscale][1][i] <<= 2;
233 234 235 236 237 238 239 240
            }
        }
    } else {
        // 10-bit
        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 1; i < 64; i++) {
                int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                /* The quantization formula from the VC-3 standard is:
                 * quantized = sign(block[i]) * floor(abs(block[i]/s) * p /
                 *             (qscale * weight_table[i]))
                 * Where p is 32 for 8-bit samples and 8 for 10-bit ones.
                 * The s factor compensates scaling of DCT coefficients done by
                 * the DCT routines, and therefore is not present in standard.
                 * It's 8 for 8-bit samples and 4 for 10-bit ones.
                 * We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
                 *     ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) /
                 *     (qscale * weight_table[i])
                 * For 10-bit samples, p / s == 2 */
                ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) /
                                            (qscale * luma_weight_table[i]);
                ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) /
                                            (qscale * chroma_weight_table[i]);
256
            }
257 258
        }
    }
259

260 261 262 263 264
    ctx->m.q_chroma_intra_matrix16 = ctx->qmatrix_c16;
    ctx->m.q_chroma_intra_matrix   = ctx->qmatrix_c;
    ctx->m.q_intra_matrix16        = ctx->qmatrix_l16;
    ctx->m.q_intra_matrix          = ctx->qmatrix_l;

265
    return 0;
266
fail:
267
    return AVERROR(ENOMEM);
268 269
}

270
static av_cold int dnxhd_init_rc(DNXHDEncContext *ctx)
271
{
272
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160 * (ctx->m.avctx->qmax + 1) * sizeof(RCEntry), fail);
273
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
274 275
        FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp,
                          ctx->m.mb_num * sizeof(RCCMPEntry), fail);
276

277 278
    ctx->frame_bits = (ctx->cid_table->coding_unit_size -
                       640 - 4 - ctx->min_padding) * 8;
279
    ctx->qscale = 1;
280
    ctx->lambda = 2 << LAMBDA_FRAC_BITS; // qscale 2
281
    return 0;
282
fail:
283
    return AVERROR(ENOMEM);
284 285
}

286
static av_cold int dnxhd_encode_init(AVCodecContext *avctx)
287 288
{
    DNXHDEncContext *ctx = avctx->priv_data;
289
    int i, index, bit_depth, ret;
290 291

    switch (avctx->pix_fmt) {
292
    case AV_PIX_FMT_YUV422P:
293 294
        bit_depth = 8;
        break;
295
    case AV_PIX_FMT_YUV422P10:
296 297 298
        bit_depth = 10;
        break;
    default:
299 300
        av_log(avctx, AV_LOG_ERROR,
               "pixel format is incompatible with DNxHD\n");
301
        return AVERROR(EINVAL);
302
    }
303

304 305
    ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
    if (!ctx->cid) {
306
        av_log(avctx, AV_LOG_ERROR,
307
               "video parameters incompatible with DNxHD. Valid DNxHD profiles:\n");
308
        ff_dnxhd_print_profiles(avctx, AV_LOG_ERROR);
309
        return AVERROR(EINVAL);
310
    }
311
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
312 313

    index = ff_dnxhd_get_cid_table(ctx->cid);
314
    av_assert0(index >= 0);
315 316
    ctx->cid_table = &ff_dnxhd_cid_table[index];

317
    ctx->m.avctx    = avctx;
318 319 320
    ctx->m.mb_intra = 1;
    ctx->m.h263_aic = 1;

321
    avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
322

323
    ff_dct_common_init(&ctx->m);
324 325
    ff_dct_encode_init(&ctx->m);

326
    if (!ctx->m.dct_quantize)
327
        ctx->m.dct_quantize = ff_dct_quantize_c;
328 329

    if (ctx->cid_table->bit_depth == 10) {
330 331 332
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 4;
333
    } else {
334 335
        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 3;
336 337
    }

338 339
    if (ARCH_X86)
        ff_dnxhdenc_init_x86(ctx);
340 341 342 343 344

    ctx->m.mb_height = (avctx->height + 15) / 16;
    ctx->m.mb_width  = (avctx->width  + 15) / 16;

    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
345
        ctx->interlaced   = 1;
346 347 348 349 350 351 352
        ctx->m.mb_height /= 2;
    }

    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;

    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
        ctx->m.intra_quant_bias = avctx->intra_quant_bias;
353 354
    // XXX tune lbias/cbias
    if ((ret = dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0)) < 0)
355
        return ret;
356

357 358
    /* Avid Nitris hardware decoder requires a minimum amount of padding
     * in the coding unit payload */
359 360 361
    if (ctx->nitris_compat)
        ctx->min_padding = 1600;

362 363 364 365
    if ((ret = dnxhd_init_vlc(ctx)) < 0)
        return ret;
    if ((ret = dnxhd_init_rc(ctx)) < 0)
        return ret;
366

367 368 369 370 371 372 373 374
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size,
                      ctx->m.mb_height * sizeof(uint32_t), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs,
                      ctx->m.mb_height * sizeof(uint32_t), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits,
                      ctx->m.mb_num * sizeof(uint16_t), fail);
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale,
                      ctx->m.mb_num * sizeof(uint8_t), fail);
375

376 377 378 379 380 381
    avctx->coded_frame = av_frame_alloc();
    if (!avctx->coded_frame)
        return AVERROR(ENOMEM);

    avctx->coded_frame->key_frame = 1;
    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
382

383
    if (avctx->thread_count > MAX_THREADS) {
384
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
385
        return AVERROR(EINVAL);
386 387
    }

388 389 390 391 392
    if (avctx->qmax <= 1) {
        av_log(avctx, AV_LOG_ERROR, "qmax must be at least 2\n");
        return AVERROR(EINVAL);
    }

393 394
    ctx->thread[0] = ctx;
    for (i = 1; i < avctx->thread_count; i++) {
395
        ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
396 397 398 399
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
    }

    return 0;
400
fail:  // for FF_ALLOCZ_OR_GOTO
401
    return AVERROR(ENOMEM);
402 403 404 405 406
}

static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
{
    DNXHDEncContext *ctx = avctx->priv_data;
407
    static const uint8_t header_prefix[5] = { 0x00, 0x00, 0x02, 0x80, 0x01 };
408

409 410
    memset(buf, 0, 640);

411
    memcpy(buf, header_prefix, 5);
412
    buf[5] = ctx->interlaced ? ctx->cur_field + 2 : 0x01;
413 414
    buf[6] = 0x80; // crc flag off
    buf[7] = 0xa0; // reserved
415
    AV_WB16(buf + 0x18, avctx->height >> ctx->interlaced); // ALPF
416
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
417
    AV_WB16(buf + 0x1d, avctx->height >> ctx->interlaced); // NAL
418

419
    buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
420
    buf[0x22] = 0x88 + (ctx->interlaced << 2);
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    AV_WB32(buf + 0x28, ctx->cid); // CID
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;

    buf[0x5f] = 0x01; // UDL

    buf[0x167] = 0x02; // reserved
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
    buf[0x16d] = ctx->m.mb_height; // Ns
    buf[0x16f] = 0x10; // reserved

    ctx->msip = buf + 0x170;
    return 0;
}

static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
{
    int nbits;
    if (diff < 0) {
439
        nbits = av_log2_16bit(-2 * diff);
440 441
        diff--;
    } else {
442
        nbits = av_log2_16bit(2 * diff);
443 444
    }
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
445 446
             (ctx->cid_table->dc_codes[nbits] << nbits) +
             (diff & ((1 << nbits) - 1)));
447 448
}

449 450 451
static av_always_inline
void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block,
                        int last_index, int n)
452 453 454 455 456 457 458 459 460 461 462 463
{
    int last_non_zero = 0;
    int slevel, i, j;

    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
    ctx->m.last_dc[n] = block[0];

    for (i = 1; i <= last_index; i++) {
        j = ctx->m.intra_scantable.permutated[i];
        slevel = block[j];
        if (slevel) {
            int run_level = i - last_non_zero - 1;
464
            int rlevel = (slevel << 1) | !!run_level;
465
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
466
            if (run_level)
467 468
                put_bits(&ctx->m.pb, ctx->run_bits[run_level],
                         ctx->run_codes[run_level]);
469 470 471
            last_non_zero = i;
        }
    }
472
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
473 474
}

475 476 477
static av_always_inline
void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n,
                        int qscale, int last_index)
478
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
479
    const uint8_t *weight_matrix;
480 481 482
    int level;
    int i;

483 484
    weight_matrix = (n & 2) ? ctx->cid_table->chroma_weight
                            : ctx->cid_table->luma_weight;
485 486 487 488 489 490

    for (i = 1; i <= last_index; i++) {
        int j = ctx->m.intra_scantable.permutated[i];
        level = block[j];
        if (level) {
            if (level < 0) {
491
                level = (1 - 2 * level) * qscale * weight_matrix[i];
492 493 494 495 496 497 498 499 500
                if (ctx->cid_table->bit_depth == 10) {
                    if (weight_matrix[i] != 8)
                        level += 8;
                    level >>= 4;
                } else {
                    if (weight_matrix[i] != 32)
                        level += 32;
                    level >>= 6;
                }
501 502
                level = -level;
            } else {
503
                level = (2 * level + 1) * qscale * weight_matrix[i];
504 505 506 507 508 509 510 511 512
                if (ctx->cid_table->bit_depth == 10) {
                    if (weight_matrix[i] != 8)
                        level += 8;
                    level >>= 4;
                } else {
                    if (weight_matrix[i] != 32)
                        level += 32;
                    level >>= 6;
                }
513 514 515 516 517 518
            }
            block[j] = level;
        }
    }
}

Diego Biurrun's avatar
Diego Biurrun committed
519
static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
520 521 522 523
{
    int score = 0;
    int i;
    for (i = 0; i < 64; i++)
524
        score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
525 526 527
    return score;
}

528 529
static av_always_inline
int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
530 531 532 533 534 535 536 537 538
{
    int last_non_zero = 0;
    int bits = 0;
    int i, j, level;
    for (i = 1; i <= last_index; i++) {
        j = ctx->m.intra_scantable.permutated[i];
        level = block[j];
        if (level) {
            int run_level = i - last_non_zero - 1;
539 540
            bits += ctx->vlc_bits[(level << 1) |
                    !!run_level] + ctx->run_bits[run_level];
541 542 543 544 545 546
            last_non_zero = i;
        }
    }
    return bits;
}

547 548
static av_always_inline
void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
549
{
550 551
    const int bs = ctx->block_width_l2;
    const int bw = 1 << bs;
552 553 554 555 556 557
    const uint8_t *ptr_y = ctx->thread[0]->src[0] +
                           ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs + 1);
    const uint8_t *ptr_u = ctx->thread[0]->src[1] +
                           ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
    const uint8_t *ptr_v = ctx->thread[0]->src[2] +
                           ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
558 559
    DSPContext *dsp = &ctx->m.dsp;

560 561 562 563
    dsp->get_pixels(ctx->blocks[0], ptr_y,      ctx->m.linesize);
    dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
    dsp->get_pixels(ctx->blocks[2], ptr_u,      ctx->m.uvlinesize);
    dsp->get_pixels(ctx->blocks[3], ptr_v,      ctx->m.uvlinesize);
564

565
    if (mb_y + 1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
566
        if (ctx->interlaced) {
567 568 569 570 571 572 573 574 575 576 577 578
            ctx->get_pixels_8x4_sym(ctx->blocks[4],
                                    ptr_y + ctx->dct_y_offset,
                                    ctx->m.linesize);
            ctx->get_pixels_8x4_sym(ctx->blocks[5],
                                    ptr_y + ctx->dct_y_offset + bw,
                                    ctx->m.linesize);
            ctx->get_pixels_8x4_sym(ctx->blocks[6],
                                    ptr_u + ctx->dct_uv_offset,
                                    ctx->m.uvlinesize);
            ctx->get_pixels_8x4_sym(ctx->blocks[7],
                                    ptr_v + ctx->dct_uv_offset,
                                    ctx->m.uvlinesize);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
579
        } else {
580 581 582 583
            dsp->clear_block(ctx->blocks[4]);
            dsp->clear_block(ctx->blocks[5]);
            dsp->clear_block(ctx->blocks[6]);
            dsp->clear_block(ctx->blocks[7]);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
584
        }
585
    } else {
586 587 588 589 590 591 592 593
        dsp->get_pixels(ctx->blocks[4],
                        ptr_y + ctx->dct_y_offset, ctx->m.linesize);
        dsp->get_pixels(ctx->blocks[5],
                        ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
        dsp->get_pixels(ctx->blocks[6],
                        ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
        dsp->get_pixels(ctx->blocks[7],
                        ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
594 595 596
    }
}

597 598
static av_always_inline
int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
599
{
600
    const static uint8_t component[8]={0,0,1,2,0,0,1,2};
601
    return component[i];
602 603
}

604 605
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg,
                                  int jobnr, int threadnr)
606
{
607 608 609
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    int qscale = ctx->qscale;
Diego Biurrun's avatar
Diego Biurrun committed
610
    LOCAL_ALIGNED_16(int16_t, block, [64]);
611
    ctx = ctx->thread[threadnr];
612

613 614
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
615
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
616 617 618 619 620 621 622 623 624 625 626

    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
        int ssd     = 0;
        int ac_bits = 0;
        int dc_bits = 0;
        int i;

        dnxhd_get_blocks(ctx, mb_x, mb_y);

        for (i = 0; i < 8; i++) {
Diego Biurrun's avatar
Diego Biurrun committed
627
            int16_t *src_block = ctx->blocks[i];
628 629 630
            int overflow, nbits, diff, last_index;
            int n = dnxhd_switch_matrix(ctx, i);

631
            memcpy(block, src_block, 64 * sizeof(*block));
632
            last_index = ctx->m.dct_quantize(&ctx->m, block, 4 & (2*i),
633 634
                                             qscale, &overflow);
            ac_bits   += dnxhd_calc_ac_bits(ctx, block, last_index);
635 636

            diff = block[0] - ctx->m.last_dc[n];
637 638 639 640
            if (diff < 0)
                nbits = av_log2_16bit(-2 * diff);
            else
                nbits = av_log2_16bit(2 * diff);
641

642
            av_assert1(nbits < ctx->cid_table->bit_depth + 4);
643 644 645 646 647 648 649 650
            dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;

            ctx->m.last_dc[n] = block[0];

            if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
                dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
                ctx->m.dsp.idct(block);
                ssd += dnxhd_ssd_block(block, src_block);
651 652
            }
        }
653 654 655
        ctx->mb_rc[qscale][mb].ssd  = ssd;
        ctx->mb_rc[qscale][mb].bits = ac_bits + dc_bits + 12 +
                                      8 * ctx->vlc_bits[0];
656
    }
657 658 659
    return 0;
}

660 661
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
662
{
663 664 665
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    ctx = ctx->thread[threadnr];
666 667
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr],
                  ctx->slice_size[jobnr]);
668

669 670
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
671
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
672 673 674 675 676
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
        int qscale = ctx->mb_qscale[mb];
        int i;

677
        put_bits(&ctx->m.pb, 12, qscale << 1);
678 679 680 681

        dnxhd_get_blocks(ctx, mb_x, mb_y);

        for (i = 0; i < 8; i++) {
Diego Biurrun's avatar
Diego Biurrun committed
682
            int16_t *block = ctx->blocks[i];
683
            int overflow, n = dnxhd_switch_matrix(ctx, i);
684
            int last_index = ctx->m.dct_quantize(&ctx->m, block, 4 & (2*i),
685
                                                 qscale, &overflow);
686
            // START_TIMER;
687
            dnxhd_encode_block(ctx, block, last_index, n);
688
            // STOP_TIMER("encode_block");
689
        }
690
    }
691 692
    if (put_bits_count(&ctx->m.pb) & 31)
        put_bits(&ctx->m.pb, 32 - (put_bits_count(&ctx->m.pb) & 31), 0);
693 694 695 696
    flush_put_bits(&ctx->m.pb);
    return 0;
}

697
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
698 699
{
    int mb_y, mb_x;
700 701 702 703
    int offset = 0;
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
        int thread_size;
        ctx->slice_offs[mb_y] = offset;
704 705 706 707 708
        ctx->slice_size[mb_y] = 0;
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
            ctx->slice_size[mb_y] += ctx->mb_bits[mb];
        }
709
        ctx->slice_size[mb_y]   = (ctx->slice_size[mb_y] + 31) & ~31;
710 711
        ctx->slice_size[mb_y] >>= 3;
        thread_size = ctx->slice_size[mb_y];
712 713 714 715
        offset += thread_size;
    }
}

716 717
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
718
{
719
    DNXHDEncContext *ctx = avctx->priv_data;
720 721 722 723
    int mb_y = jobnr, mb_x, x, y;
    int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
                           ((avctx->height >> ctx->interlaced) & 0xF);

724
    ctx = ctx->thread[threadnr];
725
    if (ctx->cid_table->bit_depth == 8) {
726
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize);
727
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
728
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            int sum;
            int varc;

            if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
                sum  = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
                varc = ctx->m.dsp.pix_norm1(pix, ctx->m.linesize);
            } else {
                int bw = FFMIN(avctx->width - 16 * mb_x, 16);
                int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
                sum = varc = 0;
                for (y = 0; y < bh; y++) {
                    for (x = 0; x < bw; x++) {
                        uint8_t val = pix[x + y * ctx->m.linesize];
                        sum  += val;
                        varc += val * val;
                    }
                }
            }
747
            varc = (varc - (((unsigned) sum * sum) >> 8) + 128) >> 8;
748

749
            ctx->mb_cmp[mb].value = varc;
750
            ctx->mb_cmp[mb].mb    = mb;
751 752 753 754
        }
    } else { // 10-bit
        int const linesize = ctx->m.linesize >> 1;
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
755 756
            uint16_t *pix = (uint16_t *)ctx->thread[0]->src[0] +
                            ((mb_y << 4) * linesize) + (mb_x << 4);
757 758 759 760
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
            int sum = 0;
            int sqsum = 0;
            int mean, sqmean;
761
            int i, j;
762
            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
763 764
            for (i = 0; i < 16; ++i) {
                for (j = 0; j < 16; ++j) {
765
                    // Turn 16-bit pixels into 10-bit ones.
766 767
                    int const sample = (unsigned) pix[j] >> 6;
                    sum   += sample;
768 769 770 771 772 773 774 775
                    sqsum += sample * sample;
                    // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
                }
                pix += linesize;
            }
            mean = sum >> 8; // 16*16 == 2^8
            sqmean = sqsum >> 8;
            ctx->mb_cmp[mb].value = sqmean - mean * mean;
776
            ctx->mb_cmp[mb].mb    = mb;
777
        }
778
    }
779 780 781 782 783
    return 0;
}

static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
{
784 785
    int lambda, up_step, down_step;
    int last_lower = INT_MAX, last_higher = 0;
786 787 788 789
    int x, y, q;

    for (q = 1; q < avctx->qmax; q++) {
        ctx->qscale = q;
790 791
        avctx->execute2(avctx, dnxhd_calc_bits_thread,
                        NULL, NULL, ctx->m.mb_height);
792
    }
793 794
    up_step = down_step = 2 << LAMBDA_FRAC_BITS;
    lambda  = ctx->lambda;
795 796 797

    for (;;) {
        int bits = 0;
798
        int end  = 0;
799
        if (lambda == last_higher) {
800
            lambda++;
801
            end = 1; // need to set final qscales/bits
802 803 804 805 806
        }
        for (y = 0; y < ctx->m.mb_height; y++) {
            for (x = 0; x < ctx->m.mb_width; x++) {
                unsigned min = UINT_MAX;
                int qscale = 1;
807
                int mb     = y * ctx->m.mb_width + x;
808
                for (q = 1; q < avctx->qmax; q++) {
809 810
                    unsigned score = ctx->mb_rc[q][mb].bits * lambda +
                                     ((unsigned) ctx->mb_rc[q][mb].ssd << LAMBDA_FRAC_BITS);
811
                    if (score < min) {
812
                        min    = score;
813 814 815 816 817
                        qscale = q;
                    }
                }
                bits += ctx->mb_rc[qscale][mb].bits;
                ctx->mb_qscale[mb] = qscale;
818
                ctx->mb_bits[mb]   = ctx->mb_rc[qscale][mb].bits;
819
            }
820
            bits = (bits + 31) & ~31; // padding
821 822 823
            if (bits > ctx->frame_bits)
                break;
        }
824 825 826
        // av_dlog(ctx->m.avctx,
        //         "lambda %d, up %u, down %u, bits %d, frame %d\n",
        //         lambda, last_higher, last_lower, bits, ctx->frame_bits);
827 828
        if (end) {
            if (bits > ctx->frame_bits)
829
                return AVERROR(EINVAL);
830 831 832
            break;
        }
        if (bits < ctx->frame_bits) {
833 834 835 836 837
            last_lower = FFMIN(lambda, last_lower);
            if (last_higher != 0)
                lambda = (lambda+last_higher)>>1;
            else
                lambda -= down_step;
838
            down_step = FFMIN((int64_t)down_step*5, INT_MAX);
839 840 841 842
            up_step = 1<<LAMBDA_FRAC_BITS;
            lambda = FFMAX(1, lambda);
            if (lambda == last_lower)
                break;
843
        } else {
844 845 846
            last_higher = FFMAX(lambda, last_higher);
            if (last_lower != INT_MAX)
                lambda = (lambda+last_lower)>>1;
847
            else if ((int64_t)lambda + up_step > INT_MAX)
848
                return AVERROR(EINVAL);
849 850
            else
                lambda += up_step;
851
            up_step = FFMIN((int64_t)up_step*5, INT_MAX);
852
            down_step = 1<<LAMBDA_FRAC_BITS;
853 854
        }
    }
855
    //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
    ctx->lambda = lambda;
    return 0;
}

static int dnxhd_find_qscale(DNXHDEncContext *ctx)
{
    int bits = 0;
    int up_step = 1;
    int down_step = 1;
    int last_higher = 0;
    int last_lower = INT_MAX;
    int qscale;
    int x, y;

    qscale = ctx->qscale;
    for (;;) {
        bits = 0;
        ctx->qscale = qscale;
        // XXX avoid recalculating bits
875 876
        ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread,
                               NULL, NULL, ctx->m.mb_height);
877 878 879 880 881 882 883
        for (y = 0; y < ctx->m.mb_height; y++) {
            for (x = 0; x < ctx->m.mb_width; x++)
                bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
            bits = (bits+31)&~31; // padding
            if (bits > ctx->frame_bits)
                break;
        }
884 885 886 887
        // av_dlog(ctx->m.avctx,
        //         "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
        //         ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits,
        //         last_higher, last_lower);
888 889
        if (bits < ctx->frame_bits) {
            if (qscale == 1)
890
                return 1;
891 892 893 894 895 896
            if (last_higher == qscale - 1) {
                qscale = last_higher;
                break;
            }
            last_lower = FFMIN(qscale, last_lower);
            if (last_higher != 0)
897
                qscale = (qscale + last_higher) >> 1;
898 899 900 901 902 903 904 905 906 907
            else
                qscale -= down_step++;
            if (qscale < 1)
                qscale = 1;
            up_step = 1;
        } else {
            if (last_lower == qscale + 1)
                break;
            last_higher = FFMAX(qscale, last_higher);
            if (last_lower != INT_MAX)
908
                qscale = (qscale + last_lower) >> 1;
909 910 911 912
            else
                qscale += up_step++;
            down_step = 1;
            if (qscale >= ctx->m.avctx->qmax)
913
                return AVERROR(EINVAL);
914 915
        }
    }
916
    //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
917 918 919 920
    ctx->qscale = qscale;
    return 0;
}

921 922 923 924 925 926 927
#define BUCKET_BITS 8
#define RADIX_PASSES 4
#define NBUCKETS (1 << BUCKET_BITS)

static inline int get_bucket(int value, int shift)
{
    value >>= shift;
928
    value  &= NBUCKETS - 1;
929 930 931
    return NBUCKETS - 1 - value;
}

932 933
static void radix_count(const RCCMPEntry *data, int size,
                        int buckets[RADIX_PASSES][NBUCKETS])
934 935 936 937 938 939 940 941 942
{
    int i, j;
    memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
    for (i = 0; i < size; i++) {
        int v = data[i].value;
        for (j = 0; j < RADIX_PASSES; j++) {
            buckets[j][get_bucket(v, 0)]++;
            v >>= BUCKET_BITS;
        }
943
        av_assert1(!v);
944 945 946 947 948
    }
    for (j = 0; j < RADIX_PASSES; j++) {
        int offset = size;
        for (i = NBUCKETS - 1; i >= 0; i--)
            buckets[j][i] = offset -= buckets[j][i];
949
        av_assert1(!buckets[j][0]);
950 951 952
    }
}

953 954
static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data,
                            int size, int buckets[NBUCKETS], int pass)
955 956 957 958
{
    int shift = pass * BUCKET_BITS;
    int i;
    for (i = 0; i < size; i++) {
959
        int v   = get_bucket(data[i].value, shift);
960 961 962 963 964 965
        int pos = buckets[v]++;
        dst[pos] = data[i];
    }
}

static void radix_sort(RCCMPEntry *data, int size)
966
{
967
    int buckets[RADIX_PASSES][NBUCKETS];
968
    RCCMPEntry *tmp = av_malloc_array(size, sizeof(*tmp));
969 970 971 972 973 974 975 976
    radix_count(data, size, buckets);
    radix_sort_pass(tmp, data, size, buckets[0], 0);
    radix_sort_pass(data, tmp, size, buckets[1], 1);
    if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
        radix_sort_pass(tmp, data, size, buckets[2], 2);
        radix_sort_pass(data, tmp, size, buckets[3], 3);
    }
    av_free(tmp);
977 978
}

979
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
980 981
{
    int max_bits = 0;
982 983
    int ret, x, y;
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
984
        return ret;
985 986
    for (y = 0; y < ctx->m.mb_height; y++) {
        for (x = 0; x < ctx->m.mb_width; x++) {
987
            int mb = y * ctx->m.mb_width + x;
988 989 990 991 992
            int delta_bits;
            ctx->mb_qscale[mb] = ctx->qscale;
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
            max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
            if (!RC_VARIANCE) {
993 994
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits -
                             ctx->mb_rc[ctx->qscale + 1][mb].bits;
995
                ctx->mb_cmp[mb].mb = mb;
996 997 998 999 1000
                ctx->mb_cmp[mb].value =
                    delta_bits ? ((ctx->mb_rc[ctx->qscale][mb].ssd -
                                   ctx->mb_rc[ctx->qscale + 1][mb].ssd) * 100) /
                                  delta_bits
                               : INT_MIN; // avoid increasing qscale
1001 1002
            }
        }
1003
        max_bits += 31; // worst padding
1004
    }
1005
    if (!ret) {
1006
        if (RC_VARIANCE)
1007 1008
            avctx->execute2(avctx, dnxhd_mb_var_thread,
                            NULL, NULL, ctx->m.mb_height);
1009
        radix_sort(ctx->mb_cmp, ctx->m.mb_num);
1010 1011
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
            int mb = ctx->mb_cmp[x].mb;
1012 1013 1014 1015
            max_bits -= ctx->mb_rc[ctx->qscale][mb].bits -
                        ctx->mb_rc[ctx->qscale + 1][mb].bits;
            ctx->mb_qscale[mb] = ctx->qscale + 1;
            ctx->mb_bits[mb]   = ctx->mb_rc[ctx->qscale + 1][mb].bits;
1016 1017 1018 1019 1020
        }
    }
    return 0;
}

Michael Niedermayer's avatar
Michael Niedermayer committed
1021
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
1022 1023 1024 1025
{
    int i;

    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
1026 1027
        ctx->thread[i]->m.linesize    = frame->linesize[0] << ctx->interlaced;
        ctx->thread[i]->m.uvlinesize  = frame->linesize[1] << ctx->interlaced;
1028 1029 1030 1031
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
    }

1032
    ctx->m.avctx->coded_frame->interlaced_frame = frame->interlaced_frame;
1033 1034 1035
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
}

1036 1037
static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *frame, int *got_packet)
1038 1039 1040 1041
{
    DNXHDEncContext *ctx = avctx->priv_data;
    int first_field = 1;
    int offset, i, ret;
1042
    uint8_t *buf;
1043

1044
    if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
1045 1046
        return ret;
    buf = pkt->data;
1047

1048
    dnxhd_load_picture(ctx, frame);
1049

1050
encode_coding_unit:
1051
    for (i = 0; i < 3; i++) {
1052
        ctx->src[i] = frame->data[i];
1053
        if (ctx->interlaced && ctx->cur_field)
1054
            ctx->src[i] += frame->linesize[i];
1055 1056 1057 1058 1059 1060 1061
    }

    dnxhd_write_header(avctx, buf);

    if (avctx->mb_decision == FF_MB_DECISION_RD)
        ret = dnxhd_encode_rdo(avctx, ctx);
    else
1062
        ret = dnxhd_encode_fast(avctx, ctx);
1063
    if (ret < 0) {
1064 1065
        av_log(avctx, AV_LOG_ERROR,
               "picture could not fit ratecontrol constraints, increase qmax\n");
1066
        return ret;
1067 1068
    }

1069
    dnxhd_setup_threads_slices(ctx);
1070 1071 1072 1073 1074

    offset = 0;
    for (i = 0; i < ctx->m.mb_height; i++) {
        AV_WB32(ctx->msip + i * 4, offset);
        offset += ctx->slice_size[i];
1075
        av_assert1(!(ctx->slice_size[i] & 3));
1076 1077
    }

1078
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
1079

1080
    av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
1081 1082
    memset(buf + 640 + offset, 0,
           ctx->cid_table->coding_unit_size - 4 - offset - 640);
1083

1084 1085 1086 1087 1088
    AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF

    if (ctx->interlaced && first_field) {
        first_field     = 0;
        ctx->cur_field ^= 1;
1089
        buf            += ctx->cid_table->coding_unit_size;
1090 1091 1092
        goto encode_coding_unit;
    }

1093
    avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
1094

1095 1096 1097
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
1098 1099
}

1100
static av_cold int dnxhd_encode_end(AVCodecContext *avctx)
1101 1102
{
    DNXHDEncContext *ctx = avctx->priv_data;
1103
    int max_level        = 1 << (ctx->cid_table->bit_depth + 2);
1104 1105
    int i;

1106 1107
    av_free(ctx->vlc_codes - max_level * 2);
    av_free(ctx->vlc_bits - max_level * 2);
1108 1109
    av_freep(&ctx->run_codes);
    av_freep(&ctx->run_bits);
1110 1111 1112 1113 1114 1115

    av_freep(&ctx->mb_bits);
    av_freep(&ctx->mb_qscale);
    av_freep(&ctx->mb_rc);
    av_freep(&ctx->mb_cmp);
    av_freep(&ctx->slice_size);
1116
    av_freep(&ctx->slice_offs);
1117 1118 1119 1120 1121 1122 1123 1124 1125

    av_freep(&ctx->qmatrix_c);
    av_freep(&ctx->qmatrix_l);
    av_freep(&ctx->qmatrix_c16);
    av_freep(&ctx->qmatrix_l16);

    for (i = 1; i < avctx->thread_count; i++)
        av_freep(&ctx->thread[i]);

1126 1127
    av_frame_free(&avctx->coded_frame);

1128 1129 1130
    return 0;
}

1131 1132 1133 1134 1135
static const AVCodecDefault dnxhd_defaults[] = {
    { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
    { NULL },
};

1136
AVCodec ff_dnxhd_encoder = {
1137
    .name           = "dnxhd",
1138
    .long_name      = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1139
    .type           = AVMEDIA_TYPE_VIDEO,
1140
    .id             = AV_CODEC_ID_DNXHD,
1141 1142
    .priv_data_size = sizeof(DNXHDEncContext),
    .init           = dnxhd_encode_init,
1143
    .encode2        = dnxhd_encode_picture,
1144
    .close          = dnxhd_encode_end,
1145
    .capabilities   = CODEC_CAP_SLICE_THREADS,
1146 1147 1148 1149 1150
    .pix_fmts       = (const enum AVPixelFormat[]) {
        AV_PIX_FMT_YUV422P,
        AV_PIX_FMT_YUV422P10,
        AV_PIX_FMT_NONE
    },
1151
    .priv_class     = &dnxhd_class,
1152
    .defaults       = dnxhd_defaults,
1153
};