GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/dnxhdenc.c Lines: 679 803 84.6 %
Date: 2020-09-25 23:16:12 Branches: 303 415 73.0 %

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 "packet_internal.h"
37
#include "profiles.h"
38
#include "dnxhdenc.h"
39
40
// The largest value that will not lead to overflow for 10-bit samples.
41
#define DNX10BIT_QMAT_SHIFT 18
42
#define RC_VARIANCE 1 // use variance or ssd for fast rc
43
#define LAMBDA_FRAC_BITS 10
44
45
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
46
static const AVOption options[] = {
47
    { "nitris_compat", "encode with Avid Nitris compatibility",
48
        offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
49
    { "ibias", "intra quant bias",
50
        offsetof(DNXHDEncContext, intra_quant_bias), AV_OPT_TYPE_INT,
51
        { .i64 = 0 }, INT_MIN, INT_MAX, VE },
52
    { "profile",       NULL, offsetof(DNXHDEncContext, profile), AV_OPT_TYPE_INT,
53
        { .i64 = FF_PROFILE_DNXHD },
54
        FF_PROFILE_DNXHD, FF_PROFILE_DNXHR_444, VE, "profile" },
55
    { "dnxhd",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHD },
56
        0, 0, VE, "profile" },
57
    { "dnxhr_444", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_444 },
58
        0, 0, VE, "profile" },
59
    { "dnxhr_hqx", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_HQX },
60
        0, 0, VE, "profile" },
61
    { "dnxhr_hq",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_HQ },
62
        0, 0, VE, "profile" },
63
    { "dnxhr_sq",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_SQ },
64
        0, 0, VE, "profile" },
65
    { "dnxhr_lb",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_PROFILE_DNXHR_LB },
66
        0, 0, VE, "profile" },
67
    { NULL }
68
};
69
70
static const AVClass dnxhd_class = {
71
    .class_name = "dnxhd",
72
    .item_name  = av_default_item_name,
73
    .option     = options,
74
    .version    = LIBAVUTIL_VERSION_INT,
75
};
76
77
97920
static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block,
78
                                          const uint8_t *pixels,
79
                                          ptrdiff_t line_size)
80
{
81
    int i;
82
489600
    for (i = 0; i < 4; i++) {
83
391680
        block[0] = pixels[0];
84
391680
        block[1] = pixels[1];
85
391680
        block[2] = pixels[2];
86
391680
        block[3] = pixels[3];
87
391680
        block[4] = pixels[4];
88
391680
        block[5] = pixels[5];
89
391680
        block[6] = pixels[6];
90
391680
        block[7] = pixels[7];
91
391680
        pixels  += line_size;
92
391680
        block   += 8;
93
    }
94
97920
    memcpy(block,      block -  8, sizeof(*block) * 8);
95
97920
    memcpy(block +  8, block - 16, sizeof(*block) * 8);
96
97920
    memcpy(block + 16, block - 24, sizeof(*block) * 8);
97
97920
    memcpy(block + 24, block - 32, sizeof(*block) * 8);
98
97920
}
99
100
static av_always_inline
101
43200
void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block,
102
                                    const uint8_t *pixels,
103
                                    ptrdiff_t line_size)
104
{
105
43200
    memcpy(block + 0 * 8, pixels + 0 * line_size, 8 * sizeof(*block));
106
43200
    memcpy(block + 7 * 8, pixels + 0 * line_size, 8 * sizeof(*block));
107
43200
    memcpy(block + 1 * 8, pixels + 1 * line_size, 8 * sizeof(*block));
108
43200
    memcpy(block + 6 * 8, pixels + 1 * line_size, 8 * sizeof(*block));
109
43200
    memcpy(block + 2 * 8, pixels + 2 * line_size, 8 * sizeof(*block));
110
43200
    memcpy(block + 5 * 8, pixels + 2 * line_size, 8 * sizeof(*block));
111
43200
    memcpy(block + 3 * 8, pixels + 3 * line_size, 8 * sizeof(*block));
112
43200
    memcpy(block + 4 * 8, pixels + 3 * line_size, 8 * sizeof(*block));
113
43200
}
114
115
static int dnxhd_10bit_dct_quantize_444(MpegEncContext *ctx, int16_t *block,
116
                                        int n, int qscale, int *overflow)
