3 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4 * Copyright (c) 2011 MirriAd Ltd
6 * VC-3 encoder funded by the British Broadcasting Corporation
7 * 10 bit support added by MirriAd Ltd, Joseph Artsimovich <joseph@mirriad.com>
9 * This file is part of FFmpeg.
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.
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.
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
26 #define RC_VARIANCE 1 // use variance or ssd for fast rc
28 #include "libavutil/attributes.h"
29 #include "libavutil/internal.h"
30 #include "libavutil/opt.h"
34 #include "mpegvideo.h"
38 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
39 #define DNX10BIT_QMAT_SHIFT 18 // The largest value that will not lead to overflow for 10bit samples.
41 static const AVOption options[]={
42 {"nitris_compat", "encode with Avid Nitris compatibility", offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, VE},
46 static const AVClass dnxhd_class = {
47 .class_name = "dnxhd",
48 .item_name = av_default_item_name,
50 .version = LIBAVUTIL_VERSION_INT,
53 #define LAMBDA_FRAC_BITS 10
55 static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block, const uint8_t *pixels, int line_size)
58 for (i = 0; i < 4; i++) {
59 block[0] = pixels[0]; block[1] = pixels[1];
60 block[2] = pixels[2]; block[3] = pixels[3];
61 block[4] = pixels[4]; block[5] = pixels[5];
62 block[6] = pixels[6]; block[7] = pixels[7];
66 memcpy(block, block - 8, sizeof(*block) * 8);
67 memcpy(block + 8, block - 16, sizeof(*block) * 8);
68 memcpy(block + 16, block - 24, sizeof(*block) * 8);
69 memcpy(block + 24, block - 32, sizeof(*block) * 8);
72 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block, const uint8_t *pixels, int line_size)
75 const uint16_t* pixels16 = (const uint16_t*)pixels;
78 for (i = 0; i < 4; i++) {
79 block[0] = pixels16[0]; block[1] = pixels16[1];
80 block[2] = pixels16[2]; block[3] = pixels16[3];
81 block[4] = pixels16[4]; block[5] = pixels16[5];
82 block[6] = pixels16[6]; block[7] = pixels16[7];
83 pixels16 += line_size;
86 memcpy(block, block - 8, sizeof(*block) * 8);
87 memcpy(block + 8, block - 16, sizeof(*block) * 8);
88 memcpy(block + 16, block - 24, sizeof(*block) * 8);
89 memcpy(block + 24, block - 32, sizeof(*block) * 8);
92 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
93 int n, int qscale, int *overflow)
95 const uint8_t *scantable= ctx->intra_scantable.scantable;
96 const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
97 int last_non_zero = 0;
100 ctx->dsp.fdct(block);
102 // Divide by 4 with rounding, to compensate scaling of DCT coefficients
103 block[0] = (block[0] + 2) >> 2;
105 for (i = 1; i < 64; ++i) {
106 int j = scantable[i];
107 int sign = block[j] >> 31;
108 int level = (block[j] ^ sign) - sign;
109 level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
110 block[j] = (level ^ sign) - sign;
115 return last_non_zero;
118 static av_cold int dnxhd_init_vlc(DNXHDEncContext *ctx)
120 int i, j, level, run;
121 int max_level = 1<<(ctx->cid_table->bit_depth+2);
123 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
124 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail);
125 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail);
126 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail);
128 ctx->vlc_codes += max_level*2;
129 ctx->vlc_bits += max_level*2;
130 for (level = -max_level; level < max_level; level++) {
131 for (run = 0; run < 2; run++) {
132 int index = (level<<1)|run;
133 int sign, offset = 0, alevel = level;
135 MASK_ABS(sign, alevel);
137 offset = (alevel-1)>>6;
140 for (j = 0; j < 257; j++) {
141 if (ctx->cid_table->ac_level[j] >> 1 == alevel &&
142 (!offset || (ctx->cid_table->ac_flags[j] & 1) && offset) &&
143 (!run || (ctx->cid_table->ac_flags[j] & 2) && run)) {
144 av_assert1(!ctx->vlc_codes[index]);
146 ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
147 ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
149 ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
150 ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
155 av_assert0(!alevel || j < 257);
157 ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
158 ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
162 for (i = 0; i < 62; i++) {
163 int run = ctx->cid_table->run[i];
164 av_assert0(run < 63);
165 ctx->run_codes[run] = ctx->cid_table->run_codes[i];
166 ctx->run_bits [run] = ctx->cid_table->run_bits[i];
173 static av_cold int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
175 // init first elem to 1 to avoid div by 0 in convert_matrix
176 uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
178 const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
179 const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
181 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
182 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
183 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
184 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
186 if (ctx->cid_table->bit_depth == 8) {
187 for (i = 1; i < 64; i++) {
188 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
189 weight_matrix[j] = ctx->cid_table->luma_weight[i];
191 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
192 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
193 for (i = 1; i < 64; i++) {
194 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
195 weight_matrix[j] = ctx->cid_table->chroma_weight[i];
197 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
198 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
200 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
201 for (i = 0; i < 64; i++) {
202 ctx->qmatrix_l [qscale] [i] <<= 2; ctx->qmatrix_c [qscale] [i] <<= 2;
203 ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
204 ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
209 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
210 for (i = 1; i < 64; i++) {
211 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
213 // The quantization formula from the VC-3 standard is:
214 // quantized = sign(block[i]) * floor(abs(block[i]/s) * p / (qscale * weight_table[i]))
215 // Where p is 32 for 8-bit samples and 8 for 10-bit ones.
216 // The s factor compensates scaling of DCT coefficients done by the DCT routines,
217 // and therefore is not present in standard. It's 8 for 8-bit samples and 4 for 10-bit ones.
218 // We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
219 // ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) / (qscale * weight_table[i])
220 // For 10-bit samples, p / s == 2
221 ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * luma_weight_table[i]);
222 ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * chroma_weight_table[i]);
227 ctx->m.q_chroma_intra_matrix16 = ctx->qmatrix_c16;
228 ctx->m.q_chroma_intra_matrix = ctx->qmatrix_c;
229 ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
230 ctx->m.q_intra_matrix = ctx->qmatrix_l;
237 static av_cold int dnxhd_init_rc(DNXHDEncContext *ctx)
239 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry), fail);
240 if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
241 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
243 ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
245 ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
251 static av_cold int dnxhd_encode_init(AVCodecContext *avctx)
253 DNXHDEncContext *ctx = avctx->priv_data;
254 int i, index, bit_depth;
256 switch (avctx->pix_fmt) {
257 case AV_PIX_FMT_YUV422P:
260 case AV_PIX_FMT_YUV422P10:
264 av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
268 ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
270 av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD. Valid DNxHD profiles:\n");
271 ff_dnxhd_print_profiles(avctx, AV_LOG_ERROR);
274 av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
276 index = ff_dnxhd_get_cid_table(ctx->cid);
277 av_assert0(index >= 0);
278 ctx->cid_table = &ff_dnxhd_cid_table[index];
280 ctx->m.avctx = avctx;
284 avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
286 ff_dct_common_init(&ctx->m);
287 ff_dct_encode_init(&ctx->m);
289 if (!ctx->m.dct_quantize)
290 ctx->m.dct_quantize = ff_dct_quantize_c;
292 if (ctx->cid_table->bit_depth == 10) {
293 ctx->m.dct_quantize = dnxhd_10bit_dct_quantize;
294 ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
295 ctx->block_width_l2 = 4;
297 ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
298 ctx->block_width_l2 = 3;
302 ff_dnxhdenc_init_x86(ctx);
304 ctx->m.mb_height = (avctx->height + 15) / 16;
305 ctx->m.mb_width = (avctx->width + 15) / 16;
307 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
309 ctx->m.mb_height /= 2;
312 ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
314 if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
315 ctx->m.intra_quant_bias = avctx->intra_quant_bias;
316 if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
319 // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
320 if (ctx->nitris_compat)
321 ctx->min_padding = 1600;
323 if (dnxhd_init_vlc(ctx) < 0)
325 if (dnxhd_init_rc(ctx) < 0)
328 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
329 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
330 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
331 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
333 ctx->frame.key_frame = 1;
334 ctx->frame.pict_type = AV_PICTURE_TYPE_I;
335 ctx->m.avctx->coded_frame = &ctx->frame;
337 if (avctx->thread_count > MAX_THREADS) {
338 av_log(avctx, AV_LOG_ERROR, "too many threads\n");
342 ctx->thread[0] = ctx;
343 for (i = 1; i < avctx->thread_count; i++) {
344 ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
345 memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
349 fail: //for FF_ALLOCZ_OR_GOTO
353 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
355 DNXHDEncContext *ctx = avctx->priv_data;
356 static const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
360 memcpy(buf, header_prefix, 5);
361 buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
362 buf[6] = 0x80; // crc flag off
363 buf[7] = 0xa0; // reserved
364 AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
365 AV_WB16(buf + 0x1a, avctx->width); // SPL
366 AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
368 buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
369 buf[0x22] = 0x88 + (ctx->interlaced<<2);
370 AV_WB32(buf + 0x28, ctx->cid); // CID
371 buf[0x2c] = ctx->interlaced ? 0 : 0x80;
373 buf[0x5f] = 0x01; // UDL
375 buf[0x167] = 0x02; // reserved
376 AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
377 buf[0x16d] = ctx->m.mb_height; // Ns
378 buf[0x16f] = 0x10; // reserved
380 ctx->msip = buf + 0x170;
384 static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
388 nbits = av_log2_16bit(-2*diff);
391 nbits = av_log2_16bit(2*diff);
393 put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
394 (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
397 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block, int last_index, int n)
399 int last_non_zero = 0;
402 dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
403 ctx->m.last_dc[n] = block[0];
405 for (i = 1; i <= last_index; i++) {
406 j = ctx->m.intra_scantable.permutated[i];
409 int run_level = i - last_non_zero - 1;
410 int rlevel = (slevel<<1)|!!run_level;
411 put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
413 put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
417 put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
420 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n, int qscale, int last_index)
422 const uint8_t *weight_matrix;
426 weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
428 for (i = 1; i <= last_index; i++) {
429 int j = ctx->m.intra_scantable.permutated[i];
433 level = (1-2*level) * qscale * weight_matrix[i];
434 if (ctx->cid_table->bit_depth == 10) {
435 if (weight_matrix[i] != 8)
439 if (weight_matrix[i] != 32)
445 level = (2*level+1) * qscale * weight_matrix[i];
446 if (ctx->cid_table->bit_depth == 10) {
447 if (weight_matrix[i] != 8)
451 if (weight_matrix[i] != 32)
461 static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
465 for (i = 0; i < 64; i++)
466 score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
470 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
472 int last_non_zero = 0;
475 for (i = 1; i <= last_index; i++) {
476 j = ctx->m.intra_scantable.permutated[i];
479 int run_level = i - last_non_zero - 1;
480 bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
487 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
489 const int bs = ctx->block_width_l2;
490 const int bw = 1 << bs;
491 const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
492 const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
493 const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
494 DSPContext *dsp = &ctx->m.dsp;
496 dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
497 dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
498 dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
499 dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
501 if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
502 if (ctx->interlaced) {
503 ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
504 ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
505 ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
506 ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
508 dsp->clear_block(ctx->blocks[4]);
509 dsp->clear_block(ctx->blocks[5]);
510 dsp->clear_block(ctx->blocks[6]);
511 dsp->clear_block(ctx->blocks[7]);
514 dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
515 dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
516 dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
517 dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
521 static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
523 const static uint8_t component[8]={0,0,1,2,0,0,1,2};
527 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
529 DNXHDEncContext *ctx = avctx->priv_data;
530 int mb_y = jobnr, mb_x;
531 int qscale = ctx->qscale;
532 LOCAL_ALIGNED_16(int16_t, block, [64]);
533 ctx = ctx->thread[threadnr];
537 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
539 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
540 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
546 dnxhd_get_blocks(ctx, mb_x, mb_y);
548 for (i = 0; i < 8; i++) {
549 int16_t *src_block = ctx->blocks[i];
550 int overflow, nbits, diff, last_index;
551 int n = dnxhd_switch_matrix(ctx, i);
553 memcpy(block, src_block, 64*sizeof(*block));
554 last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
555 ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
557 diff = block[0] - ctx->m.last_dc[n];
558 if (diff < 0) nbits = av_log2_16bit(-2*diff);
559 else nbits = av_log2_16bit( 2*diff);
561 av_assert1(nbits < ctx->cid_table->bit_depth + 4);
562 dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
564 ctx->m.last_dc[n] = block[0];
566 if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
567 dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
568 ctx->m.dsp.idct(block);
569 ssd += dnxhd_ssd_block(block, src_block);
572 ctx->mb_rc[qscale][mb].ssd = ssd;
573 ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
578 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
580 DNXHDEncContext *ctx = avctx->priv_data;
581 int mb_y = jobnr, mb_x;
582 ctx = ctx->thread[threadnr];
583 init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
587 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
588 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
589 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
590 int qscale = ctx->mb_qscale[mb];
593 put_bits(&ctx->m.pb, 12, qscale<<1);
595 dnxhd_get_blocks(ctx, mb_x, mb_y);
597 for (i = 0; i < 8; i++) {
598 int16_t *block = ctx->blocks[i];
599 int overflow, n = dnxhd_switch_matrix(ctx, i);
600 int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
602 dnxhd_encode_block(ctx, block, last_index, n);
603 //STOP_TIMER("encode_block");
606 if (put_bits_count(&ctx->m.pb)&31)
607 put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
608 flush_put_bits(&ctx->m.pb);
612 static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
616 for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
618 ctx->slice_offs[mb_y] = offset;
619 ctx->slice_size[mb_y] = 0;
620 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
621 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
622 ctx->slice_size[mb_y] += ctx->mb_bits[mb];
624 ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
625 ctx->slice_size[mb_y] >>= 3;
626 thread_size = ctx->slice_size[mb_y];
627 offset += thread_size;
631 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
633 DNXHDEncContext *ctx = avctx->priv_data;
634 int mb_y = jobnr, mb_x, x, y;
635 int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
636 ((avctx->height >> ctx->interlaced) & 0xF);
638 ctx = ctx->thread[threadnr];
639 if (ctx->cid_table->bit_depth == 8) {
640 uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
641 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
642 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
646 if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
647 sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
648 varc = ctx->m.dsp.pix_norm1(pix, ctx->m.linesize);
650 int bw = FFMIN(avctx->width - 16 * mb_x, 16);
651 int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
653 for (y = 0; y < bh; y++) {
654 for (x = 0; x < bw; x++) {
655 uint8_t val = pix[x + y * ctx->m.linesize];
661 varc = (varc - (((unsigned)sum * sum) >> 8) + 128) >> 8;
663 ctx->mb_cmp[mb].value = varc;
664 ctx->mb_cmp[mb].mb = mb;
667 int const linesize = ctx->m.linesize >> 1;
668 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
669 uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
670 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
675 // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
676 for (i = 0; i < 16; ++i) {
677 for (j = 0; j < 16; ++j) {
678 // Turn 16-bit pixels into 10-bit ones.
679 int const sample = (unsigned)pix[j] >> 6;
681 sqsum += sample * sample;
682 // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
686 mean = sum >> 8; // 16*16 == 2^8
688 ctx->mb_cmp[mb].value = sqmean - mean * mean;
689 ctx->mb_cmp[mb].mb = mb;
695 static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
697 int lambda, up_step, down_step;
698 int last_lower = INT_MAX, last_higher = 0;
701 for (q = 1; q < avctx->qmax; q++) {
703 avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
705 up_step = down_step = 2<<LAMBDA_FRAC_BITS;
706 lambda = ctx->lambda;
711 if (lambda == last_higher) {
713 end = 1; // need to set final qscales/bits
715 for (y = 0; y < ctx->m.mb_height; y++) {
716 for (x = 0; x < ctx->m.mb_width; x++) {
717 unsigned min = UINT_MAX;
719 int mb = y*ctx->m.mb_width+x;
720 for (q = 1; q < avctx->qmax; q++) {
721 unsigned score = ctx->mb_rc[q][mb].bits*lambda+
722 ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
728 bits += ctx->mb_rc[qscale][mb].bits;
729 ctx->mb_qscale[mb] = qscale;
730 ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
732 bits = (bits+31)&~31; // padding
733 if (bits > ctx->frame_bits)
736 //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
737 // lambda, last_higher, last_lower, bits, ctx->frame_bits);
739 if (bits > ctx->frame_bits)
743 if (bits < ctx->frame_bits) {
744 last_lower = FFMIN(lambda, last_lower);
745 if (last_higher != 0)
746 lambda = (lambda+last_higher)>>1;
749 down_step = FFMIN((int64_t)down_step*5, INT_MAX);
750 up_step = 1<<LAMBDA_FRAC_BITS;
751 lambda = FFMAX(1, lambda);
752 if (lambda == last_lower)
755 last_higher = FFMAX(lambda, last_higher);
756 if (last_lower != INT_MAX)
757 lambda = (lambda+last_lower)>>1;
758 else if ((int64_t)lambda + up_step > INT_MAX)
762 up_step = FFMIN((int64_t)up_step*5, INT_MAX);
763 down_step = 1<<LAMBDA_FRAC_BITS;
766 //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
767 ctx->lambda = lambda;
771 static int dnxhd_find_qscale(DNXHDEncContext *ctx)
777 int last_lower = INT_MAX;
781 qscale = ctx->qscale;
784 ctx->qscale = qscale;
785 // XXX avoid recalculating bits
786 ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
787 for (y = 0; y < ctx->m.mb_height; y++) {
788 for (x = 0; x < ctx->m.mb_width; x++)
789 bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
790 bits = (bits+31)&~31; // padding
791 if (bits > ctx->frame_bits)
794 //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
795 // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
796 if (bits < ctx->frame_bits) {
799 if (last_higher == qscale - 1) {
800 qscale = last_higher;
803 last_lower = FFMIN(qscale, last_lower);
804 if (last_higher != 0)
805 qscale = (qscale+last_higher)>>1;
807 qscale -= down_step++;
812 if (last_lower == qscale + 1)
814 last_higher = FFMAX(qscale, last_higher);
815 if (last_lower != INT_MAX)
816 qscale = (qscale+last_lower)>>1;
820 if (qscale >= ctx->m.avctx->qmax)
824 //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
825 ctx->qscale = qscale;
829 #define BUCKET_BITS 8
830 #define RADIX_PASSES 4
831 #define NBUCKETS (1 << BUCKET_BITS)
833 static inline int get_bucket(int value, int shift)
836 value &= NBUCKETS - 1;
837 return NBUCKETS - 1 - value;
840 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
843 memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
844 for (i = 0; i < size; i++) {
845 int v = data[i].value;
846 for (j = 0; j < RADIX_PASSES; j++) {
847 buckets[j][get_bucket(v, 0)]++;
852 for (j = 0; j < RADIX_PASSES; j++) {
854 for (i = NBUCKETS - 1; i >= 0; i--)
855 buckets[j][i] = offset -= buckets[j][i];
856 av_assert1(!buckets[j][0]);
860 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
862 int shift = pass * BUCKET_BITS;
864 for (i = 0; i < size; i++) {
865 int v = get_bucket(data[i].value, shift);
866 int pos = buckets[v]++;
871 static void radix_sort(RCCMPEntry *data, int size)
873 int buckets[RADIX_PASSES][NBUCKETS];
874 RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
875 radix_count(data, size, buckets);
876 radix_sort_pass(tmp, data, size, buckets[0], 0);
877 radix_sort_pass(data, tmp, size, buckets[1], 1);
878 if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
879 radix_sort_pass(tmp, data, size, buckets[2], 2);
880 radix_sort_pass(data, tmp, size, buckets[3], 3);
885 static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
889 if ((ret = dnxhd_find_qscale(ctx)) < 0)
891 for (y = 0; y < ctx->m.mb_height; y++) {
892 for (x = 0; x < ctx->m.mb_width; x++) {
893 int mb = y*ctx->m.mb_width+x;
895 ctx->mb_qscale[mb] = ctx->qscale;
896 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
897 max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
899 delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
900 ctx->mb_cmp[mb].mb = mb;
901 ctx->mb_cmp[mb].value = delta_bits ?
902 ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
903 : INT_MIN; //avoid increasing qscale
906 max_bits += 31; //worst padding
910 avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
911 radix_sort(ctx->mb_cmp, ctx->m.mb_num);
912 for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
913 int mb = ctx->mb_cmp[x].mb;
914 max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
915 ctx->mb_qscale[mb] = ctx->qscale+1;
916 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
922 static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
926 for (i = 0; i < 3; i++) {
927 ctx->frame.data[i] = frame->data[i];
928 ctx->frame.linesize[i] = frame->linesize[i];
931 for (i = 0; i < ctx->m.avctx->thread_count; i++) {
932 ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
933 ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
934 ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
935 ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
938 ctx->frame.interlaced_frame = frame->interlaced_frame;
939 ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
942 static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
943 const AVFrame *frame, int *got_packet)
945 DNXHDEncContext *ctx = avctx->priv_data;
950 if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
954 dnxhd_load_picture(ctx, frame);
957 for (i = 0; i < 3; i++) {
958 ctx->src[i] = ctx->frame.data[i];
959 if (ctx->interlaced && ctx->cur_field)
960 ctx->src[i] += ctx->frame.linesize[i];
963 dnxhd_write_header(avctx, buf);
965 if (avctx->mb_decision == FF_MB_DECISION_RD)
966 ret = dnxhd_encode_rdo(avctx, ctx);
968 ret = dnxhd_encode_fast(avctx, ctx);
970 av_log(avctx, AV_LOG_ERROR,
971 "picture could not fit ratecontrol constraints, increase qmax\n");
975 dnxhd_setup_threads_slices(ctx);
978 for (i = 0; i < ctx->m.mb_height; i++) {
979 AV_WB32(ctx->msip + i * 4, offset);
980 offset += ctx->slice_size[i];
981 av_assert1(!(ctx->slice_size[i] & 3));
984 avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
986 av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
987 memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
989 AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
991 if (ctx->interlaced && first_field) {
994 buf += ctx->cid_table->coding_unit_size;
995 goto encode_coding_unit;
998 ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
1000 pkt->flags |= AV_PKT_FLAG_KEY;
1005 static av_cold int dnxhd_encode_end(AVCodecContext *avctx)
1007 DNXHDEncContext *ctx = avctx->priv_data;
1008 int max_level = 1<<(ctx->cid_table->bit_depth+2);
1011 av_free(ctx->vlc_codes-max_level*2);
1012 av_free(ctx->vlc_bits -max_level*2);
1013 av_freep(&ctx->run_codes);
1014 av_freep(&ctx->run_bits);
1016 av_freep(&ctx->mb_bits);
1017 av_freep(&ctx->mb_qscale);
1018 av_freep(&ctx->mb_rc);
1019 av_freep(&ctx->mb_cmp);
1020 av_freep(&ctx->slice_size);
1021 av_freep(&ctx->slice_offs);
1023 av_freep(&ctx->qmatrix_c);
1024 av_freep(&ctx->qmatrix_l);
1025 av_freep(&ctx->qmatrix_c16);
1026 av_freep(&ctx->qmatrix_l16);
1028 for (i = 1; i < avctx->thread_count; i++)
1029 av_freep(&ctx->thread[i]);
1034 static const AVCodecDefault dnxhd_defaults[] = {
1035 { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1039 AVCodec ff_dnxhd_encoder = {
1041 .type = AVMEDIA_TYPE_VIDEO,
1042 .id = AV_CODEC_ID_DNXHD,
1043 .priv_data_size = sizeof(DNXHDEncContext),
1044 .init = dnxhd_encode_init,
1045 .encode2 = dnxhd_encode_picture,
1046 .close = dnxhd_encode_end,
1047 .capabilities = CODEC_CAP_SLICE_THREADS,
1048 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1049 AV_PIX_FMT_YUV422P10,
1051 .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1052 .priv_class = &dnxhd_class,
1053 .defaults = dnxhd_defaults,