Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dnxhdenc.c @ 2912e87a

History | View | Annotate | Download (29.8 KB)

1
/*
2
 * VC3/DNxHD encoder
3
 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4
 *
5
 * VC-3 encoder funded by the British Broadcasting Corporation
6
 *
7
 * This file is part of Libav.
8
 *
9
 * Libav is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * Libav is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with Libav; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
 */
23

    
24
//#define DEBUG
25
#define RC_VARIANCE 1 // use variance or ssd for fast rc
26

    
27
#include "libavutil/opt.h"
28
#include "avcodec.h"
29
#include "dsputil.h"
30
#include "mpegvideo.h"
31
#include "dnxhdenc.h"
32

    
33
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
34

    
35
static const AVOption options[]={
36
    {"nitris_compat", "encode with Avid Nitris compatibility", offsetof(DNXHDEncContext, nitris_compat), FF_OPT_TYPE_INT, 0, 0, 1, VE},
37
{NULL}
38
};
39
static const AVClass class = { "dnxhd", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
40

    
41
int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
42

    
43
#define LAMBDA_FRAC_BITS 10
44

    
45
static av_always_inline void dnxhd_get_pixels_8x4(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
46
{
47
    int i;
48
    for (i = 0; i < 4; i++) {
49
        block[0] = pixels[0]; block[1] = pixels[1];
50
        block[2] = pixels[2]; block[3] = pixels[3];
51
        block[4] = pixels[4]; block[5] = pixels[5];
52
        block[6] = pixels[6]; block[7] = pixels[7];
53
        pixels += line_size;
54
        block += 8;
55
    }
56
    memcpy(block   , block- 8, sizeof(*block)*8);
57
    memcpy(block+ 8, block-16, sizeof(*block)*8);
58
    memcpy(block+16, block-24, sizeof(*block)*8);
59
    memcpy(block+24, block-32, sizeof(*block)*8);
60
}
61

    
62
static int dnxhd_init_vlc(DNXHDEncContext *ctx)
63
{
64
    int i, j, level, run;
65
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
66

    
67
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes), fail);
68
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->vlc_bits , max_level*4*sizeof(*ctx->vlc_bits ), fail);
69
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_codes, 63*2                               , fail);
70
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->run_bits , 63                                 , fail);
71

    
72
    ctx->vlc_codes += max_level*2;
73
    ctx->vlc_bits  += max_level*2;
74
    for (level = -max_level; level < max_level; level++) {
75
        for (run = 0; run < 2; run++) {
76
            int index = (level<<1)|run;
77
            int sign, offset = 0, alevel = level;
78

    
79
            MASK_ABS(sign, alevel);
80
            if (alevel > 64) {
81
                offset = (alevel-1)>>6;
82
                alevel -= offset<<6;
83
            }
84
            for (j = 0; j < 257; j++) {
85
                if (ctx->cid_table->ac_level[j] == alevel &&
86
                    (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) &&
87
                    (!run    || (ctx->cid_table->ac_run_flag  [j] && run))) {
88
                    assert(!ctx->vlc_codes[index]);
89
                    if (alevel) {
90
                        ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
91
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
92
                    } else {
93
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
94
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
95
                    }
96
                    break;
97
                }
98
            }
99
            assert(!alevel || j < 257);
100
            if (offset) {
101
                ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
102
                ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
103
            }
104
        }
105
    }
106
    for (i = 0; i < 62; i++) {
107
        int run = ctx->cid_table->run[i];
108
        assert(run < 63);
109
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
110
        ctx->run_bits [run] = ctx->cid_table->run_bits[i];
111
    }
112
    return 0;
113
 fail:
114
    return -1;
115
}
116

    
117
static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
118
{
119
    // init first elem to 1 to avoid div by 0 in convert_matrix
120
    uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
121
    int qscale, i;
122

    
123
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l,   (ctx->m.avctx->qmax+1) * 64 *     sizeof(int)     , fail);
124
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c,   (ctx->m.avctx->qmax+1) * 64 *     sizeof(int)     , fail);
125
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
126
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t), fail);
127

    
128
    for (i = 1; i < 64; i++) {
129
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
130
        weight_matrix[j] = ctx->cid_table->luma_weight[i];
131
    }
132
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
133
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
134
    for (i = 1; i < 64; i++) {
135
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
136
        weight_matrix[j] = ctx->cid_table->chroma_weight[i];
137
    }
