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