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 Libav.
11 * Libav 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 * Libav 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 Libav; 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"
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, {.dbl = 0}, 0, 1, VE},
44 static const AVClass class = { "dnxhd", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
46 #define LAMBDA_FRAC_BITS 10
48 static void dnxhd_8bit_get_pixels_8x4_sym(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
51 for (i = 0; i < 4; i++) {
52 block[0] = pixels[0]; block[1] = pixels[1];
53 block[2] = pixels[2]; block[3] = pixels[3];
54 block[4] = pixels[4]; block[5] = pixels[5];
55 block[6] = pixels[6]; block[7] = pixels[7];
59 memcpy(block, block - 8, sizeof(*block) * 8);
60 memcpy(block + 8, block - 16, sizeof(*block) * 8);
61 memcpy(block + 16, block - 24, sizeof(*block) * 8);
62 memcpy(block + 24, block - 32, sizeof(*block) * 8);
65 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
71 for (i = 0; i < 4; i++) {
72 memcpy(block + i * 8, pixels + i * line_size, 8 * sizeof(*block));
73 memcpy(block - (i+1) * 8, pixels + i * line_size, 8 * sizeof(*block));
77 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, DCTELEM *block,
78 int n, int qscale, int *overflow)
80 const uint8_t *scantable= ctx->intra_scantable.scantable;
81 const int *qmat = ctx->q_intra_matrix[qscale];
82 int last_non_zero = 0;
87 // Divide by 4 with rounding, to compensate scaling of DCT coefficients
88 block[0] = (block[0] + 2) >> 2;
90 for (i = 1; i < 64; ++i) {
92 int sign = block[j] >> 31;
93 int level = (block[j] ^ sign) - sign;
94 level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
95 block[j] = (level ^ sign) - sign;
100 return last_non_zero;
103 static int dnxhd_init_vlc(DNXHDEncContext *ctx)
105 int i, j, level, run;
106 int max_level = 1<<(ctx->cid_table->bit_depth+2);
108 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
109 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail);
110 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail);
111 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail);
113 ctx->vlc_codes += max_level*2;
114 ctx->vlc_bits += max_level*2;
115 for (level = -max_level; level < max_level; level++) {
116 for (run = 0; run < 2; run++) {
117 int index = (level<<1)|run;
118 int sign, offset = 0, alevel = level;
120 MASK_ABS(sign, alevel);
122 offset = (alevel-1)>>6;
125 for (j = 0; j < 257; j++) {
126 if (ctx->cid_table->ac_level[j] == alevel &&
127 (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) &&
128 (!run || (ctx->cid_table->ac_run_flag [j] && run))) {
129 assert(!ctx->vlc_codes[index]);
131 ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
132 ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
134 ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
135 ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
140 assert(!alevel || j < 257);
142 ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
143 ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
147 for (i = 0; i < 62; i++) {
148 int run = ctx->cid_table->run[i];
150 ctx->run_codes[run] = ctx->cid_table->run_codes[i];
151 ctx->run_bits [run] = ctx->cid_table->run_bits[i];
158 static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
160 // init first elem to 1 to avoid div by 0 in convert_matrix
161 uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
163 const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
164 const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
166 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
167 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
168 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
169 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
171 if (ctx->cid_table->bit_depth == 8) {
172 for (i = 1; i < 64; i++) {
173 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
174 weight_matrix[j] = ctx->cid_table->luma_weight[i];
176 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
177 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
178 for (i = 1; i < 64; i++) {
179 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
180 weight_matrix[j] = ctx->cid_table->chroma_weight[i];
182 ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
183 ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
185 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
186 for (i = 0; i < 64; i++) {
187 ctx->qmatrix_l [qscale] [i] <<= 2; ctx->qmatrix_c [qscale] [i] <<= 2;
188 ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
189 ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
194 for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
195 for (i = 1; i < 64; i++) {
196 int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
198 // The quantization formula from the VC-3 standard is:
199 // quantized = sign(block[i]) * floor(abs(block[i]/s) * p / (qscale * weight_table[i]))
200 // Where p is 32 for 8-bit samples and 8 for 10-bit ones.
201 // The s factor compensates scaling of DCT coefficients done by the DCT routines,
202 // and therefore is not present in standard. It's 8 for 8-bit samples and 4 for 10-bit ones.
203 // We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
204 // ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) / (qscale * weight_table[i])
205 // For 10-bit samples, p / s == 2
206 ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * luma_weight_table[i]);
207 ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * chroma_weight_table[i]);
217 static int dnxhd_init_rc(DNXHDEncContext *ctx)
219 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry), fail);
220 if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
221 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
223 ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
225 ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
231 static int dnxhd_encode_init(AVCodecContext *avctx)
233 DNXHDEncContext *ctx = avctx->priv_data;
234 int i, index, bit_depth;
236 switch (avctx->pix_fmt) {
237 case PIX_FMT_YUV422P:
240 case PIX_FMT_YUV422P10:
244 av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
248 ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
250 av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
253 av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
255 index = ff_dnxhd_get_cid_table(ctx->cid);
256 ctx->cid_table = &ff_dnxhd_cid_table[index];
258 ctx->m.avctx = avctx;
262 avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
264 ff_dsputil_init(&ctx->m.dsp, avctx);
265 ff_dct_common_init(&ctx->m);
266 if (!ctx->m.dct_quantize)
267 ctx->m.dct_quantize = ff_dct_quantize_c;
269 if (ctx->cid_table->bit_depth == 10) {
270 ctx->m.dct_quantize = dnxhd_10bit_dct_quantize;
271 ctx->get_pixels_8x4_sym = dnxhd_10bit_get_pixels_8x4_sym;
272 ctx->block_width_l2 = 4;
274 ctx->get_pixels_8x4_sym = dnxhd_8bit_get_pixels_8x4_sym;
275 ctx->block_width_l2 = 3;
279 ff_dnxhd_init_mmx(ctx);
282 ctx->m.mb_height = (avctx->height + 15) / 16;
283 ctx->m.mb_width = (avctx->width + 15) / 16;
285 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
287 ctx->m.mb_height /= 2;
290 ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
292 if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
293 ctx->m.intra_quant_bias = avctx->intra_quant_bias;
294 if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
297 // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
298 if (ctx->nitris_compat)
299 ctx->min_padding = 1600;
301 if (dnxhd_init_vlc(ctx) < 0)
303 if (dnxhd_init_rc(ctx) < 0)
306 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
307 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
308 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
309 FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
311 ctx->frame.key_frame = 1;
312 ctx->frame.pict_type = AV_PICTURE_TYPE_I;
313 ctx->m.avctx->coded_frame = &ctx->frame;
315 if (avctx->thread_count > MAX_THREADS) {
316 av_log(avctx, AV_LOG_ERROR, "too many threads\n");
320 ctx->thread[0] = ctx;
321 for (i = 1; i < avctx->thread_count; i++) {
322 ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
323 memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
327 fail: //for FF_ALLOCZ_OR_GOTO
331 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
333 DNXHDEncContext *ctx = avctx->priv_data;
334 const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
338 memcpy(buf, header_prefix, 5);
339 buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
340 buf[6] = 0x80; // crc flag off
341 buf[7] = 0xa0; // reserved
342 AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
343 AV_WB16(buf + 0x1a, avctx->width); // SPL
344 AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
346 buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
347 buf[0x22] = 0x88 + (ctx->interlaced<<2);
348 AV_WB32(buf + 0x28, ctx->cid); // CID
349 buf[0x2c] = ctx->interlaced ? 0 : 0x80;
351 buf[0x5f] = 0x01; // UDL
353 buf[0x167] = 0x02; // reserved
354 AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
355 buf[0x16d] = ctx->m.mb_height; // Ns
356 buf[0x16f] = 0x10; // reserved
358 ctx->msip = buf + 0x170;
362 static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
366 nbits = av_log2_16bit(-2*diff);
369 nbits = av_log2_16bit(2*diff);
371 put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
372 (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
375 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
377 int last_non_zero = 0;
380 dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
381 ctx->m.last_dc[n] = block[0];
383 for (i = 1; i <= last_index; i++) {
384 j = ctx->m.intra_scantable.permutated[i];
387 int run_level = i - last_non_zero - 1;
388 int rlevel = (slevel<<1)|!!run_level;
389 put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
391 put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
395 put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
398 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
400 const uint8_t *weight_matrix;
404 weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
406 for (i = 1; i <= last_index; i++) {
407 int j = ctx->m.intra_scantable.permutated[i];
411 level = (1-2*level) * qscale * weight_matrix[i];
412 if (ctx->cid_table->bit_depth == 10) {
413 if (weight_matrix[i] != 8)
417 if (weight_matrix[i] != 32)
423 level = (2*level+1) * qscale * weight_matrix[i];
424 if (ctx->cid_table->bit_depth == 10) {
425 if (weight_matrix[i] != 8)
429 if (weight_matrix[i] != 32)
439 static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
443 for (i = 0; i < 64; i++)
444 score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
448 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
450 int last_non_zero = 0;
453 for (i = 1; i <= last_index; i++) {
454 j = ctx->m.intra_scantable.permutated[i];
457 int run_level = i - last_non_zero - 1;
458 bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
465 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
467 const int bs = ctx->block_width_l2;
468 const int bw = 1 << bs;
469 const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
470 const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
471 const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
472 DSPContext *dsp = &ctx->m.dsp;
474 dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
475 dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
476 dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
477 dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
479 if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
480 if (ctx->interlaced) {
481 ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
482 ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
483 ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
484 ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
486 dsp->clear_block(ctx->blocks[4]);
487 dsp->clear_block(ctx->blocks[5]);
488 dsp->clear_block(ctx->blocks[6]);
489 dsp->clear_block(ctx->blocks[7]);
492 dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
493 dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
494 dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
495 dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
499 static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
502 ctx->m.q_intra_matrix16 = ctx->qmatrix_c16;
503 ctx->m.q_intra_matrix = ctx->qmatrix_c;
506 ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
507 ctx->m.q_intra_matrix = ctx->qmatrix_l;
512 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
514 DNXHDEncContext *ctx = avctx->priv_data;
515 int mb_y = jobnr, mb_x;
516 int qscale = ctx->qscale;
517 LOCAL_ALIGNED_16(DCTELEM, block, [64]);
518 ctx = ctx->thread[threadnr];
522 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
524 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
525 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
531 dnxhd_get_blocks(ctx, mb_x, mb_y);
533 for (i = 0; i < 8; i++) {
534 DCTELEM *src_block = ctx->blocks[i];
535 int overflow, nbits, diff, last_index;
536 int n = dnxhd_switch_matrix(ctx, i);
538 memcpy(block, src_block, 64*sizeof(*block));
539 last_index = ctx->m.dct_quantize(&ctx->m, block, i, qscale, &overflow);
540 ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
542 diff = block[0] - ctx->m.last_dc[n];
543 if (diff < 0) nbits = av_log2_16bit(-2*diff);
544 else nbits = av_log2_16bit( 2*diff);
546 assert(nbits < ctx->cid_table->bit_depth + 4);
547 dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
549 ctx->m.last_dc[n] = block[0];
551 if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
552 dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
553 ctx->m.dsp.idct(block);
554 ssd += dnxhd_ssd_block(block, src_block);
557 ctx->mb_rc[qscale][mb].ssd = ssd;
558 ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
563 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
565 DNXHDEncContext *ctx = avctx->priv_data;
566 int mb_y = jobnr, mb_x;
567 ctx = ctx->thread[threadnr];
568 init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
572 ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
573 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
574 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
575 int qscale = ctx->mb_qscale[mb];
578 put_bits(&ctx->m.pb, 12, qscale<<1);
580 dnxhd_get_blocks(ctx, mb_x, mb_y);
582 for (i = 0; i < 8; i++) {
583 DCTELEM *block = ctx->blocks[i];
584 int overflow, n = dnxhd_switch_matrix(ctx, i);
585 int last_index = ctx->m.dct_quantize(&ctx->m, block, i,
588 dnxhd_encode_block(ctx, block, last_index, n);
589 //STOP_TIMER("encode_block");
592 if (put_bits_count(&ctx->m.pb)&31)
593 put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
594 flush_put_bits(&ctx->m.pb);
598 static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
602 for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
604 ctx->slice_offs[mb_y] = offset;
605 ctx->slice_size[mb_y] = 0;
606 for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
607 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
608 ctx->slice_size[mb_y] += ctx->mb_bits[mb];
610 ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
611 ctx->slice_size[mb_y] >>= 3;
612 thread_size = ctx->slice_size[mb_y];
613 offset += thread_size;
617 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
619 DNXHDEncContext *ctx = avctx->priv_data;
620 int mb_y = jobnr, mb_x;
621 ctx = ctx->thread[threadnr];
622 if (ctx->cid_table->bit_depth == 8) {
623 uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
624 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
625 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
626 int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
627 int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)sum*sum)>>8)+128)>>8;
628 ctx->mb_cmp[mb].value = varc;
629 ctx->mb_cmp[mb].mb = mb;
632 int const linesize = ctx->m.linesize >> 1;
633 for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
634 uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
635 unsigned mb = mb_y * ctx->m.mb_width + mb_x;
640 // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
641 for (i = 0; i < 16; ++i) {
642 for (j = 0; j < 16; ++j) {
643 // Turn 16-bit pixels into 10-bit ones.
644 int const sample = (unsigned)pix[j] >> 6;
646 sqsum += sample * sample;
647 // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
651 mean = sum >> 8; // 16*16 == 2^8
653 ctx->mb_cmp[mb].value = sqmean - mean * mean;
654 ctx->mb_cmp[mb].mb = mb;
660 static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
662 int lambda, up_step, down_step;
663 int last_lower = INT_MAX, last_higher = 0;
666 for (q = 1; q < avctx->qmax; q++) {
668 avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
670 up_step = down_step = 2<<LAMBDA_FRAC_BITS;
671 lambda = ctx->lambda;
676 if (lambda == last_higher) {
678 end = 1; // need to set final qscales/bits
680 for (y = 0; y < ctx->m.mb_height; y++) {
681 for (x = 0; x < ctx->m.mb_width; x++) {
682 unsigned min = UINT_MAX;
684 int mb = y*ctx->m.mb_width+x;
685 for (q = 1; q < avctx->qmax; q++) {
686 unsigned score = ctx->mb_rc[q][mb].bits*lambda+
687 ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
693 bits += ctx->mb_rc[qscale][mb].bits;
694 ctx->mb_qscale[mb] = qscale;
695 ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
697 bits = (bits+31)&~31; // padding
698 if (bits > ctx->frame_bits)
701 //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
702 // lambda, last_higher, last_lower, bits, ctx->frame_bits);
704 if (bits > ctx->frame_bits)
708 if (bits < ctx->frame_bits) {
709 last_lower = FFMIN(lambda, last_lower);
710 if (last_higher != 0)
711 lambda = (lambda+last_higher)>>1;
714 down_step = FFMIN((int64_t)down_step*5, INT_MAX);
715 up_step = 1<<LAMBDA_FRAC_BITS;
716 lambda = FFMAX(1, lambda);
717 if (lambda == last_lower)
720 last_higher = FFMAX(lambda, last_higher);
721 if (last_lower != INT_MAX)
722 lambda = (lambda+last_lower)>>1;
723 else if ((int64_t)lambda + up_step > INT_MAX)
727 up_step = FFMIN((int64_t)up_step*5, INT_MAX);
728 down_step = 1<<LAMBDA_FRAC_BITS;
731 //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
732 ctx->lambda = lambda;
736 static int dnxhd_find_qscale(DNXHDEncContext *ctx)
742 int last_lower = INT_MAX;
746 qscale = ctx->qscale;
749 ctx->qscale = qscale;
750 // XXX avoid recalculating bits
751 ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
752 for (y = 0; y < ctx->m.mb_height; y++) {
753 for (x = 0; x < ctx->m.mb_width; x++)
754 bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
755 bits = (bits+31)&~31; // padding
756 if (bits > ctx->frame_bits)
759 //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
760 // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
761 if (bits < ctx->frame_bits) {
764 if (last_higher == qscale - 1) {
765 qscale = last_higher;
768 last_lower = FFMIN(qscale, last_lower);
769 if (last_higher != 0)
770 qscale = (qscale+last_higher)>>1;
772 qscale -= down_step++;
777 if (last_lower == qscale + 1)
779 last_higher = FFMAX(qscale, last_higher);
780 if (last_lower != INT_MAX)
781 qscale = (qscale+last_lower)>>1;
785 if (qscale >= ctx->m.avctx->qmax)
789 //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
790 ctx->qscale = qscale;
794 #define BUCKET_BITS 8
795 #define RADIX_PASSES 4
796 #define NBUCKETS (1 << BUCKET_BITS)
798 static inline int get_bucket(int value, int shift)
801 value &= NBUCKETS - 1;
802 return NBUCKETS - 1 - value;
805 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
808 memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
809 for (i = 0; i < size; i++) {
810 int v = data[i].value;
811 for (j = 0; j < RADIX_PASSES; j++) {
812 buckets[j][get_bucket(v, 0)]++;
817 for (j = 0; j < RADIX_PASSES; j++) {
819 for (i = NBUCKETS - 1; i >= 0; i--)
820 buckets[j][i] = offset -= buckets[j][i];
821 assert(!buckets[j][0]);
825 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
827 int shift = pass * BUCKET_BITS;
829 for (i = 0; i < size; i++) {
830 int v = get_bucket(data[i].value, shift);
831 int pos = buckets[v]++;
836 static void radix_sort(RCCMPEntry *data, int size)
838 int buckets[RADIX_PASSES][NBUCKETS];
839 RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
840 radix_count(data, size, buckets);
841 radix_sort_pass(tmp, data, size, buckets[0], 0);
842 radix_sort_pass(data, tmp, size, buckets[1], 1);
843 if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
844 radix_sort_pass(tmp, data, size, buckets[2], 2);
845 radix_sort_pass(data, tmp, size, buckets[3], 3);
850 static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
854 if ((ret = dnxhd_find_qscale(ctx)) < 0)
856 for (y = 0; y < ctx->m.mb_height; y++) {
857 for (x = 0; x < ctx->m.mb_width; x++) {
858 int mb = y*ctx->m.mb_width+x;
860 ctx->mb_qscale[mb] = ctx->qscale;
861 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
862 max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
864 delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
865 ctx->mb_cmp[mb].mb = mb;
866 ctx->mb_cmp[mb].value = delta_bits ?
867 ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
868 : INT_MIN; //avoid increasing qscale
871 max_bits += 31; //worst padding
875 avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
876 radix_sort(ctx->mb_cmp, ctx->m.mb_num);
877 for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
878 int mb = ctx->mb_cmp[x].mb;
879 max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
880 ctx->mb_qscale[mb] = ctx->qscale+1;
881 ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
887 static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
891 for (i = 0; i < 3; i++) {
892 ctx->frame.data[i] = frame->data[i];
893 ctx->frame.linesize[i] = frame->linesize[i];
896 for (i = 0; i < ctx->m.avctx->thread_count; i++) {
897 ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
898 ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
899 ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
900 ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
903 ctx->frame.interlaced_frame = frame->interlaced_frame;
904 ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
907 static int dnxhd_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
908 const AVFrame *frame, int *got_packet)
910 DNXHDEncContext *ctx = avctx->priv_data;
915 if ((ret = ff_alloc_packet(pkt, ctx->cid_table->frame_size)) < 0) {
916 av_log(avctx, AV_LOG_ERROR, "output buffer is too small to compress picture\n");
921 dnxhd_load_picture(ctx, frame);
924 for (i = 0; i < 3; i++) {
925 ctx->src[i] = ctx->frame.data[i];
926 if (ctx->interlaced && ctx->cur_field)
927 ctx->src[i] += ctx->frame.linesize[i];
930 dnxhd_write_header(avctx, buf);
932 if (avctx->mb_decision == FF_MB_DECISION_RD)
933 ret = dnxhd_encode_rdo(avctx, ctx);
935 ret = dnxhd_encode_fast(avctx, ctx);
937 av_log(avctx, AV_LOG_ERROR,
938 "picture could not fit ratecontrol constraints, increase qmax\n");
942 dnxhd_setup_threads_slices(ctx);
945 for (i = 0; i < ctx->m.mb_height; i++) {
946 AV_WB32(ctx->msip + i * 4, offset);
947 offset += ctx->slice_size[i];
948 assert(!(ctx->slice_size[i] & 3));
951 avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
953 assert(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
954 memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
956 AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
958 if (ctx->interlaced && first_field) {
961 buf += ctx->cid_table->coding_unit_size;
962 goto encode_coding_unit;
965 ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
967 pkt->flags |= AV_PKT_FLAG_KEY;
972 static int dnxhd_encode_end(AVCodecContext *avctx)
974 DNXHDEncContext *ctx = avctx->priv_data;
975 int max_level = 1<<(ctx->cid_table->bit_depth+2);
978 av_free(ctx->vlc_codes-max_level*2);
979 av_free(ctx->vlc_bits -max_level*2);
980 av_freep(&ctx->run_codes);
981 av_freep(&ctx->run_bits);
983 av_freep(&ctx->mb_bits);
984 av_freep(&ctx->mb_qscale);
985 av_freep(&ctx->mb_rc);
986 av_freep(&ctx->mb_cmp);
987 av_freep(&ctx->slice_size);
988 av_freep(&ctx->slice_offs);
990 av_freep(&ctx->qmatrix_c);
991 av_freep(&ctx->qmatrix_l);
992 av_freep(&ctx->qmatrix_c16);
993 av_freep(&ctx->qmatrix_l16);
995 for (i = 1; i < avctx->thread_count; i++)
996 av_freep(&ctx->thread[i]);
1001 AVCodec ff_dnxhd_encoder = {
1003 .type = AVMEDIA_TYPE_VIDEO,
1004 .id = CODEC_ID_DNXHD,
1005 .priv_data_size = sizeof(DNXHDEncContext),
1006 .init = dnxhd_encode_init,
1007 .encode2 = dnxhd_encode_picture,
1008 .close = dnxhd_encode_end,
1009 .capabilities = CODEC_CAP_SLICE_THREADS,
1010 .pix_fmts = (const enum PixelFormat[]){ PIX_FMT_YUV422P,
1013 .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1014 .priv_class = &class,