Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dnxhdenc.c @ 00d9d0f5

History | View | Annotate | Download (28.7 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 Indexes 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
    uint32_t *vlc_codes;
71
    uint8_t  *vlc_bits;
72
    uint16_t *run_codes;
73
    uint8_t  *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, j, level, run;
94
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
95

    
96
    CHECKED_ALLOCZ(ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes));
97
    CHECKED_ALLOCZ(ctx->vlc_bits,  max_level*4*sizeof(*ctx->vlc_bits));
98
    CHECKED_ALLOCZ(ctx->run_codes, 63*2);
99
    CHECKED_ALLOCZ(ctx->run_bits,    63);
100

    
101
    ctx->vlc_codes += max_level*2;
102
    ctx->vlc_bits  += max_level*2;
103
    for (level = -max_level; level < max_level; level++) {
104
        for (run = 0; run < 2; run++) {
105
            int index = (level<<1)|run;
106
            int sign, offset = 0, alevel = level;
107

    
108
            MASK_ABS(sign, alevel);
109
            if (alevel > 64) {
110
                offset = (alevel-1)>>6;
111
                alevel -= offset<<6;
112
            }
113
            for (j = 0; j < 257; j++) {
114
                if (ctx->cid_table->ac_level[j] == alevel &&
115
                    (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) &&
116
                    (!run    || (ctx->cid_table->ac_run_flag  [j] && run))) {
117
                    assert(!ctx->vlc_codes[index]);
118
                    if (alevel) {
119
                        ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
120
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
121
                    } else {
122
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
123
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
124
                    }
125
                    break;
126
                }
127
            }
128
            assert(!alevel || j < 257);
129
            if (offset) {
130
                ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
131
                ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
132
            }
133
        }
134
    }
135
    for (i = 0; i < 62; i++) {
136
        int run = ctx->cid_table->run[i];
137
        assert(run < 63);
138
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
139
        ctx->run_bits [run] = ctx->cid_table->run_bits[i];
140
    }
141
    return 0;
142
 fail:
143
    return -1;
144
}
145

    
146
static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
147
{
148
    // init first elem to 1 to avoid div by 0 in convert_matrix
149
    uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
150
    int qscale, i;
151

    
152
    CHECKED_ALLOCZ(ctx->qmatrix_l,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
153
    CHECKED_ALLOCZ(ctx->qmatrix_c,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
154
    CHECKED_ALLOCZ(ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
155
    CHECKED_ALLOCZ(ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
156

    
157
    for (i = 1; i < 64; i++) {
158
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
159
        weight_matrix[j] = ctx->cid_table->luma_weight[i];
160
    }
161
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
162
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
163
    for (i = 1; i < 64; i++) {
164
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
165
        weight_matrix[j] = ctx->cid_table->chroma_weight[i];
166
    }
167
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
168
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
169
    for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
170
        for (i = 0; i < 64; i++) {
171
            ctx->qmatrix_l  [qscale]   [i] <<= 2; ctx->qmatrix_c  [qscale]   [i] <<= 2;
172
            ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
173
            ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
174
        }
175
    }
176
    return 0;
177
 fail:
178
    return -1;
179
}
180

    
181
static int dnxhd_init_rc(DNXHDEncContext *ctx)
182
{
183
    CHECKED_ALLOCZ(ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry));
184
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
185
        CHECKED_ALLOCZ(ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry));
186

    
187
    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4) * 8;
188
    ctx->qscale = 1;
189
    ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
190
    return 0;
191
 fail:
192
    return -1;
193
}
194

    
195
static int dnxhd_encode_init(AVCodecContext *avctx)
196
{
197
    DNXHDEncContext *ctx = avctx->priv_data;
198
    int i, index;
199

    
200
    ctx->cid = ff_dnxhd_find_cid(avctx);
201
    if (!ctx->cid || avctx->pix_fmt != PIX_FMT_YUV422P) {
202
        av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
203
        return -1;
204
    }
205
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
206

    
207
    index = ff_dnxhd_get_cid_table(ctx->cid);
208
    ctx->cid_table = &ff_dnxhd_cid_table[index];
209

    
210
    ctx->m.avctx = avctx;
211
    ctx->m.mb_intra = 1;
212
    ctx->m.h263_aic = 1;
213

    
214
    dsputil_init(&ctx->m.dsp, avctx);
215
    ff_dct_common_init(&ctx->m);
216
    if (!ctx->m.dct_quantize)
217
        ctx->m.dct_quantize = dct_quantize_c;
218

    
219
    ctx->m.mb_height = (avctx->height + 15) / 16;
220
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
221

    
222
    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
223
        ctx->interlaced = 1;
224
        ctx->m.mb_height /= 2;
225
    }
