GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/dnxhdenc.c Lines: 679 806 84.2 %
Date: 2020-04-02 05:41:20 Branches: 303 423 71.6 %

Line Branch Exec Source
1
/*
2
 * VC3/DNxHD encoder
3
 * 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
 * This file is part of FFmpeg.
10
 *
11
 * FFmpeg is free software; you can redistribute it and/or
12
 * modify it under the terms of the GNU Lesser General Public
13
 * License as published by the Free Software Foundation; either
14
 * version 2.1 of the License, or (at your option) any later version.
15
 *
16
 * FFmpeg is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
 * Lesser General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Lesser General Public
22
 * License along with FFmpeg; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24
 */
25
26
#include "libavutil/attributes.h"
27
#include "libavutil/internal.h"
28
#include "libavutil/opt.h"
29
30
#include "avcodec.h"
31
#include "blockdsp.h"
32
#include "fdctdsp.h"
33
#include "internal.h"
34
#include "mpegvideo.h"
35
#include "pixblockdsp.h"
36
#include "profiles.h"
37
#include "dnxhdenc.h"
38
39
// The largest value that will not lead to overflow for 10-bit samples.
40
#define DNX10BIT_QMAT_SHIFT 18
41
#define RC_VARIANCE 1 // use variance or ssd for fast rc
42
#define LAMBDA_FRAC_BITS 10
43
44
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
45
static const AVOption options[] = {
46
    { "nitris_compat", "encode with Avid Nitris compatibility",
47
        offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
48
    { "ibias", "intra quant bias",
49
        offsetof(DNXHDEncContext, intra_quant_bias), AV_OPT_TYPE_INT,
50
        { .i64 = 0 }, INT_MIN, INT_MAX, VE },
51
    { "profile",       NULL, offsetof(DNXHDEncContext, profile), AV_OPT_TYPE_INT,
52
        { .i64 = FF_PROFILE_DNXHD },
53
        FF_PROFILE_DNXHD, FF_PROFILE_DNXHR_444, VE, "profile" },
54
    { "dnxhd",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHD },
55
        0, 0, VE, "profile" },
56
    { "dnxhr_444", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_444 },
57
        0, 0, VE, "profile" },
58
    { "dnxhr_hqx", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_HQX },
59
        0, 0, VE, "profile" },
60
    { "dnxhr_hq",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_HQ },
61
        0, 0, VE, "profile" },
62
    { "dnxhr_sq",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_SQ },
63
        0, 0, VE, "profile" },
64
    { "dnxhr_lb",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_LB },
65
        0, 0, VE, "profile" },
66
    { NULL }
67
};
68
69
static const AVClass dnxhd_class = {
70
    .class_name = "dnxhd",
71
    .item_name  = av_default_item_name,
72
    .option     = options,
73
    .version    = LIBAVUTIL_VERSION_INT,
74
};
75
76
97920
static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block,
77
                                          const uint8_t *pixels,
78
                                          ptrdiff_t line_size)
79
{
80
    int i;
81
489600
    for (i = 0; i < 4; i++) {
82
391680
        block[0] = pixels[0];
83
391680
        block[1] = pixels[1];
84
391680
        block[2] = pixels[2];
85
391680
        block[3] = pixels[3];
86
391680
        block[4] = pixels[4];
87
391680
        block[5] = pixels[5];
88
391680
        block[6] = pixels[6];
89
391680
        block[7] = pixels[7];
90
391680
        pixels  += line_size;
91
391680
        block   += 8;
92
    }
93
97920
    memcpy(block,      block -  8, sizeof(*block) * 8);
94
97920
    memcpy(block +  8, block - 16, sizeof(*block) * 8);
95
97920
    memcpy(block + 16, block - 24, sizeof(*block) * 8);
96
97920
    memcpy(block + 24, block - 32, sizeof(*block) * 8);
97
97920
}
98
99
static av_always_inline
100
43200
void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block,
101
                                    const uint8_t *pixels,
102
                                    ptrdiff_t line_size)
103
{
104
43200
    memcpy(block + 0 * 8, pixels + 0 * line_size, 8 * sizeof(*block));
105
43200
    memcpy(block + 7 * 8, pixels + 0 * line_size, 8 * sizeof(*block));
106
43200
    memcpy(block + 1 * 8, pixels + 1 * line_size, 8 * sizeof(*block));
107
43200
    memcpy(block + 6 * 8, pixels + 1 * line_size, 8 * sizeof(*block));
108
43200
    memcpy(block + 2 * 8, pixels + 2 * line_size, 8 * sizeof(*block));
109
43200
    memcpy(block + 5 * 8, pixels + 2 * line_size, 8 * sizeof(*block));
110
43200
    memcpy(block + 3 * 8, pixels + 3 * line_size, 8 * sizeof(*block));
111
43200
    memcpy(block + 4 * 8, pixels + 3 * line_size, 8 * sizeof(*block));
112
43200
}
113
114
static int dnxhd_10bit_dct_quantize_444(MpegEncContext *ctx, int16_t *block,
115
                                        int n, int qscale, int *overflow)
116
{
117
    int i, j, level, last_non_zero, start_i;
118
    const int *qmat;
119
    const uint8_t *scantable= ctx->intra_scantable.scantable;
120
    int bias;
121
    int max = 0;
122
    unsigned int threshold1, threshold2;
123
124
    ctx->fdsp.fdct(block);
125
126
    block[0] = (block[0] + 2) >> 2;
127
    start_i = 1;
128
    last_non_zero = 0;
129
    qmat = n < 4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
130
    bias= ctx->intra_quant_bias * (1 << (16 - 8));
131
    threshold1 = (1 << 16) - bias - 1;
132
    threshold2 = (threshold1 << 1);
133
134
    for (i = 63; i >= start_i; i--) {
135
        j = scantable[i];
136
        level = block[j] * qmat[j];
137
138
        if (((unsigned)(level + threshold1)) > threshold2) {
139
            last_non_zero = i;
140
            break;
141
        } else{
142
            block[j]=0;
143
        }
144
    }
145
146
    for (i = start_i; i <= last_non_zero; i++) {
147
        j = scantable[i];
148
        level = block[j] * qmat[j];
149
150
        if (((unsigned)(level + threshold1)) > threshold2) {
151
            if (level > 0) {
152
                level = (bias + level) >> 16;
153
                block[j] = level;
154
            } else{
155
                level = (bias - level) >> 16;
156
                block[j] = -level;
157
            }
158
            max |= level;
159
        } else {
160
            block[j] = 0;
161
        }
162
    }
163
    *overflow = ctx->max_qcoeff < max; //overflow might have happened
164
165
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
166
    if (ctx->idsp.perm_type != FF_IDCT_PERM_NONE)
167
        ff_block_permute(block, ctx->idsp.idct_permutation,
168
                         scantable, last_non_zero);
169
170
    return last_non_zero;
171
}
172
173
3945600
static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
174
                                    int n, int qscale, int *overflow)
175
{
176
3945600
    const uint8_t *scantable= ctx->intra_scantable.scantable;
177
3945600
    const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
178
3945600
    int last_non_zero = 0;
179
    int i;
180
181
3945600
    ctx->fdsp.fdct(block);
182
183
    // Divide by 4 with rounding, to compensate scaling of DCT coefficients
184
3945600
    block[0] = (block[0] + 2) >> 2;
185
186
252518400
    for (i = 1; i < 64; ++i) {
187
248572800
        int j = scantable[i];
188
248572800
        int sign = FF_SIGNBIT(block[j]);
189
248572800
        int level = (block[j] ^ sign) - sign;
190
248572800
        level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
191
248572800
        block[j] = (level ^ sign) - sign;
192
248572800
        if (level)
193
32824223
            last_non_zero = i;
194
    }
195
196
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
197
3945600
    if (ctx->idsp.perm_type != FF_IDCT_PERM_NONE)
198
        ff_block_permute(block, ctx->idsp.idct_permutation,
199
                         scantable, last_non_zero);
200
201
3945600
    return last_non_zero;
202
}
203
204
73
static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
205
{
206
    int i, j, level, run;
207
73
    int max_level = 1 << (ctx->bit_depth + 2);
208
209
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->orig_vlc_codes,
210
                      max_level, 4 * sizeof(*ctx->orig_vlc_codes), fail);
