dnxhdenc.c 38.7 KB
Newer Older
B
Baptiste Coudurier 已提交
1 2 3
/*
 * VC3/DNxHD encoder
 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
J
Joseph Artsimovich 已提交
4
 * Copyright (c) 2011 MirriAd Ltd
B
Baptiste Coudurier 已提交
5 6
 *
 * VC-3 encoder funded by the British Broadcasting Corporation
J
Joseph Artsimovich 已提交
7
 * 10 bit support added by MirriAd Ltd, Joseph Artsimovich <joseph@mirriad.com>
B
Baptiste Coudurier 已提交
8
 *
9
 * This file is part of Libav.
B
Baptiste Coudurier 已提交
10
 *
11
 * Libav is free software; you can redistribute it and/or
B
Baptiste Coudurier 已提交
12 13 14 15
 * 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.
 *
16
 * Libav is distributed in the hope that it will be useful,
B
Baptiste Coudurier 已提交
17 18 19 20 21
 * 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
22
 * License along with Libav; if not, write to the Free Software
B
Baptiste Coudurier 已提交
23 24 25
 * 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

B
Baptiste Coudurier 已提交
31
#include "avcodec.h"
32
#include "blockdsp.h"
B
Baptiste Coudurier 已提交
33
#include "dsputil.h"
A
Anton Khirnov 已提交
34
#include "internal.h"
B
Baptiste Coudurier 已提交
35
#include "mpegvideo.h"
36
#include "dnxhdenc.h"
B
Baptiste Coudurier 已提交
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 51 52 53 54 55
static const AVClass class = {
    "dnxhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT
};
B
Baptiste Coudurier 已提交
56

57 58
static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *restrict block,
                                          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
    }
M
Mans Rullgard 已提交
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 81 82
static av_always_inline
void dnxhd_10bit_get_pixels_8x4_sym(int16_t *restrict block,
                                    const uint8_t *pixels,
83
                                    ptrdiff_t line_size)
J
Joseph Artsimovich 已提交
84 85 86 87 88 89
{
    int i;

    block += 32;

    for (i = 0; i < 4; i++) {
90 91
        memcpy(block + i * 8, pixels + i * line_size, 8 * sizeof(*block));
        memcpy(block - (i + 1) * 8, pixels + i * line_size, 8 * sizeof(*block));
J
Joseph Artsimovich 已提交
92 93 94
    }
}

D
Diego Biurrun 已提交
95
static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
J
Joseph Artsimovich 已提交
96 97 98 99 100
                                    int n, int qscale, int *overflow)
{
    const uint8_t *scantable= ctx->intra_scantable.scantable;
    const int *qmat = ctx->q_intra_matrix[qscale];
    int last_non_zero = 0;
101
    int i;
J
Joseph Artsimovich 已提交
102 103 104 105 106 107

    ctx->dsp.fdct(block);

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

108
    for (i = 1; i < 64; ++i) {
J
Joseph Artsimovich 已提交
109 110 111 112 113 114 115 116 117 118 119 120
        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;
}

121
static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
B
Baptiste Coudurier 已提交
122
{
123
    int i, j, level, run;
124 125 126 127 128 129 130 131 132 133 134 135 136
    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;
137 138
    for (level = -max_level; level < max_level; level++) {
        for (run = 0; run < 2; run++) {
139
            int index = (level << 1) | run;
140 141 142 143
            int sign, offset = 0, alevel = level;

            MASK_ABS(sign, alevel);
            if (alevel > 64) {
144 145
                offset  = (alevel - 1) >> 6;
                alevel -= offset << 6;
146 147 148 149 150
            }
            for (j = 0; j < 257; j++) {
                if (ctx->cid_table->ac_level[j] == alevel &&
                    (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) &&
                    (!run    || (ctx->cid_table->ac_run_flag  [j] && run))) {
151
                    assert(!ctx->vlc_codes[index]);
152
                    if (alevel) {
153 154 155
                        ctx->vlc_codes[index] =
                            (ctx->cid_table->ac_codes[j] << 1) | (sign & 1);
                        ctx->vlc_bits[index] = ctx->cid_table->ac_bits[j] + 1;
156
                    } else {
157
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
158
                        ctx->vlc_bits[index]  = ctx->cid_table->ac_bits[j];
159 160 161 162 163 164
                    }
                    break;
                }
            }
            assert(!alevel || j < 257);
            if (offset) {
165 166 167
                ctx->vlc_codes[index] =
                    (ctx->vlc_codes[index] << ctx->cid_table->index_bits) | offset;
                ctx->vlc_bits[index] += ctx->cid_table->index_bits;
168 169
            }
        }
B
Baptiste Coudurier 已提交
170 171 172 173
    }
    for (i = 0; i < 62; i++) {
        int run = ctx->cid_table->run[i];
        assert(run < 63);
174
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
175
        ctx->run_bits[run]  = ctx->cid_table->run_bits[i];
B
Baptiste Coudurier 已提交
176 177
    }
    return 0;
178
fail:
179
    return AVERROR(ENOMEM);
B
Baptiste Coudurier 已提交
180 181
}

182
static av_cold int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
B
Baptiste Coudurier 已提交
183 184
{
    // init first elem to 1 to avoid div by 0 in convert_matrix
185
    uint16_t weight_matrix[64] = { 1, }; // convert_matrix needs uint16_t*
B
Baptiste Coudurier 已提交
186
    int qscale, i;
J
Joseph Artsimovich 已提交
187 188
    const uint8_t *luma_weight_table   = ctx->cid_table->luma_weight;
    const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
B
Baptiste Coudurier 已提交
189

190 191 192 193 194 195 196 197 198 199
    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);
B
Baptiste Coudurier 已提交
200

J
Joseph Artsimovich 已提交
201 202
    if (ctx->cid_table->bit_depth == 8) {
        for (i = 1; i < 64; i++) {
203
            int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
J
Joseph Artsimovich 已提交
204 205
            weight_matrix[j] = ctx->cid_table->luma_weight[i];
        }
206
        ff_convert_matrix(&ctx->m, ctx->qmatrix_l, ctx->qmatrix_l16,
207 208
                          weight_matrix, ctx->m.intra_quant_bias, 1,
                          ctx->m.avctx->qmax, 1);
J
Joseph Artsimovich 已提交
209
        for (i = 1; i < 64; i++) {
210
            int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
J
Joseph Artsimovich 已提交
211 212
            weight_matrix[j] = ctx->cid_table->chroma_weight[i];
        }
213
        ff_convert_matrix(&ctx->m, ctx->qmatrix_c, ctx->qmatrix_c16,
214 215
                          weight_matrix, ctx->m.intra_quant_bias, 1,
                          ctx->m.avctx->qmax, 1);
J
Joseph Artsimovich 已提交
216 217 218

        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 0; i < 64; i++) {
219 220 221 222 223 224
                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;
J
Joseph Artsimovich 已提交
225 226 227 228 229 230
            }
        }
    } else {
        // 10-bit
        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
            for (i = 1; i < 64; i++) {
231
                int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
J
Joseph Artsimovich 已提交
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
                /* 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]);
J
Joseph Artsimovich 已提交
248
            }
B
Baptiste Coudurier 已提交
249 250
        }
    }
J
Joseph Artsimovich 已提交
251

B
Baptiste Coudurier 已提交
252
    return 0;
253
fail:
254
    return AVERROR(ENOMEM);
B
Baptiste Coudurier 已提交
255 256
}

257
static av_cold int dnxhd_init_rc(DNXHDEncContext *ctx)
B
Baptiste Coudurier 已提交
258
{
259 260
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc,
                      8160 * ctx->m.avctx->qmax * sizeof(RCEntry), fail);
B
Baptiste Coudurier 已提交
261
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
262 263
        FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp,
                          ctx->m.mb_num * sizeof(RCCMPEntry), fail);
B
Baptiste Coudurier 已提交
264

265 266
    ctx->frame_bits = (ctx->cid_table->coding_unit_size -
                       640 - 4 - ctx->min_padding) * 8;
B
Baptiste Coudurier 已提交
267
    ctx->qscale = 1;
268
    ctx->lambda = 2 << LAMBDA_FRAC_BITS; // qscale 2
B
Baptiste Coudurier 已提交
269
    return 0;
270
fail:
271
    return AVERROR(ENOMEM);
B
Baptiste Coudurier 已提交
272 273
}

274
static av_cold int dnxhd_encode_init(AVCodecContext *avctx)
B
Baptiste Coudurier 已提交
275 276
{
    DNXHDEncContext *ctx = avctx->priv_data;
277
    int i, index, bit_depth, ret;
J
Joseph Artsimovich 已提交
278 279

    switch (avctx->pix_fmt) {
280
    case AV_PIX_FMT_YUV422P:
J
Joseph Artsimovich 已提交
281 282
        bit_depth = 8;
        break;
283
    case AV_PIX_FMT_YUV422P10:
J
Joseph Artsimovich 已提交
284 285 286
        bit_depth = 10;
        break;
    default:
287 288
        av_log(avctx, AV_LOG_ERROR,
               "pixel format is incompatible with DNxHD\n");
289
        return AVERROR(EINVAL);
J
Joseph Artsimovich 已提交
290
    }
B
Baptiste Coudurier 已提交
291

J
Joseph Artsimovich 已提交
292 293
    ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
    if (!ctx->cid) {
294 295
        av_log(avctx, AV_LOG_ERROR,
               "video parameters incompatible with DNxHD\n");
296
        return AVERROR(EINVAL);
B
Baptiste Coudurier 已提交
297
    }
298
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
B
Baptiste Coudurier 已提交
299 300 301 302

    index = ff_dnxhd_get_cid_table(ctx->cid);
    ctx->cid_table = &ff_dnxhd_cid_table[index];

303
    ctx->m.avctx    = avctx;
B
Baptiste Coudurier 已提交
304 305 306
    ctx->m.mb_intra = 1;
    ctx->m.h263_aic = 1;

J
Joseph Artsimovich 已提交
307
    avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
B
Baptiste Coudurier 已提交
308

309
    ff_blockdsp_init(&ctx->bdsp, avctx);
310
    ff_dsputil_init(&ctx->m.dsp, avctx);
311
    ff_idctdsp_init(&ctx->m.idsp, avctx);
312
    ff_mpegvideoencdsp_init(&ctx->m.mpvencdsp, avctx);
B
Baptiste Coudurier 已提交
313
    ff_dct_common_init(&ctx->m);
J
Joseph Artsimovich 已提交
314
    if (!ctx->m.dct_quantize)
315
        ctx->m.dct_quantize = ff_dct_quantize_c;
J
Joseph Artsimovich 已提交
316 317

    if (ctx->cid_table->bit_depth == 10) {
318 319 320
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 4;
J
Joseph Artsimovich 已提交
321
    } else {
322 323
        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
        ctx->block_width_l2     = 3;
J
Joseph Artsimovich 已提交
324 325
    }

326 327
    if (ARCH_X86)
        ff_dnxhdenc_init_x86(ctx);
B
Baptiste Coudurier 已提交
328 329 330 331 332

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

    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
333
        ctx->interlaced   = 1;
B
Baptiste Coudurier 已提交
334 335 336 337 338 339 340
        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;
341 342
    // XXX tune lbias/cbias
    if ((ret = dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0)) < 0)
343
        return ret;
B
Baptiste Coudurier 已提交
344

345 346
    /* Avid Nitris hardware decoder requires a minimum amount of padding
     * in the coding unit payload */
