dnxhdenc.c 39.7 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
#include "avcodec.h"
32
#include "blockdsp.h"
33
#include "fdctdsp.h"
34
#include "internal.h"
35
#include "mpegvideo.h"
36
#include "pixblockdsp.h"
37
#include "dnxhdenc.h"
38

39

40 41 42 43
// 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
44

45 46 47 48 49
#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 }
50
};
51

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

59
static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block,
60
                                          const uint8_t *pixels,
61
                                          ptrdiff_t line_size)
62 63 64
{
    int i;
    for (i = 0; i < 4; i++) {
65 66 67 68 69 70 71 72 73 74
        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;
75
    }
76 77 78 79
    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);
80 81
}

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

    for (i = 0; i < 4; i++) {
92 93 94 95 96 97
        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;
98
    }
99 100 101 102
    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);
103 104
}

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

113
    ctx->fdsp.fdct(block);
114 115 116 117

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

118
    for (i = 1; i < 64; ++i) {
119
        int j = scantable[i];
120
        int sign = FF_SIGNBIT(block[j]);
121 122 123 124 125 126 127 128 129 130
        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;
}

131
static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
132
{
133
    int i, j, level, run;
134 135
    int max_level = 1 << (ctx->cid_table->bit_depth + 2);

136 137 138 139
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->vlc_codes,
                      max_level, 4 * sizeof(*ctx->vlc_codes), fail);
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->vlc_bits,
                      max_level, 4 * sizeof(*ctx->vlc_bits), fail);
140 141 142 143 144 145 146
    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;
147 148
    for (level = -max_level; level < max_level; level++) {
        for (run = 0; run < 2; run++) {
149
            int index = (level << 1) | run;
150 151 152 153
            int sign, offset = 0, alevel = level;

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

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

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

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

        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 0; i < 64; i++) {
229 230 231 232 233 234
                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;
235 236 237 238 239 240
            }
        }
    } else {
        // 10-bit
        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 1; i < 64; i++) {
241
                int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
                /* 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]);
258
            }
259 260
        }
    }
261

262 263 264 265 266
    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;

267
    return 0;
268
fail:
269
    return AVERROR(ENOMEM);
270 271
}

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

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

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

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

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

    index = ff_dnxhd_get_cid_table(ctx->cid);
316
    av_assert0(index >= 0);
317

318 319
    ctx->cid_table = &ff_dnxhd_cid_table[index];

320
    ctx->m.avctx    = avctx;
321 322 323
    ctx->m.mb_intra = 1;
    ctx->m.h263_aic = 1;

324
    avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
325

326
    ff_blockdsp_init(&ctx->bdsp, avctx);
327
    ff_fdctdsp_init(&ctx->m.fdsp, avctx);
328
    ff_mpv_idct_init(&ctx->m);
329
    ff_mpegvideoencdsp_init(&ctx->m.mpvencdsp, avctx);
330
    ff_pixblockdsp_init(&ctx->m.pdsp, avctx);
331 332
    ff_dct_encode_init(&ctx->m);

333
    if (!ctx->m.dct_quantize)
334
        ctx->m.dct_quantize = ff_dct_quantize_c;
335 336

    if (ctx->cid_table->bit_depth == 10) {
337 338 339
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 4;
340
    } else {
341 342
        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 3;
343 344
    }

345 346
    if (ARCH_X86)
        ff_dnxhdenc_init_x86(ctx);
347 348 349 350 351

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

    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
352
        ctx->interlaced   = 1;
353 354 355 356 357 358 359
        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;
360 361
    // XXX tune lbias/cbias
    if ((ret = dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0)) < 0)
362
        return ret;
363

364 365
    /* Avid Nitris hardware decoder requires a minimum amount of padding
     * in the coding unit payload */
366 367 368
    if (ctx->nitris_compat)
        ctx->min_padding = 1600;

369 370 371 372
    if ((ret = dnxhd_init_vlc(ctx)) < 0)
        return ret;
    if ((ret = dnxhd_init_rc(ctx)) < 0)
        return ret;
373

374 375 376 377 378 379 380 381
    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);
