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