347 348 349
    if (ctx->nitris_compat)
        ctx->min_padding = 1600;

350 351 352 353
    if ((ret = dnxhd_init_vlc(ctx)) < 0)
        return ret;
    if ((ret = dnxhd_init_rc(ctx)) < 0)
        return ret;
B
Baptiste Coudurier 已提交
354

355 356 357 358 359 360 361 362
    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);
B
Baptiste Coudurier 已提交
363

364 365 366 367 368 369
    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;
B
Baptiste Coudurier 已提交
370

371
    if (avctx->thread_count > MAX_THREADS) {
B
Baptiste Coudurier 已提交
372
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
373
        return AVERROR(EINVAL);
B
Baptiste Coudurier 已提交
374 375 376 377
    }

    ctx->thread[0] = ctx;
    for (i = 1; i < avctx->thread_count; i++) {
378
        ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
B
Baptiste Coudurier 已提交
379 380 381 382
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
    }

    return 0;
383
fail:  // for FF_ALLOCZ_OR_GOTO
384
    return AVERROR(ENOMEM);
B
Baptiste Coudurier 已提交
385 386 387 388 389
}

static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
{
    DNXHDEncContext *ctx = avctx->priv_data;
390
    const uint8_t header_prefix[5] = { 0x00, 0x00, 0x02, 0x80, 0x01 };
B
Baptiste Coudurier 已提交
391

392 393
    memset(buf, 0, 640);

B
Baptiste Coudurier 已提交
394
    memcpy(buf, header_prefix, 5);
395
    buf[5] = ctx->interlaced ? ctx->cur_field + 2 : 0x01;
B
Baptiste Coudurier 已提交
396 397
    buf[6] = 0x80; // crc flag off
    buf[7] = 0xa0; // reserved
398
    AV_WB16(buf + 0x18, avctx->height >> ctx->interlaced); // ALPF
B
Baptiste Coudurier 已提交
399
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
400
    AV_WB16(buf + 0x1d, avctx->height >> ctx->interlaced); // NAL
B
Baptiste Coudurier 已提交
401

J
Joseph Artsimovich 已提交
402
    buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
403
    buf[0x22] = 0x88 + (ctx->interlaced << 2);
B
Baptiste Coudurier 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    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) {
422
        nbits = av_log2_16bit(-2 * diff);
B
Baptiste Coudurier 已提交
423 424
        diff--;
    } else {
425
        nbits = av_log2_16bit(2 * diff);
B
Baptiste Coudurier 已提交
426 427
    }
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
428 429
             (ctx->cid_table->dc_codes[nbits] << nbits) +
             (diff & ((1 << nbits) - 1)));