117
{
118
    int i, j, level, last_non_zero, start_i;
119
    const int *qmat;
120
    const uint8_t *scantable= ctx->intra_scantable.scantable;
121
    int bias;
122
    int max = 0;
123
    unsigned int threshold1, threshold2;
124
125
    ctx->fdsp.fdct(block);
126
127
    block[0] = (block[0] + 2) >> 2;
128
    start_i = 1;
129
    last_non_zero = 0;
130
    qmat = n < 4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
131
    bias= ctx->intra_quant_bias * (1 << (16 - 8));
132
    threshold1 = (1 << 16) - bias - 1;
133
    threshold2 = (threshold1 << 1);
134
135
    for (i = 63; i >= start_i; i--) {
136
        j = scantable[i];
137
        level = block[j] * qmat[j];
138
139
        if (((unsigned)(level + threshold1)) > threshold2) {
140
            last_non_zero = i;
141
            break;
142
        } else{
143
            block[j]=0;
144
        }
145
    }
146
147
    for (i = start_i; i <= last_non_zero; i++) {
148
        j = scantable[i];
149
        level = block[j] * qmat[j];
150
151
        if (((unsigned)(level + threshold1)) > threshold2) {
152
            if (level > 0) {
153
                level = (bias + level) >> 16;
154
                block[j] = level;
155
            } else{
156
                level = (bias - level) >> 16;
157
                block[j] = -level;
158
            }
159
            max |= level;
160
        } else {
161
            block[j] = 0;
162
        }
163
    }
164
    *overflow = ctx->max_qcoeff < max; //overflow might have happened
165
166
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
167
    if (ctx->idsp.perm_type != FF_IDCT_PERM_NONE)
168
        ff_block_permute(block, ctx->idsp.idct_permutation,
169
                         scantable, last_non_zero);
170
171
    return last_non_zero;
172
}
173
174
3945600
static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
175
                                    int n, int qscale, int *overflow)