382

383 384 385 386 387 388
    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;
389

390
    if (avctx->thread_count > MAX_THREADS) {
391
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
392
        return AVERROR(EINVAL);
393 394
    }

395 396 397 398 399
    if (avctx->qmax <= 1) {
        av_log(avctx, AV_LOG_ERROR, "qmax must be at least 2\n");
        return AVERROR(EINVAL);
    }

400 401
    ctx->thread[0] = ctx;
    for (i = 1; i < avctx->thread_count; i++) {
402
        ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
403 404 405 406
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
    }

    return 0;
407
fail:  // for FF_ALLOCZ_OR_GOTO
408
    return AVERROR(ENOMEM);
409 410 411 412 413
}

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

416 417
    memset(buf, 0, 640);

418
    memcpy(buf, header_prefix, 5);
419
    buf[5] = ctx->interlaced ? ctx->cur_field + 2 : 0x01;
420 421
    buf[6] = 0x80; // crc flag off
    buf[7] = 0xa0; // reserved
422
    AV_WB16(buf + 0x18, avctx->height >> ctx->interlaced); // ALPF
423
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
424
    AV_WB16(buf + 0x1d, avctx->height >> ctx->interlaced); // NAL
425

426
    buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
427
    buf[0x22] = 0x88 + (ctx->interlaced << 2);
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    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) {
446
        nbits = av_log2_16bit(-2 * diff);
447 448
        diff--;
    } else {
449
        nbits = av_log2_16bit(2 * diff);
450 451
    }
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
452 453
             (ctx->cid_table->dc_codes[nbits] << nbits) +
             (diff & ((1 << nbits) - 1)));
454 455
}

456 457 458
static av_always_inline
void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block,
                        int last_index, int n)
459 460 461 462 463 464 465 466 467 468 469 470
{
    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;
471
            int rlevel = (slevel << 1) | !!run_level;
472
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
473
            if (run_level)
474 475
                put_bits(&ctx->m.pb, ctx->run_bits[run_level],
                         ctx->run_codes[run_level]);
476 477 478
            last_non_zero = i;
        }
    }
479
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
480 481
}

482 483 484
static av_always_inline
void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n,
                        int qscale, int last_index)
485
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
486
    const uint8_t *weight_matrix;
487 488 489
    int level;
    int i;

490 491
    weight_matrix = (n & 2) ? ctx->cid_table->chroma_weight
                            : ctx->cid_table->luma_weight;
492 493 494 495 496 497

    for (i = 1; i <= last_index; i++) {
        int j = ctx->m.intra_scantable.permutated[i];
        level = block[j];
        if (level) {
            if (level < 0) {
498
                level = (1 - 2 * level) * qscale * weight_matrix[i];
499 500 501 502 503 504 505 506 507
                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;
                }
508 509
                level = -level;
            } else {
510
                level = (2 * level + 1) * qscale * weight_matrix[i];
511 512 513 514 515 516 517 518 519
                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;
                }
520 521 522 523 524 525
            }
            block[j] = level;
        }
    }
}

Diego Biurrun's avatar
Diego Biurrun committed
526
static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
527 528 529 530
{
    int score = 0;
    int i;
    for (i = 0; i < 64; i++)
531
        score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
532 533 534
    return score;
}

535 536
static av_always_inline
int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
537 538 539 540 541 542 543 544 545
{
    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;
546 547
            bits += ctx->vlc_bits[(level << 1) |
                    !!run_level] + ctx->run_bits[run_level];
548 549 550 551 552 553
            last_non_zero = i;
        }
    }
    return bits;
}

554 555
static av_always_inline
void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
556
{
557 558
    const int bs = ctx->block_width_l2;
    const int bw = 1 << bs;
559 560 561 562 563 564
    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);