B
Baptiste Coudurier 已提交
430 431
}

432 433 434
static av_always_inline
void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block,
                        int last_index, int n)
B
Baptiste Coudurier 已提交
435 436 437 438 439 440 441 442 443 444 445 446
{
    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;
447
            int rlevel = (slevel << 1) | !!run_level;
448
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
B
Baptiste Coudurier 已提交
449
            if (run_level)
450 451
                put_bits(&ctx->m.pb, ctx->run_bits[run_level],
                         ctx->run_codes[run_level]);
B
Baptiste Coudurier 已提交
452 453 454
            last_non_zero = i;
        }
    }
455
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
B
Baptiste Coudurier 已提交
456 457
}

458 459 460
static av_always_inline
void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n,
                        int qscale, int last_index)
B
Baptiste Coudurier 已提交
461
{
B
Baptiste Coudurier 已提交
462
    const uint8_t *weight_matrix;
B
Baptiste Coudurier 已提交
463 464 465
    int level;
    int i;

466 467
    weight_matrix = (n & 2) ? ctx->cid_table->chroma_weight
                            : ctx->cid_table->luma_weight;
B
Baptiste Coudurier 已提交
468 469 470 471 472 473

    for (i = 1; i <= last_index; i++) {
        int j = ctx->m.intra_scantable.permutated[i];
        level = block[j];
        if (level) {
            if (level < 0) {
474
                level = (1 - 2 * level) * qscale * weight_matrix[i];
J
Joseph Artsimovich 已提交
475 476 477 478 479 480 481 482 483
                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;
                }
B
Baptiste Coudurier 已提交
484 485
                level = -level;
            } else {
486
                level = (2 * level + 1) * qscale * weight_matrix[i];
J
Joseph Artsimovich 已提交
487 488 489 490 491 492 493 494 495
                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;
                }
B
Baptiste Coudurier 已提交
496 497 498 499 500 501
            }
            block[j] = level;
        }
    }
}