138
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
139
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
140
    for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
141
        for (i = 0; i < 64; i++) {
142
            ctx->qmatrix_l  [qscale]   [i] <<= 2; ctx->qmatrix_c  [qscale]   [i] <<= 2;
143
            ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
144
            ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
145
        }
146
    }
147
    return 0;
148
 fail:
149
    return -1;
150
}
151

    
152
static int dnxhd_init_rc(DNXHDEncContext *ctx)
153
{
154
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry), fail);
155
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
156
        FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry), fail);
157

    
158
    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4 - ctx->min_padding) * 8;
159
    ctx->qscale = 1;
160
    ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
161
    return 0;
162
 fail:
163
    return -1;
164
}
165

    
166
static int dnxhd_encode_init(AVCodecContext *avctx)
167
{
168
    DNXHDEncContext *ctx = avctx->priv_data;
169
    int i, index;
170

    
171
    ctx->cid = ff_dnxhd_find_cid(avctx);
172
    if (!ctx->cid || avctx->pix_fmt != PIX_FMT_YUV422P) {
173
        av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
174
        return -1;
175
    }
176
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
177

    
178
    index = ff_dnxhd_get_cid_table(ctx->cid);
179
    ctx->cid_table = &ff_dnxhd_cid_table[index];
180

    
181
    ctx->m.avctx = avctx;
182
    ctx->m.mb_intra = 1;
183
    ctx->m.h263_aic = 1;
184

    
185
    ctx->get_pixels_8x4_sym = dnxhd_get_pixels_8x4;
186

    
187
    dsputil_init(&ctx->m.dsp, avctx);
188
    ff_dct_common_init(&ctx->m);
189
#if HAVE_MMX
190
    ff_dnxhd_init_mmx(ctx);
191
#endif
192
    if (!ctx->m.dct_quantize)
193
        ctx->m.dct_quantize = dct_quantize_c;
194

    
195
    ctx->m.mb_height = (avctx->height + 15) / 16;
196
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
197

    
198
    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
199
        ctx->interlaced = 1;
200
        ctx->m.mb_height /= 2;
201
    }
202

    
203
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
204

    
205
    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
206
        ctx->m.intra_quant_bias = avctx->intra_quant_bias;
207
    if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
208
        return -1;
209

    
210
    // Avid Nitris hardware decoder requires a minimum amount of padding in the coding unit payload
211
    if (ctx->nitris_compat)
212
        ctx->min_padding = 1600;
213

    
214
    if (dnxhd_init_vlc(ctx) < 0)
215
        return -1;
216
    if (dnxhd_init_rc(ctx) < 0)
217
        return -1;
218

    
219
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t), fail);
220
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->slice_offs, ctx->m.mb_height*sizeof(uint32_t), fail);
221
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_bits,    ctx->m.mb_num   *sizeof(uint16_t), fail);
222
    FF_ALLOCZ_OR_GOTO(ctx->m.avctx, ctx->mb_qscale,  ctx->m.mb_num   *sizeof(uint8_t) , fail);
223

    
224
    ctx->frame.key_frame = 1;
225
    ctx->frame.pict_type = FF_I_TYPE;
226
    ctx->m.avctx->coded_frame = &ctx->frame;
227

    
228
    if (avctx->thread_count > MAX_THREADS) {
229
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
230
        return -1;
231
    }
232

    
233
    ctx->thread[0] = ctx;
234
    for (i = 1; i < avctx->thread_count; i++) {
235
        ctx->thread[i] =  av_malloc(sizeof(DNXHDEncContext));
236
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
237
    }
238

    
239
    return 0;
240
 fail: //for FF_ALLOCZ_OR_GOTO
241
    return -1;
