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 "libavutil/timer.h"
32 #include "avcodec.h"
33 #include "dsputil.h"
34 #include "internal.h"
35 #include "mpegvideo.h"
36 #include "dnxhdenc.h"
37 
38 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
39 #define DNX10BIT_QMAT_SHIFT 18 // The largest value that will not lead to overflow for 10bit samples.
40 
41 static const AVOption options[]={
42  {"nitris_compat", "encode with Avid Nitris compatibility", offsetof(DNXHDEncContext, nitris_compat), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, VE},
43 {NULL}
44 };
45 
46 static const AVClass dnxhd_class = {
47  .class_name = "dnxhd",
48  .item_name = av_default_item_name,
49  .option = options,
50  .version = LIBAVUTIL_VERSION_INT,
51 };
52 
53 #define LAMBDA_FRAC_BITS 10
54 
55 static void dnxhd_8bit_get_pixels_8x4_sym(int16_t *av_restrict block, const uint8_t *pixels, int line_size)
56 {
57  int i;
58  for (i = 0; i < 4; i++) {
59  block[0] = pixels[0]; block[1] = pixels[1];
60  block[2] = pixels[2]; block[3] = pixels[3];
61  block[4] = pixels[4]; block[5] = pixels[5];
62  block[6] = pixels[6]; block[7] = pixels[7];
63  pixels += line_size;
64  block += 8;
65  }
66  memcpy(block, block - 8, sizeof(*block) * 8);
67  memcpy(block + 8, block - 16, sizeof(*block) * 8);
68  memcpy(block + 16, block - 24, sizeof(*block) * 8);
69  memcpy(block + 24, block - 32, sizeof(*block) * 8);
70 }
71 
72 static av_always_inline void dnxhd_10bit_get_pixels_8x4_sym(int16_t *av_restrict block, const uint8_t *pixels, int line_size)
73 {
74  int i;
75  const uint16_t* pixels16 = (const uint16_t*)pixels;
76  line_size >>= 1;
77 
78  for (i = 0; i < 4; i++) {
79  block[0] = pixels16[0]; block[1] = pixels16[1];
80  block[2] = pixels16[2]; block[3] = pixels16[3];
81  block[4] = pixels16[4]; block[5] = pixels16[5];
82  block[6] = pixels16[6]; block[7] = pixels16[7];
83  pixels16 += line_size;
84  block += 8;
85  }
86  memcpy(block, block - 8, sizeof(*block) * 8);
87  memcpy(block + 8, block - 16, sizeof(*block) * 8);
88  memcpy(block + 16, block - 24, sizeof(*block) * 8);
89  memcpy(block + 24, block - 32, sizeof(*block) * 8);
90 }
91 
92 static int dnxhd_10bit_dct_quantize(MpegEncContext *ctx, int16_t *block,
93  int n, int qscale, int *overflow)
94 {
96  const int *qmat = n<4 ? ctx->q_intra_matrix[qscale] : ctx->q_chroma_intra_matrix[qscale];
97  int last_non_zero = 0;
98  int i;
99 
100  ctx->dsp.fdct(block);
101 
102  // Divide by 4 with rounding, to compensate scaling of DCT coefficients
103  block[0] = (block[0] + 2) >> 2;
104 
105  for (i = 1; i < 64; ++i) {
106  int j = scantable[i];
107  int sign = block[j] >> 31;
108  int level = (block[j] ^ sign) - sign;
109  level = level * qmat[j] >> DNX10BIT_QMAT_SHIFT;
110  block[j] = (level ^ sign) - sign;
111  if (level)
112  last_non_zero = i;
113  }
114 
115  return last_non_zero;
116 }
117 
119 {
120  int i, j, level, run;
121  int max_level = 1<<(ctx->cid_table->bit_depth+2);
122 
123  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
124  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits, max_level*4*sizeof(*ctx->vlc_bits) , fail);
125  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2, fail);
126  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits, 63, fail);
127 
128  ctx->vlc_codes += max_level*2;
129  ctx->vlc_bits += max_level*2;
130  for (level = -max_level; level < max_level; level++) {
131  for (run = 0; run < 2; run++) {
132  int index = (level<<1)|run;
133  int sign, offset = 0, alevel = level;
134 
135  MASK_ABS(sign, alevel);
136  if (alevel > 64) {
137  offset = (alevel-1)>>6;
138  alevel -= offset<<6;
139  }
140  for (j = 0; j < 257; j++) {
141  if (ctx->cid_table->ac_level[j] >> 1 == alevel &&
142  (!offset || (ctx->cid_table->ac_flags[j] & 1) && offset) &&
143  (!run || (ctx->cid_table->ac_flags[j] & 2) && run)) {
144  av_assert1(!ctx->vlc_codes[index]);
145  if (alevel) {
146  ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
147  ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
148  } else {
149  ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
150  ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
151  }
152  break;
153  }
154  }
155  av_assert0(!alevel || j < 257);
156  if (offset) {
157  ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
158  ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
159  }
160  }
161  }
162  for (i = 0; i < 62; i++) {
163  int run = ctx->cid_table->run[i];
164  av_assert0(run < 63);
165  ctx->run_codes[run] = ctx->cid_table->run_codes[i];
166  ctx->run_bits [run] = ctx->cid_table->run_bits[i];
167  }
168  return 0;
169  fail:
170  return AVERROR(ENOMEM);
171 }
172 
173 static av_cold int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
174 {
175  // init first elem to 1 to avoid div by 0 in convert_matrix
176  uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
177  int qscale, i;
178  const uint8_t *luma_weight_table = ctx->cid_table->luma_weight;
179  const uint8_t *chroma_weight_table = ctx->cid_table->chroma_weight;
180 
181  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
182  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c, (ctx->m.avctx->qmax+1) * 64 * sizeof(int), fail);
183  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
184  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
185 
186  if (ctx->cid_table->bit_depth == 8) {
187  for (i = 1; i < 64; i++) {
188  int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
189  weight_matrix[j] = ctx->cid_table->luma_weight[i];
190  }
191  ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
192  ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
193  for (i = 1; i < 64; i++) {
194  int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
195  weight_matrix[j] = ctx->cid_table->chroma_weight[i];
196  }
197  ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
198  ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
199 
200  for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
201  for (i = 0; i < 64; i++) {
202  ctx->qmatrix_l [qscale] [i] <<= 2; ctx->qmatrix_c [qscale] [i] <<= 2;
203  ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
204  ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
205  }
206  }
207  } else {
208  // 10-bit
209  for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
210  for (i = 1; i < 64; i++) {
211  int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
212 
213  // The quantization formula from the VC-3 standard is:
214  // quantized = sign(block[i]) * floor(abs(block[i]/s) * p / (qscale * weight_table[i]))
215  // Where p is 32 for 8-bit samples and 8 for 10-bit ones.
216  // The s factor compensates scaling of DCT coefficients done by the DCT routines,
217  // and therefore is not present in standard. It's 8 for 8-bit samples and 4 for 10-bit ones.
218  // We want values of ctx->qtmatrix_l and ctx->qtmatrix_r to be:
219  // ((1 << DNX10BIT_QMAT_SHIFT) * (p / s)) / (qscale * weight_table[i])
220  // For 10-bit samples, p / s == 2
221  ctx->qmatrix_l[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * luma_weight_table[i]);
222  ctx->qmatrix_c[qscale][j] = (1 << (DNX10BIT_QMAT_SHIFT + 1)) / (qscale * chroma_weight_table[i]);
223  }
224  }
225  }
226 
228  ctx->m.q_chroma_intra_matrix = ctx->qmatrix_c;
229  ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
230  ctx->m.q_intra_matrix = ctx->qmatrix_l;
231 
232  return 0;
233  fail:
234  return AVERROR(ENOMEM);
235 }
236 
238 {
239  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*(ctx->m.avctx->qmax + 1)*sizeof(RCEntry), fail);
240  if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
241  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
242 
243  ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
244  ctx->qscale = 1;
245  ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
246  return 0;
247  fail:
248  return AVERROR(ENOMEM);
249 }
250 
252 {
253  DNXHDEncContext *ctx = avctx->priv_data;
254  int i, index, bit_depth, ret;
255 
256  switch (avctx->pix_fmt) {
257  case AV_PIX_FMT_YUV422P:
258  bit_depth = 8;
259  break;
261  bit_depth = 10;
262  break;
263  default:
264  av_log(avctx, AV_LOG_ERROR, "pixel format is incompatible with DNxHD\n");
265  return AVERROR(EINVAL);
266  }
267 
268  ctx->cid = ff_dnxhd_find_cid(avctx, bit_depth);
269  if (!ctx->cid) {
270  av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD. Valid DNxHD profiles:\n");
272  return AVERROR(EINVAL);
273  }
274  av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
275 
276  index = ff_dnxhd_get_cid_table(ctx->cid);
277  av_assert0(index >= 0);
279 
280  ctx->m.avctx = avctx;
281  ctx->m.mb_intra = 1;
282  ctx->m.h263_aic = 1;
283 
284  avctx->bits_per_raw_sample = ctx->cid_table->bit_depth;
285 
286  ff_dct_common_init(&ctx->m);
287  ff_dct_encode_init(&ctx->m);
288 
289  if (!ctx->m.dct_quantize)
291 
292  if (ctx->cid_table->bit_depth == 10) {
295  ctx->block_width_l2 = 4;
296  } else {
298  ctx->block_width_l2 = 3;
299  }
300 
301  if (ARCH_X86)
303 
304  ctx->m.mb_height = (avctx->height + 15) / 16;
305  ctx->m.mb_width = (avctx->width + 15) / 16;
306 
307  if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
308  ctx->interlaced = 1;
309  ctx->m.mb_height /= 2;
310  }
311 
312  ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
313 
315  ctx->m.intra_quant_bias = avctx->intra_quant_bias;
316  if ((ret = dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0)) < 0) // XXX tune lbias/cbias
317  return ret;
318 
319  // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
320  if (ctx->nitris_compat)
321  ctx->min_padding = 1600;
322 
323  if ((ret = dnxhd_init_vlc(ctx)) < 0)
324  return ret;
325  if ((ret = dnxhd_init_rc(ctx)) < 0)
326  return ret;
327 
328  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
329  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
330  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits, ctx->m.mb_num *sizeof(uint16_t), fail);
331  FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale, ctx->m.mb_num *sizeof(uint8_t), fail);
332 
333  avctx->coded_frame = av_frame_alloc();
334  if (!avctx->coded_frame)
335  return AVERROR(ENOMEM);
336 
337  avctx->coded_frame->key_frame = 1;
339 
340  if (avctx->thread_count > MAX_THREADS) {
341  av_log(avctx, AV_LOG_ERROR, "too many threads\n");
342  return AVERROR(EINVAL);
343  }
344 
345  if (avctx->qmax <= 1) {
346  av_log(avctx, AV_LOG_ERROR, "qmax must be at least 2\n");
347  return AVERROR(EINVAL);
348  }
349 
350  ctx->thread[0] = ctx;
351  for (i = 1; i < avctx->thread_count; i++) {
352  ctx->thread[i] = av_malloc(sizeof(DNXHDEncContext));
353  memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
354  }
355 
356  return 0;
357  fail: //for FF_ALLOCZ_OR_GOTO
358  return AVERROR(ENOMEM);
359 }
360 
362 {
363  DNXHDEncContext *ctx = avctx->priv_data;
364  static const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
365 
366  memset(buf, 0, 640);
367 
368  memcpy(buf, header_prefix, 5);
369  buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
370  buf[6] = 0x80; // crc flag off
371  buf[7] = 0xa0; // reserved
372  AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
373  AV_WB16(buf + 0x1a, avctx->width); // SPL
374  AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
375 
376  buf[0x21] = ctx->cid_table->bit_depth == 10 ? 0x58 : 0x38;
377  buf[0x22] = 0x88 + (ctx->interlaced<<2);
378  AV_WB32(buf + 0x28, ctx->cid); // CID
379  buf[0x2c] = ctx->interlaced ? 0 : 0x80;
380 
381  buf[0x5f] = 0x01; // UDL
382 
383  buf[0x167] = 0x02; // reserved
384  AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
385  buf[0x16d] = ctx->m.mb_height; // Ns
386  buf[0x16f] = 0x10; // reserved
387 
388  ctx->msip = buf + 0x170;
389  return 0;
390 }
391 
393 {
394  int nbits;
395  if (diff < 0) {
396  nbits = av_log2_16bit(-2*diff);
397  diff--;
398  } else {
399  nbits = av_log2_16bit(2*diff);
400  }
401  put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
402  (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
403 }
404 
405 static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, int16_t *block, int last_index, int n)
406 {
407  int last_non_zero = 0;
408  int slevel, i, j;
409 
410  dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
411  ctx->m.last_dc[n] = block[0];
412 
413  for (i = 1; i <= last_index; i++) {
414  j = ctx->m.intra_scantable.permutated[i];
415  slevel = block[j];
416  if (slevel) {
417  int run_level = i - last_non_zero - 1;
418  int rlevel = (slevel<<1)|!!run_level;
419  put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
420  if (run_level)
421  put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
422  last_non_zero = i;
423  }
424  }
425  put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
426 }
427 
428 static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, int16_t *block, int n, int qscale, int last_index)
429 {
430  const uint8_t *weight_matrix;
431  int level;
432  int i;
433 
434  weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
435 
436  for (i = 1; i <= last_index; i++) {
437  int j = ctx->m.intra_scantable.permutated[i];
438  level = block[j];
439  if (level) {
440  if (level < 0) {
441  level = (1-2*level) * qscale * weight_matrix[i];
442  if (ctx->cid_table->bit_depth == 10) {
443  if (weight_matrix[i] != 8)
444  level += 8;
445  level >>= 4;
446  } else {
447  if (weight_matrix[i] != 32)
448  level += 32;
449  level >>= 6;
450  }
451  level = -level;
452  } else {
453  level = (2*level+1) * qscale * weight_matrix[i];
454  if (ctx->cid_table->bit_depth == 10) {
455  if (weight_matrix[i] != 8)
456  level += 8;
457  level >>= 4;
458  } else {
459  if (weight_matrix[i] != 32)
460  level += 32;
461  level >>= 6;
462  }
463  }
464  block[j] = level;
465  }
466  }
467 }
468 
469 static av_always_inline int dnxhd_ssd_block(int16_t *qblock, int16_t *block)
470 {
471  int score = 0;
472  int i;
473  for (i = 0; i < 64; i++)
474  score += (block[i] - qblock[i]) * (block[i] - qblock[i]);
475  return score;
476 }
477 
478 static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, int16_t *block, int last_index)
479 {
480  int last_non_zero = 0;
481  int bits = 0;
482  int i, j, level;
483  for (i = 1; i <= last_index; i++) {
484  j = ctx->m.intra_scantable.permutated[i];
485  level = block[j];
486  if (level) {
487  int run_level = i - last_non_zero - 1;
488  bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
489  last_non_zero = i;
490  }
491  }
492  return bits;
493 }
494 
495 static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
496 {
497  const int bs = ctx->block_width_l2;
498  const int bw = 1 << bs;
499  const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize) + (mb_x << bs+1);
500  const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
501  const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << bs);
502  DSPContext *dsp = &ctx->m.dsp;
503 
504  dsp->get_pixels(ctx->blocks[0], ptr_y, ctx->m.linesize);
505  dsp->get_pixels(ctx->blocks[1], ptr_y + bw, ctx->m.linesize);
506  dsp->get_pixels(ctx->blocks[2], ptr_u, ctx->m.uvlinesize);
507  dsp->get_pixels(ctx->blocks[3], ptr_v, ctx->m.uvlinesize);
508 
509  if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
510  if (ctx->interlaced) {
511  ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
512  ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
513  ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
514  ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
515  } else {
516  dsp->clear_block(ctx->blocks[4]);
517  dsp->clear_block(ctx->blocks[5]);
518  dsp->clear_block(ctx->blocks[6]);
519  dsp->clear_block(ctx->blocks[7]);
520  }
521  } else {
522  dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset, ctx->m.linesize);
523  dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + bw, ctx->m.linesize);
524  dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset, ctx->m.uvlinesize);
525  dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset, ctx->m.uvlinesize);
526  }
527 }
528 
530 {
531  const static uint8_t component[8]={0,0,1,2,0,0,1,2};
532  return component[i];
533 }
534 
535 static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
536 {
537  DNXHDEncContext *ctx = avctx->priv_data;
538  int mb_y = jobnr, mb_x;
539  int qscale = ctx->qscale;
540  LOCAL_ALIGNED_16(int16_t, block, [64]);
541  ctx = ctx->thread[threadnr];
542 
543  ctx->m.last_dc[0] =
544  ctx->m.last_dc[1] =
545  ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
546 
547  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
548  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
549  int ssd = 0;
550  int ac_bits = 0;
551  int dc_bits = 0;
552  int i;
553 
554  dnxhd_get_blocks(ctx, mb_x, mb_y);
555 
556  for (i = 0; i < 8; i++) {
557  int16_t *src_block = ctx->blocks[i];
558  int overflow, nbits, diff, last_index;
559  int n = dnxhd_switch_matrix(ctx, i);
560 
561  memcpy(block, src_block, 64*sizeof(*block));
562  last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
563  ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
564 
565  diff = block[0] - ctx->m.last_dc[n];
566  if (diff < 0) nbits = av_log2_16bit(-2*diff);
567  else nbits = av_log2_16bit( 2*diff);
568 
569  av_assert1(nbits < ctx->cid_table->bit_depth + 4);
570  dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
571 
572  ctx->m.last_dc[n] = block[0];
573 
574  if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
575  dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
576  ctx->m.dsp.idct(block);
577  ssd += dnxhd_ssd_block(block, src_block);
578  }
579  }
580  ctx->mb_rc[qscale][mb].ssd = ssd;
581  ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
582  }
583  return 0;
584 }
585 
586 static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
587 {
588  DNXHDEncContext *ctx = avctx->priv_data;
589  int mb_y = jobnr, mb_x;
590  ctx = ctx->thread[threadnr];
591  init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
592 
593  ctx->m.last_dc[0] =
594  ctx->m.last_dc[1] =
595  ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
596  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
597  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
598  int qscale = ctx->mb_qscale[mb];
599  int i;
600 
601  put_bits(&ctx->m.pb, 12, qscale<<1);
602 
603  dnxhd_get_blocks(ctx, mb_x, mb_y);
604 
605  for (i = 0; i < 8; i++) {
606  int16_t *block = ctx->blocks[i];
607  int overflow, n = dnxhd_switch_matrix(ctx, i);
608  int last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
609  //START_TIMER;
610  dnxhd_encode_block(ctx, block, last_index, n);
611  //STOP_TIMER("encode_block");
612  }
613  }
614  if (put_bits_count(&ctx->m.pb)&31)
615  put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
616  flush_put_bits(&ctx->m.pb);
617  return 0;
618 }
619 
621 {
622  int mb_y, mb_x;
623  int offset = 0;
624  for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
625  int thread_size;
626  ctx->slice_offs[mb_y] = offset;
627  ctx->slice_size[mb_y] = 0;
628  for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
629  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
630  ctx->slice_size[mb_y] += ctx->mb_bits[mb];
631  }
632  ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
633  ctx->slice_size[mb_y] >>= 3;
634  thread_size = ctx->slice_size[mb_y];
635  offset += thread_size;
636  }
637 }
638 
639 static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
640 {
641  DNXHDEncContext *ctx = avctx->priv_data;
642  int mb_y = jobnr, mb_x, x, y;
643  int partial_last_row = (mb_y == ctx->m.mb_height - 1) &&
644  ((avctx->height >> ctx->interlaced) & 0xF);
645 
646  ctx = ctx->thread[threadnr];
647  if (ctx->cid_table->bit_depth == 8) {
648  uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);
649  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {
650  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
651  int sum;
652  int varc;
653 
654  if (!partial_last_row && mb_x * 16 <= avctx->width - 16) {
655  sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
656  varc = ctx->m.dsp.pix_norm1(pix, ctx->m.linesize);
657  } else {
658  int bw = FFMIN(avctx->width - 16 * mb_x, 16);
659  int bh = FFMIN((avctx->height >> ctx->interlaced) - 16 * mb_y, 16);
660  sum = varc = 0;
661  for (y = 0; y < bh; y++) {
662  for (x = 0; x < bw; x++) {
663  uint8_t val = pix[x + y * ctx->m.linesize];
664  sum += val;
665  varc += val * val;
666  }
667  }
668  }
669  varc = (varc - (((unsigned)sum * sum) >> 8) + 128) >> 8;
670 
671  ctx->mb_cmp[mb].value = varc;
672  ctx->mb_cmp[mb].mb = mb;
673  }
674  } else { // 10-bit
675  int const linesize = ctx->m.linesize >> 1;
676  for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {
677  uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);
678  unsigned mb = mb_y * ctx->m.mb_width + mb_x;
679  int sum = 0;
680  int sqsum = 0;
681  int mean, sqmean;
682  int i, j;
683  // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.
684  for (i = 0; i < 16; ++i) {
685  for (j = 0; j < 16; ++j) {
686  // Turn 16-bit pixels into 10-bit ones.
687  int const sample = (unsigned)pix[j] >> 6;
688  sum += sample;
689  sqsum += sample * sample;
690  // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX
691  }
692  pix += linesize;
693  }
694  mean = sum >> 8; // 16*16 == 2^8
695  sqmean = sqsum >> 8;
696  ctx->mb_cmp[mb].value = sqmean - mean * mean;
697  ctx->mb_cmp[mb].mb = mb;
698  }
699  }
700  return 0;
701 }
702 
704 {
705  int lambda, up_step, down_step;
706  int last_lower = INT_MAX, last_higher = 0;
707  int x, y, q;
708 
709  for (q = 1; q < avctx->qmax; q++) {
710  ctx->qscale = q;
711  avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
712  }
713  up_step = down_step = 2<<LAMBDA_FRAC_BITS;
714  lambda = ctx->lambda;
715 
716  for (;;) {
717  int bits = 0;
718  int end = 0;
719  if (lambda == last_higher) {
720  lambda++;
721  end = 1; // need to set final qscales/bits
722  }
723  for (y = 0; y < ctx->m.mb_height; y++) {
724  for (x = 0; x < ctx->m.mb_width; x++) {
725  unsigned min = UINT_MAX;
726  int qscale = 1;
727  int mb = y*ctx->m.mb_width+x;
728  for (q = 1; q < avctx->qmax; q++) {
729  unsigned score = ctx->mb_rc[q][mb].bits*lambda+
730  ((unsigned)ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
731  if (score < min) {
732  min = score;
733  qscale = q;
734  }
735  }
736  bits += ctx->mb_rc[qscale][mb].bits;
737  ctx->mb_qscale[mb] = qscale;
738  ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
739  }
740  bits = (bits+31)&~31; // padding
741  if (bits > ctx->frame_bits)
742  break;
743  }
744  //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
745  // lambda, last_higher, last_lower, bits, ctx->frame_bits);
746  if (end) {
747  if (bits > ctx->frame_bits)
748  return AVERROR(EINVAL);
749  break;
750  }
751  if (bits < ctx->frame_bits) {
752  last_lower = FFMIN(lambda, last_lower);
753  if (last_higher != 0)
754  lambda = (lambda+last_higher)>>1;
755  else
756  lambda -= down_step;
757  down_step = FFMIN((int64_t)down_step*5, INT_MAX);
758  up_step = 1<<LAMBDA_FRAC_BITS;
759  lambda = FFMAX(1, lambda);
760  if (lambda == last_lower)
761  break;
762  } else {
763  last_higher = FFMAX(lambda, last_higher);
764  if (last_lower != INT_MAX)
765  lambda = (lambda+last_lower)>>1;
766  else if ((int64_t)lambda + up_step > INT_MAX)
767  return AVERROR(EINVAL);
768  else
769  lambda += up_step;
770  up_step = FFMIN((int64_t)up_step*5, INT_MAX);
771  down_step = 1<<LAMBDA_FRAC_BITS;
772  }
773  }
774  //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
775  ctx->lambda = lambda;
776  return 0;
777 }
778 
780 {
781  int bits = 0;
782  int up_step = 1;
783  int down_step = 1;
784  int last_higher = 0;
785  int last_lower = INT_MAX;
786  int qscale;
787  int x, y;
788 
789  qscale = ctx->qscale;
790  for (;;) {
791  bits = 0;
792  ctx->qscale = qscale;
793  // XXX avoid recalculating bits
794  ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
795  for (y = 0; y < ctx->m.mb_height; y++) {
796  for (x = 0; x < ctx->m.mb_width; x++)
797  bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
798  bits = (bits+31)&~31; // padding
799  if (bits > ctx->frame_bits)
800  break;
801  }
802  //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
803  // ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
804  if (bits < ctx->frame_bits) {
805  if (qscale == 1)
806  return 1;
807  if (last_higher == qscale - 1) {
808  qscale = last_higher;
809  break;
810  }
811  last_lower = FFMIN(qscale, last_lower);
812  if (last_higher != 0)
813  qscale = (qscale+last_higher)>>1;
814  else
815  qscale -= down_step++;
816  if (qscale < 1)
817  qscale = 1;
818  up_step = 1;
819  } else {
820  if (last_lower == qscale + 1)
821  break;
822  last_higher = FFMAX(qscale, last_higher);
823  if (last_lower != INT_MAX)
824  qscale = (qscale+last_lower)>>1;
825  else
826  qscale += up_step++;
827  down_step = 1;
828  if (qscale >= ctx->m.avctx->qmax)
829  return AVERROR(EINVAL);
830  }
831  }
832  //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
833  ctx->qscale = qscale;
834  return 0;
835 }
836 
837 #define BUCKET_BITS 8
838 #define RADIX_PASSES 4
839 #define NBUCKETS (1 << BUCKET_BITS)
840 
841 static inline int get_bucket(int value, int shift)
842 {
843  value >>= shift;
844  value &= NBUCKETS - 1;
845  return NBUCKETS - 1 - value;
846 }
847 
848 static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
849 {
850  int i, j;
851  memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
852  for (i = 0; i < size; i++) {
853  int v = data[i].value;
854  for (j = 0; j < RADIX_PASSES; j++) {
855  buckets[j][get_bucket(v, 0)]++;
856  v >>= BUCKET_BITS;
857  }
858  av_assert1(!v);
859  }
860  for (j = 0; j < RADIX_PASSES; j++) {
861  int offset = size;
862  for (i = NBUCKETS - 1; i >= 0; i--)
863  buckets[j][i] = offset -= buckets[j][i];
864  av_assert1(!buckets[j][0]);
865  }
866 }
867 
868 static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
869 {
870  int shift = pass * BUCKET_BITS;
871  int i;
872  for (i = 0; i < size; i++) {
873  int v = get_bucket(data[i].value, shift);
874  int pos = buckets[v]++;
875  dst[pos] = data[i];
876  }
877 }
878 
879 static void radix_sort(RCCMPEntry *data, int size)
880 {
881  int buckets[RADIX_PASSES][NBUCKETS];
882  RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
883  radix_count(data, size, buckets);
884  radix_sort_pass(tmp, data, size, buckets[0], 0);
885  radix_sort_pass(data, tmp, size, buckets[1], 1);
886  if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
887  radix_sort_pass(tmp, data, size, buckets[2], 2);
888  radix_sort_pass(data, tmp, size, buckets[3], 3);
889  }
890  av_free(tmp);
891 }
892 
894 {
895  int max_bits = 0;
896  int ret, x, y;
897  if ((ret = dnxhd_find_qscale(ctx)) < 0)
898  return ret;
899  for (y = 0; y < ctx->m.mb_height; y++) {
900  for (x = 0; x < ctx->m.mb_width; x++) {
901  int mb = y*ctx->m.mb_width+x;
902  int delta_bits;
903  ctx->mb_qscale[mb] = ctx->qscale;
904  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
905  max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
906  if (!RC_VARIANCE) {
907  delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
908  ctx->mb_cmp[mb].mb = mb;
909  ctx->mb_cmp[mb].value = delta_bits ?
910  ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
911  : INT_MIN; //avoid increasing qscale
912  }
913  }
914  max_bits += 31; //worst padding
915  }
916  if (!ret) {
917  if (RC_VARIANCE)
918  avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
919  radix_sort(ctx->mb_cmp, ctx->m.mb_num);
920  for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
921  int mb = ctx->mb_cmp[x].mb;
922  max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
923  ctx->mb_qscale[mb] = ctx->qscale+1;
924  ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
925  }
926  }
927  return 0;
928 }
929 
931 {
932  int i;
933 
934  for (i = 0; i < ctx->m.avctx->thread_count; i++) {
935  ctx->thread[i]->m.linesize = frame->linesize[0] << ctx->interlaced;
936  ctx->thread[i]->m.uvlinesize = frame->linesize[1] << ctx->interlaced;
937  ctx->thread[i]->dct_y_offset = ctx->m.linesize *8;
938  ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
939  }
940 
942  ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
943 }
944 
946  const AVFrame *frame, int *got_packet)
947 {
948  DNXHDEncContext *ctx = avctx->priv_data;
949  int first_field = 1;
950  int offset, i, ret;
951  uint8_t *buf;
952 
953  if ((ret = ff_alloc_packet2(avctx, pkt, ctx->cid_table->frame_size)) < 0)
954  return ret;
955  buf = pkt->data;
956 
957  dnxhd_load_picture(ctx, frame);
958 
959  encode_coding_unit:
960  for (i = 0; i < 3; i++) {
961  ctx->src[i] = frame->data[i];
962  if (ctx->interlaced && ctx->cur_field)
963  ctx->src[i] += frame->linesize[i];
964  }
965 
966  dnxhd_write_header(avctx, buf);
967 
968  if (avctx->mb_decision == FF_MB_DECISION_RD)
969  ret = dnxhd_encode_rdo(avctx, ctx);
970  else
971  ret = dnxhd_encode_fast(avctx, ctx);
972  if (ret < 0) {
973  av_log(avctx, AV_LOG_ERROR,
974  "picture could not fit ratecontrol constraints, increase qmax\n");
975  return ret;
976  }
977 
979 
980  offset = 0;
981  for (i = 0; i < ctx->m.mb_height; i++) {
982  AV_WB32(ctx->msip + i * 4, offset);
983  offset += ctx->slice_size[i];
984  av_assert1(!(ctx->slice_size[i] & 3));
985  }
986 
987  avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
988 
989  av_assert1(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
990  memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
991 
992  AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
993 
994  if (ctx->interlaced && first_field) {
995  first_field = 0;
996  ctx->cur_field ^= 1;
997  buf += ctx->cid_table->coding_unit_size;
998  goto encode_coding_unit;
999  }
1000 
1001  avctx->coded_frame->quality = ctx->qscale * FF_QP2LAMBDA;
1002 
1003  pkt->flags |= AV_PKT_FLAG_KEY;
1004  *got_packet = 1;
1005  return 0;
1006 }
1007 
1009 {
1010  DNXHDEncContext *ctx = avctx->priv_data;
1011  int max_level = 1<<(ctx->cid_table->bit_depth+2);
1012  int i;
1013 
1014  av_free(ctx->vlc_codes-max_level*2);
1015  av_free(ctx->vlc_bits -max_level*2);
1016  av_freep(&ctx->run_codes);
1017  av_freep(&ctx->run_bits);
1018 
1019  av_freep(&ctx->mb_bits);
1020  av_freep(&ctx->mb_qscale);
1021  av_freep(&ctx->mb_rc);
1022  av_freep(&ctx->mb_cmp);
1023  av_freep(&ctx->slice_size);
1024  av_freep(&ctx->slice_offs);
1025 
1026  av_freep(&ctx->qmatrix_c);
1027  av_freep(&ctx->qmatrix_l);
1028  av_freep(&ctx->qmatrix_c16);
1029  av_freep(&ctx->qmatrix_l16);
1030 
1031  for (i = 1; i < avctx->thread_count; i++)
1032  av_freep(&ctx->thread[i]);
1033 
1034  av_frame_free(&avctx->coded_frame);
1035 
1036  return 0;
1037 }
1038 
1039 static const AVCodecDefault dnxhd_defaults[] = {
1040  { "qmax", "1024" }, /* Maximum quantization scale factor allowed for VC-3 */
1041  { NULL },
1042 };
1043 
1045  .name = "dnxhd",
1046  .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
1047  .type = AVMEDIA_TYPE_VIDEO,
1048  .id = AV_CODEC_ID_DNXHD,
1049  .priv_data_size = sizeof(DNXHDEncContext),
1051  .encode2 = dnxhd_encode_picture,
1053  .capabilities = CODEC_CAP_SLICE_THREADS,
1054  .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV422P,
1056  AV_PIX_FMT_NONE },
1057  .priv_class = &dnxhd_class,
1058  .defaults = dnxhd_defaults,
1059 };