565
    PixblockDSPContext *pdsp = &ctx->m.pdsp;
566

567 568 569 570
    pdsp->get_pixels(ctx->blocks[0], ptr_y,      ctx->m.linesize);
    pdsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
    pdsp->get_pixels(ctx->blocks[2], ptr_u,      ctx->m.uvlinesize);
    pdsp->get_pixels(ctx->blocks[3], ptr_v,      ctx->m.uvlinesize);
571

572
    if (mb_y + 1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
573
        if (ctx->interlaced) {
574 575 576 577 578 579 580 581 582 583 584 585
            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
586
        } else {
587 588 589 590
            ctx->bdsp.clear_block(ctx->blocks[4]);
            ctx->bdsp.clear_block(ctx->blocks[5]);
            ctx->bdsp.clear_block(ctx->blocks[6]);
            ctx->bdsp.clear_block(ctx->blocks[7]);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
591
        }
592
    } else {
593 594 595 596 597 598 599 600
        pdsp->get_pixels(ctx->blocks[4],
                         ptr_y + ctx->dct_y_offset, ctx->m.linesize);
        pdsp->get_pixels(ctx->blocks[5],
                         ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
        pdsp->get_pixels(ctx->blocks[6],
                         ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
        pdsp->get_pixels(ctx->blocks[7],
                         ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
601 602 603
    }
}

604 605
static av_always_inline
int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
606
{
607
    const static uint8_t component[8]={0,0,1,2,0,0,1,2};
608
    return component[i];
609 610
}

611 612
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg,
                                  int jobnr, int threadnr)
613
{
614 615 616
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    int qscale = ctx->qscale;
Diego Biurrun's avatar
Diego Biurrun committed
617
    LOCAL_ALIGNED_16(int16_t, block, [64]);
618
    ctx = ctx->thread[threadnr];
619

620 621
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
622
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
623 624 625 626 627 628 629 630 631 632 633

    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
634
            int16_t *src_block = ctx->blocks[i];
635 636 637
            int overflow, nbits, diff, last_index;
            int n = dnxhd_switch_matrix(ctx, i);

638
            memcpy(block, src_block, 64 * sizeof(*block));
639
            last_index = ctx->m.dct_quantize(&ctx->m, block, 4 & (2*i),
640 641
                                             qscale, &overflow);
            ac_bits   += dnxhd_calc_ac_bits(ctx, block, last_index);
642 643

            diff = block[0] - ctx->m.last_dc[n];
644 645 646 647
            if (diff < 0)
                nbits = av_log2_16bit(-2 * diff);
            else
                nbits = av_log2_16bit(2 * diff);
648

649
            av_assert1(nbits < ctx->cid_table->bit_depth + 4);
650 651 652 653 654 655
            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);
656
                ctx->m.idsp.idct(block);
657
                ssd += dnxhd_ssd_block(block, src_block);
658 659
            }
        }
660 661 662
        ctx->mb_rc[qscale][mb].ssd  = ssd;
        ctx->mb_rc[qscale][mb].bits = ac_bits + dc_bits + 12 +
                                      8 * ctx->vlc_bits[0];
663
    }
664 665 666
    return 0;
}

667 668
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
669
{
670 671 672
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    ctx = ctx->thread[threadnr];
673 674
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr],
                  ctx->slice_size[jobnr]);
675

676 677
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
678
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
679 680 681 682 683
    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;

684
        put_bits(&ctx->m.pb, 12, qscale << 1);
685 686 687 688

        dnxhd_get_blocks(ctx, mb_x, mb_y);

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

704
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
705 706
{
    int mb_y, mb_x;
707 708 709 710
    int offset = 0;
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
        int thread_size;
        ctx->slice_offs[mb_y] = offset;
711 712 713 714 715
        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];
        }
716
        ctx->slice_size[mb_y]   = (ctx->slice_size[mb_y] + 31) & ~31;