211
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->orig_vlc_bits,
212
                      max_level, 4 * sizeof(*ctx->orig_vlc_bits), fail);
213
73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes,
214
                      63 * 2, fail);
215
73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits,
216
                      63, fail);
217
218
73
    ctx->vlc_codes = ctx->orig_vlc_codes + max_level * 2;
219
73
    ctx->vlc_bits  = ctx->orig_vlc_bits + max_level * 2;
220
192585
    for (level = -max_level; level < max_level; level++) {
221
577536
        for (run = 0; run < 2; run++) {
222
385024
            int index = level * (1 << 1) | run;
223
385024
            int sign, offset = 0, alevel = level;
224
225
385024
            MASK_ABS(sign, alevel);
226
385024
            if (alevel > 64) {
227
366190
                offset  = (alevel - 1) >> 6;
228
366190
                alevel -= offset << 6;
229
            }
230
65137020
            for (j = 0; j < 257; j++) {
231

65136947
                if (ctx->cid_table->ac_info[2*j+0] >> 1 == alevel &&
232

1197496
                    (!offset || (ctx->cid_table->ac_info[2*j+1] & 1) && offset) &&
233

390917
                    (!run    || (ctx->cid_table->ac_info[2*j+1] & 2) && run)) {
234
                    av_assert1(!ctx->vlc_codes[index]);
235
384951
                    if (alevel) {
236
384878
                        ctx->vlc_codes[index] =
237
384878
                            (ctx->cid_table->ac_codes[j] << 1) | (sign & 1);
238
384878
                        ctx->vlc_bits[index] = ctx->cid_table->ac_bits[j] + 1;
239
                    } else {
240
73
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
241
73
                        ctx->vlc_bits[index]  = ctx->cid_table->ac_bits[j];
242
                    }
243
384951
                    break;
244
                }
245
            }
246

385024
            av_assert0(!alevel || j < 257);
247
385024
            if (offset) {
248
366190
                ctx->vlc_codes[index] =
249
366190
                    (ctx->vlc_codes[index] << ctx->cid_table->index_bits) | offset;
250
366190
                ctx->vlc_bits[index] += ctx->cid_table->index_bits;
251
            }
252
        }
253
    }
254
4599
    for (i = 0; i < 62; i++) {
255
4526
        int run = ctx->cid_table->run[i];
256
4526
        av_assert0(run < 63);
257
4526
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
258
4526
        ctx->run_bits[run]  = ctx->cid_table->run_bits[i];
259
    }
260
73
    return 0;
261
fail:
262
    return AVERROR(ENOMEM);
263
}
264
265
73
static av_cold int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
266
{
267
    // init first elem to 1 to avoid div by 0 in convert_matrix
268
73
    uint16_t weight_matrix[64] = { 1, }; // convert_matrix needs uint16_t*
269
    int qscale, i;
270
73
    const uint8_t *luma_weight_table   = ctx->cid_table->luma_weight;
271
73
    const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
272
273
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l,
274
                      (ctx->m.avctx->qmax + 1), 64 * sizeof(int), fail);
275
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c,
276
                      (ctx->m.avctx->qmax + 1), 64 * sizeof(int), fail);
277
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16,
278
                      (ctx->m.avctx->qmax + 1), 64 * 2 * sizeof(uint16_t),
279
                      fail);
280
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16,
281
                      (ctx->m.avctx->qmax + 1), 64 * 2 * sizeof(uint16_t),
282
                      fail);
283
284
73
    if (ctx->bit_depth == 8) {
285
4224
        for (i = 1; i < 64; i++) {
286
4158
            int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
287
4158
            weight_matrix[j] = ctx->cid_table->luma_weight[i];
288
        }
289
66
        ff_convert_matrix(&ctx->m, ctx->qmatrix_l, ctx->qmatrix_l16,
290
                          weight_matrix, ctx->intra_quant_bias, 1,
291
66
                          ctx->m.avctx->qmax, 1);
292
4224
        for (i = 1; i < 64; i++) {
293
4158
            int j = ctx->m.idsp.idct_permutation[ff_zigzag_direct[i]];
294
4158
            weight_matrix[j] = ctx->cid_table->chroma_weight[i];
295
        }
296
66
        ff_convert_matrix(&ctx->m, ctx->qmatrix_c, ctx->qmatrix_c16,
297
                          weight_matrix, ctx->intra_quant_bias, 1,
298
66
                          ctx->m.avctx->qmax, 1);
299
300
42250
        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
301
2741960
            for (i = 0; i < 64; i++) {
302
2699776
                ctx->qmatrix_l[qscale][i]      <<= 2;
303
2699776
                ctx->qmatrix_c[qscale][i]      <<= 2;
304
2699776
                ctx->qmatrix_l16[qscale][0][i] <<= 2;
305
2699776
                ctx->qmatrix_l16[qscale][1][i] <<= 2;
306
2699776
                ctx->qmatrix_c16[qscale][0][i] <<= 2;
307
2699776
                ctx->qmatrix_c16[qscale][1][i] <<= 2;
308
            }
309
        }
310
    } else {
311
        // 10-bit
312
63
        for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
313
3584
            for (i = 1; i < 64; i++) {
314
3528
                int j = ff_zigzag_direct[i];
315
316
                /* The quantization formula from the VC-3 standard is:
317
                 * quantized = sign(block[i]) * floor(abs(block[i]/s) * p /
318
                 *             (qscale * weight_table[i]))
319
                 * Where p is 32 for 8-bit samples and 8 for 10-bit ones.
320
                 * The s factor compensates scaling of DCT coefficients done by
321
                 * the DCT routines, and therefore is not present in standard.
322
                 * It's 8 for 8-bit samples and 4 for 10-bit ones.
323
                 * We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
324
                 *     ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) /
325
                 *     (qscale * weight_table[i])
326
                 * For 10-bit samples, p / s == 2 */
327
3528
                ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) /
328
3528
                                            (qscale * luma_weight_table[i]);
329
3528
                ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) /
330
3528
                                            (qscale * chroma_weight_table[i]);
331
            }
332
        }
333
    }
334
335
73
    ctx->m.q_chroma_intra_matrix16 = ctx->qmatrix_c16;
336
73
    ctx->m.q_chroma_intra_matrix   = ctx->qmatrix_c;
337
73
    ctx->m.q_intra_matrix16        = ctx->qmatrix_l16;
338
73
    ctx->m.q_intra_matrix          = ctx->qmatrix_l;
339
340
73
    return 0;
341
fail:
342
    return AVERROR(ENOMEM);
343
}
344
345
73
static av_cold int dnxhd_init_rc(DNXHDEncContext *ctx)
346
{
347
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->mb_rc, (ctx->m.avctx->qmax + 1),
348
                          ctx->m.mb_num * sizeof(RCEntry), fail);
349
73
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD) {
350
58
        FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->mb_cmp,
351
                          ctx->m.mb_num, sizeof(RCCMPEntry), fail);
352
58
        FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->mb_cmp_tmp,
353
                          ctx->m.mb_num, sizeof(RCCMPEntry), fail);
354
    }
355
73
    ctx->frame_bits = (ctx->coding_unit_size -
356
73
                       ctx->data_offset - 4 - ctx->min_padding) * 8;
357
73
    ctx->qscale = 1;
358
73
    ctx->lambda = 2 << LAMBDA_FRAC_BITS; // qscale 2
359
73
    return 0;
360
fail:
361
    return AVERROR(ENOMEM);