242
}
243

    
244
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
245
{
246
    DNXHDEncContext *ctx = avctx->priv_data;
247
    const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
248

    
249
    memset(buf, 0, 640);
250

    
251
    memcpy(buf, header_prefix, 5);
252
    buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
253
    buf[6] = 0x80; // crc flag off
254
    buf[7] = 0xa0; // reserved
255
    AV_WB16(buf + 0x18, avctx->height>>ctx->interlaced); // ALPF
256
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
257
    AV_WB16(buf + 0x1d, avctx->height>>ctx->interlaced); // NAL
258

    
259
    buf[0x21] = 0x38; // FIXME 8 bit per comp
260
    buf[0x22] = 0x88 + (ctx->interlaced<<2);
261
    AV_WB32(buf + 0x28, ctx->cid); // CID
262
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;
263

    
264
    buf[0x5f] = 0x01; // UDL
265

    
266
    buf[0x167] = 0x02; // reserved
267
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
268
    buf[0x16d] = ctx->m.mb_height; // Ns
269
    buf[0x16f] = 0x10; // reserved
270

    
271
    ctx->msip = buf + 0x170;
272
    return 0;
273
}
274

    
275
static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
276
{
277
    int nbits;
278
    if (diff < 0) {
279
        nbits = av_log2_16bit(-2*diff);
280
        diff--;
281
    } else {
282
        nbits = av_log2_16bit(2*diff);
283
    }
284
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
285
             (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
286
}
287

    
288
static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
289
{
290
    int last_non_zero = 0;
291
    int slevel, i, j;
292

    
293
    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
294
    ctx->m.last_dc[n] = block[0];
295

    
296
    for (i = 1; i <= last_index; i++) {
297
        j = ctx->m.intra_scantable.permutated[i];
298
        slevel = block[j];
299
        if (slevel) {
300
            int run_level = i - last_non_zero - 1;
301
            int rlevel = (slevel<<1)|!!run_level;
302
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
303
            if (run_level)
304
                put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
305
            last_non_zero = i;
306
        }
307
    }
308
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
309
}
310

    
311
static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
312
{
313
    const uint8_t *weight_matrix;
314
    int level;
315
    int i;
316

    
317
    weight_matrix = (n&2) ? ctx->cid_table->chroma_weight : ctx->cid_table->luma_weight;
318

    
319
    for (i = 1; i <= last_index; i++) {
320
        int j = ctx->m.intra_scantable.permutated[i];
321
        level = block[j];
322
        if (level) {
323
            if (level < 0) {
324
                level = (1-2*level) * qscale * weight_matrix[i];
325
                if (weight_matrix[i] != 32)
326
                    level += 32;
327
                level >>= 6;
328
                level = -level;
329
            } else {
330
                level = (2*level+1) * qscale * weight_matrix[i];
331
                if (weight_matrix[i] != 32)
332
                    level += 32;
333
                level >>= 6;
334
            }
335
            block[j] = level;
336
        }
337
    }
338
}
339

    
340
static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
341
{
342
    int score = 0;
343
    int i;
344
    for (i = 0; i < 64; i++)
345
        score += (block[i]-qblock[i])*(block[i]-qblock[i]);
346
    return score;
347
}
348

    
349
static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
350
{
351
    int last_non_zero = 0;
352
    int bits = 0;
353
    int i, j, level;
354
    for (i = 1; i <= last_index; i++) {
355
        j = ctx->m.intra_scantable.permutated[i];
356
        level = block[j];
357
        if (level) {
358
            int run_level = i - last_non_zero - 1;
359
            bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
360
            last_non_zero = i;
361
        }
362
    }
363
    return bits;
364
}
365

    
366
static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
367
{
368
    const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize)   + (mb_x << 4);
369
    const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
370
    const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
371
    DSPContext *dsp = &ctx->m.dsp;
372

    
373
    dsp->get_pixels(ctx->blocks[0], ptr_y    , ctx->m.linesize);
374
    dsp->get_pixels(ctx->blocks[1], ptr_y + 8, ctx->m.linesize);
375
    dsp->get_pixels(ctx->blocks[2], ptr_u    , ctx->m.uvlinesize);
376
    dsp->get_pixels(ctx->blocks[3], ptr_v    , ctx->m.uvlinesize);
377

    
378
    if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
379
        if (ctx->interlaced) {
380
            ctx->get_pixels_8x4_sym(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
381
            ctx->get_pixels_8x4_sym(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
382
            ctx->get_pixels_8x4_sym(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
383
            ctx->get_pixels_8x4_sym(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
384
        } else {
385
            dsp->clear_block(ctx->blocks[4]); dsp->clear_block(ctx->blocks[5]);
386
            dsp->clear_block(ctx->blocks[6]); dsp->clear_block(ctx->blocks[7]);
387
        }
388
    } else {
389
        dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
390
        dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
391
        dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
392
        dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
393
    }
394
}
395

    
396
static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
397
{
398
    if (i&2) {
399
        ctx->m.q_intra_matrix16 = ctx->qmatrix_c16;
400
        ctx->m.q_intra_matrix   = ctx->qmatrix_c;
401
        return 1 + (i&1);
402
    } else {
403
        ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
404
        ctx->m.q_intra_matrix   = ctx->qmatrix_l;
405
        return 0;
406
    }
407
}
408

    
409
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
410
{
411
    DNXHDEncContext *ctx = avctx->priv_data;
412
    int mb_y = jobnr, mb_x;
413
    int qscale = ctx->qscale;
414
    LOCAL_ALIGNED_16(DCTELEM, block, [64]);
415
    ctx = ctx->thread[threadnr];
416

    
417
    ctx->m.last_dc[0] =
418
    ctx->m.last_dc[1] =
419
    ctx->m.last_dc[2] = 1024;
420

    
421
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
422
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
423
        int ssd     = 0;
424
        int ac_bits = 0;
425
        int dc_bits = 0;
426
        int i;
427

    
428
        dnxhd_get_blocks(ctx, mb_x, mb_y);
429

    
430
        for (i = 0; i < 8; i++) {
431
            DCTELEM *src_block = ctx->blocks[i];
432
            int overflow, nbits, diff, last_index;
433
            int n = dnxhd_switch_matrix(ctx, i);
434

    
435
            memcpy(block, src_block, 64*sizeof(*block));
436
            last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
437
            ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
438

    
439
            diff = block[0] - ctx->m.last_dc[n];
440
            if (diff < 0) nbits = av_log2_16bit(-2*diff);
441
            else          nbits = av_log2_16bit( 2*diff);
442
            dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
443

    
444
            ctx->m.last_dc[n] = block[0];
445

    
446
            if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
447
                dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
448
                ctx->m.dsp.idct(block);
449
                ssd += dnxhd_ssd_block(block, src_block);
450
            }
451
        }
452
        ctx->mb_rc[qscale][mb].ssd = ssd;
453
        ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
454
    }
455
    return 0;
456
}
457

    
458
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
459
{
460
    DNXHDEncContext *ctx = avctx->priv_data;
461
    int mb_y = jobnr, mb_x;
462
    ctx = ctx->thread[threadnr];
463
    init_put_bits(&ctx->m.pb, (uint8_t *)arg + 640 + ctx->slice_offs[jobnr], ctx->slice_size[jobnr]);
464

    
465
    ctx->m.last_dc[0] =
466
    ctx->m.last_dc[1] =
467
    ctx->m.last_dc[2] = 1024;
468
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
469
        unsigned mb = mb_y * ctx->m.mb_width + mb_x;
470
        int qscale = ctx->mb_qscale[mb];
471
        int i;
472

    
473
        put_bits(&ctx->m.pb, 12, qscale<<1);
474

    
475
        dnxhd_get_blocks(ctx, mb_x, mb_y);
476

    
477
        for (i = 0; i < 8; i++) {
478
            DCTELEM *block = ctx->blocks[i];
479
            int last_index, overflow;
480
            int n = dnxhd_switch_matrix(ctx, i);
481
            last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
482
            //START_TIMER;
483
            dnxhd_encode_block(ctx, block, last_index, n);
484
            //STOP_TIMER("encode_block");
485
        }
486
    }
487
    if (put_bits_count(&ctx->m.pb)&31)
488
        put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
489
    flush_put_bits(&ctx->m.pb);
490
    return 0;
491
}
492

    
493
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx)
494
{
495
    int mb_y, mb_x;
496
    int offset = 0;
497
    for (mb_y = 0; mb_y < ctx->m.mb_height; mb_y++) {
498
        int thread_size;
499
        ctx->slice_offs[mb_y] = offset;
500
            ctx->slice_size[mb_y] = 0;
501
            for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
502
                unsigned mb = mb_y * ctx->m.mb_width + mb_x;
503
                ctx->slice_size[mb_y] += ctx->mb_bits[mb];
504
            }
505
            ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
506
            ctx->slice_size[mb_y] >>= 3;
507
            thread_size = ctx->slice_size[mb_y];
508
        offset += thread_size;
509
    }