717 718
        ctx->slice_size[mb_y] >>= 3;
        thread_size = ctx->slice_size[mb_y];
719 720 721 722
        offset += thread_size;
    }
}

723 724
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
725
{
726
    DNXHDEncContext *ctx = avctx->priv_data;
727 728 729 730
    int mb_y = jobnr, mb_x, x, y;
    int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
                           ((avctx->height >> ctx->interlaced) & 0xF);

731
    ctx = ctx->thread[threadnr];
732
    if (ctx->cid_table->bit_depth == 8) {
733
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize);
734
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
735
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
736 737 738 739
            int sum;
            int varc;

            if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
740 741
                sum  = ctx->m.mpvencdsp.pix_sum(pix, ctx->m.linesize);
                varc = ctx->m.mpvencdsp.pix_norm1(pix, ctx->m.linesize);
742 743 744 745 746 747 748 749 750 751 752 753
            } 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;
                    }
                }
            }
754
            varc = (varc - (((unsigned) sum * sum) >> 8) + 128) >> 8;
755

756
            ctx->mb_cmp[mb].value = varc;
757
            ctx->mb_cmp[mb].mb    = mb;
758 759 760 761
        }
    } else { // 10-bit
        int const linesize = ctx->m.linesize >> 1;
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
762 763
            uint16_t *pix = (uint16_t *)ctx->thread[0]->src[0] +
                            ((mb_y << 4) * linesize) + (mb_x << 4);
764 765 766 767
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
            int sum = 0;
            int sqsum = 0;
            int mean, sqmean;
768
            int i, j;
769
            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
770 771
            for (i = 0; i < 16; ++i) {
                for (j = 0; j < 16; ++j) {
772
                    // Turn 16-bit pixels into 10-bit ones.
773 774
                    int const sample = (unsigned) pix[j] >> 6;
                    sum   += sample;
775 776 777 778 779 780 781 782
                    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;
783
            ctx->mb_cmp[mb].mb    = mb;
784
        }
785
    }
786 787 788 789 790
    return 0;
}

static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
{
791 792
    int lambda, up_step, down_step;
    int last_lower = INT_MAX, last_higher = 0;
793 794 795 796
    int x, y, q;

    for (q = 1; q < avctx->qmax; q++) {
        ctx->qscale = q;
797 798
        avctx->execute2(avctx, dnxhd_calc_bits_thread,
                        NULL, NULL, ctx->m.mb_height);
799
    }
800 801
    up_step = down_step = 2 << LAMBDA_FRAC_BITS;
    lambda  = ctx->lambda;
802 803 804

    for (;;) {
        int bits = 0;
805
        int end  = 0;
806
        if (lambda == last_higher) {
807
            lambda++;
808
            end = 1; // need to set final qscales/bits
809 810 811 812 813
        }
        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;
814
                int mb     = y * ctx->m.mb_width + x;
815
                for (q = 1; q < avctx->qmax; q++) {
816 817
                    unsigned score = ctx->mb_rc[q][mb].bits * lambda +
                                     ((unsigned) ctx->mb_rc[q][mb].ssd << LAMBDA_FRAC_BITS);
818
                    if (score < min) {
819
                        min    = score;
820 821 822 823 824
                        qscale = q;
                    }
                }
                bits += ctx->mb_rc[qscale][mb].bits;
                ctx->mb_qscale[mb] = qscale;
825
                ctx->mb_bits[mb]   = ctx->mb_rc[qscale][mb].bits;
826
            }
827
            bits = (bits + 31) & ~31; // padding
828 829 830
            if (bits > ctx->frame_bits)
                break;
        }
831 832 833
        // 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);