362
}
363
364
73
static av_cold int dnxhd_encode_init(AVCodecContext *avctx)
365
{
366
73
    DNXHDEncContext *ctx = avctx->priv_data;
367
    int i, index, ret;
368
369
73
    switch (avctx->pix_fmt) {
370
66
    case AV_PIX_FMT_YUV422P:
371
66
        ctx->bit_depth = 8;
372
66
        break;
373
7
    case AV_PIX_FMT_YUV422P10:
374
    case AV_PIX_FMT_YUV444P10:
375
    case AV_PIX_FMT_GBRP10:
376
7
        ctx->bit_depth = 10;
377
7
        break;
378
    default:
379
        av_log(avctx, AV_LOG_ERROR,
380
               "pixel format is incompatible with DNxHD\n");
381
        return AVERROR(EINVAL);
382
    }
383
384

73
    if ((ctx->profile == FF_PROFILE_DNXHR_444 && (avctx->pix_fmt != AV_PIX_FMT_YUV444P10 &&
385
                                                  avctx->pix_fmt != AV_PIX_FMT_GBRP10)) ||
386

73
        (ctx->profile != FF_PROFILE_DNXHR_444 && (avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ||
387
73
                                                  avctx->pix_fmt == AV_PIX_FMT_GBRP10))) {
388
        av_log(avctx, AV_LOG_ERROR,
389
               "pixel format is incompatible with DNxHD profile\n");
390
        return AVERROR(EINVAL);
391
    }
392
393

73
    if (ctx->profile == FF_PROFILE_DNXHR_HQX && avctx->pix_fmt != AV_PIX_FMT_YUV422P10) {
394
        av_log(avctx, AV_LOG_ERROR,
395
               "pixel format is incompatible with DNxHR HQX profile\n");
396
        return AVERROR(EINVAL);
397
    }
398
399
73
    if ((ctx->profile == FF_PROFILE_DNXHR_LB ||
400
61
         ctx->profile == FF_PROFILE_DNXHR_SQ ||
401

73
         ctx->profile == FF_PROFILE_DNXHR_HQ) && avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
402
        av_log(avctx, AV_LOG_ERROR,
403
               "pixel format is incompatible with DNxHR LB/SQ/HQ profile\n");
404
        return AVERROR(EINVAL);
405
    }
406
407
73
    ctx->is_444 = ctx->profile == FF_PROFILE_DNXHR_444;
408
73
    avctx->profile = ctx->profile;
409
73
    ctx->cid = ff_dnxhd_find_cid(avctx, ctx->bit_depth);
410
73
    if (!ctx->cid) {
411
        av_log(avctx, AV_LOG_ERROR,
412
               "video parameters incompatible with DNxHD. Valid DNxHD profiles:\n");
413
        ff_dnxhd_print_profiles(avctx, AV_LOG_ERROR);
414
        return AVERROR(EINVAL);
415
    }
416
73
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
417
418

73
    if (ctx->cid >= 1270 && ctx->cid <= 1274)
419
40
        avctx->codec_tag = MKTAG('A','V','d','h');
420
421

73
    if (avctx->width < 256 || avctx->height < 120) {
422
        av_log(avctx, AV_LOG_ERROR,
423
               "Input dimensions too small, input must be at least 256x120\n");
424
        return AVERROR(EINVAL);
425
    }
426
427
73
    index = ff_dnxhd_get_cid_table(ctx->cid);
428
73
    av_assert0(index >= 0);
429
430
73
    ctx->cid_table = &ff_dnxhd_cid_table[index];
431
432
73
    ctx->m.avctx    = avctx;
433
73
    ctx->m.mb_intra = 1;
434
73
    ctx->m.h263_aic = 1;
435
436
73
    avctx->bits_per_raw_sample = ctx->bit_depth;
437
438
73
    ff_blockdsp_init(&ctx->bdsp, avctx);
439
73
    ff_fdctdsp_init(&ctx->m.fdsp, avctx);
440
73
    ff_mpv_idct_init(&ctx->m);
441
73
    ff_mpegvideoencdsp_init(&ctx->m.mpvencdsp, avctx);
442
73
    ff_pixblockdsp_init(&ctx->m.pdsp, avctx);
443
73
    ff_dct_encode_init(&ctx->m);
444
445
73
    if (ctx->profile != FF_PROFILE_DNXHD)
446
40
        ff_videodsp_init(&ctx->m.vdsp, ctx->bit_depth);
447
448
73
    if (!ctx->m.dct_quantize)
449
        ctx->m.dct_quantize = ff_dct_quantize_c;
450
451

73
    if (ctx->is_444 || ctx->profile == FF_PROFILE_DNXHR_HQX) {
452
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize_444;
453
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
454
        ctx->block_width_l2     = 4;
455
73
    } else if (ctx->bit_depth == 10) {
456
7
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;
457
7
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
458
7
        ctx->block_width_l2     = 4;
459
    } else {
460
66
        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
461
66
        ctx->block_width_l2     = 3;
462
    }
463
464
    if (ARCH_X86)
465
73
        ff_dnxhdenc_init_x86(ctx);
466
467
73
    ctx->m.mb_height = (avctx->height + 15) / 16;
468
73
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
469
470
73
    if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
471
11
        ctx->interlaced   = 1;
472
11
        ctx->m.mb_height /= 2;
473
    }
474
475

73
    if (ctx->interlaced && ctx->profile != FF_PROFILE_DNXHD) {
476
        av_log(avctx, AV_LOG_ERROR,
477
               "Interlaced encoding is not supported for DNxHR profiles.\n");
478
        return AVERROR(EINVAL);
479
    }
480
481
73
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
482
483
73
    if (ctx->cid_table->frame_size == DNXHD_VARIABLE) {
484
40
        ctx->frame_size = avpriv_dnxhd_get_hr_frame_size(ctx->cid,
485
                                                     avctx->width, avctx->height);
486
40
        av_assert0(ctx->frame_size >= 0);
487
40
        ctx->coding_unit_size = ctx->frame_size;
488
    } else {
489
33
        ctx->frame_size = ctx->cid_table->frame_size;
490
33
        ctx->coding_unit_size = ctx->cid_table->coding_unit_size;
491
    }
492
493
73
    if (ctx->m.mb_height > 68)
494
12
        ctx->data_offset = 0x170 + (ctx->m.mb_height << 2);
495
    else
496
61
        ctx->data_offset = 0x280;
497
498
    // XXX tune lbias/cbias
499
73
    if ((ret = dnxhd_init_qmat(ctx, ctx->intra_quant_bias, 0)) < 0)
500
        return ret;
501
502
    /* Avid Nitris hardware decoder requires a minimum amount of padding
503
     * in the coding unit payload */
504
73
    if (ctx->nitris_compat)
505
        ctx->min_padding = 1600;
506
507
73
    if ((ret = dnxhd_init_vlc(ctx)) < 0)
508
        return ret;
509
73
    if ((ret = dnxhd_init_rc(ctx)) < 0)
510
        return ret;
511
512

73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size,
513
                      ctx->m.mb_height * sizeof(uint32_t), fail);
514

73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs,
515
                      ctx->m.mb_height * sizeof(uint32_t), fail);
516

73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits,
517
                      ctx->m.mb_num * sizeof(uint16_t), fail);
518

73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale,
519
                      ctx->m.mb_num * sizeof(uint8_t), fail);
520
521
#if FF_API_CODED_FRAME
522
FF_DISABLE_DEPRECATION_WARNINGS
523
73
    avctx->coded_frame->key_frame = 1;
524
73
    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
525
FF_ENABLE_DEPRECATION_WARNINGS
526
#endif
527
528
73
    if (avctx->active_thread_type == FF_THREAD_SLICE) {
529
        if (avctx->thread_count > MAX_THREADS) {
530
            av_log(avctx, AV_LOG_ERROR, "too many threads\n");
531
            return AVERROR(EINVAL);
532
        }
533
    }
534
535
73
    if (avctx->qmax <= 1) {
536
        av_log(avctx, AV_LOG_ERROR, "qmax must be at least 2\n");
537
        return AVERROR(EINVAL);
538
    }
