FFmpeg
 All Data Structures Namespaces 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 RC_VARIANCE 1 // use variance or ssd for fast rc
27 
28 #include "libavutil/attributes.h"
29 #include "libavutil/internal.h"
30 #include "libavutil/opt.h"
31 #include "avcodec.h"
32 #include "dsputil.h"
33 #include "internal.h"
34 #include "mpegvideo.h"
35 #include "dnxhdenc.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 dnxhd_class = {
46  .class_name = "dnxhd",
47  .item_name = av_default_item_name,
48  .option = options,
49  .version = LIBAVUTIL_VERSION_INT,
50 };
51 
52 #define LAMBDA_FRAC_BITS 10
53 
54 static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *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 
71 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block, const uint8_t *pixels, int line_size)
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 
91 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
92  int n, int qscale, int *overflow)
93 {
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 av_cold 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 + 1)*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. Valid DNxHD profiles:\n");
271  return -1;
272  }
273  av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
274 
275  index = ff_dnxhd_get_cid_table(ctx->cid);
276  av_assert0(index >= 0);
278 
279  ctx->m.avctx = avctx;
280  ctx->m.mb_intra = 1;
281  ctx->m.h263_aic = 1;
282 
283  avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
284 
285  ff_dct_common_init(&ctx->m);
286  ff_dct_encode_init(&ctx->m);
287 
288  if (!ctx->m.dct_quantize)
290 
291  if (ctx->cid_table->bit_depth == 10) {
294  ctx->block_width_l2 = 4;
295  } else {
297  ctx->block_width_l2 = 3;
298  }
299 
300  if (ARCH_X86)
302 
303  ctx->m.mb_height = (avctx->height + 15) / 16;
304  ctx->m.mb_width = (avctx->width + 15) / 16;
305 
306  if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
307  ctx->interlaced = 1;
308  ctx->m.mb_height /= 2;
309  }
310 
311  ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
312 
314  ctx->m.intra_quant_bias = avctx->intra_quant_bias;
315  if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
316  return -1;
317 
318  // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
319  if (ctx->nitris_compat)
320  ctx->min_padding = 1600;
321 
322  if (dnxhd_init_vlc(ctx) < 0)
323  return -1;
324  if (dnxhd_init_rc(ctx) < 0)
325  return -1;
326 
327  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
328  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
329  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
330  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
331 
332  avctx->coded_frame = av_frame_alloc();
333  if (!avctx->coded_frame)
334  return AVERROR(ENOMEM);
335 
336  avctx->coded_frame->key_frame = 1;
338 
339  if (avctx->thread_count > MAX_THREADS) {
340  av_log(avctx, AV_LOG_ERROR, "too many threads\n");
341  return -1;
342  }
343 
344  ctx->thread[0] = ctx;
345  for (i = 1; i < avctx->thread_count; i++) {
346  ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
347  memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
348  }
349 
350  return 0;
351  fail: //for FF_ALLOCZ_OR_GOTO
352  return -1;
353 }
354 
356 {
357  DNXHDEncContext *ctx = avctx->priv_data;
358  static const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
359 
360  memset(buf, 0, 640);
361 
362  memcpy(buf, header_prefix, 5);
363  buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
364  buf[6] = 0x80; // crc flag off
365  buf[7] = 0xa0; // reserved
366  AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
367  AV_WB16(buf + 0x1a, avctx->width); // SPL
368  AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
369 
370  buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
371  buf[0x22] = 0x88 + (ctx->interlaced<<2);
372  AV_WB32(buf + 0x28, ctx->cid); // CID
373  buf[0x2c] = ctx->interlaced ? 0 : 0x80;
374 
375  buf[0x5f] = 0x01; // UDL
376 
377  buf[0x167] = 0x02; // reserved
378  AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
379  buf[0x16d] = ctx->m.mb_height; // Ns
380  buf[0x16f] = 0x10; // reserved
381 
382  ctx->msip = buf + 0x170;
383  return 0;
384 }
385 
387 {
388  int nbits;
389  if (diff < 0) {
390  nbits = av_log2_16bit(-2*diff);
391  diff--;
392  } else {
393  nbits = av_log2_16bit(2*diff);
394  }
395  put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
396  (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
397 }
398 
399 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block, int last_index, int n)
400 {
401  int last_non_zero = 0;
402  int slevel, i, j;
403 
404  dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
405  ctx->m.last_dc[n] = block[0];
406 
407  for (i = 1; i <= last_index; i++) {
408  j = ctx->m.intra_scantable.permutated[i];
409  slevel = block[j];
410  if (slevel) {
411  int run_level = i - last_non_zero - 1;
412  int rlevel = (slevel<<1)|!!run_level;
413  put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
414  if (run_level)
415  put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
416  last_non_zero = i;
417  }
418  }
419  put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
420 }
421 
422 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n, int qscale, int last_index)
423 {
424  const uint8_t *weight_matrix;
425  int level;
426  int i;
427 
428  weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
429 
430  for (i = 1; i <= last_index; i++) {
431  int j = ctx->m.intra_scantable.permutated[i];
432  level = block[j];
433  if (level) {
434  if (level < 0) {
435  level = (1-2*level) * qscale * weight_matrix[i];
436  if (ctx->cid_table->bit_depth == 10) {
437  if (weight_matrix[i] != 8)
438  level += 8;
439  level >>= 4;
440  } else {
441  if (weight_matrix[i] != 32)
442  level += 32;
443  level >>= 6;
444  }
445  level = -level;
446  } else {
447  level = (2*level+1) * qscale * weight_matrix[i];
448  if (ctx->cid_table->bit_depth == 10) {
449  if (weight_matrix[i] != 8)
450  level += 8;
451  level >>= 4;
452  } else {
453  if (weight_matrix[i] != 32)
454  level += 32;
455  level >>= 6;
456  }
457  }
458  block[j] = level;
459  }
460  }
461 }
462 
463 static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
464 {
465  int score = 0;
466  int i;
467  for (i = 0; i < 64; i++)
468  score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
469  return score;
470 }
471 
472 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
473 {
474  int last_non_zero = 0;
475  int bits = 0;
476  int i, j, level;
477  for (i = 1; i <= last_index; i++) {
478  j = ctx->m.intra_scantable.permutated[i];
479  level = block[j];
480  if (level) {
481  int run_level = i - last_non_zero - 1;
482  bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
483  last_non_zero = i;
484  }
485  }
486  return bits;
487 }
488 
489 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
490 {
491  const int bs = ctx->block_width_l2;
492  const int bw = 1 << bs;
493  const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
494  const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
495  const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
496  DSPContext *dsp = &ctx->m.dsp;
497 
498  dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
499  dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
500  dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
501  dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
502 
503  if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
504  if (ctx->interlaced) {
505  ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
506  ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
507  ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
508  ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
509  } else {
510  dsp->clear_block(ctx->blocks[4]);
511  dsp->clear_block(ctx->blocks[5]);
512  dsp->clear_block(ctx->blocks[6]);
513  dsp->clear_block(ctx->blocks[7]);
514  }
515  } else {
516  dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
517  dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
518  dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
519  dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
520  }
521 }
522 
524 {
525  const static uint8_t component[8]={0,0,1,2,0,0,1,2};
526  return component[i];
527 }
528 
529 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
530 {
531  DNXHDEncContext *ctx = avctx->priv_data;
532  int mb_y = jobnr, mb_x;
533  int qscale = ctx->qscale;
534  LOCAL_ALIGNED_16(int16_t, block, [64]);
535  ctx = ctx->thread[threadnr];
536 
537  ctx->m.last_dc[0] =
538  ctx->m.last_dc[1] =
539  ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
540 
541  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
542  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
543  int ssd = 0;
544  int ac_bits = 0;
545  int dc_bits = 0;
546  int i;
547 
548  dnxhd_get_blocks(ctx, mb_x, mb_y);
549 
550  for (i = 0; i < 8; i++) {
551  int16_t *src_block = ctx->blocks[i];
552  int overflow, nbits, diff, last_index;
553  int n = dnxhd_switch_matrix(ctx, i);
554 
555  memcpy(block, src_block, 64*sizeof(*block));
556  last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
557  ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
558 
559  diff = block[0] - ctx->m.last_dc[n];
560  if (diff < 0) nbits = av_log2_16bit(-2*diff);
561  else nbits = av_log2_16bit( 2*diff);
562 
563  av_assert1(nbits < ctx->cid_table->bit_depth + 4);
564  dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
565 
566  ctx->m.last_dc[n] = block[0];
567 
568  if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
569  dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
570  ctx->m.dsp.idct(block);
571  ssd += dnxhd_ssd_block(block, src_block);
572  }
573  }
574  ctx->mb_rc[qscale][mb].ssd = ssd;
575  ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
576  }
577  return 0;
578 }
579 
580 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
581 {
582  DNXHDEncContext *ctx = avctx->priv_data;
583  int mb_y = jobnr, mb_x;
584  ctx = ctx->thread[threadnr];
585  init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
586 
587  ctx->m.last_dc[0] =
588  ctx->m.last_dc[1] =
589  ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
590  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
591  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
592  int qscale = ctx->mb_qscale[mb];
593  int i;
594 
595  put_bits(&ctx->m.pb, 12, qscale<<1);
596 
597  dnxhd_get_blocks(ctx, mb_x, mb_y);
598 
599  for (i = 0; i < 8; i++) {
600  int16_t *block = ctx->blocks[i];
601  int overflow, n = dnxhd_switch_matrix(ctx, i);
602  int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
603  //START_TIMER;
604  dnxhd_encode_block(ctx, block, last_index, n);
605  //STOP_TIMER("encode_block");
606  }
607  }
608  if (put_bits_count(&ctx->m.pb)&31)
609  put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
610  flush_put_bits(&ctx->m.pb);
611  return 0;
612 }
613 
615 {
616  int mb_y, mb_x;
617  int offset = 0;
618  for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
619  int thread_size;
620  ctx->slice_offs[mb_y] = offset;
621  ctx->slice_size[mb_y] = 0;
622  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
623  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
624  ctx->slice_size[mb_y] += ctx->mb_bits[mb];
625  }
626  ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
627  ctx->slice_size[mb_y] >>= 3;
628  thread_size = ctx->slice_size[mb_y];
629  offset += thread_size;
630  }
631 }
632 
633 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
634 {
635  DNXHDEncContext *ctx = avctx->priv_data;
636  int mb_y = jobnr, mb_x, x, y;
637  int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
638  ((avctx->height >> ctx->interlaced) & 0xF);
639 
640  ctx = ctx->thread[threadnr];
641  if (ctx->cid_table->bit_depth == 8) {
642  uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
643  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
644  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
645  int sum;
646  int varc;
647 
648  if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
649  sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
650  varc = ctx->m.dsp.pix_norm1(pix, ctx->m.linesize);
651  } else {
652  int bw = FFMIN(avctx->width - 16 * mb_x, 16);
653  int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
654  sum = varc = 0;
655  for (y = 0; y < bh; y++) {
656  for (x = 0; x < bw; x++) {
657  uint8_t val = pix[x + y * ctx->m.linesize];
658  sum += val;
659  varc += val * val;
660  }
661  }
662  }
663  varc = (varc - (((unsigned)sum * sum) >> 8) + 128) >> 8;
664 
665  ctx->mb_cmp[mb].value = varc;
666  ctx->mb_cmp[mb].mb = mb;
667  }
668  } else { // 10-bit
669  int const linesize = ctx->m.linesize >> 1;
670  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
671  uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
672  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
673  int sum = 0;
674  int sqsum = 0;
675  int mean, sqmean;
676  int i, j;
677  // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
678  for (i = 0; i < 16; ++i) {
679  for (j = 0; j < 16; ++j) {
680  // Turn 16-bit pixels into 10-bit ones.
681  int const sample = (unsigned)pix[j] >> 6;
682  sum += sample;
683  sqsum += sample * sample;
684  // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
685  }
686  pix += linesize;
687  }
688  mean = sum >> 8; // 16*16 == 2^8
689  sqmean = sqsum >> 8;
690  ctx->mb_cmp[mb].value = sqmean - mean * mean;
691  ctx->mb_cmp[mb].mb = mb;
692  }
693  }
694  return 0;
695 }
696 
698 {
699  int lambda, up_step, down_step;
700  int last_lower = INT_MAX, last_higher = 0;
701  int x, y, q;
702 
703  for (q = 1; q < avctx->qmax; q++) {
704  ctx->qscale = q;
705  avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
706  }
707  up_step = down_step = 2<<LAMBDA_FRAC_BITS;
708  lambda = ctx->lambda;
709 
710  for (;;) {
711  int bits = 0;
712  int end = 0;
713  if (lambda == last_higher) {
714  lambda++;
715  end = 1; // need to set final qscales/bits
716  }
717  for (y = 0; y < ctx->m.mb_height; y++) {
718  for (x = 0; x < ctx->m.mb_width; x++) {
719  unsigned min = UINT_MAX;
720  int qscale = 1;
721  int mb = y*ctx->m.mb_width+x;
722  for (q = 1; q < avctx->qmax; q++) {
723  unsigned score = ctx->mb_rc[q][mb].bits*lambda+
724  ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
725  if (score < min) {
726  min = score;
727  qscale = q;
728  }
729  }
730  bits += ctx->mb_rc[qscale][mb].bits;
731  ctx->mb_qscale[mb] = qscale;
732  ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
733  }
734  bits = (bits+31)&~31; // padding
735  if (bits > ctx->frame_bits)
736  break;
737  }
738  //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
739  // lambda, last_higher, last_lower, bits, ctx->frame_bits);
740  if (end) {
741  if (bits > ctx->frame_bits)
742  return -1;
743  break;
744  }
745  if (bits < ctx->frame_bits) {
746  last_lower = FFMIN(lambda, last_lower);
747  if (last_higher != 0)
748  lambda = (lambda+last_higher)>>1;
749  else
750  lambda -= down_step;
751  down_step = FFMIN((int64_t)down_step*5, INT_MAX);
752  up_step = 1<<LAMBDA_FRAC_BITS;
753  lambda = FFMAX(1, lambda);
754  if (lambda == last_lower)
755  break;
756  } else {
757  last_higher = FFMAX(lambda, last_higher);
758  if (last_lower != INT_MAX)
759  lambda = (lambda+last_lower)>>1;
760  else if ((int64_t)lambda + up_step > INT_MAX)
761  return -1;
762  else
763  lambda += up_step;
764  up_step = FFMIN((int64_t)up_step*5, INT_MAX);
765  down_step = 1<<LAMBDA_FRAC_BITS;
766  }
767  }
768  //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
769  ctx->lambda = lambda;
770  return 0;
771 }
772 
774 {
775  int bits = 0;
776  int up_step = 1;
777  int down_step = 1;
778  int last_higher = 0;
779  int last_lower = INT_MAX;
780  int qscale;
781  int x, y;
782 
783  qscale = ctx->qscale;
784  for (;;) {
785  bits = 0;
786  ctx->qscale = qscale;
787  // XXX avoid recalculating bits
788  ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
789  for (y = 0; y < ctx->m.mb_height; y++) {
790  for (x = 0; x < ctx->m.mb_width; x++)
791  bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
792  bits = (bits+31)&~31; // padding
793  if (bits > ctx->frame_bits)
794  break;
795  }
796  //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
797  // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
798  if (bits < ctx->frame_bits) {
799  if (qscale == 1)
800  return 1;
801  if (last_higher == qscale - 1) {
802  qscale = last_higher;
803  break;
804  }
805  last_lower = FFMIN(qscale, last_lower);
806  if (last_higher != 0)
807  qscale = (qscale+last_higher)>>1;
808  else
809  qscale -= down_step++;
810  if (qscale < 1)
811  qscale = 1;
812  up_step = 1;
813  } else {
814  if (last_lower == qscale + 1)
815  break;
816  last_higher = FFMAX(qscale, last_higher);
817  if (last_lower != INT_MAX)
818  qscale = (qscale+last_lower)>>1;
819  else
820  qscale += up_step++;
821  down_step = 1;
822  if (qscale >= ctx->m.avctx->qmax)
823  return -1;
824  }
825  }
826  //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
827  ctx->qscale = qscale;
828  return 0;
829 }
830 
831 #define BUCKET_BITS 8
832 #define RADIX_PASSES 4
833 #define NBUCKETS (1 << BUCKET_BITS)
834 
835 static inline int get_bucket(int value, int shift)
836 {
837  value >>= shift;
838  value &= NBUCKETS - 1;
839  return NBUCKETS - 1 - value;
840 }
841 
842 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
843 {
844  int i, j;
845  memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
846  for (i = 0; i < size; i++) {
847  int v = data[i].value;
848  for (j = 0; j < RADIX_PASSES; j++) {
849  buckets[j][get_bucket(v, 0)]++;
850  v >>= BUCKET_BITS;
851  }
852  av_assert1(!v);
853  }
854  for (j = 0; j < RADIX_PASSES; j++) {
855  int offset = size;
856  for (i = NBUCKETS - 1; i >= 0; i--)
857  buckets[j][i] = offset -= buckets[j][i];
858  av_assert1(!buckets[j][0]);
859  }
860 }
861 
862 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
863 {
864  int shift = pass * BUCKET_BITS;
865  int i;
866  for (i = 0; i < size; i++) {
867  int v = get_bucket(data[i].value, shift);
868  int pos = buckets[v]++;
869  dst[pos] = data[i];
870  }
871 }
872 
873 static void radix_sort(RCCMPEntry *data, int size)
874 {
875  int buckets[RADIX_PASSES][NBUCKETS];
876  RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
877  radix_count(data, size, buckets);
878  radix_sort_pass(tmp, data, size, buckets[0], 0);
879  radix_sort_pass(data, tmp, size, buckets[1], 1);
880  if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
881  radix_sort_pass(tmp, data, size, buckets[2], 2);
882  radix_sort_pass(data, tmp, size, buckets[3], 3);
883  }
884  av_free(tmp);
885 }
886 
888 {
889  int max_bits = 0;
890  int ret, x, y;
891  if ((ret = dnxhd_find_qscale(ctx)) < 0)
892  return -1;
893  for (y = 0; y < ctx->m.mb_height; y++) {
894  for (x = 0; x < ctx->m.mb_width; x++) {
895  int mb = y*ctx->m.mb_width+x;
896  int delta_bits;
897  ctx->mb_qscale[mb] = ctx->qscale;
898  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
899  max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
900  if (!RC_VARIANCE) {
901  delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
902  ctx->mb_cmp[mb].mb = mb;
903  ctx->mb_cmp[mb].value = delta_bits ?
904  ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
905  : INT_MIN; //avoid increasing qscale
906  }
907  }
908  max_bits += 31; //worst padding
909  }
910  if (!ret) {
911  if (RC_VARIANCE)
912  avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
913  radix_sort(ctx->mb_cmp, ctx->m.mb_num);
914  for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
915  int mb = ctx->mb_cmp[x].mb;
916  max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
917  ctx->mb_qscale[mb] = ctx->qscale+1;
918  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
919  }
920  }
921  return 0;
922 }
923 
925 {
926  int i;
927 
928  for (i = 0; i < ctx->m.avctx->thread_count; i++) {
929  ctx->thread[i]->m.linesize = frame->linesize[0] << ctx->interlaced;
930  ctx->thread[i]->m.uvlinesize = frame->linesize[1] << ctx->interlaced;
931  ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
932  ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
933  }
934 
936  ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
937 }
938 
940  const AVFrame *frame, int *got_packet)
941 {
942  DNXHDEncContext *ctx = avctx->priv_data;
943  int first_field = 1;
944  int offset, i, ret;
945  uint8_t *buf;
946 
947  if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
948  return ret;
949  buf = pkt->data;
950 
951  dnxhd_load_picture(ctx, frame);
952 
953  encode_coding_unit:
954  for (i = 0; i < 3; i++) {
955  ctx->src[i] = frame->data[i];
956  if (ctx->interlaced && ctx->cur_field)
957  ctx->src[i] += frame->linesize[i];
958  }
959 
960  dnxhd_write_header(avctx, buf);
961 
962  if (avctx->mb_decision == FF_MB_DECISION_RD)
963  ret = dnxhd_encode_rdo(avctx, ctx);
964  else
965  ret = dnxhd_encode_fast(avctx, ctx);
966  if (ret < 0) {
967  av_log(avctx, AV_LOG_ERROR,
968  "picture could not fit ratecontrol constraints, increase qmax\n");
969  return -1;
970  }
971 
973 
974  offset = 0;
975  for (i = 0; i < ctx->m.mb_height; i++) {
976  AV_WB32(ctx->msip + i * 4, offset);
977  offset += ctx->slice_size[i];
978  av_assert1(!(ctx->slice_size[i] & 3));
979  }
980 
981  avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
982 
983  av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
984  memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
985 
986  AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
987 
988  if (ctx->interlaced && first_field) {
989  first_field = 0;
990  ctx->cur_field ^= 1;
991  buf += ctx->cid_table->coding_unit_size;
992  goto encode_coding_unit;
993  }
994 
995  avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
996 
997  pkt->flags |= AV_PKT_FLAG_KEY;
998  *got_packet = 1;
999  return 0;
1000 }
1001 
1003 {
1004  DNXHDEncContext *ctx = avctx->priv_data;
1005  int max_level = 1<<(ctx->cid_table->bit_depth+2);
1006  int i;
1007 
1008  av_free(ctx->vlc_codes-max_level*2);
1009  av_free(ctx->vlc_bits -max_level*2);
1010  av_freep(&ctx->run_codes);
1011  av_freep(&ctx->run_bits);
1012 
1013  av_freep(&ctx->mb_bits);
1014  av_freep(&ctx->mb_qscale);
1015  av_freep(&ctx->mb_rc);
1016  av_freep(&ctx->mb_cmp);
1017  av_freep(&ctx->slice_size);
1018  av_freep(&ctx->slice_offs);
1019 
1020  av_freep(&ctx->qmatrix_c);
1021  av_freep(&ctx->qmatrix_l);
1022  av_freep(&ctx->qmatrix_c16);
1023  av_freep(&ctx->qmatrix_l16);
1024 
1025  for (i = 1; i < avctx->thread_count; i++)
1026  av_freep(&ctx->thread[i]);
1027 
1028  av_frame_free(&avctx->coded_frame);
1029 
1030  return 0;
1031 }
1032 
1033 static const AVCodecDefault dnxhd_defaults[] = {
1034  { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1035  { NULL },
1036 };
1037 
1039  .name = "dnxhd",
1040  .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1041  .type = AVMEDIA_TYPE_VIDEO,
1042  .id = AV_CODEC_ID_DNXHD,
1043  .priv_data_size = sizeof(DNXHDEncContext),
1045  .encode2 = dnxhd_encode_picture,
1047  .capabilities = CODEC_CAP_SLICE_THREADS,
1048  .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1050  AV_PIX_FMT_NONE },
1051  .priv_class = &dnxhd_class,
1052  .defaults = dnxhd_defaults,
1053 };