176
{
177
3945600
    const uint8_t *scantable= ctx->intra_scantable.scantable;
178
3945600
    const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
179
3945600
    int last_non_zero = 0;
180
    int i;
181
182
3945600
    ctx->fdsp.fdct(block);
183
184
    // Divide by 4 with rounding, to compensate scaling of DCT coefficients
185
3945600
    block[0] = (block[0] + 2) >> 2;
186
187
252518400
    for (i = 1; i < 64; ++i) {
188
248572800
        int j = scantable[i];
189
248572800
        int sign = FF_SIGNBIT(block[j]);
190
248572800
        int level = (block[j] ^ sign) - sign;
191
248572800
        level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
192
248572800
        block[j] = (level ^ sign) - sign;
193
248572800
        if (level)
194
32824223
            last_non_zero = i;
195
    }
196
197
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
198
3945600
    if (ctx->idsp.perm_type != FF_IDCT_PERM_NONE)
199
        ff_block_permute(block, ctx->idsp.idct_permutation,
200
                         scantable, last_non_zero);
201
202
3945600
    return last_non_zero;
203
}
204
205
73
static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
206
{
207
    int i, j, level, run;
208
73
    int max_level = 1 << (ctx->bit_depth + 2);
209
210
73
    if (!FF_ALLOCZ_TYPED_ARRAY(ctx->orig_vlc_codes, max_level * 4) ||
211
73
        !FF_ALLOCZ_TYPED_ARRAY(ctx->orig_vlc_bits,  max_level * 4) ||
212
73
        !(ctx->run_codes = av_mallocz(63 * 2))                     ||
213
73
        !(ctx->run_bits  = av_mallocz(63)))
214
        return AVERROR(ENOMEM);
215
73
    ctx->vlc_codes = ctx->orig_vlc_codes + max_level * 2;
216
73
    ctx->vlc_bits  = ctx->orig_vlc_bits + max_level * 2;
217
192585
    for (level = -max_level; level < max_level; level++) {
218
577536
        for (run = 0; run < 2; run++) {
219
385024
            int index = level * (1 << 1) | run;
220
385024
            int sign, offset = 0, alevel = level;
221
222
385024
            MASK_ABS(sign, alevel);
223
385024
            if (alevel > 64) {
224
366190
                offset  = (alevel - 1) >> 6;
225
366190
                alevel -= offset << 6;
226
            }
227
65137020
            for (j = 0; j < 257; j++) {
228

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

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

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

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

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

73
        (ctx->profile != FF_PROFILE_DNXHR_444 && (avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ||
373
73
                                                  avctx->pix_fmt == AV_PIX_FMT_GBRP10))) {
374
        av_log(avctx, AV_LOG_ERROR,
375
               "pixel format is incompatible with DNxHD profile\n");
376
        return AVERROR(EINVAL);
377
    }
378
379

73
    if (ctx->profile == FF_PROFILE_DNXHR_HQX && avctx->pix_fmt != AV_PIX_FMT_YUV422P10) {
380
        av_log(avctx, AV_LOG_ERROR,
381
               "pixel format is incompatible with DNxHR HQX profile\n");
382
        return AVERROR(EINVAL);
383
    }
384
385
73
    if ((ctx->profile == FF_PROFILE_DNXHR_LB ||
386
61
         ctx->profile == FF_PROFILE_DNXHR_SQ ||
387

73
         ctx->profile == FF_PROFILE_DNXHR_HQ) && avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
388
        av_log(avctx, AV_LOG_ERROR,
389
               "pixel format is incompatible with DNxHR LB/SQ/HQ profile\n");
390
        return AVERROR(EINVAL);
391
    }
392
393
73
    ctx->is_444 = ctx->profile == FF_PROFILE_DNXHR_444;
394
73
    avctx->profile = ctx->profile;
395
73
    ctx->cid = ff_dnxhd_find_cid(avctx, ctx->bit_depth);
396
73
    if (!ctx->cid) {
397
        av_log(avctx, AV_LOG_ERROR,
398
               "video parameters incompatible with DNxHD. Valid DNxHD profiles:\n");
399
        ff_dnxhd_print_profiles(avctx, AV_LOG_ERROR);
400
        return AVERROR(EINVAL);
401
    }
402
73
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
403
404

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

73
    if (avctx->width < 256 || avctx->height < 120) {
408
        av_log(avctx, AV_LOG_ERROR,
409
               "Input dimensions too small, input must be at least 256x120\n");
410
        return AVERROR(EINVAL);
411
    }
412
413
73
    index = ff_dnxhd_get_cid_table(ctx->cid);
414
73
    av_assert0(index >= 0);
415
416
73
    ctx->cid_table = &ff_dnxhd_cid_table[index];
417
418
73
    ctx->m.avctx    = avctx;
419
73
    ctx->m.mb_intra = 1;
420
73
    ctx->m.h263_aic = 1;
421
422
73
    avctx->bits_per_raw_sample = ctx->bit_depth;
423
424
73
    ff_blockdsp_init(&ctx->bdsp, avctx);
425
73
    ff_fdctdsp_init(&ctx->m.fdsp, avctx);
426
73
    ff_mpv_idct_init(&ctx->m);
427
73
    ff_mpegvideoencdsp_init(&ctx->m.mpvencdsp, avctx);
428
73
    ff_pixblockdsp_init(&ctx->m.pdsp, avctx);
429
73
    ff_dct_encode_init(&ctx->m);
430
431
73
    if (ctx->profile != FF_PROFILE_DNXHD)
432
40
        ff_videodsp_init(&ctx->m.vdsp, ctx->bit_depth);
433
434
73
    if (!ctx->m.dct_quantize)
435
        ctx->m.dct_quantize = ff_dct_quantize_c;
436
437

73
    if (ctx->is_444 || ctx->profile == FF_PROFILE_DNXHR_HQX) {
438
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize_444;
439
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
440
        ctx->block_width_l2     = 4;
441
73
    } else if (ctx->bit_depth == 10) {
442
7
        ctx->m.dct_quantize     = dnxhd_10bit_dct_quantize;
443
7
        ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
444
7
        ctx->block_width_l2     = 4;
445
    } else {
446
66
        ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
447
66
        ctx->block_width_l2     = 3;
448
    }
449
450
    if (ARCH_X86)
451
73
        ff_dnxhdenc_init_x86(ctx);
452
453
73
    ctx->m.mb_height = (avctx->height + 15) / 16;
454
73
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
455
456
73
    if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
457
11
        ctx->interlaced   = 1;
458
11
        ctx->m.mb_height /= 2;
459
    }
460
461

73
    if (ctx->interlaced && ctx->profile != FF_PROFILE_DNXHD) {
462
        av_log(avctx, AV_LOG_ERROR,
463
               "Interlaced encoding is not supported for DNxHR profiles.\n");
464
        return AVERROR(EINVAL);
465
    }
466
467
73
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
468
469
73
    if (ctx->cid_table->frame_size == DNXHD_VARIABLE) {
470
40
        ctx->frame_size = avpriv_dnxhd_get_hr_frame_size(ctx->cid,
471
                                                     avctx->width, avctx->height);
472
40
        av_assert0(ctx->frame_size >= 0);
473
40
        ctx->coding_unit_size = ctx->frame_size;
474
    } else {
475
33
        ctx->frame_size = ctx->cid_table->frame_size;
476
33
        ctx->coding_unit_size = ctx->cid_table->coding_unit_size;
477
    }
478
479
73
    if (ctx->m.mb_height > 68)
480
12
        ctx->data_offset = 0x170 + (ctx->m.mb_height << 2);
481
    else
482
61
        ctx->data_offset = 0x280;
483
484
    // XXX tune lbias/cbias
485
73
    if ((ret = dnxhd_init_qmat(ctx, ctx->intra_quant_bias, 0)) < 0)
486
        return ret;
487
488
    /* Avid Nitris hardware decoder requires a minimum amount of padding
489
     * in the coding unit payload */
490
73
    if (ctx->nitris_compat)
491
        ctx->min_padding = 1600;
492
493
73
    if ((ret = dnxhd_init_vlc(ctx)) < 0)
494
        return ret;
495
73
    if ((ret = dnxhd_init_rc(ctx)) < 0)
496
        return ret;
497
498
73
    if (!FF_ALLOCZ_TYPED_ARRAY(ctx->slice_size, ctx->m.mb_height) ||
499
73
        !FF_ALLOCZ_TYPED_ARRAY(ctx->slice_offs, ctx->m.mb_height) ||
500
73
        !FF_ALLOCZ_TYPED_ARRAY(ctx->mb_bits,    ctx->m.mb_num)    ||
501
73
        !FF_ALLOCZ_TYPED_ARRAY(ctx->mb_qscale,  ctx->m.mb_num))
502
        return AVERROR(ENOMEM);
503
#if FF_API_CODED_FRAME
504
FF_DISABLE_DEPRECATION_WARNINGS
505
73
    avctx->coded_frame->key_frame = 1;
506
73
    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
507
FF_ENABLE_DEPRECATION_WARNINGS
508
#endif
509
510
73
    if (avctx->active_thread_type == FF_THREAD_SLICE) {
511
        if (avctx->thread_count > MAX_THREADS) {
512
            av_log(avctx, AV_LOG_ERROR, "too many threads\n");
513
            return AVERROR(EINVAL);
514
        }
515
    }
516
517
73
    if (avctx->qmax <= 1) {
518
        av_log(avctx, AV_LOG_ERROR, "qmax must be at least 2\n");
519
        return AVERROR(EINVAL);
520
    }
521
522
73
    ctx->thread[0] = ctx;
523
73
    if (avctx->active_thread_type == FF_THREAD_SLICE) {
524
        for (i = 1; i < avctx->thread_count; i++) {
525
            ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
526
            if (!ctx->thread[i])
527
                return AVERROR(ENOMEM);
528
            memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
529
        }
530
    }
531
532
73
    return 0;
533
}
534
535
380
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
536
{
537
380
    DNXHDEncContext *ctx = avctx->priv_data;
538
539
380
    memset(buf, 0, ctx->data_offset);
540
541
    // * write prefix */
542
380
    AV_WB16(buf + 0x02, ctx->data_offset);
543

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

9849999
    if (ctx->bit_depth != 10 && vdsp->emulated_edge_mc && ((mb_x << 4) + 16 > ctx->m.avctx->width ||
707
7203152
                                                           (mb_y << 4) + 16 > ctx->m.avctx->height)) {
708
22511
        int y_w = ctx->m.avctx->width  - (mb_x << 4);
709
22511
        int y_h = ctx->m.avctx->height - (mb_y << 4);
710
22511
        int uv_w = (y_w + 1) / 2;
711
22511
        int uv_h = y_h;
712
22511
        linesize = 16;
713
22511
        uvlinesize = 8;
714
715
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_y[0], ptr_y,
716
                               linesize, ctx->m.linesize,
717
                               linesize, 16,
718
                               0, 0, y_w, y_h);
719
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[0][0], ptr_u,
720
                               uvlinesize, ctx->m.uvlinesize,
721
                               uvlinesize, 16,
722
                               0, 0, uv_w, uv_h);
723
22511
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[1][0], ptr_v,
724
                               uvlinesize, ctx->m.uvlinesize,
725
                               uvlinesize, 16,
726
                               0, 0, uv_w, uv_h);