539
540
73
    ctx->thread[0] = ctx;
541
73
    if (avctx->active_thread_type == FF_THREAD_SLICE) {
542
        for (i = 1; i < avctx->thread_count; i++) {
543
            ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
544
            if (!ctx->thread[i])
545
                goto fail;
546
            memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
547
        }
548
    }
549
550
73
    return 0;
551
fail:  // for FF_ALLOCZ_OR_GOTO
552
    return AVERROR(ENOMEM);
553
}
554
555
380
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
556
{
557
380
    DNXHDEncContext *ctx = avctx->priv_data;
558
559
380
    memset(buf, 0, ctx->data_offset);
560
561
    // * write prefix */
562
380
    AV_WB16(buf + 0x02, ctx->data_offset);
563

380
    if (ctx->cid >= 1270 && ctx->cid <= 1274)
564
200
        buf[4] = 0x03;
565
    else
566
180
        buf[4] = 0x01;
567
568
380
    buf[5] = ctx->interlaced ? ctx->cur_field + 2 : 0x01;
569
380
    buf[6] = 0x80; // crc flag off
570
380
    buf[7] = 0xa0; // reserved
571
380
    AV_WB16(buf + 0x18, avctx->height >> ctx->interlaced); // ALPF
572
380
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
573
380
    AV_WB16(buf + 0x1d, avctx->height >> ctx->interlaced); // NAL
574
575
380
    buf[0x21] = ctx->bit_depth == 10 ? 0x58 : 0x38;
576
380
    buf[0x22] = 0x88 + (ctx->interlaced << 2);
577
380
    AV_WB32(buf + 0x28, ctx->cid); // CID
578
380
    buf[0x2c] = (!ctx->interlaced << 7) | (ctx->is_444 << 6) | (avctx->pix_fmt == AV_PIX_FMT_YUV444P10);
579
580
380
    buf[0x5f] = 0x01; // UDL
581
582
380
    buf[0x167] = 0x02; // reserved
583
380
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
584
380
    AV_WB16(buf + 0x16c, ctx->m.mb_height); // Ns
585
380
    buf[0x16f] = 0x10; // reserved
586
587
380
    ctx->msip = buf + 0x170;
588
380
    return 0;
589
}
590
591
26918560
static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
592
{
593
    int nbits;
594
26918560
    if (diff < 0) {
595
12317800
        nbits = av_log2_16bit(-2 * diff);
596
12317800
        diff--;
597
    } else {
598
14600760
        nbits = av_log2_16bit(2 * diff);
599
    }
600
26918560
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
601
26918560
             (ctx->cid_table->dc_codes[nbits] << nbits) +
602
26918560
             av_mod_uintp2(diff, nbits));
603
26918560
}
604
605
static av_always_inline
606
26918560
void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block,
607
                        int last_index, int n)
608
{
609
26918560
    int last_non_zero = 0;
610
    int slevel, i, j;
611
612
26918560
    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
613
26918560
    ctx->m.last_dc[n] = block[0];
614
615
323734349
    for (i = 1; i <= last_index; i++) {
616
296815789
        j = ctx->m.intra_scantable.permutated[i];
617
296815789
        slevel = block[j];
618
296815789
        if (slevel) {
619
111021078
            int run_level = i - last_non_zero - 1;
620
111021078
            int rlevel = slevel * (1 << 1) | !!run_level;
621
111021078
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
622
111021078
            if (run_level)
623
36001894
                put_bits(&ctx->m.pb, ctx->run_bits[run_level],
624
36001894
                         ctx->run_codes[run_level]);
625
111021078
            last_non_zero = i;
626
        }
627
    }
628
26918560
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
629
26918560
}
630
631
static av_always_inline
632
3024000
void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n,
633
                        int qscale, int last_index)
634
{
635
    const uint8_t *weight_matrix;
636
    int level;
637
    int i;
638
639
3024000
    if (ctx->is_444) {
640
        weight_matrix = ((n % 6) < 2) ? ctx->cid_table->luma_weight
641
                                      : ctx->cid_table->chroma_weight;
642
    } else {
643
3024000
        weight_matrix = (n & 2) ? ctx->cid_table->chroma_weight
644
3024000
                                : ctx->cid_table->luma_weight;
645
    }
646
647
35797315
    for (i = 1; i <= last_index; i++) {
648
32773315
        int j = ctx->m.intra_scantable.permutated[i];
649
32773315
        level = block[j];
650
32773315
        if (level) {
651
16774641
            if (level < 0) {
652
8458215
                level = (1 - 2 * level) * qscale * weight_matrix[i];
653
8458215
                if (ctx->bit_depth == 10) {
654
                    if (weight_matrix[i] != 8)
655
                        level += 8;
656
                    level >>= 4;
657
                } else {
658
8458215
                    if (weight_matrix[i] != 32)
659
6479585
                        level += 32;
660
8458215
                    level >>= 6;
661
                }
662
8458215
                level = -level;
663
            } else {
664
8316426
                level = (2 * level + 1) * qscale * weight_matrix[i];
665
8316426
                if (ctx->bit_depth == 10) {
666
                    if (weight_matrix[i] != 8)
667
                        level += 8;
668
                    level >>= 4;
669
                } else {
670
8316426
                    if (weight_matrix[i] != 32)
671
6813970
                        level += 32;
672
8316426
                    level >>= 6;
673
                }
674
            }
675
16774641
            block[j] = level;
676
        }
677
    }
678
3024000
}
679
680
3024000
static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
681
{
682
3024000
    int score = 0;
683
    int i;
684
196560000
    for (i = 0; i < 64; i++)
685
193536000
        score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
686
3024000
    return score;
687
}
688
689
static av_always_inline
690
51881432
int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
691
{
692
51881432
    int last_non_zero = 0;
693
51881432
    int bits = 0;
694
    int i, j, level;
695
515019637
    for (i = 1; i <= last_index; i++) {
696
463138205
        j = ctx->m.intra_scantable.permutated[i];
697
463138205
        level = block[j];
698
463138205
        if (level) {
699
191817206
            int run_level = i - last_non_zero - 1;
700
191817206
            bits += ctx->vlc_bits[level * (1 << 1) |
701
191817206
                    !!run_level] + ctx->run_bits[run_level];
702
191817206
            last_non_zero = i;
703
        }
704
    }
705
51881432
    return bits;
706
}
707
708
static av_always_inline
709
9849999
void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
710
{
711
9849999
    const int bs = ctx->block_width_l2;
712
9849999
    const int bw = 1 << bs;
713
9849999
    int dct_y_offset = ctx->dct_y_offset;
714
9849999
    int dct_uv_offset = ctx->dct_uv_offset;
715
9849999
    int linesize = ctx->m.linesize;
716
9849999
    int uvlinesize = ctx->m.uvlinesize;
717
9849999
    const uint8_t *ptr_y = ctx->thread[0]->src[0] +
718
9849999
                           ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs + 1);
719
9849999
    const uint8_t *ptr_u = ctx->thread[0]->src[1] +
720
9849999
                           ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs + ctx->is_444);
721
9849999
    const uint8_t *ptr_v = ctx->thread[0]->src[2] +
722
9849999
                           ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs + ctx->is_444);
723
9849999
    PixblockDSPContext *pdsp = &ctx->m.pdsp;
724
9849999
    VideoDSPContext *vdsp = &ctx->m.vdsp;
725
726

9849999
    if (ctx->bit_depth != 10 && vdsp->emulated_edge_mc && ((mb_x << 4) + 16 > ctx->m.avctx->width ||
727
7203152
                                                           (mb_y << 4) + 16 > ctx->m.avctx->height)) {
728
22511
        int y_w = ctx->m.avctx->width  - (mb_x << 4);
729
22511
        int y_h = ctx->m.avctx->height - (mb_y << 4);
730
22511
        int uv_w = (y_w + 1) / 2;
731
22511
        int uv_h = y_h;
732
22511
        linesize = 16;
733
22511
        uvlinesize = 8;
734
735
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_y[0], ptr_y,
736
                               linesize, ctx->m.linesize,
737
                               linesize, 16,
738
                               0, 0, y_w, y_h);