510
}
511

    
512
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
513
{
514
    DNXHDEncContext *ctx = avctx->priv_data;
515
    int mb_y = jobnr, mb_x;
516
    ctx = ctx->thread[threadnr];
517
    for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
518
        unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
519
        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize) + (mb_x<<4);
520
        int sum      = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
521
        int varc     = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)(sum*sum))>>8)+128)>>8;
522
        ctx->mb_cmp[mb].value = varc;
523
        ctx->mb_cmp[mb].mb = mb;
524
    }
525
    return 0;
526
}
527

    
528
static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
529
{
530
    int lambda, up_step, down_step;
531
    int last_lower = INT_MAX, last_higher = 0;
532
    int x, y, q;
533

    
534
    for (q = 1; q < avctx->qmax; q++) {
535
        ctx->qscale = q;
536
        avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
537
    }
538
    up_step = down_step = 2<<LAMBDA_FRAC_BITS;
539
    lambda = ctx->lambda;
540

    
541
    for (;;) {
542
        int bits = 0;
543
        int end = 0;
544
        if (lambda == last_higher) {
545
            lambda++;
546
            end = 1; // need to set final qscales/bits
547
        }
548
        for (y = 0; y < ctx->m.mb_height; y++) {
549
            for (x = 0; x < ctx->m.mb_width; x++) {
550
                unsigned min = UINT_MAX;
551
                int qscale = 1;
552
                int mb = y*ctx->m.mb_width+x;
553
                for (q = 1; q < avctx->qmax; q++) {
554
                    unsigned score = ctx->mb_rc[q][mb].bits*lambda+(ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
555
                    if (score < min) {
556
                        min = score;
557
                        qscale = q;
558
                    }
559
                }
560
                bits += ctx->mb_rc[qscale][mb].bits;
561
                ctx->mb_qscale[mb] = qscale;
562
                ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
563
            }
564
            bits = (bits+31)&~31; // padding
565
            if (bits > ctx->frame_bits)
566
                break;
567
        }
568
        //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
569
        //        lambda, last_higher, last_lower, bits, ctx->frame_bits);
570
        if (end) {
571
            if (bits > ctx->frame_bits)
572
                return -1;
573
            break;
574
        }
575
        if (bits < ctx->frame_bits) {
576
            last_lower = FFMIN(lambda, last_lower);
577
            if (last_higher != 0)
578
                lambda = (lambda+last_higher)>>1;
579
            else
580
                lambda -= down_step;
581
            down_step *= 5; // XXX tune ?
582
            up_step = 1<<LAMBDA_FRAC_BITS;
583
            lambda = FFMAX(1, lambda);
584
            if (lambda == last_lower)
585
                break;
586
        } else {
587
            last_higher = FFMAX(lambda, last_higher);
588
            if (last_lower != INT_MAX)
589
                lambda = (lambda+last_lower)>>1;
590
            else if ((int64_t)lambda + up_step > INT_MAX)
591
                return -1;
592
            else
593
                lambda += up_step;
594
            up_step = FFMIN((int64_t)up_step*5, INT_MAX);
595
            down_step = 1<<LAMBDA_FRAC_BITS;
596
        }
597
    }
598
    //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);
599
    ctx->lambda = lambda;
600
    return 0;
601
}
602

    
603
static int dnxhd_find_qscale(DNXHDEncContext *ctx)
604
{
605
    int bits = 0;
606
    int up_step = 1;
607
    int down_step = 1;
608
    int last_higher = 0;
609
    int last_lower = INT_MAX;
610
    int qscale;
611
    int x, y;
612

    
613
    qscale = ctx->qscale;
614
    for (;;) {
615
        bits = 0;
616
        ctx->qscale = qscale;
617
        // XXX avoid recalculating bits
618
        ctx->m.avctx->execute2(ctx->m.avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);
619
        for (y = 0; y < ctx->m.mb_height; y++) {
620
            for (x = 0; x < ctx->m.mb_width; x++)
621
                bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
622
            bits = (bits+31)&~31; // padding
623
            if (bits > ctx->frame_bits)
624
                break;
625
        }
626
        //av_dlog(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
627
        //        ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
628
        if (bits < ctx->frame_bits) {
629
            if (qscale == 1)
630
                return 1;
631
            if (last_higher == qscale - 1) {
632
                qscale = last_higher;
633
                break;
634
            }
635
            last_lower = FFMIN(qscale, last_lower);
636
            if (last_higher != 0)
637
                qscale = (qscale+last_higher)>>1;
638
            else
639
                qscale -= down_step++;
640
            if (qscale < 1)
641
                qscale = 1;
642
            up_step = 1;
643
        } else {
644
            if (last_lower == qscale + 1)
645
                break;
646
            last_higher = FFMAX(qscale, last_higher);
647
            if (last_lower != INT_MAX)
648
                qscale = (qscale+last_lower)>>1;
649
            else
650
                qscale += up_step++;
651
            down_step = 1;
652
            if (qscale >= ctx->m.avctx->qmax)
653
                return -1;
654
        }
655
    }
656
    //av_dlog(ctx->m.avctx, "out qscale %d\n", qscale);
657
    ctx->qscale = qscale;
658
    return 0;
659
}
660

    
661
#define BUCKET_BITS 8
662
#define RADIX_PASSES 4
663
#define NBUCKETS (1 << BUCKET_BITS)
664

    
665
static inline int get_bucket(int value, int shift)
666
{
667
    value >>= shift;
668
    value &= NBUCKETS - 1;
669
    return NBUCKETS - 1 - value;
670
}
671

    
672
static void radix_count(const RCCMPEntry *data, int size, int buckets[RADIX_PASSES][NBUCKETS])
673
{
674
    int i, j;
675
    memset(buckets, 0, sizeof(buckets[0][0]) * RADIX_PASSES * NBUCKETS);
676
    for (i = 0; i < size; i++) {
677
        int v = data[i].value;
678
        for (j = 0; j < RADIX_PASSES; j++) {
679
            buckets[j][get_bucket(v, 0)]++;
680
            v >>= BUCKET_BITS;
681
        }
682
        assert(!v);
683
    }
684
    for (j = 0; j < RADIX_PASSES; j++) {
685
        int offset = size;
686
        for (i = NBUCKETS - 1; i >= 0; i--)
687
            buckets[j][i] = offset -= buckets[j][i];
688
        assert(!buckets[j][0]);
689
    }
690
}
691

    
692
static void radix_sort_pass(RCCMPEntry *dst, const RCCMPEntry *data, int size, int buckets[NBUCKETS], int pass)
693
{
694
    int shift = pass * BUCKET_BITS;
695
    int i;
696
    for (i = 0; i < size; i++) {
697
        int v = get_bucket(data[i].value, shift);
698
        int pos = buckets[v]++;
699
        dst[pos] = data[i];
700
    }
701
}
702

    
703
static void radix_sort(RCCMPEntry *data, int size)
704
{
705
    int buckets[RADIX_PASSES][NBUCKETS];
706
    RCCMPEntry *tmp = av_malloc(sizeof(*tmp) * size);
707
    radix_count(data, size, buckets);
708
    radix_sort_pass(tmp, data, size, buckets[0], 0);
709
    radix_sort_pass(data, tmp, size, buckets[1], 1);
710
    if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {
711
        radix_sort_pass(tmp, data, size, buckets[2], 2);
712
        radix_sort_pass(data, tmp, size, buckets[3], 3);
713
    }
714
    av_free(tmp);
715
}
716

    
717
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
718
{
719
    int max_bits = 0;
720
    int ret, x, y;
721
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
722
        return -1;
723
    for (y = 0; y < ctx->m.mb_height; y++) {
724
        for (x = 0; x < ctx->m.mb_width; x++) {
725
            int mb = y*ctx->m.mb_width+x;
726
            int delta_bits;
727
            ctx->mb_qscale[mb] = ctx->qscale;
728
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
729
            max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
730
            if (!RC_VARIANCE) {
731
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
732
                ctx->mb_cmp[mb].mb = mb;
733
                ctx->mb_cmp[mb].value = delta_bits ?
734
                    ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
735
                    : INT_MIN; //avoid increasing qscale
736
            }
737
        }
738
        max_bits += 31; //worst padding
739
    }
740
    if (!ret) {
741
        if (RC_VARIANCE)
742
            avctx->execute2(avctx, dnxhd_mb_var_thread, NULL, NULL, ctx->m.mb_height);
743
        radix_sort(ctx->mb_cmp, ctx->m.mb_num);
744
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
745
            int mb = ctx->mb_cmp[x].mb;
746
            max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
747
            ctx->mb_qscale[mb] = ctx->qscale+1;
748
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
749
        }
750
    }
751
    return 0;
752
}
753

    
754
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
755
{
756
    int i;
757

    
758
    for (i = 0; i < 3; i++) {
759
        ctx->frame.data[i]     = frame->data[i];
760
        ctx->frame.linesize[i] = frame->linesize[i];
761
    }
762

    
763
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
764
        ctx->thread[i]->m.linesize    = ctx->frame.linesize[0]<<ctx->interlaced;
765
        ctx->thread[i]->m.uvlinesize  = ctx->frame.linesize[1]<<ctx->interlaced;
766
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
767
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
768
    }