D
Diego Biurrun 已提交
502
static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
B
Baptiste Coudurier 已提交
503 504 505 506
{
    int score = 0;
    int i;
    for (i = 0; i < 64; i++)
M
Mans Rullgard 已提交
507
        score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
B
Baptiste Coudurier 已提交
508 509 510
    return score;
}

511 512
static av_always_inline
int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
B
Baptiste Coudurier 已提交
513 514 515 516 517 518 519 520 521
{
    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;
522 523
            bits += ctx->vlc_bits[(level << 1) |
                    !!run_level] + ctx->run_bits[run_level];
B
Baptiste Coudurier 已提交
524 525 526 527 528 529
            last_non_zero = i;
        }
    }
    return bits;
}

530 531
static av_always_inline
void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
B
Baptiste Coudurier 已提交
532
{
J
Joseph Artsimovich 已提交
533 534
    const int bs = ctx->block_width_l2;
    const int bw = 1 << bs;
535 536 537 538 539 540
    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);
B
Baptiste Coudurier 已提交
541 542
    DSPContext *dsp = &ctx->m.dsp;

J
Joseph Artsimovich 已提交
543 544 545 546
    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);
B
Baptiste Coudurier 已提交
547

548
    if (mb_y + 1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
B
Baptiste Coudurier 已提交
549
        if (ctx->interlaced) {
550 551 552 553 554 555 556 557 558 559 560 561
            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);
B
Baptiste Coudurier 已提交
562
        } else {
563 564 565 566
            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]);