739
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[0][0], ptr_u,
740
                               uvlinesize, ctx->m.uvlinesize,
741
                               uvlinesize, 16,
742
                               0, 0, uv_w, uv_h);
743
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[1][0], ptr_v,
744
                               uvlinesize, ctx->m.uvlinesize,
745
                               uvlinesize, 16,
746
                               0, 0, uv_w, uv_h);
747
748
22511
        dct_y_offset =  bw * linesize;
749
22511
        dct_uv_offset = bw * uvlinesize;
750
22511
        ptr_y = &ctx->edge_buf_y[0];
751
22511
        ptr_u = &ctx->edge_buf_uv[0][0];
752
22511
        ptr_v = &ctx->edge_buf_uv[1][0];
753

9827488
    } else if (ctx->bit_depth == 10 && vdsp->emulated_edge_mc && ((mb_x << 4) + 16 > ctx->m.avctx->width ||
754
                                                                  (mb_y << 4) + 16 > ctx->m.avctx->height)) {
755
        int y_w = ctx->m.avctx->width  - (mb_x << 4);
756
        int y_h = ctx->m.avctx->height - (mb_y << 4);
757
        int uv_w = ctx->is_444 ? y_w : (y_w + 1) / 2;
758
        int uv_h = y_h;
759
        linesize = 32;
760
        uvlinesize = 16 + 16 * ctx->is_444;
761
762
        vdsp->emulated_edge_mc(&ctx->edge_buf_y[0], ptr_y,
763
                               linesize, ctx->m.linesize,
764
                               linesize / 2, 16,
765
                               0, 0, y_w, y_h);
766
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[0][0], ptr_u,
767
                               uvlinesize, ctx->m.uvlinesize,
768
                               uvlinesize / 2, 16,
769
                               0, 0, uv_w, uv_h);
770
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[1][0], ptr_v,
771
                               uvlinesize, ctx->m.uvlinesize,
772
                               uvlinesize / 2, 16,
773
                               0, 0, uv_w, uv_h);
774
775
        dct_y_offset =  bw * linesize / 2;
776
        dct_uv_offset = bw * uvlinesize / 2;
777
        ptr_y = &ctx->edge_buf_y[0];
778
        ptr_u = &ctx->edge_buf_uv[0][0];
779
        ptr_v = &ctx->edge_buf_uv[1][0];
780
    }
781
782
9849999
    if (!ctx->is_444) {
783
9849999
        pdsp->get_pixels(ctx->blocks[0], ptr_y,      linesize);
784
9849999
        pdsp->get_pixels(ctx->blocks[1], ptr_y + bw, linesize);
785
9849999
        pdsp->get_pixels(ctx->blocks[2], ptr_u,      uvlinesize);
786
9849999
        pdsp->get_pixels(ctx->blocks[3], ptr_v,      uvlinesize);
787
788

9849999
        if (mb_y + 1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
789
56560
            if (ctx->interlaced) {
790
35280
                ctx->get_pixels_8x4_sym(ctx->blocks[4],
791
                                        ptr_y + dct_y_offset,
792
                                        linesize);
793
35280
                ctx->get_pixels_8x4_sym(ctx->blocks[5],
794
35280
                                        ptr_y + dct_y_offset + bw,
795
                                        linesize);
796
35280
                ctx->get_pixels_8x4_sym(ctx->blocks[6],
797
                                        ptr_u + dct_uv_offset,
798
                                        uvlinesize);
799
35280
                ctx->get_pixels_8x4_sym(ctx->blocks[7],
800
                                        ptr_v + dct_uv_offset,
801
                                        uvlinesize);
802
            } else {
803
21280
                ctx->bdsp.clear_block(ctx->blocks[4]);
804
21280
                ctx->bdsp.clear_block(ctx->blocks[5]);
805
21280
                ctx->bdsp.clear_block(ctx->blocks[6]);
806
21280
                ctx->bdsp.clear_block(ctx->blocks[7]);
807
            }
808
        } else {
809
9793439
            pdsp->get_pixels(ctx->blocks[4],
810
                             ptr_y + dct_y_offset, linesize);
811
9793439
            pdsp->get_pixels(ctx->blocks[5],
812
9793439
                             ptr_y + dct_y_offset + bw, linesize);
813
9793439
            pdsp->get_pixels(ctx->blocks[6],
814
                             ptr_u + dct_uv_offset, uvlinesize);
815
9793439
            pdsp->get_pixels(ctx->blocks[7],
816
                             ptr_v + dct_uv_offset, uvlinesize);
817
        }
818
    } else {
819
        pdsp->get_pixels(ctx->blocks[0], ptr_y,      linesize);
820
        pdsp->get_pixels(ctx->blocks[1], ptr_y + bw, linesize);
821
        pdsp->get_pixels(ctx->blocks[6], ptr_y + dct_y_offset, linesize);
822
        pdsp->get_pixels(ctx->blocks[7], ptr_y + dct_y_offset + bw, linesize);
823
824
        pdsp->get_pixels(ctx->blocks[2], ptr_u,      uvlinesize);
825
        pdsp->get_pixels(ctx->blocks[3], ptr_u + bw, uvlinesize);
826
        pdsp->get_pixels(ctx->blocks[8], ptr_u + dct_uv_offset, uvlinesize);
827
        pdsp->get_pixels(ctx->blocks[9], ptr_u + dct_uv_offset + bw, uvlinesize);
828
829
        pdsp->get_pixels(ctx->blocks[4], ptr_v,      uvlinesize);
830
        pdsp->get_pixels(ctx->blocks[5], ptr_v + bw, uvlinesize);
831
        pdsp->get_pixels(ctx->blocks[10], ptr_v + dct_uv_offset, uvlinesize);
832
        pdsp->get_pixels(ctx->blocks[11], ptr_v + dct_uv_offset + bw, uvlinesize);
833
    }
834
9849999
}
835
836
static av_always_inline
837
78799992
int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
838
{
839
    int x;
840
841
78799992
    if (ctx->is_444) {
842
        x = (i >> 1) % 3;
843
    } else {
844
        const static uint8_t component[8]={0,0,1,2,0,0,1,2};
845
78799992
        x = component[i];
846
    }
847
78799992
    return x;
848
}
849
850
41557
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg,
851
                                  int jobnr, int threadnr)
852
{
853
41557
    DNXHDEncContext *ctx = avctx->priv_data;
854
41557
    int mb_y = jobnr, mb_x;
855
41557
    int qscale = ctx->qscale;
856
41557
    LOCAL_ALIGNED_16(int16_t, block, [64]);
857
41557
    ctx = ctx->thread[threadnr];
858
859
41557
    ctx->m.last_dc[0] =
860
41557
    ctx->m.last_dc[1] =
861
41557
    ctx->m.last_dc[2] = 1 << (ctx->bit_depth + 2);
862
863
6526736
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
864
6485179
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
865
6485179
        int ssd     = 0;
866
6485179
        int ac_bits = 0;
867
6485179
        int dc_bits = 0;
868
        int i;
869
870
6485179
        dnxhd_get_blocks(ctx, mb_x, mb_y);
871
872
58366611
        for (i = 0; i < 8 + 4 * ctx->is_444; i++) {
873
51881432
            int16_t *src_block = ctx->blocks[i];
874
            int overflow, nbits, diff, last_index;
875
51881432
            int n = dnxhd_switch_matrix(ctx, i);
876
877
51881432
            memcpy(block, src_block, 64 * sizeof(*block));
878
51881432
            last_index = ctx->m.dct_quantize(&ctx->m, block,
879

51881432
                                             ctx->is_444 ? 4 * (n > 0): 4 & (2*i),
880
                                             qscale, &overflow);
881
51881432
            ac_bits   += dnxhd_calc_ac_bits(ctx, block, last_index);
882
883
51881432
            diff = block[0] - ctx->m.last_dc[n];
884
51881432
            if (diff < 0)
885
23766663
                nbits = av_log2_16bit(-2 * diff);
886
            else
887
28114769
                nbits = av_log2_16bit(2 * diff);
888
889
            av_assert1(nbits < ctx->bit_depth + 4);
890
51881432
            dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
891
892
51881432
            ctx->m.last_dc[n] = block[0];
893
894
51881432
            if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
895
3024000
                dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
896
3024000
                ctx->m.idsp.idct(block);
897
3024000
                ssd += dnxhd_ssd_block(block, src_block);
898
            }
899
        }
