Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dnxhdenc.c @ 45b8e9e5

History | View | Annotate | Download (28.3 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 FFmpeg.
8
 *
9
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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 "avcodec.h"
28
#include "dsputil.h"
29
#include "mpegvideo.h"
30
#include "dnxhddata.h"
31

    
32
typedef struct {
33
    uint16_t mb;
34
    int value;
35
} RCCMPEntry;
36

    
37
typedef struct {
38
    int ssd;
39
    int bits;
40
} RCEntry;
41

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

    
44
typedef struct DNXHDEncContext {
45
    MpegEncContext m; ///< Used for quantization dsp functions
46

    
47
    AVFrame frame;
48
    int cid;
49
    const CIDEntry *cid_table;
50
    uint8_t *msip; ///< Macroblock Scan Indices Payload
51
    uint32_t *slice_size;
52

    
53
    struct DNXHDEncContext *thread[MAX_THREADS];
54

    
55
    unsigned dct_y_offset;
56
    unsigned dct_uv_offset;
57
    int interlaced;
58
    int cur_field;
59

    
60
    DECLARE_ALIGNED_16(DCTELEM, blocks[8][64]);
61

    
62
    int      (*qmatrix_c)     [64];
63
    int      (*qmatrix_l)     [64];
64
    uint16_t (*qmatrix_l16)[2][64];
65
    uint16_t (*qmatrix_c16)[2][64];
66

    
67
    unsigned frame_bits;
68
    uint8_t *src[3];
69

    
70
    uint16_t *table_vlc_codes;
71
    uint8_t  *table_vlc_bits;
72
    uint16_t *table_run_codes;
73
    uint8_t  *table_run_bits;
74

    
75
    /** Rate control */
76
    unsigned slice_bits;
77
    unsigned qscale;
78
    unsigned lambda;
79

    
80
    unsigned thread_size;
81

    
82
    uint16_t *mb_bits;
83
    uint8_t  *mb_qscale;
84

    
85
    RCCMPEntry *mb_cmp;
86
    RCEntry   (*mb_rc)[8160];
87
} DNXHDEncContext;
88

    
89
#define LAMBDA_FRAC_BITS 10
90

    
91
static int dnxhd_init_vlc(DNXHDEncContext *ctx)
92
{
93
    int i;
94

    
95
    CHECKED_ALLOCZ(ctx->table_vlc_codes, 449*2);
96
    CHECKED_ALLOCZ(ctx->table_vlc_bits,    449);
97
    CHECKED_ALLOCZ(ctx->table_run_codes,  63*2);
98
    CHECKED_ALLOCZ(ctx->table_run_bits,     63);
99

    
100
    for (i = 0; i < 257; i++) {
101
        int level = ctx->cid_table->ac_level[i] +
102
            (ctx->cid_table->ac_run_flag[i] << 7) + (ctx->cid_table->ac_index_flag[i] << 8);
103
        assert(level < 449);
104
        if (ctx->cid_table->ac_level[i] == 64 && ctx->cid_table->ac_index_flag[i])
105
            level -= 64; // use 0+(1<<8) level
106
        ctx->table_vlc_codes[level] = ctx->cid_table->ac_codes[i];
107
        ctx->table_vlc_bits [level] = ctx->cid_table->ac_bits[i];
108
    }
109
    for (i = 0; i < 62; i++) {
110
        int run = ctx->cid_table->run[i];
111
        assert(run < 63);
112
        ctx->table_run_codes[run] = ctx->cid_table->run_codes[i];
113
        ctx->table_run_bits [run] = ctx->cid_table->run_bits[i];
114
    }
115
    return 0;
116
 fail:
117
    return -1;
118
}
119

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

    
126
    CHECKED_ALLOCZ(ctx->qmatrix_l,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
127
    CHECKED_ALLOCZ(ctx->qmatrix_c,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
128
    CHECKED_ALLOCZ(ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
129
    CHECKED_ALLOCZ(ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
130

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

    
155
static int dnxhd_init_rc(DNXHDEncContext *ctx)
156
{
157
    CHECKED_ALLOCZ(ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry));
158
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
159
        CHECKED_ALLOCZ(ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry));
160

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

    
169
static int dnxhd_encode_init(AVCodecContext *avctx)
170
{
171
    DNXHDEncContext *ctx = avctx->priv_data;
172
    int i, index;
173

    
174
    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
175
        if      (avctx->bit_rate == 120000000)
176
            ctx->cid = 1242;
177
        else if (avctx->bit_rate == 185000000)
178
            ctx->cid = 1243;
179
    } else {
180
        if      (avctx->bit_rate == 120000000)
181
            ctx->cid = 1237;
182
        else if (avctx->bit_rate == 185000000)
183
            ctx->cid = 1238;
184
        else if (avctx->bit_rate ==  36000000)
185
            ctx->cid = 1253;
186
    }
187
    if (!ctx->cid || avctx->width != 1920 || avctx->height != 1080 || avctx->pix_fmt != PIX_FMT_YUV422P) {
188
        av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
189
        return -1;
190
    }
191

    
192
    index = ff_dnxhd_get_cid_table(ctx->cid);
193
    ctx->cid_table = &ff_dnxhd_cid_table[index];
194

    
195
    ctx->m.avctx = avctx;
196
    ctx->m.mb_intra = 1;
197
    ctx->m.h263_aic = 1;
198

    
199
    dsputil_init(&ctx->m.dsp, avctx);
200
    ff_dct_common_init(&ctx->m);
201
    if (!ctx->m.dct_quantize)
202
        ctx->m.dct_quantize = dct_quantize_c;
203

    
204
    ctx->m.mb_height = (avctx->height + 15) / 16;
205
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
206

    
207
    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
208
        ctx->interlaced = 1;
209
        ctx->m.mb_height /= 2;
210
    }
211

    
212
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
213

    
214
    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
215
        ctx->m.intra_quant_bias = avctx->intra_quant_bias;
216
    if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
217
        return -1;
218

    
219
    if (dnxhd_init_vlc(ctx) < 0)
220
        return -1;
221
    if (dnxhd_init_rc(ctx) < 0)
222
        return -1;
223

    
224
    CHECKED_ALLOCZ(ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t));
225
    CHECKED_ALLOCZ(ctx->mb_bits,    ctx->m.mb_num   *sizeof(uint16_t));
226
    CHECKED_ALLOCZ(ctx->mb_qscale,  ctx->m.mb_num   *sizeof(uint8_t));
227

    
228
    ctx->frame.key_frame = 1;
229
    ctx->frame.pict_type = FF_I_TYPE;
230
    ctx->m.avctx->coded_frame = &ctx->frame;
231

    
232
    if (avctx->thread_count > MAX_THREADS || (avctx->thread_count > ctx->m.mb_height)) {
233
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
234
        return -1;
235
    }
236

    
237
    ctx->thread[0] = ctx;
238
    for (i = 1; i < avctx->thread_count; i++) {
239
        ctx->thread[i] =  av_malloc(sizeof(DNXHDEncContext));
240
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
241
    }
242

    
243
    for (i = 0; i < avctx->thread_count; i++) {
244
        ctx->thread[i]->m.start_mb_y = (ctx->m.mb_height*(i  ) + avctx->thread_count/2) / avctx->thread_count;
245
        ctx->thread[i]->m.end_mb_y   = (ctx->m.mb_height*(i+1) + avctx->thread_count/2) / avctx->thread_count;
246
    }
247

    
248
    return 0;
249
 fail: //for CHECKED_ALLOCZ
250
    return -1;
251
}
252

    
253
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
254
{
255
    DNXHDEncContext *ctx = avctx->priv_data;
256
    const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
257

    
258
    memcpy(buf, header_prefix, 5);
259
    buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
260
    buf[6] = 0x80; // crc flag off
261
    buf[7] = 0xa0; // reserved
262
    AV_WB16(buf + 0x18, avctx->height); // ALPF
263
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
264
    AV_WB16(buf + 0x1d, avctx->height); // NAL
265

    
266
    buf[0x21] = 0x38; // FIXME 8 bit per comp
267
    buf[0x22] = 0x88 + (ctx->frame.interlaced_frame<<2);
268
    AV_WB32(buf + 0x28, ctx->cid); // CID
269
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;
270

    
271
    buf[0x5f] = 0x01; // UDL
272

    
273
    buf[0x167] = 0x02; // reserved
274
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
275
    buf[0x16d] = ctx->m.mb_height; // Ns
276
    buf[0x16f] = 0x10; // reserved
277

    
278
    ctx->msip = buf + 0x170;
279
    return 0;
280
}
281

    
282
static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
283
{
284
    int nbits;
285
    if (diff < 0) {
286
        nbits = av_log2_16bit(-2*diff);
287
        diff--;
288
    } else {
289
        nbits = av_log2_16bit(2*diff);
290
    }
291
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
292
             (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
293
}
294

    
295
static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
296
{
297
    int last_non_zero = 0;
298
    int offset = 0;
299
    int slevel, i, j;
300

    
301
    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
302
    ctx->m.last_dc[n] = block[0];
303

    
304
    for (i = 1; i <= last_index; i++) {
305
        j = ctx->m.intra_scantable.permutated[i];
306
        slevel = block[j];
307
        if (slevel) {
308
            int run_level = i - last_non_zero - 1;
309
            int sign;
310
            MASK_ABS(sign, slevel);
311
            if (slevel > 64) {
312
                offset = (slevel-1) >> 6;
313
                slevel = 256 | (slevel & 63); // level 64 is treated as 0
314
            }
315
            if (run_level)
316
                slevel |= 128;
317
            put_bits(&ctx->m.pb, ctx->table_vlc_bits[slevel]+1, (ctx->table_vlc_codes[slevel]<<1)|(sign&1));
318
            if (offset) {
319
                put_bits(&ctx->m.pb, 4, offset);
320
                offset = 0;
321
            }
322
            if (run_level)
323
                put_bits(&ctx->m.pb, ctx->table_run_bits[run_level], ctx->table_run_codes[run_level]);
324
            last_non_zero = i;
325
        }
326
    }
327
    put_bits(&ctx->m.pb, ctx->table_vlc_bits[0], ctx->table_vlc_codes[0]); // EOB
328
}
329

    
330
static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
331
{
332
    const uint8_t *weight_matrix;
333
    int level;
334
    int i;
335

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

    
338
    for (i = 1; i <= last_index; i++) {
339
        int j = ctx->m.intra_scantable.permutated[i];
340
        level = block[j];
341
        if (level) {
342
            if (level < 0) {
343
                level = (1-2*level) * qscale * weight_matrix[i];
344
                if (weight_matrix[i] != 32)
345
                    level += 32;
346
                level >>= 6;
347
                level = -level;
348
            } else {
349
                level = (2*level+1) * qscale * weight_matrix[i];
350
                if (weight_matrix[i] != 32)
351
                    level += 32;
352
                level >>= 6;
353
            }
354
            block[j] = level;
355
        }
356
    }
357
}
358

    
359
static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
360
{
361
    int score = 0;
362
    int i;
363
    for (i = 0; i < 64; i++)
364
        score += (block[i]-qblock[i])*(block[i]-qblock[i]);
365
    return score;
366
}
367

    
368
static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
369
{
370
    int last_non_zero = 0;
371
    int bits = 0;
372
    int i, j, level;
373
    for (i = 1; i <= last_index; i++) {
374
        j = ctx->m.intra_scantable.permutated[i];
375
        level = block[j];
376
        if (level) {
377
            int run_level = i - last_non_zero - 1;
378
            level = FFABS(level);
379
            if (level > 64) {
380
                level = 256 | (level & 63); // level 64 is treated as 0
381
                bits += 4;
382
            }
383
            level |= (!!run_level)<<7;
384
            bits += ctx->table_vlc_bits[level]+1 + ctx->table_run_bits[run_level];
385
            last_non_zero = i;
386
        }
387
    }
388
    return bits;
389
}
390

    
391
static av_always_inline void dnxhd_get_pixels_4x8(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
392
{
393
    int i;
394
    for (i = 0; i < 4; i++) {
395
        block[0] = pixels[0];
396
        block[1] = pixels[1];
397
        block[2] = pixels[2];
398
        block[3] = pixels[3];
399
        block[4] = pixels[4];
400
        block[5] = pixels[5];
401
        block[6] = pixels[6];
402
        block[7] = pixels[7];
403
        pixels += line_size;
404
        block += 8;
405
    }
406
    memcpy(block   , block- 8, sizeof(*block)*8);
407
    memcpy(block+ 8, block-16, sizeof(*block)*8);
408
    memcpy(block+16, block-24, sizeof(*block)*8);
409
    memcpy(block+24, block-32, sizeof(*block)*8);
410
}
411

    
412
static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
413
{
414
    const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize)   + (mb_x << 4);
415
    const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
416
    const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
417
    DSPContext *dsp = &ctx->m.dsp;
418

    
419
    dsp->get_pixels(ctx->blocks[0], ptr_y    , ctx->m.linesize);
420
    dsp->get_pixels(ctx->blocks[1], ptr_y + 8, ctx->m.linesize);
421
    dsp->get_pixels(ctx->blocks[2], ptr_u    , ctx->m.uvlinesize);
422
    dsp->get_pixels(ctx->blocks[3], ptr_v    , ctx->m.uvlinesize);
423

    
424
    if (mb_y+1 == ctx->m.mb_height) {
425
        if (ctx->interlaced) {
426
            dnxhd_get_pixels_4x8(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
427
            dnxhd_get_pixels_4x8(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
428
            dnxhd_get_pixels_4x8(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
429
            dnxhd_get_pixels_4x8(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
430
        } else
431
            memset(ctx->blocks[4], 0, 4*64*sizeof(DCTELEM));
432
    } else {
433
        dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
434
        dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
435
        dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
436
        dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
437
    }
438
}
439

    
440
static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
441
{
442
    if (i&2) {
443
        ctx->m.q_intra_matrix16 = ctx->qmatrix_c16;
444
        ctx->m.q_intra_matrix   = ctx->qmatrix_c;
445
        return 1 + (i&1);
446
    } else {
447
        ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
448
        ctx->m.q_intra_matrix   = ctx->qmatrix_l;
449
        return 0;
450
    }
451
}
452

    
453
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg)
454
{
455
    DNXHDEncContext *ctx = arg;
456
    int mb_y, mb_x;
457
    int qscale = ctx->thread[0]->qscale;
458

    
459
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
460
        ctx->m.last_dc[0] =
461
        ctx->m.last_dc[1] =
462
        ctx->m.last_dc[2] = 1024;
463

    
464
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
465
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
466
            int ssd     = 0;
467
            int ac_bits = 0;
468
            int dc_bits = 0;
469
            int i;
470

    
471
            dnxhd_get_blocks(ctx, mb_x, mb_y);
472

    
473
            for (i = 0; i < 8; i++) {
474
                DECLARE_ALIGNED_16(DCTELEM, block[64]);
475
                DCTELEM *src_block = ctx->blocks[i];
476
                int overflow, nbits, diff, last_index;
477
                int n = dnxhd_switch_matrix(ctx, i);
478

    
479
                memcpy(block, src_block, sizeof(block));
480
                last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
481
                ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
482

    
483
                diff = block[0] - ctx->m.last_dc[n];
484
                if (diff < 0) nbits = av_log2_16bit(-2*diff);
485
                else          nbits = av_log2_16bit( 2*diff);
486
                dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
487

    
488
                ctx->m.last_dc[n] = block[0];
489

    
490
                if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
491
                    dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
492
                    ctx->m.dsp.idct(block);
493
                    ssd += dnxhd_ssd_block(block, src_block);
494
                }
495
            }
496
            ctx->mb_rc[qscale][mb].ssd = ssd;
497
            ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->table_vlc_bits[0];
498
        }
499
    }
500
    return 0;
501
}
502

    
503
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg)
504
{
505
    DNXHDEncContext *ctx = arg;
506
    int mb_y, mb_x;
507

    
508
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
509
        ctx->m.last_dc[0] =
510
        ctx->m.last_dc[1] =
511
        ctx->m.last_dc[2] = 1024;
512
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
513
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
514
            int qscale = ctx->mb_qscale[mb];
515
            int i;
516

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

    
519
            dnxhd_get_blocks(ctx, mb_x, mb_y);
520

    
521
            for (i = 0; i < 8; i++) {
522
                DCTELEM *block = ctx->blocks[i];
523
                int last_index, overflow;
524
                int n = dnxhd_switch_matrix(ctx, i);
525
                last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
526
                dnxhd_encode_block(ctx, block, last_index, n);
527
            }
528
        }
529
        if (put_bits_count(&ctx->m.pb)&31)
530
            put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
531
    }
