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"
34 #include "mpegvideo_common.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, {.dbl = 0}, 0, 1, VE},
45 static const AVClass class = { "dnxhd", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
47 #define LAMBDA_FRAC_BITS 10
49 static void dnxhd_8bit_get_pixels_8x4_sym(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
52 for (i = 0; i < 4; i++) {
53 block[0] = pixels[0]; block[1] = pixels[1];
54 block[2] = pixels[2]; block[3] = pixels[3];
55 block[4] = pixels[4]; block[5] = pixels[5];
56 block[6] = pixels[6]; block[7] = pixels[7];
60 memcpy(block, block - 8, sizeof(*block) * 8);
61 memcpy(block + 8, block - 16, sizeof(*block) * 8);
62 memcpy(block + 16, block - 24, sizeof(*block) * 8);
63 memcpy(block + 24, block - 32, sizeof(*block) * 8);
66 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
72 for (i = 0; i < 4; i++) {
73 memcpy(block + i * 8, pixels + i * line_size, 8 * sizeof(*block));
74 memcpy(block - (i+1) * 8, pixels + i * line_size, 8 * sizeof(*block));
78 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, DCTELEM *block,
79 int n, int qscale, int *overflow)
81 const uint8_t *scantable= ctx->intra_scantable.scantable;
82 const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
83 int last_non_zero = 0;
88 // Divide by 4 with rounding, to compensate scaling of DCT coefficients
89 block[0] = (block[0] + 2) >> 2;
91 for (i = 1; i < 64; ++i) {
93 int sign = block[j] >> 31;
94 int level = (block[j] ^ sign) - sign;
95 level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
96 block[j] = (level ^ sign) - sign;
101 return last_non_zero;
104 static int dnxhd_init_vlc(DNXHDEncContext *ctx)
106 int i, j, level, run;
107 int max_level = 1<<(ctx->cid_table->bit_depth+2);
109 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
110 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail);
111 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail);
112 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail);
114 ctx->vlc_codes += max_level*2;
115 ctx->vlc_bits += max_level*2;
116 for (level = -max_level; level < max_level; level++) {
117 for (run = 0; run < 2; run++) {
118 int index = (level<<1)|run;
119 int sign, offset = 0, alevel = level;
121 MASK_ABS(sign, alevel);
123 offset = (alevel-1)>>6;
126 for (j = 0; j < 257; j++) {
127 if (ctx->cid_table->ac_level[j] >> 1 == alevel &&
128 (!offset || (ctx->cid_table->ac_flags[j] & 1) && offset) &&
129 (!run || (ctx->cid_table->ac_flags[j] & 2) && run)) {
130 assert(!ctx->vlc_codes[index]);
132 ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
133 ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
135 ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
136 ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
141 assert(!alevel || j < 257);
143 ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
144 ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
148 for (i = 0; i < 62; i++) {
149 int run = ctx->cid_table->run[i];
151 ctx->run_codes[run] = ctx->cid_table->run_codes[i];
152 ctx->run_bits [run] = ctx->cid_table->run_bits[i];
159 static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
161 // init first elem to 1 to avoid div by 0 in convert_matrix
162 uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
164 const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
165 const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
167 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
168 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
169 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
170 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
172 if (ctx->cid_table->bit_depth == 8) {
173 for (i = 1; i < 64; i++) {
174 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
175 weight_matrix[j] = ctx->cid_table->luma_weight[i];
177 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
178 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
179 for (i = 1; i < 64; i++) {
180 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
181 weight_matrix[j] = ctx->cid_table->chroma_weight[i];
183 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
184 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
186 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
187 for (i = 0; i < 64; i++) {
188 ctx->qmatrix_l [qscale] [i] <<= 2; ctx->qmatrix_c [qscale] [i] <<= 2;
189 ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
190 ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
195 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
196 for (i = 1; i < 64; i++) {
197 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
199 // The quantization formula from the VC-3 standard is:
200 // quantized = sign(block[i]) * floor(abs(block[i]/s) * p / (qscale * weight_table[i]))
201 // Where p is 32 for 8-bit samples and 8 for 10-bit ones.
202 // The s factor compensates scaling of DCT coefficients done by the DCT routines,
203 // and therefore is not present in standard. It's 8 for 8-bit samples and 4 for 10-bit ones.
204 // We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
205 // ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) / (qscale * weight_table[i])
206 // For 10-bit samples, p / s == 2
207 ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * luma_weight_table[i]);
208 ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * chroma_weight_table[i]);
213 ctx->m.q_chroma_intra_matrix16 = ctx->qmatrix_c16;
214 ctx->m.q_chroma_intra_matrix = ctx->qmatrix_c;
215 ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
216 ctx->m.q_intra_matrix = ctx->qmatrix_l;
223 static int dnxhd_init_rc(DNXHDEncContext *ctx)
225 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry), fail);
226 if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
227 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
229 ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
231 ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
237 static int dnxhd_encode_init(AVCodecContext *avctx)
239 DNXHDEncContext *ctx = avctx->priv_data;
240 int i, index, bit_depth;
242 switch (avctx->pix_fmt) {
243 case PIX_FMT_YUV422P:
246 case PIX_FMT_YUV422P10:
250 av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
254 ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
256 av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
259 av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
261 index = ff_dnxhd_get_cid_table(ctx->cid);
262 ctx->cid_table = &ff_dnxhd_cid_table[index];
264 ctx->m.avctx = avctx;
268 avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
270 ff_dsputil_init(&ctx->m.dsp, avctx);
271 ff_dct_common_init(&ctx->m);
272 if (!ctx->m.dct_quantize)
273 ctx->m.dct_quantize = ff_dct_quantize_c;
275 if (ctx->cid_table->bit_depth == 10) {
276 ctx->m.dct_quantize = dnxhd_10bit_dct_quantize;
277 ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
278 ctx->block_width_l2 = 4;
280 ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
281 ctx->block_width_l2 = 3;
285 ff_dnxhd_init_mmx(ctx);
288 ctx->m.mb_height = (avctx->height + 15) / 16;
289 ctx->m.mb_width = (avctx->width + 15) / 16;
291 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
293 ctx->m.mb_height /= 2;
296 ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
298 if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
299 ctx->m.intra_quant_bias = avctx->intra_quant_bias;
300 if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
303 // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
304 if (ctx->nitris_compat)
305 ctx->min_padding = 1600;
307 if (dnxhd_init_vlc(ctx) < 0)
309 if (dnxhd_init_rc(ctx) < 0)
312 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
313 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
314 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
315 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
317 ctx->frame.key_frame = 1;
318 ctx->frame.pict_type = AV_PICTURE_TYPE_I;
319 ctx->m.avctx->coded_frame = &ctx->frame;
321 if (avctx->thread_count > MAX_THREADS) {
322 av_log(avctx, AV_LOG_ERROR, "too many threads\n");
326 ctx->thread[0] = ctx;
327 for (i = 1; i < avctx->thread_count; i++) {
328 ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
329 memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
333 fail: //for FF_ALLOCZ_OR_GOTO
337 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
339 DNXHDEncContext *ctx = avctx->priv_data;
340 const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
344 memcpy(buf, header_prefix, 5);
345 buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
346 buf[6] = 0x80; // crc flag off
347 buf[7] = 0xa0; // reserved
348 AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
349 AV_WB16(buf + 0x1a, avctx->width); // SPL
350 AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
352 buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
353 buf[0x22] = 0x88 + (ctx->interlaced<<2);
354 AV_WB32(buf + 0x28, ctx->cid); // CID
355 buf[0x2c] = ctx->interlaced ? 0 : 0x80;
357 buf[0x5f] = 0x01; // UDL
359 buf[0x167] = 0x02; // reserved
360 AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
361 buf[0x16d] = ctx->m.mb_height; // Ns
362 buf[0x16f] = 0x10; // reserved
364 ctx->msip = buf + 0x170;
368 static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
372 nbits = av_log2_16bit(-2*diff);
375 nbits = av_log2_16bit(2*diff);
377 put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
378 (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
381 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
383 int last_non_zero = 0;
386 dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
387 ctx->m.last_dc[n] = block[0];
389 for (i = 1; i <= last_index; i++) {
390 j = ctx->m.intra_scantable.permutated[i];
393 int run_level = i - last_non_zero - 1;
394 int rlevel = (slevel<<1)|!!run_level;
395 put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
397 put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
401 put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
404 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
406 const uint8_t *weight_matrix;
410 weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
412 for (i = 1; i <= last_index; i++) {
413 int j = ctx->m.intra_scantable.permutated[i];
417 level = (1-2*level) * qscale * weight_matrix[i];
418 if (ctx->cid_table->bit_depth == 10) {
419 if (weight_matrix[i] != 8)
423 if (weight_matrix[i] != 32)
429 level = (2*level+1) * qscale * weight_matrix[i];
430 if (ctx->cid_table->bit_depth == 10) {
431 if (weight_matrix[i] != 8)
435 if (weight_matrix[i] != 32)
445 static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
449 for (i = 0; i < 64; i++)
450 score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
454 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
456 int last_non_zero = 0;
459 for (i = 1; i <= last_index; i++) {
460 j = ctx->m.intra_scantable.permutated[i];
463 int run_level = i - last_non_zero - 1;
464 bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
471 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
473 const int bs = ctx->block_width_l2;
474 const int bw = 1 << bs;
475 const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
476 const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
477 const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
478 DSPContext *dsp = &ctx->m.dsp;
480 dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
481 dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
482 dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
483 dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
485 if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
486 if (ctx->interlaced) {
487 ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
488 ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
489 ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
490 ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
492 dsp->clear_block(ctx->blocks[4]);
493 dsp->clear_block(ctx->blocks[5]);
494 dsp->clear_block(ctx->blocks[6]);
495 dsp->clear_block(ctx->blocks[7]);
498 dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
499 dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
500 dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
501 dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
505 static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
507 const static uint8_t component[8]={0,0,1,2,0,0,1,2};
511 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
513 DNXHDEncContext *ctx = avctx->priv_data;
514 int mb_y = jobnr, mb_x;
515 int qscale = ctx->qscale;
516 LOCAL_ALIGNED_16(DCTELEM, block, [64]);
517 ctx = ctx->thread[threadnr];
521 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
523 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
524 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
530 dnxhd_get_blocks(ctx, mb_x, mb_y);
532 for (i = 0; i < 8; i++) {
533 DCTELEM *src_block = ctx->blocks[i];
534 int overflow, nbits, diff, last_index;
535 int n = dnxhd_switch_matrix(ctx, i);
537 memcpy(block, src_block, 64*sizeof(*block));
538 last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
539 ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
541 diff = block[0] - ctx->m.last_dc[n];
542 if (diff < 0) nbits = av_log2_16bit(-2*diff);
543 else nbits = av_log2_16bit( 2*diff);
545 assert(nbits < ctx->cid_table->bit_depth + 4);
546 dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
548 ctx->m.last_dc[n] = block[0];
550 if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
551 dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
552 ctx->m.dsp.idct(block);
553 ssd += dnxhd_ssd_block(block, src_block);
556 ctx->mb_rc[qscale][mb].ssd = ssd;
557 ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
562 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
564 DNXHDEncContext *ctx = avctx->priv_data;
565 int mb_y = jobnr, mb_x;
566 ctx = ctx->thread[threadnr];
567 init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
571 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
572 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
573 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
574 int qscale = ctx->mb_qscale[mb];
577 put_bits(&ctx->m.pb, 12, qscale<<1);
579 dnxhd_get_blocks(ctx, mb_x, mb_y);
581 for (i = 0; i < 8; i++) {
582 DCTELEM *block = ctx->blocks[i];
583 int overflow, n = dnxhd_switch_matrix(ctx, i);
584 int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
586 dnxhd_encode_block(ctx, block, last_index, n);
587 //STOP_TIMER("encode_block");
590 if (put_bits_count(&ctx->m.pb)&31)
591 put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
592 flush_put_bits(&ctx->m.pb);
596 static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
600 for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
602 ctx->slice_offs[mb_y] = offset;
603 ctx->slice_size[mb_y] = 0;
604 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
605 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
606 ctx->slice_size[mb_y] += ctx->mb_bits[mb];
608 ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
609 ctx->slice_size[mb_y] >>= 3;
610 thread_size = ctx->slice_size[mb_y];
611 offset += thread_size;
615 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
617 DNXHDEncContext *ctx = avctx->priv_data;
618 int mb_y = jobnr, mb_x;
619 ctx = ctx->thread[threadnr];
620 if (ctx->cid_table->bit_depth == 8) {
621 uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
622 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
623 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
624 int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
625 int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)sum*sum)>>8)+128)>>8;
626 ctx->mb_cmp[mb].value = varc;
627 ctx->mb_cmp[mb].mb = mb;
630 int const linesize = ctx->m.linesize >> 1;
631 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
632 uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
633 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
638 // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
639 for (i = 0; i < 16; ++i) {
640 for (j = 0; j < 16; ++j) {
641 // Turn 16-bit pixels into 10-bit ones.
642 int const sample = (unsigned)pix[j] >> 6;
644 sqsum += sample * sample;
645 // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
649 mean = sum >> 8; // 16*16 == 2^8
651 ctx->mb_cmp[mb].value = sqmean - mean * mean;
652 ctx->mb_cmp[mb].mb = mb;
658 static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
660 int lambda, up_step, down_step;
661 int last_lower = INT_MAX, last_higher = 0;
664 for (q = 1; q < avctx->qmax; q++) {
666 avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
668 up_step = down_step = 2<<LAMBDA_FRAC_BITS;
669 lambda = ctx->lambda;
674 if (lambda == last_higher) {
676 end = 1; // need to set final qscales/bits
678 for (y = 0; y < ctx->m.mb_height; y++) {
679 for (x = 0; x < ctx->m.mb_width; x++) {
680 unsigned min = UINT_MAX;
682 int mb = y*ctx->m.mb_width+x;
683 for (q = 1; q < avctx->qmax; q++) {
684 unsigned score = ctx->mb_rc[q][mb].bits*lambda+
685 ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
691 bits += ctx->mb_rc[qscale][mb].bits;
692 ctx->mb_qscale[mb] = qscale;
693 ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
695 bits = (bits+31)&~31; // padding
696 if (bits > ctx->frame_bits)
699 //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
700 // lambda, last_higher, last_lower, bits, ctx->frame_bits);
702 if (bits > ctx->frame_bits)
706 if (bits < ctx->frame_bits) {
707 last_lower = FFMIN(lambda, last_lower);
708 if (last_higher != 0)
709 lambda = (lambda+last_higher)>>1;
712 down_step = FFMIN((int64_t)down_step*5, INT_MAX);
713 up_step = 1<<LAMBDA_FRAC_BITS;
714 lambda = FFMAX(1, lambda);
715 if (lambda == last_lower)
718 last_higher = FFMAX(lambda, last_higher);
719 if (last_lower != INT_MAX)
720 lambda = (lambda+last_lower)>>1;
721 else if ((int64_t)lambda + up_step > INT_MAX)
725 up_step = FFMIN((int64_t)up_step*5, INT_MAX);
726 down_step = 1<<LAMBDA_FRAC_BITS;
729 //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
730 ctx->lambda = lambda;
734 static int dnxhd_find_qscale(DNXHDEncContext *ctx)
740 int last_lower = INT_MAX;
744 qscale = ctx->qscale;
747 ctx->qscale = qscale;
748 // XXX avoid recalculating bits
749 ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
750 for (y = 0; y < ctx->m.mb_height; y++) {
751 for (x = 0; x < ctx->m.mb_width; x++)
752 bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
753 bits = (bits+31)&~31; // padding
754 if (bits > ctx->frame_bits)
757 //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
758 // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
759 if (bits < ctx->frame_bits) {
762 if (last_higher == qscale - 1) {
763 qscale = last_higher;
766 last_lower = FFMIN(qscale, last_lower);
767 if (last_higher != 0)
768 qscale = (qscale+last_higher)>>1;
770 qscale -= down_step++;
775 if (last_lower == qscale + 1)
777 last_higher = FFMAX(qscale, last_higher);
778 if (last_lower != INT_MAX)
779 qscale = (qscale+last_lower)>>1;
783 if (qscale >= ctx->m.avctx->qmax)
787 //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
788 ctx->qscale = qscale;
792 #define BUCKET_BITS 8
793 #define RADIX_PASSES 4
794 #define NBUCKETS (1 << BUCKET_BITS)
796 static inline int get_bucket(int value, int shift)
799 value &= NBUCKETS - 1;
800 return NBUCKETS - 1 - value;
803 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
806 memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
807 for (i = 0; i < size; i++) {
808 int v = data[i].value;
809 for (j = 0; j < RADIX_PASSES; j++) {
810 buckets[j][get_bucket(v, 0)]++;
815 for (j = 0; j < RADIX_PASSES; j++) {
817 for (i = NBUCKETS - 1; i >= 0; i--)
818 buckets[j][i] = offset -= buckets[j][i];
819 assert(!buckets[j][0]);
823 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
825 int shift = pass * BUCKET_BITS;
827 for (i = 0; i < size; i++) {
828 int v = get_bucket(data[i].value, shift);
829 int pos = buckets[v]++;
834 static void radix_sort(RCCMPEntry *data, int size)
836 int buckets[RADIX_PASSES][NBUCKETS];
837 RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
838 radix_count(data, size, buckets);
839 radix_sort_pass(tmp, data, size, buckets[0], 0);
840 radix_sort_pass(data, tmp, size, buckets[1], 1);
841 if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
842 radix_sort_pass(tmp, data, size, buckets[2], 2);
843 radix_sort_pass(data, tmp, size, buckets[3], 3);
848 static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
852 if ((ret = dnxhd_find_qscale(ctx)) < 0)
854 for (y = 0; y < ctx->m.mb_height; y++) {
855 for (x = 0; x < ctx->m.mb_width; x++) {
856 int mb = y*ctx->m.mb_width+x;
858 ctx->mb_qscale[mb] = ctx->qscale;
859 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
860 max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
862 delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
863 ctx->mb_cmp[mb].mb = mb;
864 ctx->mb_cmp[mb].value = delta_bits ?
865 ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
866 : INT_MIN; //avoid increasing qscale
869 max_bits += 31; //worst padding
873 avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
874 radix_sort(ctx->mb_cmp, ctx->m.mb_num);
875 for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
876 int mb = ctx->mb_cmp[x].mb;
877 max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
878 ctx->mb_qscale[mb] = ctx->qscale+1;
879 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
885 static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
889 for (i = 0; i < 3; i++) {
890 ctx->frame.data[i] = frame->data[i];
891 ctx->frame.linesize[i] = frame->linesize[i];
894 for (i = 0; i < ctx->m.avctx->thread_count; i++) {
895 ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
896 ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
897 ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
898 ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
901 ctx->frame.interlaced_frame = frame->interlaced_frame;
902 ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
905 static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
906 const AVFrame *frame, int *got_packet)
908 DNXHDEncContext *ctx = avctx->priv_data;
913 if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
917 dnxhd_load_picture(ctx, frame);
920 for (i = 0; i < 3; i++) {
921 ctx->src[i] = ctx->frame.data[i];
922 if (ctx->interlaced && ctx->cur_field)
923 ctx->src[i] += ctx->frame.linesize[i];
926 dnxhd_write_header(avctx, buf);
928 if (avctx->mb_decision == FF_MB_DECISION_RD)
929 ret = dnxhd_encode_rdo(avctx, ctx);
931 ret = dnxhd_encode_fast(avctx, ctx);
933 av_log(avctx, AV_LOG_ERROR,
934 "picture could not fit ratecontrol constraints, increase qmax\n");
938 dnxhd_setup_threads_slices(ctx);
941 for (i = 0; i < ctx->m.mb_height; i++) {
942 AV_WB32(ctx->msip + i * 4, offset);
943 offset += ctx->slice_size[i];
944 assert(!(ctx->slice_size[i] & 3));
947 avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
949 assert(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
950 memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
952 AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
954 if (ctx->interlaced && first_field) {
957 buf += ctx->cid_table->coding_unit_size;
958 goto encode_coding_unit;
961 ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
963 pkt->flags |= AV_PKT_FLAG_KEY;
968 static int dnxhd_encode_end(AVCodecContext *avctx)
970 DNXHDEncContext *ctx = avctx->priv_data;
971 int max_level = 1<<(ctx->cid_table->bit_depth+2);
974 av_free(ctx->vlc_codes-max_level*2);
975 av_free(ctx->vlc_bits -max_level*2);
976 av_freep(&ctx->run_codes);
977 av_freep(&ctx->run_bits);
979 av_freep(&ctx->mb_bits);
980 av_freep(&ctx->mb_qscale);
981 av_freep(&ctx->mb_rc);
982 av_freep(&ctx->mb_cmp);
983 av_freep(&ctx->slice_size);
984 av_freep(&ctx->slice_offs);
986 av_freep(&ctx->qmatrix_c);
987 av_freep(&ctx->qmatrix_l);
988 av_freep(&ctx->qmatrix_c16);
989 av_freep(&ctx->qmatrix_l16);
991 for (i = 1; i < avctx->thread_count; i++)
992 av_freep(&ctx->thread[i]);
997 static const AVCodecDefault dnxhd_defaults[] = {
998 { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1002 AVCodec ff_dnxhd_encoder = {
1004 .type = AVMEDIA_TYPE_VIDEO,
1005 .id = CODEC_ID_DNXHD,
1006 .priv_data_size = sizeof(DNXHDEncContext),
1007 .init = dnxhd_encode_init,
1008 .encode2 = dnxhd_encode_picture,
1009 .close = dnxhd_encode_end,
1010 .capabilities = CODEC_CAP_SLICE_THREADS,
1011 .pix_fmts = (const enum PixelFormat[]){ PIX_FMT_YUV422P,
1014 .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1015 .priv_class = &class,
1016 .defaults = dnxhd_defaults,