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 av_assert0(index >= 0);
276 ctx->cid_table = &ff_dnxhd_cid_table[index];
278 ctx->m.avctx = avctx;
282 avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
284 ff_dct_common_init(&ctx->m);
285 ff_dct_encode_init(&ctx->m);
287 if (!ctx->m.dct_quantize)
288 ctx->m.dct_quantize = ff_dct_quantize_c;
290 if (ctx->cid_table->bit_depth == 10) {
291 ctx->m.dct_quantize = dnxhd_10bit_dct_quantize;
292 ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
293 ctx->block_width_l2 = 4;
295 ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
296 ctx->block_width_l2 = 3;
300 ff_dnxhdenc_init_x86(ctx);
302 ctx->m.mb_height = (avctx->height + 15) / 16;
303 ctx->m.mb_width = (avctx->width + 15) / 16;
305 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
307 ctx->m.mb_height /= 2;
310 ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
312 if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
313 ctx->m.intra_quant_bias = avctx->intra_quant_bias;
314 if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
317 // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
318 if (ctx->nitris_compat)
319 ctx->min_padding = 1600;
321 if (dnxhd_init_vlc(ctx) < 0)
323 if (dnxhd_init_rc(ctx) < 0)
326 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
327 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
328 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
329 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
331 ctx->frame.key_frame = 1;
332 ctx->frame.pict_type = AV_PICTURE_TYPE_I;
333 ctx->m.avctx->coded_frame = &ctx->frame;
335 if (avctx->thread_count > MAX_THREADS) {
336 av_log(avctx, AV_LOG_ERROR, "too many threads\n");
340 ctx->thread[0] = ctx;
341 for (i = 1; i < avctx->thread_count; i++) {
342 ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
343 memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
347 fail: //for FF_ALLOCZ_OR_GOTO
351 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
353 DNXHDEncContext *ctx = avctx->priv_data;
354 const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
358 memcpy(buf, header_prefix, 5);
359 buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
360 buf[6] = 0x80; // crc flag off
361 buf[7] = 0xa0; // reserved
362 AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
363 AV_WB16(buf + 0x1a, avctx->width); // SPL
364 AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
366 buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
367 buf[0x22] = 0x88 + (ctx->interlaced<<2);
368 AV_WB32(buf + 0x28, ctx->cid); // CID
369 buf[0x2c] = ctx->interlaced ? 0 : 0x80;
371 buf[0x5f] = 0x01; // UDL
373 buf[0x167] = 0x02; // reserved
374 AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
375 buf[0x16d] = ctx->m.mb_height; // Ns
376 buf[0x16f] = 0x10; // reserved
378 ctx->msip = buf + 0x170;
382 static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
386 nbits = av_log2_16bit(-2*diff);
389 nbits = av_log2_16bit(2*diff);
391 put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
392 (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
395 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
397 int last_non_zero = 0;
400 dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
401 ctx->m.last_dc[n] = block[0];
403 for (i = 1; i <= last_index; i++) {
404 j = ctx->m.intra_scantable.permutated[i];
407 int run_level = i - last_non_zero - 1;
408 int rlevel = (slevel<<1)|!!run_level;
409 put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
411 put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
415 put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
418 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
420 const uint8_t *weight_matrix;
424 weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
426 for (i = 1; i <= last_index; i++) {
427 int j = ctx->m.intra_scantable.permutated[i];
431 level = (1-2*level) * qscale * weight_matrix[i];
432 if (ctx->cid_table->bit_depth == 10) {
433 if (weight_matrix[i] != 8)
437 if (weight_matrix[i] != 32)
443 level = (2*level+1) * qscale * weight_matrix[i];
444 if (ctx->cid_table->bit_depth == 10) {
445 if (weight_matrix[i] != 8)
449 if (weight_matrix[i] != 32)
459 static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
463 for (i = 0; i < 64; i++)
464 score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
468 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
470 int last_non_zero = 0;
473 for (i = 1; i <= last_index; i++) {
474 j = ctx->m.intra_scantable.permutated[i];
477 int run_level = i - last_non_zero - 1;
478 bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
485 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
487 const int bs = ctx->block_width_l2;
488 const int bw = 1 << bs;
489 const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
490 const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
491 const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
492 DSPContext *dsp = &ctx->m.dsp;
494 dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
495 dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
496 dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
497 dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
499 if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
500 if (ctx->interlaced) {
501 ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
502 ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
503 ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
504 ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
506 dsp->clear_block(ctx->blocks[4]);
507 dsp->clear_block(ctx->blocks[5]);
508 dsp->clear_block(ctx->blocks[6]);
509 dsp->clear_block(ctx->blocks[7]);
512 dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
513 dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
514 dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
515 dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
519 static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
521 const static uint8_t component[8]={0,0,1,2,0,0,1,2};
525 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
527 DNXHDEncContext *ctx = avctx->priv_data;
528 int mb_y = jobnr, mb_x;
529 int qscale = ctx->qscale;
530 LOCAL_ALIGNED_16(DCTELEM, block, [64]);
531 ctx = ctx->thread[threadnr];
535 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
537 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
538 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
544 dnxhd_get_blocks(ctx, mb_x, mb_y);
546 for (i = 0; i < 8; i++) {
547 DCTELEM *src_block = ctx->blocks[i];
548 int overflow, nbits, diff, last_index;
549 int n = dnxhd_switch_matrix(ctx, i);
551 memcpy(block, src_block, 64*sizeof(*block));
552 last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
553 ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
555 diff = block[0] - ctx->m.last_dc[n];
556 if (diff < 0) nbits = av_log2_16bit(-2*diff);
557 else nbits = av_log2_16bit( 2*diff);
559 av_assert1(nbits < ctx->cid_table->bit_depth + 4);
560 dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
562 ctx->m.last_dc[n] = block[0];
564 if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
565 dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
566 ctx->m.dsp.idct(block);
567 ssd += dnxhd_ssd_block(block, src_block);
570 ctx->mb_rc[qscale][mb].ssd = ssd;
571 ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
576 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
578 DNXHDEncContext *ctx = avctx->priv_data;
579 int mb_y = jobnr, mb_x;
580 ctx = ctx->thread[threadnr];
581 init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
585 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
586 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
587 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
588 int qscale = ctx->mb_qscale[mb];
591 put_bits(&ctx->m.pb, 12, qscale<<1);
593 dnxhd_get_blocks(ctx, mb_x, mb_y);
595 for (i = 0; i < 8; i++) {
596 DCTELEM *block = ctx->blocks[i];
597 int overflow, n = dnxhd_switch_matrix(ctx, i);
598 int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
600 dnxhd_encode_block(ctx, block, last_index, n);
601 //STOP_TIMER("encode_block");
604 if (put_bits_count(&ctx->m.pb)&31)
605 put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
606 flush_put_bits(&ctx->m.pb);
610 static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
614 for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
616 ctx->slice_offs[mb_y] = offset;
617 ctx->slice_size[mb_y] = 0;
618 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
619 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
620 ctx->slice_size[mb_y] += ctx->mb_bits[mb];
622 ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
623 ctx->slice_size[mb_y] >>= 3;
624 thread_size = ctx->slice_size[mb_y];
625 offset += thread_size;
629 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
631 DNXHDEncContext *ctx = avctx->priv_data;
632 int mb_y = jobnr, mb_x;
633 ctx = ctx->thread[threadnr];
634 if (ctx->cid_table->bit_depth == 8) {
635 uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
636 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
637 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
638 int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
639 int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)sum*sum)>>8)+128)>>8;
640 ctx->mb_cmp[mb].value = varc;
641 ctx->mb_cmp[mb].mb = mb;
644 int const linesize = ctx->m.linesize >> 1;
645 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
646 uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
647 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
652 // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
653 for (i = 0; i < 16; ++i) {
654 for (j = 0; j < 16; ++j) {
655 // Turn 16-bit pixels into 10-bit ones.
656 int const sample = (unsigned)pix[j] >> 6;
658 sqsum += sample * sample;
659 // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
663 mean = sum >> 8; // 16*16 == 2^8
665 ctx->mb_cmp[mb].value = sqmean - mean * mean;
666 ctx->mb_cmp[mb].mb = mb;
672 static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
674 int lambda, up_step, down_step;
675 int last_lower = INT_MAX, last_higher = 0;
678 for (q = 1; q < avctx->qmax; q++) {
680 avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
682 up_step = down_step = 2<<LAMBDA_FRAC_BITS;
683 lambda = ctx->lambda;
688 if (lambda == last_higher) {
690 end = 1; // need to set final qscales/bits
692 for (y = 0; y < ctx->m.mb_height; y++) {
693 for (x = 0; x < ctx->m.mb_width; x++) {
694 unsigned min = UINT_MAX;
696 int mb = y*ctx->m.mb_width+x;
697 for (q = 1; q < avctx->qmax; q++) {
698 unsigned score = ctx->mb_rc[q][mb].bits*lambda+
699 ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
705 bits += ctx->mb_rc[qscale][mb].bits;
706 ctx->mb_qscale[mb] = qscale;
707 ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
709 bits = (bits+31)&~31; // padding
710 if (bits > ctx->frame_bits)
713 //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
714 // lambda, last_higher, last_lower, bits, ctx->frame_bits);
716 if (bits > ctx->frame_bits)
720 if (bits < ctx->frame_bits) {
721 last_lower = FFMIN(lambda, last_lower);
722 if (last_higher != 0)
723 lambda = (lambda+last_higher)>>1;
726 down_step = FFMIN((int64_t)down_step*5, INT_MAX);
727 up_step = 1<<LAMBDA_FRAC_BITS;
728 lambda = FFMAX(1, lambda);
729 if (lambda == last_lower)
732 last_higher = FFMAX(lambda, last_higher);
733 if (last_lower != INT_MAX)
734 lambda = (lambda+last_lower)>>1;
735 else if ((int64_t)lambda + up_step > INT_MAX)
739 up_step = FFMIN((int64_t)up_step*5, INT_MAX);
740 down_step = 1<<LAMBDA_FRAC_BITS;
743 //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
744 ctx->lambda = lambda;
748 static int dnxhd_find_qscale(DNXHDEncContext *ctx)
754 int last_lower = INT_MAX;
758 qscale = ctx->qscale;
761 ctx->qscale = qscale;
762 // XXX avoid recalculating bits
763 ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
764 for (y = 0; y < ctx->m.mb_height; y++) {
765 for (x = 0; x < ctx->m.mb_width; x++)
766 bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
767 bits = (bits+31)&~31; // padding
768 if (bits > ctx->frame_bits)
771 //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
772 // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
773 if (bits < ctx->frame_bits) {
776 if (last_higher == qscale - 1) {
777 qscale = last_higher;
780 last_lower = FFMIN(qscale, last_lower);
781 if (last_higher != 0)
782 qscale = (qscale+last_higher)>>1;
784 qscale -= down_step++;
789 if (last_lower == qscale + 1)
791 last_higher = FFMAX(qscale, last_higher);
792 if (last_lower != INT_MAX)
793 qscale = (qscale+last_lower)>>1;
797 if (qscale >= ctx->m.avctx->qmax)
801 //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
802 ctx->qscale = qscale;
806 #define BUCKET_BITS 8
807 #define RADIX_PASSES 4
808 #define NBUCKETS (1 << BUCKET_BITS)
810 static inline int get_bucket(int value, int shift)
813 value &= NBUCKETS - 1;
814 return NBUCKETS - 1 - value;
817 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
820 memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
821 for (i = 0; i < size; i++) {
822 int v = data[i].value;
823 for (j = 0; j < RADIX_PASSES; j++) {
824 buckets[j][get_bucket(v, 0)]++;
829 for (j = 0; j < RADIX_PASSES; j++) {
831 for (i = NBUCKETS - 1; i >= 0; i--)
832 buckets[j][i] = offset -= buckets[j][i];
833 av_assert1(!buckets[j][0]);
837 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
839 int shift = pass * BUCKET_BITS;
841 for (i = 0; i < size; i++) {
842 int v = get_bucket(data[i].value, shift);
843 int pos = buckets[v]++;
848 static void radix_sort(RCCMPEntry *data, int size)
850 int buckets[RADIX_PASSES][NBUCKETS];
851 RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
852 radix_count(data, size, buckets);
853 radix_sort_pass(tmp, data, size, buckets[0], 0);
854 radix_sort_pass(data, tmp, size, buckets[1], 1);
855 if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
856 radix_sort_pass(tmp, data, size, buckets[2], 2);
857 radix_sort_pass(data, tmp, size, buckets[3], 3);
862 static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
866 if ((ret = dnxhd_find_qscale(ctx)) < 0)
868 for (y = 0; y < ctx->m.mb_height; y++) {
869 for (x = 0; x < ctx->m.mb_width; x++) {
870 int mb = y*ctx->m.mb_width+x;
872 ctx->mb_qscale[mb] = ctx->qscale;
873 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
874 max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
876 delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
877 ctx->mb_cmp[mb].mb = mb;
878 ctx->mb_cmp[mb].value = delta_bits ?
879 ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
880 : INT_MIN; //avoid increasing qscale
883 max_bits += 31; //worst padding
887 avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
888 radix_sort(ctx->mb_cmp, ctx->m.mb_num);
889 for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
890 int mb = ctx->mb_cmp[x].mb;
891 max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
892 ctx->mb_qscale[mb] = ctx->qscale+1;
893 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
899 static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
903 for (i = 0; i < 3; i++) {
904 ctx->frame.data[i] = frame->data[i];
905 ctx->frame.linesize[i] = frame->linesize[i];
908 for (i = 0; i < ctx->m.avctx->thread_count; i++) {
909 ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
910 ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
911 ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
912 ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
915 ctx->frame.interlaced_frame = frame->interlaced_frame;
916 ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
919 static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
920 const AVFrame *frame, int *got_packet)
922 DNXHDEncContext *ctx = avctx->priv_data;
927 if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
931 dnxhd_load_picture(ctx, frame);
934 for (i = 0; i < 3; i++) {
935 ctx->src[i] = ctx->frame.data[i];
936 if (ctx->interlaced && ctx->cur_field)
937 ctx->src[i] += ctx->frame.linesize[i];
940 dnxhd_write_header(avctx, buf);
942 if (avctx->mb_decision == FF_MB_DECISION_RD)
943 ret = dnxhd_encode_rdo(avctx, ctx);
945 ret = dnxhd_encode_fast(avctx, ctx);
947 av_log(avctx, AV_LOG_ERROR,
948 "picture could not fit ratecontrol constraints, increase qmax\n");
952 dnxhd_setup_threads_slices(ctx);
955 for (i = 0; i < ctx->m.mb_height; i++) {
956 AV_WB32(ctx->msip + i * 4, offset);
957 offset += ctx->slice_size[i];
958 av_assert1(!(ctx->slice_size[i] & 3));
961 avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
963 av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
964 memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
966 AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
968 if (ctx->interlaced && first_field) {
971 buf += ctx->cid_table->coding_unit_size;
972 goto encode_coding_unit;
975 ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
977 pkt->flags |= AV_PKT_FLAG_KEY;
982 static int dnxhd_encode_end(AVCodecContext *avctx)
984 DNXHDEncContext *ctx = avctx->priv_data;
985 int max_level = 1<<(ctx->cid_table->bit_depth+2);
988 av_free(ctx->vlc_codes-max_level*2);
989 av_free(ctx->vlc_bits -max_level*2);
990 av_freep(&ctx->run_codes);
991 av_freep(&ctx->run_bits);
993 av_freep(&ctx->mb_bits);
994 av_freep(&ctx->mb_qscale);
995 av_freep(&ctx->mb_rc);
996 av_freep(&ctx->mb_cmp);
997 av_freep(&ctx->slice_size);
998 av_freep(&ctx->slice_offs);
1000 av_freep(&ctx->qmatrix_c);
1001 av_freep(&ctx->qmatrix_l);
1002 av_freep(&ctx->qmatrix_c16);
1003 av_freep(&ctx->qmatrix_l16);
1005 for (i = 1; i < avctx->thread_count; i++)
1006 av_freep(&ctx->thread[i]);
1011 static const AVCodecDefault dnxhd_defaults[] = {
1012 { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1016 AVCodec ff_dnxhd_encoder = {
1018 .type = AVMEDIA_TYPE_VIDEO,
1019 .id = AV_CODEC_ID_DNXHD,
1020 .priv_data_size = sizeof(DNXHDEncContext),
1021 .init = dnxhd_encode_init,
1022 .encode2 = dnxhd_encode_picture,
1023 .close = dnxhd_encode_end,
1024 .capabilities = CODEC_CAP_SLICE_THREADS,
1025 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1026 AV_PIX_FMT_YUV422P10,
1028 .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1029 .priv_class = &class,
1030 .defaults = dnxhd_defaults,