532
    flush_put_bits(&ctx->m.pb);
533
    return 0;
534
}
535

    
536
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx, uint8_t *buf)
537
{
538
    int mb_y, mb_x;
539
    int i, offset = 0;
540
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
541
        int thread_size = 0;
542
        for (mb_y = ctx->thread[i]->m.start_mb_y; mb_y < ctx->thread[i]->m.end_mb_y; mb_y++) {
543
            ctx->slice_size[mb_y] = 0;
544
            for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
545
                unsigned mb = mb_y * ctx->m.mb_width + mb_x;
546
                ctx->slice_size[mb_y] += ctx->mb_bits[mb];
547
            }
548
            ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
549
            ctx->slice_size[mb_y] >>= 3;
550
            thread_size += ctx->slice_size[mb_y];
551
        }
552
        init_put_bits(&ctx->thread[i]->m.pb, buf + 640 + offset, thread_size);
553
        offset += thread_size;
554
    }
555
}
556

    
557
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg)
558
{
559
    DNXHDEncContext *ctx = arg;
560
    int mb_y, mb_x;
561
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
562
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
563
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
564
            uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize) + (mb_x<<4);
565
            int sum      = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
566
            int varc     = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)(sum*sum))>>8)+128)>>8;
567
            ctx->mb_cmp[mb].value = varc;