727
728
22511
        dct_y_offset =  bw * linesize;
729
22511
        dct_uv_offset = bw * uvlinesize;
730
22511
        ptr_y = &ctx->edge_buf_y[0];
731
22511
        ptr_u = &ctx->edge_buf_uv[0][0];
732
22511
        ptr_v = &ctx->edge_buf_uv[1][0];
733

9827488
    } else if (ctx->bit_depth == 10 && vdsp->emulated_edge_mc && ((mb_x << 4) + 16 > ctx->m.avctx->width ||
734
                                                                  (mb_y << 4) + 16 > ctx->m.avctx->height)) {
735
        int y_w = ctx->m.avctx->width  - (mb_x << 4);
736
        int y_h = ctx->m.avctx->height - (mb_y << 4);
737
        int uv_w = ctx->is_444 ? y_w : (y_w + 1) / 2;
738
        int uv_h = y_h;
739
        linesize = 32;
740
        uvlinesize = 16 + 16 * ctx->is_444;
741
742
        vdsp->emulated_edge_mc(&ctx->edge_buf_y[0], ptr_y,
743
                               linesize, ctx->m.linesize,
744
                               linesize / 2, 16,
745
                               0, 0, y_w, y_h);
746
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[0][0], ptr_u,
747
                               uvlinesize, ctx->m.uvlinesize,
748
                               uvlinesize / 2, 16,
749
                               0, 0, uv_w, uv_h);
