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
27 #define RC_VARIANCE 1 // use variance or ssd for fast rc
29 #include "libavutil/opt.h"
33 #include "mpegvideo.h"
37 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
38 #define DNX10BIT_QMAT_SHIFT 18 // The largest value that will not lead to overflow for 10bit samples.
40 static const AVOption options[]={
41 {"nitris_compat", "encode with Avid Nitris compatibility", offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, VE},
45 static const AVClass class = {
46 .class_name = "dnxhd",
47 .item_name = av_default_item_name,
49 .version = LIBAVUTIL_VERSION_INT,
52 #define LAMBDA_FRAC_BITS 10
54 static void dnxhd_8bit_get_pixels_8x4_sym(DCTELEM *av_restrict block, const uint8_t *pixels, int line_size)
57 for (i = 0; i < 4; i++) {
58 block[0] = pixels[0]; block[1] = pixels[1];
59 block[2] = pixels[2]; block[3] = pixels[3];
60 block[4] = pixels[4]; block[5] = pixels[5];
61 block[6] = pixels[6]; block[7] = pixels[7];
65 memcpy(block, block - 8, sizeof(*block) * 8);
66 memcpy(block + 8, block - 16, sizeof(*block) * 8);
67 memcpy(block + 16, block - 24, sizeof(*block) * 8);
68 memcpy(block + 24, block - 32, sizeof(*block) * 8);
71 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(DCTELEM *av_restrict block, const uint8_t *pixels, int line_size)
74 const uint16_t* pixels16 = (const uint16_t*)pixels;
77 for (i = 0; i < 4; i++) {
78 block[0] = pixels16[0]; block[1] = pixels16[1];
79 block[2] = pixels16[2]; block[3] = pixels16[3];
80 block[4] = pixels16[4]; block[5] = pixels16[5];
81 block[6] = pixels16[6]; block[7] = pixels16[7];
82 pixels16 += line_size;
85 memcpy(block, block - 8, sizeof(*block) * 8);
86 memcpy(block + 8, block - 16, sizeof(*block) * 8);
87 memcpy(block + 16, block - 24, sizeof(*block) * 8);
88 memcpy(block + 24, block - 32, sizeof(*block) * 8);
91 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, DCTELEM *block,
92 int n, int qscale, int *overflow)
94 const uint8_t *scantable= ctx->intra_scantable.scantable;
95 const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
96 int last_non_zero = 0;
101 // Divide by 4 with rounding, to compensate scaling of DCT coefficients
102 block[0] = (block[0] + 2) >> 2;
104 for (i = 1; i < 64; ++i) {
105 int j = scantable[i];
106 int sign = block[j] >> 31;
107 int level = (block[j] ^ sign) - sign;
108 level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
109 block[j] = (level ^ sign) - sign;
114 return last_non_zero;
117 static int dnxhd_init_vlc(DNXHDEncContext *ctx)
119 int i, j, level, run;
120 int max_level = 1<<(ctx->cid_table->bit_depth+2);
122 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
123 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail);
124 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail);
125 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail);
127 ctx->vlc_codes += max_level*2;
128 ctx->vlc_bits += max_level*2;
129 for (level = -max_level; level < max_level; level++) {
130 for (run = 0; run < 2; run++) {
131 int index = (level<<1)|run;
132 int sign, offset = 0, alevel = level;
134 MASK_ABS(sign, alevel);
136 offset = (alevel-1)>>6;
139 for (j = 0; j < 257; j++) {
140 if (ctx->cid_table->ac_level[j] >> 1 == alevel &&
141 (!offset || (ctx->cid_table->ac_flags[j] & 1) && offset) &&
142 (!run || (ctx->cid_table->ac_flags[j] & 2) && run)) {
143 av_assert1(!ctx->vlc_codes[index]);
145 ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
146 ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
148 ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
149 ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
154 av_assert0(!alevel || j < 257);
156 ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
157 ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
161 for (i = 0; i < 62; i++) {
162 int run = ctx->cid_table->run[i];
163 av_assert0(run < 63);
164 ctx->run_codes[run] = ctx->cid_table->run_codes[i];
165 ctx->run_bits [run] = ctx->cid_table->run_bits[i];
172 static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
174 // init first elem to 1 to avoid div by 0 in convert_matrix
175 uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
177 const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
178 const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
180 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
181 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
182 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
183 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
185 if (ctx->cid_table->bit_depth == 8) {
186 for (i = 1; i < 64; i++) {
187 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
188 weight_matrix[j] = ctx->cid_table->luma_weight[i];
190 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
191 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
192 for (i = 1; i < 64; i++) {
193 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
194 weight_matrix[j] = ctx->cid_table->chroma_weight[i];
196 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
197 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
199 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
200 for (i = 0; i < 64; i++) {
201 ctx->qmatrix_l [qscale] [i] <<= 2; ctx->qmatrix_c [qscale] [i] <<= 2;
202 ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
203 ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
208 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
209 for (i = 1; i < 64; i++) {
210 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
212 // The quantization formula from the VC-3 standard is:
213 // quantized = sign(block[i]) * floor(abs(block[i]/s) * p / (qscale * weight_table[i]))
214 // Where p is 32 for 8-bit samples and 8 for 10-bit ones.
215 // The s factor compensates scaling of DCT coefficients done by the DCT routines,
216 // and therefore is not present in standard. It's 8 for 8-bit samples and 4 for 10-bit ones.
217 // We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
218 // ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) / (qscale * weight_table[i])
219 // For 10-bit samples, p / s == 2
220 ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * luma_weight_table[i]);
221 ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * chroma_weight_table[i]);
226 ctx->m.q_chroma_intra_matrix16 = ctx->qmatrix_c16;
227 ctx->m.q_chroma_intra_matrix = ctx->qmatrix_c;
228 ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
229 ctx->m.q_intra_matrix = ctx->qmatrix_l;
236 static int dnxhd_init_rc(DNXHDEncContext *ctx)
238 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry), fail);
239 if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
240 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
242 ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
244 ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
250 static int dnxhd_encode_init(AVCodecContext *avctx)
252 DNXHDEncContext *ctx = avctx->priv_data;
253 int i, index, bit_depth;
255 switch (avctx->pix_fmt) {
256 case AV_PIX_FMT_YUV422P:
259 case AV_PIX_FMT_YUV422P10:
263 av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
267 ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
269 av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
272 av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
274 index = ff_dnxhd_get_cid_table(ctx->cid);
275 ctx->cid_table = &ff_dnxhd_cid_table[index];
277 ctx->m.avctx = avctx;
281 avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
283 ff_dct_common_init(&ctx->m);
284 ff_dct_encode_init(&ctx->m);
286 if (!ctx->m.dct_quantize)
287 ctx->m.dct_quantize = ff_dct_quantize_c;
289 if (ctx->cid_table->bit_depth == 10) {
290 ctx->m.dct_quantize = dnxhd_10bit_dct_quantize;
291 ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
292 ctx->block_width_l2 = 4;
294 ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
295 ctx->block_width_l2 = 3;
299 ff_dnxhdenc_init_x86(ctx);
301 ctx->m.mb_height = (avctx->height + 15) / 16;
302 ctx->m.mb_width = (avctx->width + 15) / 16;
304 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
306 ctx->m.mb_height /= 2;
309 ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
311 if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
312 ctx->m.intra_quant_bias = avctx->intra_quant_bias;
313 if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
316 // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
317 if (ctx->nitris_compat)
318 ctx->min_padding = 1600;
320 if (dnxhd_init_vlc(ctx) < 0)
322 if (dnxhd_init_rc(ctx) < 0)
325 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
326 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
327 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
328 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
330 ctx->frame.key_frame = 1;
331 ctx->frame.pict_type = AV_PICTURE_TYPE_I;
332 ctx->m.avctx->coded_frame = &ctx->frame;
334 if (avctx->thread_count > MAX_THREADS) {
335 av_log(avctx, AV_LOG_ERROR, "too many threads\n");
339 ctx->thread[0] = ctx;
340 for (i = 1; i < avctx->thread_count; i++) {
341 ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
342 memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
346 fail: //for FF_ALLOCZ_OR_GOTO
350 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
352 DNXHDEncContext *ctx = avctx->priv_data;
353 const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
357 memcpy(buf, header_prefix, 5);
358 buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
359 buf[6] = 0x80; // crc flag off
360 buf[7] = 0xa0; // reserved
361 AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
362 AV_WB16(buf + 0x1a, avctx->width); // SPL
363 AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
365 buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
366 buf[0x22] = 0x88 + (ctx->interlaced<<2);
367 AV_WB32(buf + 0x28, ctx->cid); // CID
368 buf[0x2c] = ctx->interlaced ? 0 : 0x80;
370 buf[0x5f] = 0x01; // UDL
372 buf[0x167] = 0x02; // reserved
373 AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
374 buf[0x16d] = ctx->m.mb_height; // Ns
375 buf[0x16f] = 0x10; // reserved
377 ctx->msip = buf + 0x170;
381 static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
385 nbits = av_log2_16bit(-2*diff);
388 nbits = av_log2_16bit(2*diff);
390 put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
391 (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
394 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
396 int last_non_zero = 0;
399 dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
400 ctx->m.last_dc[n] = block[0];
402 for (i = 1; i <= last_index; i++) {
403 j = ctx->m.intra_scantable.permutated[i];
406 int run_level = i - last_non_zero - 1;
407 int rlevel = (slevel<<1)|!!run_level;
408 put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
410 put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
414 put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
417 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
419 const uint8_t *weight_matrix;
423 weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
425 for (i = 1; i <= last_index; i++) {
426 int j = ctx->m.intra_scantable.permutated[i];
430 level = (1-2*level) * qscale * weight_matrix[i];
431 if (ctx->cid_table->bit_depth == 10) {
432 if (weight_matrix[i] != 8)
436 if (weight_matrix[i] != 32)
442 level = (2*level+1) * qscale * weight_matrix[i];
443 if (ctx->cid_table->bit_depth == 10) {
444 if (weight_matrix[i] != 8)
448 if (weight_matrix[i] != 32)
458 static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
462 for (i = 0; i < 64; i++)
463 score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
467 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
469 int last_non_zero = 0;
472 for (i = 1; i <= last_index; i++) {
473 j = ctx->m.intra_scantable.permutated[i];
476 int run_level = i - last_non_zero - 1;
477 bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
484 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
486 const int bs = ctx->block_width_l2;
487 const int bw = 1 << bs;
488 const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
489 const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
490 const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
491 DSPContext *dsp = &ctx->m.dsp;
493 dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
494 dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
495 dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
496 dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
498 if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
499 if (ctx->interlaced) {
500 ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
501 ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
502 ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
503 ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
505 dsp->clear_block(ctx->blocks[4]);
506 dsp->clear_block(ctx->blocks[5]);
507 dsp->clear_block(ctx->blocks[6]);
508 dsp->clear_block(ctx->blocks[7]);
511 dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
512 dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
513 dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
514 dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
518 static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
520 const static uint8_t component[8]={0,0,1,2,0,0,1,2};
524 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
526 DNXHDEncContext *ctx = avctx->priv_data;
527 int mb_y = jobnr, mb_x;
528 int qscale = ctx->qscale;
529 LOCAL_ALIGNED_16(DCTELEM, block, [64]);
530 ctx = ctx->thread[threadnr];
534 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
536 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
537 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
543 dnxhd_get_blocks(ctx, mb_x, mb_y);
545 for (i = 0; i < 8; i++) {
546 DCTELEM *src_block = ctx->blocks[i];
547 int overflow, nbits, diff, last_index;
548 int n = dnxhd_switch_matrix(ctx, i);
550 memcpy(block, src_block, 64*sizeof(*block));
551 last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
552 ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
554 diff = block[0] - ctx->m.last_dc[n];
555 if (diff < 0) nbits = av_log2_16bit(-2*diff);
556 else nbits = av_log2_16bit( 2*diff);
558 av_assert1(nbits < ctx->cid_table->bit_depth + 4);
559 dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
561 ctx->m.last_dc[n] = block[0];
563 if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
564 dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
565 ctx->m.dsp.idct(block);
566 ssd += dnxhd_ssd_block(block, src_block);
569 ctx->mb_rc[qscale][mb].ssd = ssd;
570 ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
575 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
577 DNXHDEncContext *ctx = avctx->priv_data;
578 int mb_y = jobnr, mb_x;
579 ctx = ctx->thread[threadnr];
580 init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
584 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
585 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
586 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
587 int qscale = ctx->mb_qscale[mb];
590 put_bits(&ctx->m.pb, 12, qscale<<1);
592 dnxhd_get_blocks(ctx, mb_x, mb_y);
594 for (i = 0; i < 8; i++) {
595 DCTELEM *block = ctx->blocks[i];
596 int overflow, n = dnxhd_switch_matrix(ctx, i);
597 int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
599 dnxhd_encode_block(ctx, block, last_index, n);
600 //STOP_TIMER("encode_block");
603 if (put_bits_count(&ctx->m.pb)&31)
604 put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
605 flush_put_bits(&ctx->m.pb);
609 static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
613 for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
615 ctx->slice_offs[mb_y] = offset;
616 ctx->slice_size[mb_y] = 0;
617 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
618 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
619 ctx->slice_size[mb_y] += ctx->mb_bits[mb];
621 ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
622 ctx->slice_size[mb_y] >>= 3;
623 thread_size = ctx->slice_size[mb_y];
624 offset += thread_size;
628 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
630 DNXHDEncContext *ctx = avctx->priv_data;
631 int mb_y = jobnr, mb_x;
632 ctx = ctx->thread[threadnr];
633 if (ctx->cid_table->bit_depth == 8) {
634 uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
635 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
636 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
637 int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
638 int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)sum*sum)>>8)+128)>>8;
639 ctx->mb_cmp[mb].value = varc;
640 ctx->mb_cmp[mb].mb = mb;
643 int const linesize = ctx->m.linesize >> 1;
644 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
645 uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
646 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
651 // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
652 for (i = 0; i < 16; ++i) {
653 for (j = 0; j < 16; ++j) {
654 // Turn 16-bit pixels into 10-bit ones.
655 int const sample = (unsigned)pix[j] >> 6;
657 sqsum += sample * sample;
658 // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
662 mean = sum >> 8; // 16*16 == 2^8
664 ctx->mb_cmp[mb].value = sqmean - mean * mean;
665 ctx->mb_cmp[mb].mb = mb;
671 static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
673 int lambda, up_step, down_step;
674 int last_lower = INT_MAX, last_higher = 0;
677 for (q = 1; q < avctx->qmax; q++) {
679 avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
681 up_step = down_step = 2<<LAMBDA_FRAC_BITS;
682 lambda = ctx->lambda;
687 if (lambda == last_higher) {
689 end = 1; // need to set final qscales/bits
691 for (y = 0; y < ctx->m.mb_height; y++) {
692 for (x = 0; x < ctx->m.mb_width; x++) {
693 unsigned min = UINT_MAX;
695 int mb = y*ctx->m.mb_width+x;
696 for (q = 1; q < avctx->qmax; q++) {
697 unsigned score = ctx->mb_rc[q][mb].bits*lambda+
698 ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
704 bits += ctx->mb_rc[qscale][mb].bits;
705 ctx->mb_qscale[mb] = qscale;
706 ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
708 bits = (bits+31)&~31; // padding
709 if (bits > ctx->frame_bits)
712 //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
713 // lambda, last_higher, last_lower, bits, ctx->frame_bits);
715 if (bits > ctx->frame_bits)
719 if (bits < ctx->frame_bits) {
720 last_lower = FFMIN(lambda, last_lower);
721 if (last_higher != 0)
722 lambda = (lambda+last_higher)>>1;
725 down_step = FFMIN((int64_t)down_step*5, INT_MAX);
726 up_step = 1<<LAMBDA_FRAC_BITS;
727 lambda = FFMAX(1, lambda);
728 if (lambda == last_lower)
731 last_higher = FFMAX(lambda, last_higher);
732 if (last_lower != INT_MAX)
733 lambda = (lambda+last_lower)>>1;
734 else if ((int64_t)lambda + up_step > INT_MAX)
738 up_step = FFMIN((int64_t)up_step*5, INT_MAX);
739 down_step = 1<<LAMBDA_FRAC_BITS;
742 //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
743 ctx->lambda = lambda;
747 static int dnxhd_find_qscale(DNXHDEncContext *ctx)
753 int last_lower = INT_MAX;
757 qscale = ctx->qscale;
760 ctx->qscale = qscale;
761 // XXX avoid recalculating bits
762 ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
763 for (y = 0; y < ctx->m.mb_height; y++) {
764 for (x = 0; x < ctx->m.mb_width; x++)
765 bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
766 bits = (bits+31)&~31; // padding
767 if (bits > ctx->frame_bits)
770 //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
771 // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
772 if (bits < ctx->frame_bits) {
775 if (last_higher == qscale - 1) {
776 qscale = last_higher;
779 last_lower = FFMIN(qscale, last_lower);
780 if (last_higher != 0)
781 qscale = (qscale+last_higher)>>1;
783 qscale -= down_step++;
788 if (last_lower == qscale + 1)
790 last_higher = FFMAX(qscale, last_higher);
791 if (last_lower != INT_MAX)
792 qscale = (qscale+last_lower)>>1;
796 if (qscale >= ctx->m.avctx->qmax)
800 //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
801 ctx->qscale = qscale;
805 #define BUCKET_BITS 8
806 #define RADIX_PASSES 4
807 #define NBUCKETS (1 << BUCKET_BITS)
809 static inline int get_bucket(int value, int shift)
812 value &= NBUCKETS - 1;
813 return NBUCKETS - 1 - value;
816 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
819 memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
820 for (i = 0; i < size; i++) {
821 int v = data[i].value;
822 for (j = 0; j < RADIX_PASSES; j++) {
823 buckets[j][get_bucket(v, 0)]++;
828 for (j = 0; j < RADIX_PASSES; j++) {
830 for (i = NBUCKETS - 1; i >= 0; i--)
831 buckets[j][i] = offset -= buckets[j][i];
832 av_assert1(!buckets[j][0]);
836 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
838 int shift = pass * BUCKET_BITS;
840 for (i = 0; i < size; i++) {
841 int v = get_bucket(data[i].value, shift);
842 int pos = buckets[v]++;
847 static void radix_sort(RCCMPEntry *data, int size)
849 int buckets[RADIX_PASSES][NBUCKETS];
850 RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
851 radix_count(data, size, buckets);
852 radix_sort_pass(tmp, data, size, buckets[0], 0);
853 radix_sort_pass(data, tmp, size, buckets[1], 1);
854 if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
855 radix_sort_pass(tmp, data, size, buckets[2], 2);
856 radix_sort_pass(data, tmp, size, buckets[3], 3);
861 static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
865 if ((ret = dnxhd_find_qscale(ctx)) < 0)
867 for (y = 0; y < ctx->m.mb_height; y++) {
868 for (x = 0; x < ctx->m.mb_width; x++) {
869 int mb = y*ctx->m.mb_width+x;
871 ctx->mb_qscale[mb] = ctx->qscale;
872 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
873 max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
875 delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
876 ctx->mb_cmp[mb].mb = mb;
877 ctx->mb_cmp[mb].value = delta_bits ?
878 ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
879 : INT_MIN; //avoid increasing qscale
882 max_bits += 31; //worst padding
886 avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
887 radix_sort(ctx->mb_cmp, ctx->m.mb_num);
888 for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
889 int mb = ctx->mb_cmp[x].mb;
890 max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
891 ctx->mb_qscale[mb] = ctx->qscale+1;
892 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
898 static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
902 for (i = 0; i < 3; i++) {
903 ctx->frame.data[i] = frame->data[i];
904 ctx->frame.linesize[i] = frame->linesize[i];
907 for (i = 0; i < ctx->m.avctx->thread_count; i++) {
908 ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
909 ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
910 ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
911 ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
914 ctx->frame.interlaced_frame = frame->interlaced_frame;
915 ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
918 static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
919 const AVFrame *frame, int *got_packet)
921 DNXHDEncContext *ctx = avctx->priv_data;
926 if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
930 dnxhd_load_picture(ctx, frame);
933 for (i = 0; i < 3; i++) {
934 ctx->src[i] = ctx->frame.data[i];
935 if (ctx->interlaced && ctx->cur_field)
936 ctx->src[i] += ctx->frame.linesize[i];
939 dnxhd_write_header(avctx, buf);
941 if (avctx->mb_decision == FF_MB_DECISION_RD)
942 ret = dnxhd_encode_rdo(avctx, ctx);
944 ret = dnxhd_encode_fast(avctx, ctx);
946 av_log(avctx, AV_LOG_ERROR,
947 "picture could not fit ratecontrol constraints, increase qmax\n");
951 dnxhd_setup_threads_slices(ctx);
954 for (i = 0; i < ctx->m.mb_height; i++) {
955 AV_WB32(ctx->msip + i * 4, offset);
956 offset += ctx->slice_size[i];
957 av_assert1(!(ctx->slice_size[i] & 3));
960 avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
962 av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
963 memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
965 AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
967 if (ctx->interlaced && first_field) {
970 buf += ctx->cid_table->coding_unit_size;
971 goto encode_coding_unit;
974 ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
976 pkt->flags |= AV_PKT_FLAG_KEY;
981 static int dnxhd_encode_end(AVCodecContext *avctx)
983 DNXHDEncContext *ctx = avctx->priv_data;
984 int max_level = 1<<(ctx->cid_table->bit_depth+2);
987 av_free(ctx->vlc_codes-max_level*2);
988 av_free(ctx->vlc_bits -max_level*2);
989 av_freep(&ctx->run_codes);
990 av_freep(&ctx->run_bits);
992 av_freep(&ctx->mb_bits);
993 av_freep(&ctx->mb_qscale);
994 av_freep(&ctx->mb_rc);
995 av_freep(&ctx->mb_cmp);
996 av_freep(&ctx->slice_size);
997 av_freep(&ctx->slice_offs);
999 av_freep(&ctx->qmatrix_c);
1000 av_freep(&ctx->qmatrix_l);
1001 av_freep(&ctx->qmatrix_c16);
1002 av_freep(&ctx->qmatrix_l16);
1004 for (i = 1; i < avctx->thread_count; i++)
1005 av_freep(&ctx->thread[i]);
1010 static const AVCodecDefault dnxhd_defaults[] = {
1011 { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1015 AVCodec ff_dnxhd_encoder = {
1017 .type = AVMEDIA_TYPE_VIDEO,
1018 .id = AV_CODEC_ID_DNXHD,
1019 .priv_data_size = sizeof(DNXHDEncContext),
1020 .init = dnxhd_encode_init,
1021 .encode2 = dnxhd_encode_picture,
1022 .close = dnxhd_encode_end,
1023 .capabilities = CODEC_CAP_SLICE_THREADS,
1024 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1025 AV_PIX_FMT_YUV422P10,
1027 .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1028 .priv_class = &class,
1029 .defaults = dnxhd_defaults,