568
            ctx->mb_cmp[mb].mb = mb;
569
        }
570
    }
571
    return 0;
572
}
573

    
574
static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
575
{
576
    int lambda, up_step, down_step;
577
    int last_lower = INT_MAX, last_higher = 0;
578
    int x, y, q;
579

    
580
    for (q = 1; q < avctx->qmax; q++) {
581
        ctx->qscale = q;
582
        avctx->execute(avctx, dnxhd_calc_bits_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count);
583
    }
584
    up_step = down_step = 2<<LAMBDA_FRAC_BITS;
585
    lambda = ctx->lambda;
586

    
587
    for (;;) {
588
        int bits = 0;
589
        int end = 0;
590
        if (lambda == last_higher) {
591
            lambda++;
592
            end = 1; // need to set final qscales/bits
593
        }
594
        for (y = 0; y < ctx->m.mb_height; y++) {
595
            for (x = 0; x < ctx->m.mb_width; x++) {
596
                unsigned min = UINT_MAX;
597
                int qscale = 1;
598
                int mb = y*ctx->m.mb_width+x;
599
                for (q = 1; q < avctx->qmax; q++) {
600
                    unsigned score = ctx->mb_rc[q][mb].bits*lambda+(ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);
601
                    if (score < min) {
602
                        min = score;
603
                        qscale = q;
604
                    }
605
                }
606
                bits += ctx->mb_rc[qscale][mb].bits;
607
                ctx->mb_qscale[mb] = qscale;
608
                ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;
609
            }
610
            bits = (bits+31)&~31; // padding
611
            if (bits > ctx->frame_bits)
612
                break;
613
        }
614
        //dprintf(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",
615
        //        lambda, last_higher, last_lower, bits, ctx->frame_bits);
616
        if (end) {
617
            if (bits > ctx->frame_bits)
618
                return -1;
619
            break;
620
        }
621
        if (bits < ctx->frame_bits) {
622
            last_lower = FFMIN(lambda, last_lower);
623
            if (last_higher != 0)
624
                lambda = (lambda+last_higher)>>1;
625
            else
626
                lambda -= down_step;
627
            down_step *= 5; // XXX tune ?
628
            up_step = 1<<LAMBDA_FRAC_BITS;
629
            lambda = FFMAX(1, lambda);
630
            if (lambda == last_lower)
631
                break;
632
        } else {
633
            last_higher = FFMAX(lambda, last_higher);
634
            if (last_lower != INT_MAX)
635
                lambda = (lambda+last_lower)>>1;
636
            else
637
                lambda += up_step;
638
            up_step *= 5;
639
            down_step = 1<<LAMBDA_FRAC_BITS;
640
        }
641
    }
642
    //dprintf(ctx->m.avctx, "out lambda %d\n", lambda);
643
    ctx->lambda = lambda;
644
    return 0;
645
}
646

    
647
static int dnxhd_find_qscale(DNXHDEncContext *ctx)
648
{
649
    int bits = 0;
650
    int up_step = 1;
651
    int down_step = 1;
652
    int last_higher = 0;
653
    int last_lower = INT_MAX;
654
    int qscale;
655
    int x, y;
656

    
657
    qscale = ctx->qscale;
658
    for (;;) {
659
        bits = 0;
660
        ctx->qscale = qscale;
661
        // XXX avoid recalculating bits
662
        ctx->m.avctx->execute(ctx->m.avctx, dnxhd_calc_bits_thread, (void**)&ctx->thread[0], NULL, ctx->m.avctx->thread_count);
663
        for (y = 0; y < ctx->m.mb_height; y++) {
664
            for (x = 0; x < ctx->m.mb_width; x++)
665
                bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
666
            bits = (bits+31)&~31; // padding
667
            if (bits > ctx->frame_bits)
668
                break;
669
        }
670
        //dprintf(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
671
        //        ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
672
        if (bits < ctx->frame_bits) {
673
            if (qscale == 1)
674
                break;
675
            if (last_higher == qscale - 1) {
676
                qscale = last_higher;
677
                break;
678
            }
679
            last_lower = FFMIN(qscale, last_lower);
680
            if (last_higher != 0)
681
                qscale = (qscale+last_higher)>>1;
682
            else
683
                qscale -= down_step++;
684
            if (qscale < 1)
685
                qscale = 1;
686
            up_step = 1;
687
        } else {
688
            if (last_lower == qscale + 1)
689
                break;
690
            last_higher = FFMAX(qscale, last_higher);
691
            if (last_lower != INT_MAX)
692
                qscale = (qscale+last_lower)>>1;
693
            else
694
                qscale += up_step++;
695
            down_step = 1;
696
            if (qscale >= ctx->m.avctx->qmax)
697
                return -1;
698
        }
699
    }
700
    //dprintf(ctx->m.avctx, "out qscale %d\n", qscale);
701
    ctx->qscale = qscale;
702
    return 0;
703
}
704

    
705
static int dnxhd_rc_cmp(const void *a, const void *b)
706
{
707
    return ((RCCMPEntry *)b)->value - ((RCCMPEntry *)a)->value;
708
}
709

    
710
static int dnxhd_encode_variance(AVCodecContext *avctx, DNXHDEncContext *ctx)
711
{
712
    int max_bits = 0;
713
    int x, y;
714
    if (dnxhd_find_qscale(ctx) < 0)
715
        return -1;
716
    for (y = 0; y < ctx->m.mb_height; y++) {
717
        for (x = 0; x < ctx->m.mb_width; x++) {
718
            int mb = y*ctx->m.mb_width+x;
719
            int delta_bits;
720
            ctx->mb_qscale[mb] = ctx->qscale;
721
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
722
            max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
723
            if (!RC_VARIANCE) {
724
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
725
                ctx->mb_cmp[mb].mb = mb;
726
                ctx->mb_cmp[mb].value = delta_bits ?
727
                    ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
728
                    : INT_MIN; //avoid increasing qscale
729
            }
730
        }
731
        max_bits += 31; //worst padding
732
    }
733
    if (max_bits > ctx->frame_bits) {
734
        if (RC_VARIANCE)
735
            avctx->execute(avctx, dnxhd_mb_var_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count);
736
        qsort(ctx->mb_cmp, ctx->m.mb_num, sizeof(RCEntry), dnxhd_rc_cmp);
737
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
738
            int mb = ctx->mb_cmp[x].mb;
739
            max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
740
            ctx->mb_qscale[mb] = ctx->qscale+1;
741
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
742
        }
743
    }