750
        vdsp->emulated_edge_mc(&ctx->edge_buf_uv[1][0], ptr_v,
751
                               uvlinesize, ctx->m.uvlinesize,
752
                               uvlinesize / 2, 16,
753
                               0, 0, uv_w, uv_h);
754
755
        dct_y_offset =  bw * linesize / 2;
756
        dct_uv_offset = bw * uvlinesize / 2;
757
        ptr_y = &ctx->edge_buf_y[0];
758
        ptr_u = &ctx->edge_buf_uv[0][0];
759
        ptr_v = &ctx->edge_buf_uv[1][0];
760
    }
761
762
9849999
    if (!ctx->is_444) {
763
9849999
        pdsp->get_pixels(ctx->blocks[0], ptr_y,      linesize);
764
9849999
        pdsp->get_pixels(ctx->blocks[1], ptr_y + bw, linesize);
765
9849999
        pdsp->get_pixels(ctx->blocks[2], ptr_u,      uvlinesize);
766
9849999
        pdsp->get_pixels(ctx->blocks[3], ptr_v,      uvlinesize);
767
768

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

51881432
                                             ctx->is_444 ? 4 * (n > 0): 4 & (2*i),
860
                                             qscale, &overflow);
861
51881432
            ac_bits   += dnxhd_calc_ac_bits(ctx, block, last_index);
862
863
51881432
            diff = block[0] - ctx->m.last_dc[n];
864
51881432
            if (diff < 0)
865
23766663
                nbits = av_log2_16bit(-2 * diff);
866
            else
867
28114769
                nbits = av_log2_16bit(2 * diff);
868
869
            av_assert1(nbits < ctx->bit_depth + 4);
870
51881432
            dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
871
872
51881432
            ctx->m.last_dc[n] = block[0];
873
874
51881432
            if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
875
3024000
                dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
876
3024000
                ctx->m.idsp.idct(block);
877
3024000
                ssd += dnxhd_ssd_block(block, src_block);
878
            }
879
        }
880
6485179
        ctx->mb_rc[(qscale * ctx->m.mb_num) + mb].ssd  = ssd;
881
6485179
        ctx->mb_rc[(qscale * ctx->m.mb_num) + mb].bits = ac_bits + dc_bits + 12 +
882
6485179
                                     (1 + ctx->is_444) * 8 * ctx->vlc_bits[0];
883
    }
884
41557
    return 0;
885
}
886
887
20765
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg,
888
                               int jobnr, int threadnr)