226

    
227
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
228

    
229
    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
230
        ctx->m.intra_quant_bias = avctx->intra_quant_bias;
231
    if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
232
        return -1;
233

    
234
    if (dnxhd_init_vlc(ctx) < 0)
235
        return -1;
236
    if (dnxhd_init_rc(ctx) < 0)
237
        return -1;
238

    
239
    CHECKED_ALLOCZ(ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t));
240
    CHECKED_ALLOCZ(ctx->mb_bits,    ctx->m.mb_num   *sizeof(uint16_t));
241
    CHECKED_ALLOCZ(ctx->mb_qscale,  ctx->m.mb_num   *sizeof(uint8_t));
242

    
243
    ctx->frame.key_frame = 1;
244
    ctx->frame.pict_type = FF_I_TYPE;
245
    ctx->m.avctx->coded_frame = &ctx->frame;
246

    
247
    if (avctx->thread_count > MAX_THREADS || (avctx->thread_count > ctx->m.mb_height)) {
248
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
249
        return -1;
250
    }
251

    
252
    ctx->thread[0] = ctx;
253
    for (i = 1; i < avctx->thread_count; i++) {
254
        ctx->thread[i] =  av_malloc(sizeof(DNXHDEncContext));
255
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
256
    }
257

    
258
    for (i = 0; i < avctx->thread_count; i++) {
259
        ctx->thread[i]->m.start_mb_y = (ctx->m.mb_height*(i  ) + avctx->thread_count/2) / avctx->thread_count;
260
        ctx->thread[i]->m.end_mb_y   = (ctx->m.mb_height*(i+1) + avctx->thread_count/2) / avctx->thread_count;
261
    }
262

    
263
    return 0;
264
 fail: //for CHECKED_ALLOCZ
265
    return -1;