900
6485179
        ctx->mb_rc[(qscale * ctx->m.mb_num) + mb].ssd  = ssd;
901
6485179
        ctx->mb_rc[(qscale * ctx->m.mb_num) + mb].bits = ac_bits + dc_bits + 12 +
902
6485179
                                     (1 + ctx->is_444) * 8 * ctx->vlc_bits[0];
903
    }
904
41557
    return 0;
905
}
906
907
20765
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg,
908
                               int jobnr, int threadnr)
909
{
910
20765
    DNXHDEncContext *ctx = avctx->priv_data;
911
20765
    int mb_y = jobnr, mb_x;
912
20765
    ctx = ctx->thread[threadnr];
913
20765
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + ctx->data_offset + ctx->slice_offs[jobnr],
914
20765
                  ctx->slice_size[jobnr]);
915
916
20765
    ctx->m.last_dc[0] =
917
20765
    ctx->m.last_dc[1] =
918
20765
    ctx->m.last_dc[2] = 1 << (ctx->bit_depth + 2);
919
3385585
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
920
3364820
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
921
3364820
        int qscale = ctx->mb_qscale[mb];
922
        int i;
923
924
3364820
        put_bits(&ctx->m.pb, 11, qscale);
925
3364820
        put_bits(&ctx->m.pb, 1, avctx->pix_fmt == AV_PIX_FMT_YUV444P10);
926
927
3364820
        dnxhd_get_blocks(ctx, mb_x, mb_y);
928
929
30283380
        for (i = 0; i < 8 + 4 * ctx->is_444; i++) {
930
26918560
            int16_t *block = ctx->blocks[i];
931
26918560
            int overflow, n = dnxhd_switch_matrix(ctx, i);
932
26918560
            int last_index = ctx->m.dct_quantize(&ctx->m, block,
933

26918560
                                                 ctx->is_444 ? (((i >> 1) % 3) < 1 ? 0 : 4): 4 & (2*i),
934
                                                 qscale, &overflow);
935
936
26918560
            dnxhd_encode_block(ctx, block, last_index, n);
937
        }
938
    }
939
20765
    if (put_bits_count(&ctx->m.pb) & 31)
940
20137
        put_bits(&ctx->m.pb, 32 - (put_bits_count(&ctx->m.pb) & 31), 0);
941
20765
    flush_put_bits(&ctx->m.pb);
942
20765
    return 0;
943
}
944
945
380
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
946
{
947
    int mb_y, mb_x;
948
380
    int offset = 0;
949
21145
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
950
        int thread_size;
951
20765
        ctx->slice_offs[mb_y] = offset;
952
20765
        ctx->slice_size[mb_y] = 0;
953
3385585
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
954
3364820
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
955
3364820
            ctx->slice_size[mb_y] += ctx->mb_bits[mb];
956
        }
957
20765
        ctx->slice_size[mb_y]   = (ctx->slice_size[mb_y] + 31) & ~31;
958
20765
        ctx->slice_size[mb_y] >>= 3;
959
20765
        thread_size = ctx->slice_size[mb_y];
960
20765
        offset += thread_size;
961
    }
962
380
}
963
964
11520
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg,
965
                               int jobnr, int threadnr)
966
{
967
11520
    DNXHDEncContext *ctx = avctx->priv_data;
968
11520
    int mb_y = jobnr, mb_x, x, y;
969
11740
    int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
970
220
                           ((avctx->height >> ctx->interlaced) & 0xF);
971
972
11520
    ctx = ctx->thread[threadnr];
973
11520
    if (ctx->bit_depth == 8) {
974
10955
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize);
975
1930655
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
976
1919700
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
977
            int sum;
978
            int varc;
979
980

1919700
            if (!partial_last_row && mb_x * 16 <= avctx->width - 16 && (avctx->width % 16) == 0) {
981
1901720
                sum  = ctx->m.mpvencdsp.pix_sum(pix, ctx->m.linesize);
982
1901720
                varc = ctx->m.mpvencdsp.pix_norm1(pix, ctx->m.linesize);
983
            } else {
984
17980
                int bw = FFMIN(avctx->width - 16 * mb_x, 16);
985
17980
                int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
986
17980
                sum = varc = 0;
987
244175
                for (y = 0; y < bh; y++) {
988
3800030
                    for (x = 0; x < bw; x++) {
989
3573835
                        uint8_t val = pix[x + y * ctx->m.linesize];
990
3573835
                        sum  += val;
991
3573835
                        varc += val * val;
992
                    }
993
                }
994
            }
995
1919700
            varc = (varc - (((unsigned) sum * sum) >> 8) + 128) >> 8;
996
997
1919700
            ctx->mb_cmp[mb].value = varc;
998
1919700
            ctx->mb_cmp[mb].mb    = mb;
999
        }
1000
    } else { // 10-bit
1001
565
        const int linesize = ctx->m.linesize >> 1;
1002
59365
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
1003
58800
            uint16_t *pix = (uint16_t *)ctx->thread[0]->src[0] +
1004
58800
                            ((mb_y << 4) * linesize) + (mb_x << 4);
1005
58800
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
1006
58800
            int sum = 0;
1007
58800
            int sqsum = 0;
1008
58800
            int bw = FFMIN(avctx->width - 16 * mb_x, 16);
1009
58800
            int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
1010
            int mean, sqmean;
1011
            int i, j;
1012
            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
1013
994800
            for (i = 0; i < bh; ++i) {
1014
15912000
                for (j = 0; j < bw; ++j) {
1015
                    // Turn 16-bit pixels into 10-bit ones.
1016
14976000
                    const int sample = (unsigned) pix[j] >> 6;
1017
14976000
                    sum   += sample;
1018
14976000
                    sqsum += sample * sample;
1019
                    // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
1020
                }
1021
936000
                pix += linesize;
1022
            }
1023
58800
            mean = sum >> 8; // 16*16 == 2^8
1024
58800
            sqmean = sqsum >> 8;
1025
58800
            ctx->mb_cmp[mb].value = sqmean - mean * mean;
1026
58800
            ctx->mb_cmp[mb].mb    = mb;
1027
        }
1028
    }
1029
11520
    return 0;