B
Baptiste Coudurier 已提交
567
        }
B
Baptiste Coudurier 已提交
568
    } else {
569 570 571 572 573 574 575 576
        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);
B
Baptiste Coudurier 已提交
577 578 579
    }
}

580 581
static av_always_inline
int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
B
Baptiste Coudurier 已提交
582
{
583
    if (i & 2) {
B
Baptiste Coudurier 已提交
584 585
        ctx->m.q_intra_matrix16 = ctx->qmatrix_c16;
        ctx->m.q_intra_matrix   = ctx->qmatrix_c;
586
        return 1 + (i & 1);
B
Baptiste Coudurier 已提交
587 588 589 590 591 592 593
    } else {
        ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
        ctx->m.q_intra_matrix   = ctx->qmatrix_l;
        return 0;
    }
}

594 595
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg,
                                  int jobnr, int threadnr)
B
Baptiste Coudurier 已提交
596
{
597 598 599
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    int qscale = ctx->qscale;
D
Diego Biurrun 已提交
600
    LOCAL_ALIGNED_16(int16_t, block, [64]);
601
    ctx = ctx->thread[threadnr];
B
Baptiste Coudurier 已提交
602

603 604
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
J
Joseph Artsimovich 已提交
605
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
606 607 608 609 610 611 612 613 614 615 616

    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++) {
D
Diego Biurrun 已提交
617
            int16_t *src_block = ctx->blocks[i];
618 619 620
            int overflow, nbits, diff, last_index;
            int n = dnxhd_switch_matrix(ctx, i);

621 622 623 624
            memcpy(block, src_block, 64 * sizeof(*block));
            last_index = ctx->m.dct_quantize(&ctx->m, block, i,
                                             qscale, &overflow);
            ac_bits   += dnxhd_calc_ac_bits(ctx, block, last_index);
625 626

            diff = block[0] - ctx->m.last_dc[n];
627 628 629 630
            if (diff < 0)
                nbits = av_log2_16bit(-2 * diff);
            else
                nbits = av_log2_16bit(2 * diff);
J
Joseph Artsimovich 已提交
631 632

            assert(nbits < ctx->cid_table->bit_depth + 4);
633 634 635 636 637 638
            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);
639
                ctx->m.idsp.idct(block);
640
                ssd += dnxhd_ssd_block(block, src_block);
B
Baptiste Coudurier 已提交
641 642
            }
        }
643 644 645
        ctx->mb_rc[qscale][mb].ssd  = ssd;
        ctx->mb_rc[qscale][mb].bits = ac_bits + dc_bits + 12 +
                                      8 * ctx->vlc_bits[0];
646
    }
B
Baptiste Coudurier 已提交
647 648 649
    return 0;
}

650 651
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
B
Baptiste Coudurier 已提交
652
{
653 654 655
    DNXHDEncContext *ctx = avctx->priv_data;
    int mb_y = jobnr, mb_x;
    ctx = ctx->thread[threadnr];
656 657
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr],
                  ctx->slice_size[jobnr]);
B
Baptiste Coudurier 已提交
658

659 660
    ctx->m.last_dc[0] =
    ctx->m.last_dc[1] =
J
Joseph Artsimovich 已提交
661
    ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
662 663 664 665 666
    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;

667
        put_bits(&ctx->m.pb, 12, qscale << 1);
668 669 670 671

        dnxhd_get_blocks(ctx, mb_x, mb_y);

        for (i = 0; i < 8; i++) {
D
Diego Biurrun 已提交
672
            int16_t *block = ctx->blocks[i];
673 674 675
            int overflow, n = dnxhd_switch_matrix(ctx, i);
            int last_index = ctx->m.dct_quantize(&ctx->m, block, i,
                                                 qscale, &overflow);
676
            // START_TIMER;
677
            dnxhd_encode_block(ctx, block, last_index, n);
678
            // STOP_TIMER("encode_block");
B
Baptiste Coudurier 已提交
679
        }
