GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/dnxhdenc.c Lines: 679 806 84.2 %
Date: 2019-11-22 03:34:36 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
#include "libavutil/timer.h"
30
31
#include "avcodec.h"
32
#include "blockdsp.h"
33
#include "fdctdsp.h"
34
#include "internal.h"
35
#include "mpegvideo.h"
36
#include "pixblockdsp.h"
37
#include "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
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->orig_vlc_codes,
211
                      max_level, 4 * sizeof(*ctx->orig_vlc_codes), fail);
212
73
    FF_ALLOCZ_ARRAY_OR_GOTO(ctx->m.avctx, ctx->orig_vlc_bits,
213
                      max_level, 4 * sizeof(*ctx->orig_vlc_bits), fail);
214
73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes,
215
                      63 * 2, fail);
216
73
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits,
217
                      63, fail);
218
219
73
    ctx->vlc_codes = ctx->orig_vlc_codes + max_level * 2;
220
73
    ctx->vlc_bits  = ctx->orig_vlc_bits + max_level * 2;
221
192585
    for (level = -max_level; level < max_level; level++) {
222
577536
        for (run = 0; run < 2; run++) {
223
385024
            int index = level * (1 << 1) | run;
224
385024
            int sign, offset = 0, alevel = level;
225
226
385024
            MASK_ABS(sign, alevel);
227
385024
            if (alevel > 64) {
228
366190
                offset  = (alevel - 1) >> 6;
229
366190
                alevel -= offset << 6;
230
            }
231
65137020
            for (j = 0; j < 257; j++) {
232

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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