769

    
770
    ctx->frame.interlaced_frame = frame->interlaced_frame;
771
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
772
}
773

    
774
static int dnxhd_encode_picture(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data)
775
{
776
    DNXHDEncContext *ctx = avctx->priv_data;
777
    int first_field = 1;
778
    int offset, i, ret;
779

    
780
    if (buf_size < ctx->cid_table->frame_size) {
781
        av_log(avctx, AV_LOG_ERROR, "output buffer is too small to compress picture\n");
782
        return -1;
783
    }
784

    
785
    dnxhd_load_picture(ctx, data);
786

    
787
 encode_coding_unit:
788
    for (i = 0; i < 3; i++) {
789
        ctx->src[i] = ctx->frame.data[i];
790
        if (ctx->interlaced && ctx->cur_field)
791
            ctx->src[i] += ctx->frame.linesize[i];
792
    }
793

    
794
    dnxhd_write_header(avctx, buf);
795

    
796
    if (avctx->mb_decision == FF_MB_DECISION_RD)
797
        ret = dnxhd_encode_rdo(avctx, ctx);
798
    else
799
        ret = dnxhd_encode_fast(avctx, ctx);
800
    if (ret < 0) {
801
        av_log(avctx, AV_LOG_ERROR,
802
               "picture could not fit ratecontrol constraints, increase qmax\n");
803
        return -1;
804
    }
805

    
806
    dnxhd_setup_threads_slices(ctx);
807

    
808
    offset = 0;
809
    for (i = 0; i < ctx->m.mb_height; i++) {
810
        AV_WB32(ctx->msip + i * 4, offset);
811
        offset += ctx->slice_size[i];
812
        assert(!(ctx->slice_size[i] & 3));
813
    }
814

    
815
    avctx->execute2(avctx, dnxhd_encode_thread, buf, NULL, ctx->m.mb_height);
816

    
817
    assert(640 + offset + 4 <= ctx->cid_table->coding_unit_size);
818
    memset(buf + 640 + offset, 0, ctx->cid_table->coding_unit_size - 4 - offset - 640);
819

    
820
    AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); // EOF