1030
}
1031
1032
15
static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
1033
{
1034
    int lambda, up_step, down_step;
1035
15
    int last_lower = INT_MAX, last_higher = 0;
1036
    int x, y, q;
1037
1038
120
    for (q = 1; q < avctx->qmax; q++) {
1039
105
        ctx->qscale = q;
1040
105
        avctx->execute2(avctx, dnxhd_calc_bits_thread,
1041
                        NULL, NULL, ctx->m.mb_height);
1042
    }
1043
15
    up_step = down_step = 2 << LAMBDA_FRAC_BITS;
1044
15
    lambda  = ctx->lambda;
1045
1046
70
    for (;;) {
1047
85
        int bits = 0;
1048
85
        int end  = 0;
1049
85
        if (lambda == last_higher) {
1050
5
            lambda++;
1051
5
            end = 1; // need to set final qscales/bits
1052
        }
1053
3862
        for (y = 0; y < ctx->m.mb_height; y++) {
1054
308529
            for (x = 0; x < ctx->m.mb_width; x++) {
1055
304720
                unsigned min = UINT_MAX;
1056
304720
                int qscale = 1;
1057
304720
                int mb     = y * ctx->m.mb_width + x;
1058
304720
                int rc = 0;
1059
2437760
                for (q = 1; q < avctx->qmax; q++) {
1060
2133040
                    int i = (q*ctx->m.mb_num) + mb;
1061
2133040
                    unsigned score = ctx->mb_rc[i].bits * lambda +
1062
2133040
                                     ((unsigned) ctx->mb_rc[i].ssd << LAMBDA_FRAC_BITS);
1063
2133040
                    if (score < min) {
1064
493989
                        min    = score;
1065
493989
                        qscale = q;
1066
493989
                        rc = i;
1067
                    }
1068
                }
1069
304720
                bits += ctx->mb_rc[rc].bits;
1070
304720
                ctx->mb_qscale[mb] = qscale;
1071
304720
                ctx->mb_bits[mb]   = ctx->mb_rc[rc].bits;
1072
            }
1073
3809
            bits = (bits + 31) & ~31; // padding
1074
3809
            if (bits > ctx->frame_bits)
1075
32
                break;
1076
        }
1077
85
        if (end) {
1078
5
            if (bits > ctx->frame_bits)
1079
                return AVERROR(EINVAL);
1080
5
            break;
1081
        }
1082
80
        if (bits < ctx->frame_bits) {
1083
48
            last_lower = FFMIN(lambda, last_lower);
1084
48
            if (last_higher != 0)
1085
25
                lambda = (lambda+last_higher)>>1;
1086
            else
1087
23
                lambda -= down_step;
1088
48
            down_step = FFMIN((int64_t)down_step*5, INT_MAX);
1089
48
            up_step = 1<<LAMBDA_FRAC_BITS;
1090
48
            lambda = FFMAX(1, lambda);
1091
48
            if (lambda == last_lower)
1092
10
                break;
1093
        } else {
1094
32
            last_higher = FFMAX(lambda, last_higher);
1095
32
            if (last_lower != INT_MAX)
1096
32
                lambda = (lambda+last_lower)>>1;
1097
            else if ((int64_t)lambda + up_step > INT_MAX)
1098
                return AVERROR(EINVAL);
1099
            else
1100
                lambda += up_step;
1101
32
            up_step = FFMIN((int64_t)up_step*5, INT_MAX);
1102
32
            down_step = 1<<LAMBDA_FRAC_BITS;
1103
        }
1104
    }
1105
15
    ctx->lambda = lambda;
1106
15
    return 0;
1107
}
1108
1109
365
static int dnxhd_find_qscale(DNXHDEncContext *ctx)
1110
{
1111
365
    int bits = 0;
1112
365
    int up_step = 1;
1113
365
    int down_step = 1;
1114
365
    int last_higher = 0;
1115
365
    int last_lower = INT_MAX;
1116
    int qscale;
1117
    int x, y;
1118
1119
365
    qscale = ctx->qscale;
1120
    for (;;) {
1121
691
        bits = 0;
1122
691
        ctx->qscale = qscale;
1123
        // XXX avoid recalculating bits
1124
691
        ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread,
1125
                               NULL, NULL, ctx->m.mb_height);
1126
35231
        for (y = 0; y < ctx->m.mb_height; y++) {
1127
5794959
            for (x = 0; x < ctx->m.mb_width; x++)
1128
5760121
                bits += ctx->mb_rc[(qscale*ctx->m.mb_num) + (y*ctx->m.mb_width+x)].bits;
1129
34838
            bits = (bits+31)&~31; // padding
1130
34838
            if (bits > ctx->frame_bits)
1131
298
                break;
1132
        }
1133
691
        if (bits < ctx->frame_bits) {
1134
393
            if (qscale == 1)
1135
145
                return 1;
1136
248
            if (last_higher == qscale - 1) {
1137
195
                qscale = last_higher;
1138
195
                break;
1139
            }
1140
53
            last_lower = FFMIN(qscale, last_lower);
1141
53
            if (last_higher != 0)
1142
38
                qscale = (qscale + last_higher) >> 1;
1143
            else
1144
15
                qscale -= down_step++;
1145
53
            if (qscale < 1)
1146
                qscale = 1;
1147
53
            up_step = 1;
1148
        } else {
1149
298
            if (last_lower == qscale + 1)
1150
25
                break;
1151
273
            last_higher = FFMAX(qscale, last_higher);
1152
273
            if (last_lower != INT_MAX)
1153
5
                qscale = (qscale + last_lower) >> 1;
1154
            else
1155
268
                qscale += up_step++;
1156
273
            down_step = 1;
1157
273
            if (qscale >= ctx->m.avctx->qmax)
1158
                return AVERROR(EINVAL);
1159
        }
1160
    }
1161
220
    ctx->qscale = qscale;
1162
220
    return 0;
1163
}
1164
1165
#define BUCKET_BITS 8
1166
#define RADIX_PASSES 4
1167
#define NBUCKETS (1 << BUCKET_BITS)
1168
1169
11871000
static inline int get_bucket(int value, int shift)
1170
{
1171
11871000
    value >>= shift;
1172
11871000
    value  &= NBUCKETS - 1;
1173
11871000
    return NBUCKETS - 1 - value;
1174
}
1175
1176
220
static void radix_count(const RCCMPEntry *data, int size,
1177
                        int buckets[RADIX_PASSES][NBUCKETS])
1178
{
1179
    int i, j;
1180
220
    memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
1181
1978720
    for (i = 0; i < size; i++) {
1182
1978500
        int v = data[i].value;
1183
9892500
        for (j = 0; j < RADIX_PASSES; j++) {
1184
7914000
            buckets[j][get_bucket(v, 0)]++;
1185
7914000
            v >>= BUCKET_BITS;
1186
        }
1187
        av_assert1(!v);
1188
    }
1189
1100
    for (j = 0; j < RADIX_PASSES; j++) {
1190
880
        int offset = size;
1191
226160
        for (i = NBUCKETS - 1; i >= 0; i--)
1192
225280
            buckets[j][i] = offset -= buckets[j][i];
1193
        av_assert1(!buckets[j][0]);
1194
    }
1195
220
}
1196
1197
440
static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data,
1198
                            int size, int buckets[NBUCKETS], int pass)
1199
{
1200
440
    int shift = pass * BUCKET_BITS;
1201
    int i;
1202
3957440
    for (i = 0; i < size; i++) {
1203
3957000
        int v   = get_bucket(data[i].value, shift);
1204
3957000
        int pos = buckets[v]++;
1205
3957000
        dst[pos] = data[i];
1206
    }
1207
440
}
1208
1209
220
static void radix_sort(RCCMPEntry *data, RCCMPEntry *tmp, int size)
1210
{
1211
    int buckets[RADIX_PASSES][NBUCKETS];
1212
220
    radix_count(data, size, buckets);
1213
220
    radix_sort_pass(tmp, data, size, buckets[0], 0);
1214
220
    radix_sort_pass(data, tmp, size, buckets[1], 1);
1215

220
    if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
1216
        radix_sort_pass(tmp, data, size, buckets[2], 2);
1217
        radix_sort_pass(data, tmp, size, buckets[3], 3);
1218
    }