680
    }
681 682
    if (put_bits_count(&ctx->m.pb) & 31)
        put_bits(&ctx->m.pb, 32 - (put_bits_count(&ctx->m.pb) & 31), 0);
B
Baptiste Coudurier 已提交
683 684 685 686
    flush_put_bits(&ctx->m.pb);
    return 0;
}

687
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
B
Baptiste Coudurier 已提交
688 689
{
    int mb_y, mb_x;
690 691 692 693
    int offset = 0;
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
        int thread_size;
        ctx->slice_offs[mb_y] = offset;
M
Mans Rullgard 已提交
694 695 696 697 698
        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];
        }
699
        ctx->slice_size[mb_y]   = (ctx->slice_size[mb_y] + 31) & ~31;
M
Mans Rullgard 已提交
700 701
        ctx->slice_size[mb_y] >>= 3;
        thread_size = ctx->slice_size[mb_y];
B
Baptiste Coudurier 已提交
702 703 704 705
        offset += thread_size;
    }
}

706 707
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg,
                               int jobnr, int threadnr)
B
Baptiste Coudurier 已提交
708
{
709
    DNXHDEncContext *ctx = avctx->priv_data;
710 711 712 713
    int mb_y = jobnr, mb_x, x, y;
    int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
                           ((avctx->height >> ctx->interlaced) & 0xF);

714
    ctx = ctx->thread[threadnr];
J
Joseph Artsimovich 已提交
715
    if (ctx->cid_table->bit_depth == 8) {
716
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize);
J
Joseph Artsimovich 已提交
717
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
718
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
719 720 721 722
            int sum;
            int varc;

            if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
723 724
                sum  = ctx->m.mpvencdsp.pix_sum(pix, ctx->m.linesize);
                varc = ctx->m.mpvencdsp.pix_norm1(pix, ctx->m.linesize);
725 726 727 728 729 730 731 732 733 734 735 736
            } 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;
                    }
                }
            }
737
            varc = (varc - (((unsigned) sum * sum) >> 8) + 128) >> 8;
738

J
Joseph Artsimovich 已提交
739
            ctx->mb_cmp[mb].value = varc;
740
            ctx->mb_cmp[mb].mb    = mb;
J
Joseph Artsimovich 已提交
741 742 743 744
        }
    } else { // 10-bit
        int const linesize = ctx->m.linesize >> 1;
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
745 746
            uint16_t *pix = (uint16_t *)ctx->thread[0]->src[0] +
                            ((mb_y << 4) * linesize) + (mb_x << 4);
J
Joseph Artsimovich 已提交
747 748 749 750
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
            int sum = 0;
            int sqsum = 0;
            int mean, sqmean;
751
            int i, j;
J
Joseph Artsimovich 已提交
752
            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
753 754
            for (i = 0; i < 16; ++i) {
                for (j = 0; j < 16; ++j) {
J
Joseph Artsimovich 已提交
755
                    // Turn 16-bit pixels into 10-bit ones.
756 757
                    int const sample = (unsigned) pix[j] >> 6;
                    sum   += sample;
J
Joseph Artsimovich 已提交
758 759 760 761 762 763 764 765
                    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;
766
            ctx->mb_cmp[mb].mb    = mb;
J
Joseph Artsimovich 已提交
767
        }
768
    }
B
Baptiste Coudurier 已提交
769 770 771 772 773
    return 0;
}