821

    
822
    if (ctx->interlaced && first_field) {
823
        first_field     = 0;
824
        ctx->cur_field ^= 1;
825
        buf      += ctx->cid_table->coding_unit_size;
826
        buf_size -= ctx->cid_table->coding_unit_size;
827
        goto encode_coding_unit;
828
    }
829

    
830
    ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
831

    
832
    return ctx->cid_table->frame_size;
833
}
834

    
835
static int dnxhd_encode_end(AVCodecContext *avctx)
836
{
837
    DNXHDEncContext *ctx = avctx->priv_data;
838
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
839
    int i;
840

    
841
    av_free(ctx->vlc_codes-max_level*2);
842
    av_free(ctx->vlc_bits -max_level*2);
843
    av_freep(&ctx->run_codes);
844
    av_freep(&ctx->run_bits);
845

    
846
    av_freep(&ctx->mb_bits);
847
    av_freep(&ctx->mb_qscale);
848
    av_freep(&ctx->mb_rc);
849
    av_freep(&ctx->mb_cmp);
850
    av_freep(&ctx->slice_size);
851
    av_freep(&ctx->slice_offs);
852

    
853
    av_freep(&ctx->qmatrix_c);
854
    av_freep(&ctx->qmatrix_l);
855
    av_freep(&ctx->qmatrix_c16);
856
    av_freep(&ctx->qmatrix_l16);
857

    
858
    for (i = 1; i < avctx->thread_count; i++)
859
        av_freep(&ctx->thread[i]);
860

    
861
    return 0;
862
}
863

    
864
AVCodec ff_dnxhd_encoder = {
865
    "dnxhd",
866
    AVMEDIA_TYPE_VIDEO,
867
    CODEC_ID_DNXHD,
868
    sizeof(DNXHDEncContext),
869
    dnxhd_encode_init,
870
    dnxhd_encode_picture,
871
    dnxhd_encode_end,
872
    .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV422P, PIX_FMT_NONE},
873
    .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
874
    .priv_class = &class,
875
};