FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
dnxhdenc.c
Go to the documentation of this file.
1 /*
2  * VC3/DNxHD encoder
3  * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  * Copyright (c) 2011 MirriAd Ltd
5  *
6  * VC-3 encoder funded by the British Broadcasting Corporation
7  * 10 bit support added by MirriAd Ltd, Joseph Artsimovich <joseph@mirriad.com>
8  *
9  * This file is part of FFmpeg.
10  *
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.
15  *
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.
20  *
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
24  */
25 
26 //#define DEBUG
27 #define RC_VARIANCE 1 // use variance or ssd for fast rc
28 
29 #include "libavutil/opt.h"
30 #include "avcodec.h"
31 #include "dsputil.h"
32 #include "internal.h"
33 #include "mpegvideo.h"
34 #include "dnxhdenc.h"
35 #include "internal.h"
36 
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.
39 
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},
42 {NULL}
43 };
44 
45 static const AVClass class = {
46  .class_name = "dnxhd",
47  .item_name = av_default_item_name,
48  .option = options,
50 };
51 
52 #define LAMBDA_FRAC_BITS 10
53 
54 static void dnxhd_8bit_get_pixels_8x4_sym(DCTELEM *av_restrict block, const uint8_t *pixels, int line_size)
55 {
56  int i;
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];
62  pixels += line_size;
63  block += 8;
64  }
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);
69 }
70 
72 {
73  int i;
74  const uint16_t* pixels16 = (const uint16_t*)pixels;
75  line_size >>= 1;
76 
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;
83  block += 8;
84  }
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);
89 }
90 
92  int n, int qscale, int *overflow)
93 {
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;
97  int i;
98 
99  ctx->dsp.fdct(block);
100 
101  // Divide by 4 with rounding, to compensate scaling of DCT coefficients
102  block[0] = (block[0] + 2) >> 2;
103 
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;
110  if (level)
111  last_non_zero = i;
112  }
113 
114  return last_non_zero;
115 }
116 
118 {
119  int i, j, level, run;
120  int max_level = 1<<(ctx->cid_table->bit_depth+2);
121 
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);
126 
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;
133 
134  MASK_ABS(sign, alevel);
135  if (alevel > 64) {
136  offset = (alevel-1)>>6;
137  alevel -= offset<<6;
138  }
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]);
144  if (alevel) {
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;
147  } else {
148  ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
149  ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
150  }
151  break;
152  }
153  }
154  av_assert0(!alevel || j < 257);
155  if (offset) {
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;
158  }
159  }
160  }
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];
166  }
167  return 0;
168  fail:
169  return -1;
170 }
171 
172 static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
173 {
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*
176  int qscale, i;
177  const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
178  const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
179 
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);
184 
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];
189  }
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];
195  }
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);
198 
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;
204  }
205  }
206  } else {
207  // 10-bit
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]];
211 
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]);
222  }
223  }
224  }
225 
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;
230 
231  return 0;
232  fail:
233  return -1;
234 }
235 
237 {
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);
241 
242  ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
243  ctx->qscale = 1;
244  ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
245  return 0;
246  fail:
247  return -1;
248 }
249 
251 {
252  DNXHDEncContext *ctx = avctx->priv_data;
253  int i, index, bit_depth;
254 
255  switch (avctx->pix_fmt) {
256  case AV_PIX_FMT_YUV422P:
257  bit_depth = 8;
258  break;
260  bit_depth = 10;
261  break;
262  default:
263  av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
264  return -1;
265  }
266 
267  ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
268  if (!ctx->cid) {
269  av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
270  return -1;
271  }
272  av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
273 
274  index = ff_dnxhd_get_cid_table(ctx->cid);
275  av_assert0(index >= 0);
277 
278  ctx->m.avctx = avctx;
279  ctx->m.mb_intra = 1;
280  ctx->m.h263_aic = 1;
281 
282  avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
283 
284  ff_dct_common_init(&ctx->m);
285  ff_dct_encode_init(&ctx->m);
286 
287  if (!ctx->m.dct_quantize)
289 
290  if (ctx->cid_table->bit_depth == 10) {
293  ctx->block_width_l2 = 4;
294  } else {
296  ctx->block_width_l2 = 3;
297  }
298 
299  if (ARCH_X86)
301 
302  ctx->m.mb_height = (avctx->height + 15) / 16;
303  ctx->m.mb_width = (avctx->width + 15) / 16;
304 
305  if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
306  ctx->interlaced = 1;
307  ctx->m.mb_height /= 2;
308  }
309 
310  ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
311 
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
315  return -1;
316 
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;
320 
321  if (dnxhd_init_vlc(ctx) < 0)
322  return -1;
323  if (dnxhd_init_rc(ctx) < 0)
324  return -1;
325 
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);
330 
331  ctx->frame.key_frame = 1;
333  ctx->m.avctx->coded_frame = &ctx->frame;
334 
335  if (avctx->thread_count > MAX_THREADS) {
336  av_log(avctx, AV_LOG_ERROR, "too many threads\n");
337  return -1;
338  }
339 
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));
344  }
345 
346  return 0;
347  fail: //for FF_ALLOCZ_OR_GOTO
348  return -1;
349 }
350 
351 static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
352 {
353  DNXHDEncContext *ctx = avctx->priv_data;
354  const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
355 
356  memset(buf, 0, 640);
357 
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
365 
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;
370 
371  buf[0x5f] = 0x01; // UDL
372 
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
377 
378  ctx->msip = buf + 0x170;
379  return 0;
380 }
381 
383 {
384  int nbits;
385  if (diff < 0) {
386  nbits = av_log2_16bit(-2*diff);
387  diff--;
388  } else {
389  nbits = av_log2_16bit(2*diff);
390  }
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)));
393 }
394 
395 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
396 {
397  int last_non_zero = 0;
398  int slevel, i, j;
399 
400  dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
401  ctx->m.last_dc[n] = block[0];
402 
403  for (i = 1; i <= last_index; i++) {
404  j = ctx->m.intra_scantable.permutated[i];
405  slevel = block[j];
406  if (slevel) {
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]);
410  if (run_level)
411  put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
412  last_non_zero = i;
413  }
414  }
415  put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
416 }
417 
418 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
419 {
420  const uint8_t *weight_matrix;
421  int level;
422  int i;
423 
424  weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
425 
426  for (i = 1; i <= last_index; i++) {
427  int j = ctx->m.intra_scantable.permutated[i];
428  level = block[j];
429  if (level) {
430  if (level < 0) {
431  level = (1-2*level) * qscale * weight_matrix[i];
432  if (ctx->cid_table->bit_depth == 10) {
433  if (weight_matrix[i] != 8)
434  level += 8;
435  level >>= 4;
436  } else {
437  if (weight_matrix[i] != 32)
438  level += 32;
439  level >>= 6;
440  }
441  level = -level;
442  } else {
443  level = (2*level+1) * qscale * weight_matrix[i];
444  if (ctx->cid_table->bit_depth == 10) {
445  if (weight_matrix[i] != 8)
446  level += 8;
447  level >>= 4;
448  } else {
449  if (weight_matrix[i] != 32)
450  level += 32;
451  level >>= 6;
452  }
453  }
454  block[j] = level;
455  }
456  }
457 }
458 
460 {
461  int score = 0;
462  int i;
463  for (i = 0; i < 64; i++)
464  score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
465  return score;
466 }
467 
469 {
470  int last_non_zero = 0;
471  int bits = 0;
472  int i, j, level;
473  for (i = 1; i <= last_index; i++) {
474  j = ctx->m.intra_scantable.permutated[i];
475  level = block[j];
476  if (level) {
477  int run_level = i - last_non_zero - 1;
478  bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
479  last_non_zero = i;
480  }
481  }
482  return bits;
483 }
484 
485 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
486 {
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;
493 
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);
498 
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);
505  } else {
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]);
510  }
511  } else {
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);
516  }
517 }
518 
520 {
521  const static uint8_t component[8]={0,0,1,2,0,0,1,2};
522  return component[i];
523 }
524 
525 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
526 {
527  DNXHDEncContext *ctx = avctx->priv_data;
528  int mb_y = jobnr, mb_x;
529  int qscale = ctx->qscale;
531  ctx = ctx->thread[threadnr];
532 
533  ctx->m.last_dc[0] =
534  ctx->m.last_dc[1] =
535  ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
536 
537  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
538  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
539  int ssd = 0;
540  int ac_bits = 0;
541  int dc_bits = 0;
542  int i;
543 
544  dnxhd_get_blocks(ctx, mb_x, mb_y);
545 
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);
550 
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);
554 
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);
558 
559  av_assert1(nbits < ctx->cid_table->bit_depth + 4);
560  dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
561 
562  ctx->m.last_dc[n] = block[0];
563 
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);
568  }
569  }
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];
572  }
573  return 0;
574 }
575 
576 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
577 {
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]);
582 
583  ctx->m.last_dc[0] =
584  ctx->m.last_dc[1] =
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];
589  int i;
590 
591  put_bits(&ctx->m.pb, 12, qscale<<1);
592 
593  dnxhd_get_blocks(ctx, mb_x, mb_y);
594 
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);
599  //START_TIMER;
600  dnxhd_encode_block(ctx, block, last_index, n);
601  //STOP_TIMER("encode_block");
602  }
603  }
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);
607  return 0;
608 }
609 
611 {
612  int mb_y, mb_x;
613  int offset = 0;
614  for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
615  int thread_size;
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];
621  }
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;
626  }
627 }
628 
629 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
630 {
631  DNXHDEncContext *ctx = avctx->priv_data;
632  int mb_y = jobnr, mb_x, x, y;
633  int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
634  ((avctx->height >> ctx->interlaced) & 0xF);
635 
636  ctx = ctx->thread[threadnr];
637  if (ctx->cid_table->bit_depth == 8) {
638  uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
639  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
640  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
641  int sum;
642  int varc;
643 
644  if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
645  sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
646  varc = ctx->m.dsp.pix_norm1(pix, ctx->m.linesize);
647  } else {
648  int bw = FFMIN(avctx->width - 16 * mb_x, 16);
649  int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
650  sum = varc = 0;
651  for (y = 0; y < bh; y++) {
652  for (x = 0; x < bw; x++) {
653  uint8_t val = pix[x + y * ctx->m.linesize];
654  sum += val;
655  varc += val * val;
656  }
657  }
658  }
659  varc = (varc - (((unsigned)sum * sum) >> 8) + 128) >> 8;
660 
661  ctx->mb_cmp[mb].value = varc;
662  ctx->mb_cmp[mb].mb = mb;
663  }
664  } else { // 10-bit
665  int const linesize = ctx->m.linesize >> 1;
666  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
667  uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
668  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
669  int sum = 0;
670  int sqsum = 0;
671  int mean, sqmean;
672  int i, j;
673  // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
674  for (i = 0; i < 16; ++i) {
675  for (j = 0; j < 16; ++j) {
676  // Turn 16-bit pixels into 10-bit ones.
677  int const sample = (unsigned)pix[j] >> 6;
678  sum += sample;
679  sqsum += sample * sample;
680  // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
681  }
682  pix += linesize;
683  }
684  mean = sum >> 8; // 16*16 == 2^8
685  sqmean = sqsum >> 8;
686  ctx->mb_cmp[mb].value = sqmean - mean * mean;
687  ctx->mb_cmp[mb].mb = mb;
688  }
689  }
690  return 0;
691 }
692 
694 {
695  int lambda, up_step, down_step;
696  int last_lower = INT_MAX, last_higher = 0;
697  int x, y, q;
698 
699  for (q = 1; q < avctx->qmax; q++) {
700  ctx->qscale = q;
701  avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
702  }
703  up_step = down_step = 2<<LAMBDA_FRAC_BITS;
704  lambda = ctx->lambda;
705 
706  for (;;) {
707  int bits = 0;
708  int end = 0;
709  if (lambda == last_higher) {
710  lambda++;
711  end = 1; // need to set final qscales/bits
712  }
713  for (y = 0; y < ctx->m.mb_height; y++) {
714  for (x = 0; x < ctx->m.mb_width; x++) {
715  unsigned min = UINT_MAX;
716  int qscale = 1;
717  int mb = y*ctx->m.mb_width+x;
718  for (q = 1; q < avctx->qmax; q++) {
719  unsigned score = ctx->mb_rc[q][mb].bits*lambda+
720  ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
721  if (score < min) {
722  min = score;
723  qscale = q;
724  }
725  }
726  bits += ctx->mb_rc[qscale][mb].bits;
727  ctx->mb_qscale[mb] = qscale;
728  ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
729  }
730  bits = (bits+31)&~31; // padding
731  if (bits > ctx->frame_bits)
732  break;
733  }
734  //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
735  // lambda, last_higher, last_lower, bits, ctx->frame_bits);
736  if (end) {
737  if (bits > ctx->frame_bits)
738  return -1;
739  break;
740  }
741  if (bits < ctx->frame_bits) {
742  last_lower = FFMIN(lambda, last_lower);
743  if (last_higher != 0)
744  lambda = (lambda+last_higher)>>1;
745  else
746  lambda -= down_step;
747  down_step = FFMIN((int64_t)down_step*5, INT_MAX);
748  up_step = 1<<LAMBDA_FRAC_BITS;
749  lambda = FFMAX(1, lambda);
750  if (lambda == last_lower)
751  break;
752  } else {
753  last_higher = FFMAX(lambda, last_higher);
754  if (last_lower != INT_MAX)
755  lambda = (lambda+last_lower)>>1;
756  else if ((int64_t)lambda + up_step > INT_MAX)
757  return -1;
758  else
759  lambda += up_step;
760  up_step = FFMIN((int64_t)up_step*5, INT_MAX);
761  down_step = 1<<LAMBDA_FRAC_BITS;
762  }
763  }
764  //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
765  ctx->lambda = lambda;
766  return 0;
767 }
768 
770 {
771  int bits = 0;
772  int up_step = 1;
773  int down_step = 1;
774  int last_higher = 0;
775  int last_lower = INT_MAX;
776  int qscale;
777  int x, y;
778 
779  qscale = ctx->qscale;
780  for (;;) {
781  bits = 0;
782  ctx->qscale = qscale;
783  // XXX avoid recalculating bits
785  for (y = 0; y < ctx->m.mb_height; y++) {
786  for (x = 0; x < ctx->m.mb_width; x++)
787  bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
788  bits = (bits+31)&~31; // padding
789  if (bits > ctx->frame_bits)
790  break;
791  }
792  //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
793  // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
794  if (bits < ctx->frame_bits) {
795  if (qscale == 1)
796  return 1;
797  if (last_higher == qscale - 1) {
798  qscale = last_higher;
799  break;
800  }
801  last_lower = FFMIN(qscale, last_lower);
802  if (last_higher != 0)
803  qscale = (qscale+last_higher)>>1;
804  else
805  qscale -= down_step++;
806  if (qscale < 1)
807  qscale = 1;
808  up_step = 1;
809  } else {
810  if (last_lower == qscale + 1)
811  break;
812  last_higher = FFMAX(qscale, last_higher);
813  if (last_lower != INT_MAX)
814  qscale = (qscale+last_lower)>>1;
815  else
816  qscale += up_step++;
817  down_step = 1;
818  if (qscale >= ctx->m.avctx->qmax)
819  return -1;
820  }
821  }
822  //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
823  ctx->qscale = qscale;
824  return 0;
825 }
826 
827 #define BUCKET_BITS 8
828 #define RADIX_PASSES 4
829 #define NBUCKETS (1 << BUCKET_BITS)
830 
831 static inline int get_bucket(int value, int shift)
832 {
833  value >>= shift;
834  value &= NBUCKETS - 1;
835  return NBUCKETS - 1 - value;
836 }
837 
838 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
839 {
840  int i, j;
841  memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
842  for (i = 0; i < size; i++) {
843  int v = data[i].value;
844  for (j = 0; j < RADIX_PASSES; j++) {
845  buckets[j][get_bucket(v, 0)]++;
846  v >>= BUCKET_BITS;
847  }
848  av_assert1(!v);
849  }
850  for (j = 0; j < RADIX_PASSES; j++) {
851  int offset = size;
852  for (i = NBUCKETS - 1; i >= 0; i--)
853  buckets[j][i] = offset -= buckets[j][i];
854  av_assert1(!buckets[j][0]);
855  }
856 }
857 
858 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
859 {
860  int shift = pass * BUCKET_BITS;
861  int i;
862  for (i = 0; i < size; i++) {
863  int v = get_bucket(data[i].value, shift);
864  int pos = buckets[v]++;
865  dst[pos] = data[i];
866  }
867 }
868 
869 static void radix_sort(RCCMPEntry *data, int size)
870 {
871  int buckets[RADIX_PASSES][NBUCKETS];
872  RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
873  radix_count(data, size, buckets);
874  radix_sort_pass(tmp, data, size, buckets[0], 0);
875  radix_sort_pass(data, tmp, size, buckets[1], 1);
876  if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
877  radix_sort_pass(tmp, data, size, buckets[2], 2);
878  radix_sort_pass(data, tmp, size, buckets[3], 3);
879  }
880  av_free(tmp);
881 }
882 
884 {
885  int max_bits = 0;
886  int ret, x, y;
887  if ((ret = dnxhd_find_qscale(ctx)) < 0)
888  return -1;
889  for (y = 0; y < ctx->m.mb_height; y++) {
890  for (x = 0; x < ctx->m.mb_width; x++) {
891  int mb = y*ctx->m.mb_width+x;
892  int delta_bits;
893  ctx->mb_qscale[mb] = ctx->qscale;
894  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
895  max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
896  if (!RC_VARIANCE) {
897  delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
898  ctx->mb_cmp[mb].mb = mb;
899  ctx->mb_cmp[mb].value = delta_bits ?
900  ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
901  : INT_MIN; //avoid increasing qscale
902  }
903  }
904  max_bits += 31; //worst padding
905  }
906  if (!ret) {
907  if (RC_VARIANCE)
908  avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
909  radix_sort(ctx->mb_cmp, ctx->m.mb_num);
910  for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
911  int mb = ctx->mb_cmp[x].mb;
912  max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
913  ctx->mb_qscale[mb] = ctx->qscale+1;
914  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
915  }
916  }
917  return 0;
918 }
919 
921 {
922  int i;
923 
924  for (i = 0; i < 3; i++) {
925  ctx->frame.data[i] = frame->data[i];
926  ctx->frame.linesize[i] = frame->linesize[i];
927  }
928 
929  for (i = 0; i < ctx->m.avctx->thread_count; i++) {
930  ctx->thread[i]->m.linesize = ctx->frame.linesize[0]<<ctx->interlaced;
931  ctx->thread[i]->m.uvlinesize = ctx->frame.linesize[1]<<ctx->interlaced;
932  ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
933  ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
934  }
935 
937  ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
938 }
939 
941  const AVFrame *frame, int *got_packet)
942 {
943  DNXHDEncContext *ctx = avctx->priv_data;
944  int first_field = 1;
945  int offset, i, ret;
946  uint8_t *buf;
947 
948  if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
949  return ret;
950  buf = pkt->data;
951 
952  dnxhd_load_picture(ctx, frame);
953 
954  encode_coding_unit:
955  for (i = 0; i < 3; i++) {
956  ctx->src[i] = ctx->frame.data[i];
957  if (ctx->interlaced && ctx->cur_field)
958  ctx->src[i] += ctx->frame.linesize[i];
959  }
960 
961  dnxhd_write_header(avctx, buf);
962 
963  if (avctx->mb_decision == FF_MB_DECISION_RD)
964  ret = dnxhd_encode_rdo(avctx, ctx);
965  else
966  ret = dnxhd_encode_fast(avctx, ctx);
967  if (ret < 0) {
968  av_log(avctx, AV_LOG_ERROR,
969  "picture could not fit ratecontrol constraints, increase qmax\n");
970  return -1;
971  }
972 
974 
975  offset = 0;
976  for (i = 0; i < ctx->m.mb_height; i++) {
977  AV_WB32(ctx->msip + i * 4, offset);
978  offset += ctx->slice_size[i];
979  av_assert1(!(ctx->slice_size[i] & 3));
980  }
981 
982  avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
983 
984  av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
985  memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
986 
987  AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
988 
989  if (ctx->interlaced && first_field) {
990  first_field = 0;
991  ctx->cur_field ^= 1;
992  buf += ctx->cid_table->coding_unit_size;
993  goto encode_coding_unit;
994  }
995 
996  ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
997 
998  pkt->flags |= AV_PKT_FLAG_KEY;
999  *got_packet = 1;
1000  return 0;
1001 }
1002 
1004 {
1005  DNXHDEncContext *ctx = avctx->priv_data;
1006  int max_level = 1<<(ctx->cid_table->bit_depth+2);
1007  int i;
1008 
1009  av_free(ctx->vlc_codes-max_level*2);
1010  av_free(ctx->vlc_bits -max_level*2);
1011  av_freep(&ctx->run_codes);
1012  av_freep(&ctx->run_bits);
1013 
1014  av_freep(&ctx->mb_bits);
1015  av_freep(&ctx->mb_qscale);
1016  av_freep(&ctx->mb_rc);
1017  av_freep(&ctx->mb_cmp);
1018  av_freep(&ctx->slice_size);
1019  av_freep(&ctx->slice_offs);
1020 
1021  av_freep(&ctx->qmatrix_c);
1022  av_freep(&ctx->qmatrix_l);
1023  av_freep(&ctx->qmatrix_c16);
1024  av_freep(&ctx->qmatrix_l16);
1025 
1026  for (i = 1; i < avctx->thread_count; i++)
1027  av_freep(&ctx->thread[i]);
1028 
1029  return 0;
1030 }
1031 
1032 static const AVCodecDefault dnxhd_defaults[] = {
1033  { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1034  { NULL },
1035 };
1036 
1038  .name = "dnxhd",
1039  .type = AVMEDIA_TYPE_VIDEO,
1040  .id = AV_CODEC_ID_DNXHD,
1041  .priv_data_size = sizeof(DNXHDEncContext),
1043  .encode2 = dnxhd_encode_picture,
1045  .capabilities = CODEC_CAP_SLICE_THREADS,
1046  .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1048  AV_PIX_FMT_NONE },
1049  .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1050  .priv_class = &class,
1051  .defaults = dnxhd_defaults,
1052 };