static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
{
B
Baptiste Coudurier 已提交
774 775
    int lambda, up_step, down_step;
    int last_lower = INT_MAX, last_higher = 0;
B
Baptiste Coudurier 已提交
776 777 778 779
    int x, y, q;

    for (q = 1; q < avctx->qmax; q++) {
        ctx->qscale = q;
780 781
        avctx->execute2(avctx, dnxhd_calc_bits_thread,
                        NULL, NULL, ctx->m.mb_height);
B
Baptiste Coudurier 已提交
782
    }
783 784
    up_step = down_step = 2 << LAMBDA_FRAC_BITS;
    lambda  = ctx->lambda;
B
Baptiste Coudurier 已提交
785 786 787

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

911 912 913 914 915 916 917
#define BUCKET_BITS 8
#define RADIX_PASSES 4
#define NBUCKETS (1 << BUCKET_BITS)

static inline int get_bucket(int value, int shift)
{
    value >>= shift;
918
    value  &= NBUCKETS - 1;
919 920 921
    return NBUCKETS - 1 - value;
}

922 923
static void radix_count(const RCCMPEntry *data, int size,
                        int buckets[RADIX_PASSES][NBUCKETS])
924 925 926 927 928 929 930 931 932 933 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;
        }
        assert(!v);
    }
    for (j = 0; j < RADIX_PASSES; j++) {
        int offset = size;
        for (i = NBUCKETS - 1; i >= 0; i--)
            buckets[j][i] = offset -= buckets[j][i];
        assert(!buckets[j][0]);
    }
}

943 944
static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data,
                            int size, int buckets[NBUCKETS], int pass)
945 946 947 948
{
    int shift = pass * BUCKET_BITS;
    int i;
    for (i = 0; i < size; i++) {
949
        int v   = get_bucket(data[i].value, shift);
950 951 952 953 954 955
        int pos = buckets[v]++;
        dst[pos] = data[i];
    }
}

static void radix_sort(RCCMPEntry *data, int size)
B
Baptiste Coudurier 已提交
956
{
957 958 959 960 961 962 963 964 965 966
    int buckets[RADIX_PASSES][NBUCKETS];
    RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
    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);
B
Baptiste Coudurier 已提交
967 968
}

969
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
B
Baptiste Coudurier 已提交
970 971
{
    int max_bits = 0;
972 973
    int ret, x, y;
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
974
        return ret;
B
Baptiste Coudurier 已提交
975 976
    for (y = 0; y < ctx->m.mb_height; y++) {
        for (x = 0; x < ctx->m.mb_width; x++) {
977
            int mb = y * ctx->m.mb_width + x;
B
Baptiste Coudurier 已提交
978 979 980 981 982
            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) {
983 984
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits -
                             ctx->mb_rc[ctx->qscale + 1][mb].bits;
B
Baptiste Coudurier 已提交
985
                ctx->mb_cmp[mb].mb = mb;
986 987 988 989 990
                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
B
Baptiste Coudurier 已提交
991 992
            }
        }
993
        max_bits += 31; // worst padding
B
Baptiste Coudurier 已提交
994
    }
995
    if (!ret) {
B
Baptiste Coudurier 已提交
996
        if (RC_VARIANCE)
997 998
            avctx->execute2(avctx, dnxhd_mb_var_thread,
                            NULL, NULL, ctx->m.mb_height);
999
        radix_sort(ctx->mb_cmp, ctx->m.mb_num);
B
Baptiste Coudurier 已提交
1000 1001
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
            int mb = ctx->mb_cmp[x].mb;
1002 1003 1004 1005
            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;
B
Baptiste Coudurier 已提交
1006 1007 1008 1009 1010
        }
    }
    return 0;
}

M
consts  
Michael Niedermayer 已提交
1011
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
B
Baptiste Coudurier 已提交
1012 1013 1014 1015
{
    int i;

    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
1016 1017
        ctx->thread[i]->m.linesize    = frame->linesize[0] << ctx->interlaced;
        ctx->thread[i]->m.uvlinesize  = frame->linesize[1] << ctx->interlaced;
B
Baptiste Coudurier 已提交
1018 1019 1020 1021
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
    }

1022
    ctx->m.avctx->coded_frame->interlaced_frame = frame->interlaced_frame;
B
Baptiste Coudurier 已提交
1023 1024 1025
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
}