889
{
890
20765
    DNXHDEncContext *ctx = avctx->priv_data;
891
20765
    int mb_y = jobnr, mb_x;
892
20765
    ctx = ctx->thread[threadnr];
893
20765
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + ctx->data_offset + ctx->slice_offs[jobnr],
894
20765
                  ctx->slice_size[jobnr]);
895
896
20765
    ctx->m.last_dc[0] =
897
20765
    ctx->m.last_dc[1] =
898
20765
    ctx->m.last_dc[2] = 1 << (ctx->bit_depth + 2);
899
3385585
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
900
3364820
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
901
3364820
        int qscale = ctx->mb_qscale[mb];
902
        int i;
903
904
3364820
        put_bits(&ctx->m.pb, 11, qscale);
905
3364820
        put_bits(&ctx->m.pb, 1, avctx->pix_fmt == AV_PIX_FMT_YUV444P10);
906
907
3364820
        dnxhd_get_blocks(ctx, mb_x, mb_y);
908
909
30283380
        for (i = 0; i < 8 + 4 * ctx->is_444; i++) {
910
26918560
            int16_t *block = ctx->blocks[i];
911
26918560
            int overflow, n = dnxhd_switch_matrix(ctx, i);
912
26918560
            int last_index = ctx->m.dct_quantize(&ctx->m, block,
913

26918560
                                                 ctx->is_444 ? (((i >> 1) % 3) < 1 ? 0 : 4): 4 & (2*i),
914
                                                 qscale, &overflow);
915
916
26918560
            dnxhd_encode_block(ctx, block, last_index, n);
917
        }
918
    }
919
20765
    if (put_bits_count(&ctx->m.pb) & 31)
920
20137
        put_bits(&ctx->m.pb, 32 - (put_bits_count(&ctx->m.pb) & 31), 0);
921
20765
    flush_put_bits(&ctx->m.pb);
922
20765
    return 0;
923
}
924
925
380
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
926
{
927
    int mb_y, mb_x;
928
380
    int offset = 0;
929
21145
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
930
        int thread_size;
931
20765
        ctx->slice_offs[mb_y] = offset;
932
20765
        ctx->slice_size[mb_y] = 0;
933
3385585
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
934
3364820
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
935
3364820
            ctx->slice_size[mb_y] += ctx->mb_bits[mb];
936
        }
937
20765
        ctx->slice_size[mb_y]   = (ctx->slice_size[mb_y] + 31) & ~31;
938
20765
        ctx->slice_size[mb_y] >>= 3;
939
20765
        thread_size = ctx->slice_size[mb_y];
940
20765
        offset += thread_size;
941
    }
942
380
}
943
944
11520
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg,
945
                               int jobnr, int threadnr)
946
{
947
11520
    DNXHDEncContext *ctx = avctx->priv_data;
948
11520
    int mb_y = jobnr, mb_x, x, y;
949
11740
    int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
950
220
                           ((avctx->height >> ctx->interlaced) & 0xF);
951
952
11520
    ctx = ctx->thread[threadnr];
953
11520
    if (ctx->bit_depth == 8) {
954
10955
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize);
955
1930655
        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
956
1919700
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
957
            int sum;
958
            int varc;
959
960

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

220
    if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
1196
        radix_sort_pass(tmp, data, size, buckets[2], 2);
1197
        radix_sort_pass(data, tmp, size, buckets[3], 3);
1198
    }