1219
220
}
1220
1221
365
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
1222
{
1223
365
    int max_bits = 0;
1224
    int ret, x, y;
1225
365
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
1226
        return ret;
1227
20455
    for (y = 0; y < ctx->m.mb_height; y++) {
1228
3330910
        for (x = 0; x < ctx->m.mb_width; x++) {
1229
3310820
            int mb = y * ctx->m.mb_width + x;
1230
3310820
            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;
1231
            int delta_bits;
1232
3310820
            ctx->mb_qscale[mb] = ctx->qscale;
1233
3310820
            ctx->mb_bits[mb] = ctx->mb_rc[rc].bits;
1234
3310820
            max_bits += ctx->mb_rc[rc].bits;
1235
            if (!RC_VARIANCE) {
1236
                delta_bits = ctx->mb_rc[rc].bits -
1237
                             ctx->mb_rc[rc + ctx->m.mb_num].bits;
1238
                ctx->mb_cmp[mb].mb = mb;
1239
                ctx->mb_cmp[mb].value =
1240
                    delta_bits ? ((ctx->mb_rc[rc].ssd -
1241
                                   ctx->mb_rc[rc + ctx->m.mb_num].ssd) * 100) /
1242
                                  delta_bits
1243
                               : INT_MIN; // avoid increasing qscale
1244
            }
1245
        }
1246
20090
        max_bits += 31; // worst padding
1247
    }
1248
365
    if (!ret) {
1249
        if (RC_VARIANCE)
1250
220
            avctx->execute2(avctx, dnxhd_mb_var_thread,
1251
                            NULL, NULL, ctx->m.mb_height);
1252
220
        radix_sort(ctx->mb_cmp, ctx->mb_cmp_tmp, ctx->m.mb_num);
1253

647025
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
1254
646805
            int mb = ctx->mb_cmp[x].mb;
1255
646805
            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;
1256
646805
            max_bits -= ctx->mb_rc[rc].bits -
1257
646805
                        ctx->mb_rc[rc + ctx->m.mb_num].bits;
1258
646805
            ctx->mb_qscale[mb] = ctx->qscale + 1;
1259
646805
            ctx->mb_bits[mb]   = ctx->mb_rc[rc + ctx->m.mb_num].bits;
1260
        }
1261
    }
1262
365
    return 0;
1263
}
1264
1265
325
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
1266
{
1267
    int i;
1268
1269
650
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
1270
325
        ctx->thread[i]->m.linesize    = frame->linesize[0] << ctx->interlaced;
1271
325
        ctx->thread[i]->m.uvlinesize  = frame->linesize[1] << ctx->interlaced;
1272
325
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
1273
325
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
1274
    }
1275
1276
#if FF_API_CODED_FRAME
1277
FF_DISABLE_DEPRECATION_WARNINGS
1278
325
    ctx->m.avctx->coded_frame->interlaced_frame = frame->interlaced_frame;
1279
FF_ENABLE_DEPRECATION_WARNINGS
1280
#endif
1281

325
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
1282
325
}
1283
1284
325
static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
1285
                                const AVFrame *frame, int *got_packet)
1286
{
1287
325
    DNXHDEncContext *ctx = avctx->priv_data;
1288
325
    int first_field = 1;
1289
    int offset, i, ret;
1290
    uint8_t *buf;
1291
1292
325
    if ((ret = ff_alloc_packet2(avctx, pkt, ctx->frame_size, 0)) < 0)
1293
        return ret;
1294
325
    buf = pkt->data;
1295
1296
325
    dnxhd_load_picture(ctx, frame);
1297
1298
380
encode_coding_unit:
1299
1520
    for (i = 0; i < 3; i++) {
1300
1140
        ctx->src[i] = frame->data[i];
1301

1140
        if (ctx->interlaced && ctx->cur_field)
1302
165
            ctx->src[i] += frame->linesize[i];
1303
    }
1304
1305
380
    dnxhd_write_header(avctx, buf);
1306
1307
380
    if (avctx->mb_decision == FF_MB_DECISION_RD)
1308
15
        ret = dnxhd_encode_rdo(avctx, ctx);
1309
    else
1310
365
        ret = dnxhd_encode_fast(avctx, ctx);
1311
380
    if (ret < 0) {
1312
        av_log(avctx, AV_LOG_ERROR,
1313
               "picture could not fit ratecontrol constraints, increase qmax\n");
1314
        return ret;
1315
    }
1316
1317
380
    dnxhd_setup_threads_slices(ctx);
1318
1319
380
    offset = 0;
1320
21145
    for (i = 0; i < ctx->m.mb_height; i++) {
1321
20765
        AV_WB32(ctx->msip + i * 4, offset);
1322
20765
        offset += ctx->slice_size[i];
1323
        av_assert1(!(ctx->slice_size[i] & 3));
1324
    }
1325
1326
380
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
1327
1328
    av_assert1(ctx->data_offset + offset + 4 <= ctx->coding_unit_size);
1329
380
    memset(buf + ctx->data_offset + offset, 0,
1330
380
           ctx->coding_unit_size - 4 - offset - ctx->data_offset);
1331
1332
380
    AV_WB32(buf + ctx->coding_unit_size - 4, 0x600DC0DE); // EOF
1333
1334

380
    if (ctx->interlaced && first_field) {
1335
55
        first_field     = 0;
1336
55
        ctx->cur_field ^= 1;
1337
55
        buf            += ctx->coding_unit_size;
1338
55
        goto encode_coding_unit;
1339
    }
1340
1341
#if FF_API_CODED_FRAME
1342
FF_DISABLE_DEPRECATION_WARNINGS
1343
325
    avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
1344
FF_ENABLE_DEPRECATION_WARNINGS
1345
#endif
1346
1347
325
    ff_side_data_set_encoder_stats(pkt, ctx->qscale * FF_QP2LAMBDA, NULL, 0, AV_PICTURE_TYPE_I);
1348
1349
325
    pkt->flags |= AV_PKT_FLAG_KEY;
1350
325
    *got_packet = 1;
1351
325
    return 0;
1352
}
1353
1354
73
static av_cold int dnxhd_encode_end(AVCodecContext *avctx)
1355
{
1356
73
    DNXHDEncContext *ctx = avctx->priv_data;
1357
    int i;
1358
1359
73
    av_freep(&ctx->orig_vlc_codes);
1360
73
    av_freep(&ctx->orig_vlc_bits);
1361
73
    av_freep(&ctx->run_codes);
1362
73
    av_freep(&ctx->run_bits);
1363
1364
73
    av_freep(&ctx->mb_bits);
1365
73
    av_freep(&ctx->mb_qscale);
1366
73
    av_freep(&ctx->mb_rc);
1367
73
    av_freep(&ctx->mb_cmp);
1368
73
    av_freep(&ctx->mb_cmp_tmp);
1369
73
    av_freep(&ctx->slice_size);
1370
73
    av_freep(&ctx->slice_offs);
1371
1372
73
    av_freep(&ctx->qmatrix_c);
1373
73
    av_freep(&ctx->qmatrix_l);
1374
73
    av_freep(&ctx->qmatrix_c16);
1375
73
    av_freep(&ctx->qmatrix_l16);
1376
1377
73
    if (avctx->active_thread_type == FF_THREAD_SLICE) {
1378
        for (i = 1; i < avctx->thread_count; i++)
1379
            av_freep(&ctx->thread[i]);
1380
    }
1381
1382
73
    return 0;
1383
}
1384
1385
static const AVCodecDefault dnxhd_defaults[] = {
1386
    { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1387
    { NULL },
1388
};
1389
1390
AVCodec ff_dnxhd_encoder = {
1391
    .name           = "dnxhd",
1392
    .long_name      = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1393
    .type           = AVMEDIA_TYPE_VIDEO,
1394
    .id             = AV_CODEC_ID_DNXHD,
1395
    .priv_data_size = sizeof(DNXHDEncContext),
1396
    .init           = dnxhd_encode_init,
1397
    .encode2        = dnxhd_encode_picture,
1398
    .close          = dnxhd_encode_end,
1399
    .capabilities   = AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
1400
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1401
    .pix_fmts       = (const enum AVPixelFormat[]) {
1402
        AV_PIX_FMT_YUV422P,
1403
        AV_PIX_FMT_YUV422P10,
1404
        AV_PIX_FMT_YUV444P10,
1405
        AV_PIX_FMT_GBRP10,
1406
        AV_PIX_FMT_NONE
1407
    },
1408
    .priv_class     = &dnxhd_class,
1409
    .defaults       = dnxhd_defaults,
1410
    .profiles       = NULL_IF_CONFIG_SMALL(ff_dnxhd_profiles),
1411
};