A
Anton Khirnov 已提交
1026 1027
static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *frame, int *got_packet)
B
Baptiste Coudurier 已提交
1028 1029 1030 1031
{
    DNXHDEncContext *ctx = avctx->priv_data;
    int first_field = 1;
    int offset, i, ret;
A
Anton Khirnov 已提交
1032
    uint8_t *buf;
B
Baptiste Coudurier 已提交
1033

A
Anton Khirnov 已提交
1034
    if ((ret = ff_alloc_packet(pkt, ctx->cid_table->frame_size)) < 0) {
1035 1036
        av_log(avctx, AV_LOG_ERROR,
               "output buffer is too small to compress picture\n");
A
Anton Khirnov 已提交
1037
        return ret;
B
Baptiste Coudurier 已提交
1038
    }
A
Anton Khirnov 已提交
1039
    buf = pkt->data;
B
Baptiste Coudurier 已提交
1040

A
Anton Khirnov 已提交
1041
    dnxhd_load_picture(ctx, frame);
B
Baptiste Coudurier 已提交
1042

1043
encode_coding_unit:
B
Baptiste Coudurier 已提交
1044
    for (i = 0; i < 3; i++) {
1045
        ctx->src[i] = frame->data[i];
B
Baptiste Coudurier 已提交
1046
        if (ctx->interlaced && ctx->cur_field)
1047
            ctx->src[i] += frame->linesize[i];
B
Baptiste Coudurier 已提交
1048 1049 1050 1051 1052 1053 1054
    }

    dnxhd_write_header(avctx, buf);

    if (avctx->mb_decision == FF_MB_DECISION_RD)
        ret = dnxhd_encode_rdo(avctx, ctx);
    else
1055
        ret = dnxhd_encode_fast(avctx, ctx);
B
Baptiste Coudurier 已提交
1056
    if (ret < 0) {
1057 1058
        av_log(avctx, AV_LOG_ERROR,
               "picture could not fit ratecontrol constraints, increase qmax\n");
1059
        return ret;
B
Baptiste Coudurier 已提交
1060 1061
    }

1062
    dnxhd_setup_threads_slices(ctx);
B
Baptiste Coudurier 已提交
1063 1064 1065 1066 1067 1068 1069 1070

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

1071
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
B
Baptiste Coudurier 已提交
1072

1073
    assert(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
1074 1075
    memset(buf + 640 + offset, 0,
           ctx->cid_table->coding_unit_size - 4 - offset - 640);
1076

B
Baptiste Coudurier 已提交
1077 1078 1079 1080 1081
    AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF

    if (ctx->interlaced && first_field) {
        first_field     = 0;
        ctx->cur_field ^= 1;
1082
        buf            += ctx->cid_table->coding_unit_size;
B
Baptiste Coudurier 已提交
1083 1084 1085
        goto encode_coding_unit;
    }

1086
    avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
1087

A
Anton Khirnov 已提交
1088 1089 1090
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
B
Baptiste Coudurier 已提交
1091 1092
}

1093
static av_cold int dnxhd_encode_end(AVCodecContext *avctx)
B
Baptiste Coudurier 已提交
1094 1095
{
    DNXHDEncContext *ctx = avctx->priv_data;
1096
    int max_level        = 1 << (ctx->cid_table->bit_depth + 2);
B
Baptiste Coudurier 已提交
1097 1098
    int i;

1099 1100
    av_free(ctx->vlc_codes - max_level * 2);
    av_free(ctx->vlc_bits - max_level * 2);
1101 1102
    av_freep(&ctx->run_codes);
    av_freep(&ctx->run_bits);
B
Baptiste Coudurier 已提交
1103 1104 1105 1106 1107 1108

    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);
1109
    av_freep(&ctx->slice_offs);
B
Baptiste Coudurier 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118

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

1119 1120
    av_frame_free(&avctx->coded_frame);

B
Baptiste Coudurier 已提交
1121 1122 1123
    return 0;
}

1124
AVCodec ff_dnxhd_encoder = {
1125
    .name           = "dnxhd",
1126
    .long_name      = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1127
    .type           = AVMEDIA_TYPE_VIDEO,
1128
    .id             = AV_CODEC_ID_DNXHD,
1129 1130
    .priv_data_size = sizeof(DNXHDEncContext),
    .init           = dnxhd_encode_init,
A
Anton Khirnov 已提交
1131
    .encode2        = dnxhd_encode_picture,
1132
    .close          = dnxhd_encode_end,
1133
    .capabilities   = CODEC_CAP_SLICE_THREADS,
1134 1135 1136 1137 1138
    .pix_fmts       = (const enum AVPixelFormat[]) {
        AV_PIX_FMT_YUV422P,
        AV_PIX_FMT_YUV422P10,
        AV_PIX_FMT_NONE
    },
1139
    .priv_class     = &class,
B
Baptiste Coudurier 已提交
1140
};