834 835
        if (end) {
            if (bits > ctx->frame_bits)
836
                return AVERROR(EINVAL);
837 838 839
            break;
        }
        if (bits < ctx->frame_bits) {
840 841 842 843 844
            last_lower = FFMIN(lambda, last_lower);
            if (last_higher != 0)
                lambda = (lambda+last_higher)>>1;
            else
                lambda -= down_step;
845
            down_step = FFMIN((int64_t)down_step*5, INT_MAX);
846 847 848 849
            up_step = 1<<LAMBDA_FRAC_BITS;
            lambda = FFMAX(1, lambda);
            if (lambda == last_lower)
                break;
850
        } else {
851 852 853
            last_higher = FFMAX(lambda, last_higher);
            if (last_lower != INT_MAX)
                lambda = (lambda+last_lower)>>1;
854
            else if ((int64_t)lambda + up_step > INT_MAX)
855
                return AVERROR(EINVAL);
856 857
            else
                lambda += up_step;
858
            up_step = FFMIN((int64_t)up_step*5, INT_MAX);
859
            down_step = 1<<LAMBDA_FRAC_BITS;
860 861
        }
    }
862
    //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    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
882 883
        ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread,
                               NULL, NULL, ctx->m.mb_height);
884 885 886 887 888 889 890
        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;
        }
891 892 893 894
        // 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);
895 896
        if (bits < ctx->frame_bits) {
            if (qscale == 1)
897
                return 1;
898 899 900 901 902 903
            if (last_higher == qscale - 1) {
                qscale = last_higher;
                break;
            }
            last_lower = FFMIN(qscale, last_lower);
            if (last_higher != 0)
904
                qscale = (qscale + last_higher) >> 1;
905 906 907 908 909 910 911 912 913 914
            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)
915
                qscale = (qscale + last_lower) >> 1;
916 917 918 919
            else
                qscale += up_step++;
            down_step = 1;
            if (qscale >= ctx->m.avctx->qmax)
920
                return AVERROR(EINVAL);
921 922
        }
    }
923
    //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
924 925 926 927
    ctx->qscale = qscale;
    return 0;
}

928 929 930 931 932 933 934
#define BUCKET_BITS 8
#define RADIX_PASSES 4
#define NBUCKETS (1 << BUCKET_BITS)

static inline int get_bucket(int value, int shift)
{
    value >>= shift;
935
    value  &= NBUCKETS - 1;
936 937 938
    return NBUCKETS - 1 - value;
}

939 940
static void radix_count(const RCCMPEntry *data, int size,
                        int buckets[RADIX_PASSES][NBUCKETS])
941 942 943 944 945 946 947 948 949
{
    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;
        }
950
        av_assert1(!v);
951 952 953 954 955
    }
    for (j = 0; j < RADIX_PASSES; j++) {
        int offset = size;
        for (i = NBUCKETS - 1; i >= 0; i--)
            buckets[j][i] = offset -= buckets[j][i];
956
        av_assert1(!buckets[j][0]);
957 958 959
    }
}

960 961
static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data,
                            int size, int buckets[NBUCKETS], int pass)
962 963 964 965
{
    int shift = pass * BUCKET_BITS;
    int i;
    for (i = 0; i < size; i++) {
966
        int v   = get_bucket(data[i].value, shift);
967 968 969 970 971 972
        int pos = buckets[v]++;
        dst[pos] = data[i];
    }
}

static void radix_sort(RCCMPEntry *data, int size)
973
{
974
    int buckets[RADIX_PASSES][NBUCKETS];
975
    RCCMPEntry *tmp = av_malloc_array(size, sizeof(*tmp));
976 977 978 979 980 981 982 983
    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);
984 985
}

986
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
987 988
{
    int max_bits = 0;
989 990
    int ret, x, y;
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
991
        return ret;
992 993
    for (y = 0; y < ctx->m.mb_height; y++) {
        for (x = 0; x < ctx->m.mb_width; x++) {
994
            int mb = y * ctx->m.mb_width + x;
995 996 997 998 999
            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) {
1000 1001
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits -
                             ctx->mb_rc[ctx->qscale + 1][mb].bits;
1002
                ctx->mb_cmp[mb].mb = mb;
1003 1004 1005 1006 1007
                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
1008 1009
            }
        }
1010
        max_bits += 31; // worst padding
1011
    }