1199
220
}
1200
1201
365
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
1202
{
1203
365
    int max_bits = 0;
1204
    int ret, x, y;
1205
365
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
1206
        return ret;
1207
20455
    for (y = 0; y < ctx->m.mb_height; y++) {
1208
3330910
        for (x = 0; x < ctx->m.mb_width; x++) {
1209
3310820
            int mb = y * ctx->m.mb_width + x;
1210
3310820
            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;
1211
            int delta_bits;
1212
3310820
            ctx->mb_qscale[mb] = ctx->qscale;
1213
3310820
            ctx->mb_bits[mb] = ctx->mb_rc[rc].bits;
1214
3310820
            max_bits += ctx->mb_rc[rc].bits;
1215
            if (!RC_VARIANCE) {
1216
                delta_bits = ctx->mb_rc[rc].bits -
1217
                             ctx->mb_rc[rc + ctx->m.mb_num].bits;
1218
                ctx->mb_cmp[mb].mb = mb;
1219
                ctx->mb_cmp[mb].value =
1220
                    delta_bits ? ((ctx->mb_rc[rc].ssd -
1221
                                   ctx->mb_rc[rc + ctx->m.mb_num].ssd) * 100) /
1222
                                  delta_bits
1223
                               : INT_MIN; // avoid increasing qscale
1224
            }
1225
        }
1226
20090
        max_bits += 31; // worst padding
1227
    }
1228
365
    if (!ret) {
1229
        if (RC_VARIANCE)
1230
220
            avctx->execute2(avctx, dnxhd_mb_var_thread,
1231
                            NULL, NULL, ctx->m.mb_height);
1232
220
        radix_sort(ctx->mb_cmp, ctx->mb_cmp_tmp, ctx->m.mb_num);
1233

647025
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
1234
646805
            int mb = ctx->mb_cmp[x].mb;
1235
646805
            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;
1236
646805
            max_bits -= ctx->mb_rc[rc].bits -
1237
646805
                        ctx->mb_rc[rc + ctx->m.mb_num].bits;
1238
646805
            ctx->mb_qscale[mb] = ctx->qscale + 1;
1239
646805
            ctx->mb_bits[mb]   = ctx->mb_rc[rc + ctx->m.mb_num].bits;
1240
        }
1241
    }
1242
365
    return 0;
1243
}
1244
1245
325
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
1246
{
1247
    int i;
1248
1249
650
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
1250
325
        ctx->thread[i]->m.linesize    = frame->linesize[0] << ctx->interlaced;
1251
325
        ctx->thread[i]->m.uvlinesize  = frame->linesize[1] << ctx->interlaced;
1252
325
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
1253
325
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
1254
    }
1255
1256
#if FF_API_CODED_FRAME
1257
FF_DISABLE_DEPRECATION_WARNINGS
1258
325
    ctx->m.avctx->coded_frame->interlaced_frame = frame->interlaced_frame;
1259
FF_ENABLE_DEPRECATION_WARNINGS
1260
#endif
1261

325
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
1262
325
}
1263
1264
325
static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
1265
                                const AVFrame *frame, int *got_packet)
1266
{
1267
325
    DNXHDEncContext *ctx = avctx->priv_data;
1268
325
    int first_field = 1;
1269
    int offset, i, ret;
1270
    uint8_t *buf;
1271
1272
325
    if ((ret = ff_alloc_packet2(avctx, pkt, ctx->frame_size, 0)) < 0)
1273
        return ret;
1274
325
    buf = pkt->data;
1275
1276
325
    dnxhd_load_picture(ctx, frame);
1277
1278
380
encode_coding_unit:
1279
1520
    for (i = 0; i < 3; i++) {
1280
1140
        ctx->src[i] = frame->data[i];
1281

1140
        if (ctx->interlaced && ctx->cur_field)
1282
165
            ctx->src[i] += frame->linesize[i];
1283
    }
1284
1285
380
    dnxhd_write_header(avctx, buf);
1286
1287
380
    if (avctx->mb_decision == FF_MB_DECISION_RD)
1288
15
        ret = dnxhd_encode_rdo(avctx, ctx);
1289
    else
1290
365
        ret = dnxhd_encode_fast(avctx, ctx);
1291
380
    if (ret < 0) {
1292
        av_log(avctx, AV_LOG_ERROR,
1293
               "picture could not fit ratecontrol constraints, increase qmax\n");
1294
        return ret;
1295
    }
1296
1297
380
    dnxhd_setup_threads_slices(ctx);
1298
1299
380
    offset = 0;
1300
21145
    for (i = 0; i < ctx->m.mb_height; i++) {
1301
20765
        AV_WB32(ctx->msip + i * 4, offset);
1302
20765
        offset += ctx->slice_size[i];
1303
        av_assert1(!(ctx->slice_size[i] & 3));
1304
    }
1305
1306
380
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
1307
1308
    av_assert1(ctx->data_offset + offset + 4 <= ctx->coding_unit_size);
1309
380
    memset(buf + ctx->data_offset + offset, 0,
1310
380
           ctx->coding_unit_size - 4 - offset - ctx->data_offset);
1311
1312
380
    AV_WB32(buf + ctx->coding_unit_size - 4, 0x600DC0DE); // EOF
1313
1314

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