744
    return 0;
745
}
746

    
747
static void dnxhd_load_picture(DNXHDEncContext *ctx, AVFrame *frame)
748
{
749
    int i;
750

    
751
    for (i = 0; i < 3; i++) {
752
        ctx->frame.data[i]     = frame->data[i];
753
        ctx->frame.linesize[i] = frame->linesize[i];
754
    }
755

    
756
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
757
        ctx->thread[i]->m.linesize    = ctx->frame.linesize[0]<<ctx->interlaced;
758
        ctx->thread[i]->m.uvlinesize  = ctx->frame.linesize[1]<<ctx->interlaced;
759
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
760
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
761
    }
762

    
763
    ctx->frame.interlaced_frame = frame->interlaced_frame;
764
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
765
}
766

    
767
static int dnxhd_encode_picture(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data)
768
{
769
    DNXHDEncContext *ctx = avctx->priv_data;
770
    int first_field = 1;
771
    int offset, i, ret;
772

    
773
    if (buf_size < ctx->cid_table->frame_size) {
774
        av_log(avctx, AV_LOG_ERROR, "output buffer is too small to compress picture\n");
775
        return -1;
776
    }
777

    
778
    dnxhd_load_picture(ctx, data);
779

    
780
 encode_coding_unit:
781
    for (i = 0; i < 3; i++) {
782
        ctx->src[i] = ctx->frame.data[i];
783
        if (ctx->interlaced && ctx->cur_field)
784
            ctx->src[i] += ctx->frame.linesize[i];
785
    }
786

    
787
    dnxhd_write_header(avctx, buf);
788

    
789
    if (avctx->mb_decision == FF_MB_DECISION_RD)
790
        ret = dnxhd_encode_rdo(avctx, ctx);
791
    else
792
        ret = dnxhd_encode_variance(avctx, ctx);
793
    if (ret < 0) {
794
        av_log(avctx, AV_LOG_ERROR, "picture could not fit ratecontrol constraints\n");
795
        return -1;
796
    }
797

    
798
    dnxhd_setup_threads_slices(ctx, buf);
799

    
800
    offset = 0;
801
    for (i = 0; i < ctx->m.mb_height; i++) {
802
        AV_WB32(ctx->msip + i * 4, offset);
803
        offset += ctx->slice_size[i];
804
        assert(!(ctx->slice_size[i] & 3));
805
    }
806

    
807
    avctx->execute(avctx, dnxhd_encode_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count);
808

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

    
811
    if (ctx->interlaced && first_field) {
812
        first_field     = 0;
813
        ctx->cur_field ^= 1;
814
        buf      += ctx->cid_table->coding_unit_size;
815
        buf_size -= ctx->cid_table->coding_unit_size;
816
        goto encode_coding_unit;
817
    }
818

    
819
    return ctx->cid_table->frame_size;
820
}
821

    
822
static int dnxhd_encode_end(AVCodecContext *avctx)
823
{
824
    DNXHDEncContext *ctx = avctx->priv_data;
825
    int i;
826

    
827
    av_freep(&ctx->table_vlc_codes);
828
    av_freep(&ctx->table_vlc_bits);
829
    av_freep(&ctx->table_run_codes);
830
    av_freep(&ctx->table_run_bits);
831

    
832
    av_freep(&ctx->mb_bits);
833
    av_freep(&ctx->mb_qscale);
834
    av_freep(&ctx->mb_rc);
835
    av_freep(&ctx->mb_cmp);
836
    av_freep(&ctx->slice_size);
837

    
838
    av_freep(&ctx->qmatrix_c);
839
    av_freep(&ctx->qmatrix_l);
840
    av_freep(&ctx->qmatrix_c16);
841
    av_freep(&ctx->qmatrix_l16);
842

    
843
    for (i = 1; i < avctx->thread_count; i++)
844
        av_freep(&ctx->thread[i]);
845

    
846
    return 0;
847
}
848

    
849
AVCodec dnxhd_encoder = {
850
    "dnxhd",
851
    CODEC_TYPE_VIDEO,
852
    CODEC_ID_DNXHD,
853
    sizeof(DNXHDEncContext),
854
    dnxhd_encode_init,
855
    dnxhd_encode_picture,
856
    dnxhd_encode_end,
857
    .pix_fmts = (enum PixelFormat[]){PIX_FMT_YUV422P, -1},
858
};