266
}
267

    
268
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
269
{
270
    DNXHDEncContext *ctx = avctx->priv_data;
271
    const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
272

    
273
    memcpy(buf, header_prefix, 5);
274
    buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
275
    buf[6] = 0x80; // crc flag off
276
    buf[7] = 0xa0; // reserved
277
    AV_WB16(buf + 0x18, avctx->height); // ALPF
278
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
279
    AV_WB16(buf + 0x1d, avctx->height); // NAL
280

    
281
    buf[0x21] = 0x38; // FIXME 8 bit per comp
282
    buf[0x22] = 0x88 + (ctx->frame.interlaced_frame<<2);
283
    AV_WB32(buf + 0x28, ctx->cid); // CID
284
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;
285

    
286
    buf[0x5f] = 0x01; // UDL
287

    
288
    buf[0x167] = 0x02; // reserved
289
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
290
    buf[0x16d] = ctx->m.mb_height; // Ns
291
    buf[0x16f] = 0x10; // reserved
292

    
293
    ctx->msip = buf + 0x170;
294
    return 0;
295
}
296

    
297
static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
298
{
299
    int nbits;
300
    if (diff < 0) {
301
        nbits = av_log2_16bit(-2*diff);
302
        diff--;
303
    } else {
304
        nbits = av_log2_16bit(2*diff);
305
    }
306
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
307
             (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
308
}
309

    
310
static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
311
{
312
    int last_non_zero = 0;
313
    int slevel, i, j;
314

    
315
    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
316
    ctx->m.last_dc[n] = block[0];
317

    
318
    for (i = 1; i <= last_index; i++) {
319
        j = ctx->m.intra_scantable.permutated[i];
320
        slevel = block[j];
321
        if (slevel) {
322
            int run_level = i - last_non_zero - 1;
323
            int rlevel = (slevel<<1)|!!run_level;
324
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
325
            if (run_level)
326
                put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
327
            last_non_zero = i;
328
        }
329
    }
330
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
331
}
332

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

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

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

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

    
371
static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
372
{
373
    int last_non_zero = 0;
374
    int bits = 0;
375
    int i, j, level;
376
    for (i = 1; i <= last_index; i++) {
377
        j = ctx->m.intra_scantable.permutated[i];
378
        level = block[j];
379
        if (level) {
380
            int run_level = i - last_non_zero - 1;
381
            bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
382
            last_non_zero = i;
383
        }
384
    }
385
    return bits;
386
}
387

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

    
405
static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
406
{
407
    const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize)   + (mb_x << 4);
408
    const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
409
    const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
410
    DSPContext *dsp = &ctx->m.dsp;
411

    
412
    dsp->get_pixels(ctx->blocks[0], ptr_y    , ctx->m.linesize);
413
    dsp->get_pixels(ctx->blocks[1], ptr_y + 8, ctx->m.linesize);
414
    dsp->get_pixels(ctx->blocks[2], ptr_u    , ctx->m.uvlinesize);
415
    dsp->get_pixels(ctx->blocks[3], ptr_v    , ctx->m.uvlinesize);
416

    
417
    if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
418
        if (ctx->interlaced) {
419
            dnxhd_get_pixels_4x8(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
420
            dnxhd_get_pixels_4x8(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
421
            dnxhd_get_pixels_4x8(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
422
            dnxhd_get_pixels_4x8(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
423
        } else {
424
            dsp->clear_block(ctx->blocks[4]); dsp->clear_block(ctx->blocks[5]);
425
            dsp->clear_block(ctx->blocks[6]); dsp->clear_block(ctx->blocks[7]);
426
        }
427
    } else {
428
        dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
429
        dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
430
        dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
431
        dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
432
    }
433
}
434

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

    
448
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg)
449
{
450
    DNXHDEncContext *ctx = *(void**)arg;
451
    int mb_y, mb_x;
452
    int qscale = ctx->thread[0]->qscale;
453

    
454
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
455
        ctx->m.last_dc[0] =
456
        ctx->m.last_dc[1] =
457
        ctx->m.last_dc[2] = 1024;
458

    
459
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
460
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
461
            int ssd     = 0;
462
            int ac_bits = 0;
463
            int dc_bits = 0;
464
            int i;
465

    
466
            dnxhd_get_blocks(ctx, mb_x, mb_y);
467

    
468
            for (i = 0; i < 8; i++) {
469
                DECLARE_ALIGNED_16(DCTELEM, block[64]);
470
                DCTELEM *src_block = ctx->blocks[i];
471
                int overflow, nbits, diff, last_index;
472
                int n = dnxhd_switch_matrix(ctx, i);
473

    
474
                memcpy(block, src_block, sizeof(block));
475
                last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
476
                ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
477

    
478
                diff = block[0] - ctx->m.last_dc[n];
479
                if (diff < 0) nbits = av_log2_16bit(-2*diff);
480
                else          nbits = av_log2_16bit( 2*diff);
481
                dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
482

    
483
                ctx->m.last_dc[n] = block[0];
484

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

    
498
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg)
499
{
500
    DNXHDEncContext *ctx = *(void**)arg;
501
    int mb_y, mb_x;
502

    
503
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
504
        ctx->m.last_dc[0] =
505
        ctx->m.last_dc[1] =
506
        ctx->m.last_dc[2] = 1024;
507
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
508
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
509
            int qscale = ctx->mb_qscale[mb];
510
            int i;
511

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

    
514
            dnxhd_get_blocks(ctx, mb_x, mb_y);
515

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

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

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

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

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

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

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

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

    
702
static int dnxhd_rc_cmp(const void *a, const void *b)
703
{
704
    return ((const RCCMPEntry *)b)->value - ((const RCCMPEntry *)a)->value;
705
}
706

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

    
744
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
745
{
746
    int i;
747

    
748
    for (i = 0; i < 3; i++) {
749
        ctx->frame.data[i]     = frame->data[i];
750
        ctx->frame.linesize[i] = frame->linesize[i];
751
    }
752

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

    
760
    ctx->frame.interlaced_frame = frame->interlaced_frame;
761
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
762
}
763

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

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

    
775
    dnxhd_load_picture(ctx, data);
776

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

    
784
    dnxhd_write_header(avctx, buf);
785

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

    
795
    dnxhd_setup_threads_slices(ctx, buf);
796

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

    
804
    avctx->execute(avctx, dnxhd_encode_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count, sizeof(void*));
805

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

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

    
816
    ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
817

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

    
821
static int dnxhd_encode_end(AVCodecContext *avctx)
822
{
823
    DNXHDEncContext *ctx = avctx->priv_data;
824
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
825
    int i;
826

    
827
    av_free(ctx->vlc_codes-max_level*2);
828
    av_free(ctx->vlc_bits -max_level*2);
829
    av_freep(&ctx->run_codes);
830
    av_freep(&ctx->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, PIX_FMT_NONE},
858
    .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
859
};