1012
    if (!ret) {
1013
        if (RC_VARIANCE)
1014 1015
            avctx->execute2(avctx, dnxhd_mb_var_thread,
                            NULL, NULL, ctx->m.mb_height);
1016
        radix_sort(ctx->mb_cmp, ctx->m.mb_num);
1017 1018
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
            int mb = ctx->mb_cmp[x].mb;
1019 1020 1021 1022
            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;
1023 1024 1025 1026 1027
        }
    }
    return 0;
}

Michael Niedermayer's avatar
Michael Niedermayer committed
1028
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
1029 1030 1031 1032
{
    int i;

    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
1033 1034
        ctx->thread[i]->m.linesize    = frame->linesize[0] << ctx->interlaced;
        ctx->thread[i]->m.uvlinesize  = frame->linesize[1] << ctx->interlaced;
1035 1036 1037 1038
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
    }

1039
    ctx->m.avctx->coded_frame->interlaced_frame = frame->interlaced_frame;
1040 1041 1042
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
}

1043 1044
static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *frame, int *got_packet)
1045 1046 1047 1048
{
    DNXHDEncContext *ctx = avctx->priv_data;
    int first_field = 1;
    int offset, i, ret;
1049
    uint8_t *buf;
1050

1051
    if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
1052 1053
        return ret;
    buf = pkt->data;
1054

1055
    dnxhd_load_picture(ctx, frame);
1056

1057
encode_coding_unit:
1058
    for (i = 0; i < 3; i++) {
1059
        ctx->src[i] = frame->data[i];
1060
        if (ctx->interlaced && ctx->cur_field)
1061
            ctx->src[i] += frame->linesize[i];
1062 1063 1064 1065 1066 1067 1068
    }

    dnxhd_write_header(avctx, buf);

    if (avctx->mb_decision == FF_MB_DECISION_RD)
        ret = dnxhd_encode_rdo(avctx, ctx);
    else
1069
        ret = dnxhd_encode_fast(avctx, ctx);
1070
    if (ret < 0) {
1071 1072
        av_log(avctx, AV_LOG_ERROR,
               "picture could not fit ratecontrol constraints, increase qmax\n");
1073
        return ret;
1074 1075
    }

1076
    dnxhd_setup_threads_slices(ctx);
1077 1078 1079 1080 1081

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

1085
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
1086

1087
    av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
1088 1089
    memset(buf + 640 + offset, 0,
           ctx->cid_table->coding_unit_size - 4 - offset - 640);
1090

1091 1092 1093 1094 1095
    AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF

    if (ctx->interlaced && first_field) {
        first_field     = 0;
        ctx->cur_field ^= 1;
1096
        buf            += ctx->cid_table->coding_unit_size;
1097 1098 1099
        goto encode_coding_unit;
    }

1100
    avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
1101

1102 1103 1104
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
1105 1106
}

1107
static av_cold int dnxhd_encode_end(AVCodecContext *avctx)
1108 1109
{
    DNXHDEncContext *ctx = avctx->priv_data;
1110
    int max_level        = 1 << (ctx->cid_table->bit_depth + 2);
1111 1112
    int i;

1113 1114
    av_free(ctx->vlc_codes - max_level * 2);
    av_free(ctx->vlc_bits - max_level * 2);
1115 1116
    av_freep(&ctx->run_codes);
    av_freep(&ctx->run_bits);
1117 1118 1119 1120 1121 1122

    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);
1123
    av_freep(&ctx->slice_offs);
1124 1125 1126 1127 1128 1129 1130 1131 1132

    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]);

1133 1134
    av_frame_free(&avctx->coded_frame);

1135 1136 1137
    return 0;
}

1138 1139 1140 1141 1142
static const AVCodecDefault dnxhd_defaults[] = {
    { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
    { NULL },
};

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