Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dnxhdenc.c @ 8c9c0ea4

History | View | Annotate | Download (27.6 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 "dnxhdenc.h"
31

    
32
int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
33

    
34
#define LAMBDA_FRAC_BITS 10
35

    
36
static int dnxhd_init_vlc(DNXHDEncContext *ctx)
37
{
38
    int i, j, level, run;
39
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
40

    
41
    CHECKED_ALLOCZ(ctx->vlc_codes, max_level*4*sizeof(*ctx->vlc_codes));
42
    CHECKED_ALLOCZ(ctx->vlc_bits,  max_level*4*sizeof(*ctx->vlc_bits));
43
    CHECKED_ALLOCZ(ctx->run_codes, 63*2);
44
    CHECKED_ALLOCZ(ctx->run_bits,    63);
45

    
46
    ctx->vlc_codes += max_level*2;
47
    ctx->vlc_bits  += max_level*2;
48
    for (level = -max_level; level < max_level; level++) {
49
        for (run = 0; run < 2; run++) {
50
            int index = (level<<1)|run;
51
            int sign, offset = 0, alevel = level;
52

    
53
            MASK_ABS(sign, alevel);
54
            if (alevel > 64) {
55
                offset = (alevel-1)>>6;
56
                alevel -= offset<<6;
57
            }
58
            for (j = 0; j < 257; j++) {
59
                if (ctx->cid_table->ac_level[j] == alevel &&
60
                    (!offset || (ctx->cid_table->ac_index_flag[j] && offset)) &&
61
                    (!run    || (ctx->cid_table->ac_run_flag  [j] && run))) {
62
                    assert(!ctx->vlc_codes[index]);
63
                    if (alevel) {
64
                        ctx->vlc_codes[index] = (ctx->cid_table->ac_codes[j]<<1)|(sign&1);
65
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits[j]+1;
66
                    } else {
67
                        ctx->vlc_codes[index] = ctx->cid_table->ac_codes[j];
68
                        ctx->vlc_bits [index] = ctx->cid_table->ac_bits [j];
69
                    }
70
                    break;
71
                }
72
            }
73
            assert(!alevel || j < 257);
74
            if (offset) {
75
                ctx->vlc_codes[index] = (ctx->vlc_codes[index]<<ctx->cid_table->index_bits)|offset;
76
                ctx->vlc_bits [index]+= ctx->cid_table->index_bits;
77
            }
78
        }
79
    }
80
    for (i = 0; i < 62; i++) {
81
        int run = ctx->cid_table->run[i];
82
        assert(run < 63);
83
        ctx->run_codes[run] = ctx->cid_table->run_codes[i];
84
        ctx->run_bits [run] = ctx->cid_table->run_bits[i];
85
    }
86
    return 0;
87
 fail:
88
    return -1;
89
}
90

    
91
static int dnxhd_init_qmat(DNXHDEncContext *ctx, int lbias, int cbias)
92
{
93
    // init first elem to 1 to avoid div by 0 in convert_matrix
94
    uint16_t weight_matrix[64] = {1,}; // convert_matrix needs uint16_t*
95
    int qscale, i;
96

    
97
    CHECKED_ALLOCZ(ctx->qmatrix_l,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
98
    CHECKED_ALLOCZ(ctx->qmatrix_c,   (ctx->m.avctx->qmax+1) * 64 * sizeof(int));
99
    CHECKED_ALLOCZ(ctx->qmatrix_l16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
100
    CHECKED_ALLOCZ(ctx->qmatrix_c16, (ctx->m.avctx->qmax+1) * 64 * 2 * sizeof(uint16_t));
101

    
102
    for (i = 1; i < 64; i++) {
103
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
104
        weight_matrix[j] = ctx->cid_table->luma_weight[i];
105
    }
106
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_l, ctx->qmatrix_l16, weight_matrix,
107
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
108
    for (i = 1; i < 64; i++) {
109
        int j = ctx->m.dsp.idct_permutation[ff_zigzag_direct[i]];
110
        weight_matrix[j] = ctx->cid_table->chroma_weight[i];
111
    }
112
    ff_convert_matrix(&ctx->m.dsp, ctx->qmatrix_c, ctx->qmatrix_c16, weight_matrix,
113
                      ctx->m.intra_quant_bias, 1, ctx->m.avctx->qmax, 1);
114
    for (qscale = 1; qscale <= ctx->m.avctx->qmax; qscale++) {
115
        for (i = 0; i < 64; i++) {
116
            ctx->qmatrix_l  [qscale]   [i] <<= 2; ctx->qmatrix_c  [qscale]   [i] <<= 2;
117
            ctx->qmatrix_l16[qscale][0][i] <<= 2; ctx->qmatrix_l16[qscale][1][i] <<= 2;
118
            ctx->qmatrix_c16[qscale][0][i] <<= 2; ctx->qmatrix_c16[qscale][1][i] <<= 2;
119
        }
120
    }
121
    return 0;
122
 fail:
123
    return -1;
124
}
125

    
126
static int dnxhd_init_rc(DNXHDEncContext *ctx)
127
{
128
    CHECKED_ALLOCZ(ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry));
129
    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)
130
        CHECKED_ALLOCZ(ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry));
131

    
132
    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4) * 8;
133
    ctx->qscale = 1;
134
    ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2
135
    return 0;
136
 fail:
137
    return -1;
138
}
139

    
140
static int dnxhd_encode_init(AVCodecContext *avctx)
141
{
142
    DNXHDEncContext *ctx = avctx->priv_data;
143
    int i, index;
144

    
145
    ctx->cid = ff_dnxhd_find_cid(avctx);
146
    if (!ctx->cid || avctx->pix_fmt != PIX_FMT_YUV422P) {
147
        av_log(avctx, AV_LOG_ERROR, "video parameters incompatible with DNxHD\n");
148
        return -1;
149
    }
150
    av_log(avctx, AV_LOG_DEBUG, "cid %d\n", ctx->cid);
151

    
152
    index = ff_dnxhd_get_cid_table(ctx->cid);
153
    ctx->cid_table = &ff_dnxhd_cid_table[index];
154

    
155
    ctx->m.avctx = avctx;
156
    ctx->m.mb_intra = 1;
157
    ctx->m.h263_aic = 1;
158

    
159
    dsputil_init(&ctx->m.dsp, avctx);
160
    ff_dct_common_init(&ctx->m);
161
    if (!ctx->m.dct_quantize)
162
        ctx->m.dct_quantize = dct_quantize_c;
163

    
164
    ctx->m.mb_height = (avctx->height + 15) / 16;
165
    ctx->m.mb_width  = (avctx->width  + 15) / 16;
166

    
167
    if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
168
        ctx->interlaced = 1;
169
        ctx->m.mb_height /= 2;
170
    }
171

    
172
    ctx->m.mb_num = ctx->m.mb_height * ctx->m.mb_width;
173

    
174
    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
175
        ctx->m.intra_quant_bias = avctx->intra_quant_bias;
176
    if (dnxhd_init_qmat(ctx, ctx->m.intra_quant_bias, 0) < 0) // XXX tune lbias/cbias
177
        return -1;
178

    
179
    if (dnxhd_init_vlc(ctx) < 0)
180
        return -1;
181
    if (dnxhd_init_rc(ctx) < 0)
182
        return -1;
183

    
184
    CHECKED_ALLOCZ(ctx->slice_size, ctx->m.mb_height*sizeof(uint32_t));
185
    CHECKED_ALLOCZ(ctx->mb_bits,    ctx->m.mb_num   *sizeof(uint16_t));
186
    CHECKED_ALLOCZ(ctx->mb_qscale,  ctx->m.mb_num   *sizeof(uint8_t));
187

    
188
    ctx->frame.key_frame = 1;
189
    ctx->frame.pict_type = FF_I_TYPE;
190
    ctx->m.avctx->coded_frame = &ctx->frame;
191

    
192
    if (avctx->thread_count > MAX_THREADS || (avctx->thread_count > ctx->m.mb_height)) {
193
        av_log(avctx, AV_LOG_ERROR, "too many threads\n");
194
        return -1;
195
    }
196

    
197
    ctx->thread[0] = ctx;
198
    for (i = 1; i < avctx->thread_count; i++) {
199
        ctx->thread[i] =  av_malloc(sizeof(DNXHDEncContext));
200
        memcpy(ctx->thread[i], ctx, sizeof(DNXHDEncContext));
201
    }
202

    
203
    for (i = 0; i < avctx->thread_count; i++) {
204
        ctx->thread[i]->m.start_mb_y = (ctx->m.mb_height*(i  ) + avctx->thread_count/2) / avctx->thread_count;
205
        ctx->thread[i]->m.end_mb_y   = (ctx->m.mb_height*(i+1) + avctx->thread_count/2) / avctx->thread_count;
206
    }
207

    
208
    return 0;
209
 fail: //for CHECKED_ALLOCZ
210
    return -1;
211
}
212

    
213
static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
214
{
215
    DNXHDEncContext *ctx = avctx->priv_data;
216
    const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
217

    
218
    memcpy(buf, header_prefix, 5);
219
    buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
220
    buf[6] = 0x80; // crc flag off
221
    buf[7] = 0xa0; // reserved
222
    AV_WB16(buf + 0x18, avctx->height); // ALPF
223
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
224
    AV_WB16(buf + 0x1d, avctx->height); // NAL
225

    
226
    buf[0x21] = 0x38; // FIXME 8 bit per comp
227
    buf[0x22] = 0x88 + (ctx->frame.interlaced_frame<<2);
228
    AV_WB32(buf + 0x28, ctx->cid); // CID
229
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;
230

    
231
    buf[0x5f] = 0x01; // UDL
232

    
233
    buf[0x167] = 0x02; // reserved
234
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
235
    buf[0x16d] = ctx->m.mb_height; // Ns
236
    buf[0x16f] = 0x10; // reserved
237

    
238
    ctx->msip = buf + 0x170;
239
    return 0;
240
}
241

    
242
static av_always_inline void dnxhd_encode_dc(DNXHDEncContext *ctx, int diff)
243
{
244
    int nbits;
245
    if (diff < 0) {
246
        nbits = av_log2_16bit(-2*diff);
247
        diff--;
248
    } else {
249
        nbits = av_log2_16bit(2*diff);
250
    }
251
    put_bits(&ctx->m.pb, ctx->cid_table->dc_bits[nbits] + nbits,
252
             (ctx->cid_table->dc_codes[nbits]<<nbits) + (diff & ((1 << nbits) - 1)));
253
}
254

    
255
static av_always_inline void dnxhd_encode_block(DNXHDEncContext *ctx, DCTELEM *block, int last_index, int n)
256
{
257
    int last_non_zero = 0;
258
    int slevel, i, j;
259

    
260
    dnxhd_encode_dc(ctx, block[0] - ctx->m.last_dc[n]);
261
    ctx->m.last_dc[n] = block[0];
262

    
263
    for (i = 1; i <= last_index; i++) {
264
        j = ctx->m.intra_scantable.permutated[i];
265
        slevel = block[j];
266
        if (slevel) {
267
            int run_level = i - last_non_zero - 1;
268
            int rlevel = (slevel<<1)|!!run_level;
269
            put_bits(&ctx->m.pb, ctx->vlc_bits[rlevel], ctx->vlc_codes[rlevel]);
270
            if (run_level)
271
                put_bits(&ctx->m.pb, ctx->run_bits[run_level], ctx->run_codes[run_level]);
272
            last_non_zero = i;
273
        }
274
    }
275
    put_bits(&ctx->m.pb, ctx->vlc_bits[0], ctx->vlc_codes[0]); // EOB
276
}
277

    
278
static av_always_inline void dnxhd_unquantize_c(DNXHDEncContext *ctx, DCTELEM *block, int n, int qscale, int last_index)
279
{
280
    const uint8_t *weight_matrix;
281
    int level;
282
    int i;
283

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

    
286
    for (i = 1; i <= last_index; i++) {
287
        int j = ctx->m.intra_scantable.permutated[i];
288
        level = block[j];
289
        if (level) {
290
            if (level < 0) {
291
                level = (1-2*level) * qscale * weight_matrix[i];
292
                if (weight_matrix[i] != 32)
293
                    level += 32;
294
                level >>= 6;
295
                level = -level;
296
            } else {
297
                level = (2*level+1) * qscale * weight_matrix[i];
298
                if (weight_matrix[i] != 32)
299
                    level += 32;
300
                level >>= 6;
301
            }
302
            block[j] = level;
303
        }
304
    }
305
}
306

    
307
static av_always_inline int dnxhd_ssd_block(DCTELEM *qblock, DCTELEM *block)
308
{
309
    int score = 0;
310
    int i;
311
    for (i = 0; i < 64; i++)
312
        score += (block[i]-qblock[i])*(block[i]-qblock[i]);
313
    return score;
314
}
315

    
316
static av_always_inline int dnxhd_calc_ac_bits(DNXHDEncContext *ctx, DCTELEM *block, int last_index)
317
{
318
    int last_non_zero = 0;
319
    int bits = 0;
320
    int i, j, level;
321
    for (i = 1; i <= last_index; i++) {
322
        j = ctx->m.intra_scantable.permutated[i];
323
        level = block[j];
324
        if (level) {
325
            int run_level = i - last_non_zero - 1;
326
            bits += ctx->vlc_bits[(level<<1)|!!run_level]+ctx->run_bits[run_level];
327
            last_non_zero = i;
328
        }
329
    }
330
    return bits;
331
}
332

    
333
static av_always_inline void dnxhd_get_pixels_8x4(DCTELEM *restrict block, const uint8_t *pixels, int line_size)
334
{
335
    int i;
336
    for (i = 0; i < 4; i++) {
337
        block[0] = pixels[0]; block[1] = pixels[1];
338
        block[2] = pixels[2]; block[3] = pixels[3];
339
        block[4] = pixels[4]; block[5] = pixels[5];
340
        block[6] = pixels[6]; block[7] = pixels[7];
341
        pixels += line_size;
342
        block += 8;
343
    }
344
    memcpy(block   , block- 8, sizeof(*block)*8);
345
    memcpy(block+ 8, block-16, sizeof(*block)*8);
346
    memcpy(block+16, block-24, sizeof(*block)*8);
347
    memcpy(block+24, block-32, sizeof(*block)*8);
348
}
349

    
350
static av_always_inline void dnxhd_get_blocks(DNXHDEncContext *ctx, int mb_x, int mb_y)
351
{
352
    const uint8_t *ptr_y = ctx->thread[0]->src[0] + ((mb_y << 4) * ctx->m.linesize)   + (mb_x << 4);
353
    const uint8_t *ptr_u = ctx->thread[0]->src[1] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
354
    const uint8_t *ptr_v = ctx->thread[0]->src[2] + ((mb_y << 4) * ctx->m.uvlinesize) + (mb_x << 3);
355
    DSPContext *dsp = &ctx->m.dsp;
356

    
357
    dsp->get_pixels(ctx->blocks[0], ptr_y    , ctx->m.linesize);
358
    dsp->get_pixels(ctx->blocks[1], ptr_y + 8, ctx->m.linesize);
359
    dsp->get_pixels(ctx->blocks[2], ptr_u    , ctx->m.uvlinesize);
360
    dsp->get_pixels(ctx->blocks[3], ptr_v    , ctx->m.uvlinesize);
361

    
362
    if (mb_y+1 == ctx->m.mb_height && ctx->m.avctx->height == 1080) {
363
        if (ctx->interlaced) {
364
            dnxhd_get_pixels_8x4(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
365
            dnxhd_get_pixels_8x4(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
366
            dnxhd_get_pixels_8x4(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
367
            dnxhd_get_pixels_8x4(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
368
        } else {
369
            dsp->clear_block(ctx->blocks[4]); dsp->clear_block(ctx->blocks[5]);
370
            dsp->clear_block(ctx->blocks[6]); dsp->clear_block(ctx->blocks[7]);
371
        }
372
    } else {
373
        dsp->get_pixels(ctx->blocks[4], ptr_y + ctx->dct_y_offset    , ctx->m.linesize);
374
        dsp->get_pixels(ctx->blocks[5], ptr_y + ctx->dct_y_offset + 8, ctx->m.linesize);
375
        dsp->get_pixels(ctx->blocks[6], ptr_u + ctx->dct_uv_offset   , ctx->m.uvlinesize);
376
        dsp->get_pixels(ctx->blocks[7], ptr_v + ctx->dct_uv_offset   , ctx->m.uvlinesize);
377
    }
378
}
379

    
380
static av_always_inline int dnxhd_switch_matrix(DNXHDEncContext *ctx, int i)
381
{
382
    if (i&2) {
383
        ctx->m.q_intra_matrix16 = ctx->qmatrix_c16;
384
        ctx->m.q_intra_matrix   = ctx->qmatrix_c;
385
        return 1 + (i&1);
386
    } else {
387
        ctx->m.q_intra_matrix16 = ctx->qmatrix_l16;
388
        ctx->m.q_intra_matrix   = ctx->qmatrix_l;
389
        return 0;
390
    }
391
}
392

    
393
static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg)
394
{
395
    DNXHDEncContext *ctx = *(void**)arg;
396
    int mb_y, mb_x;
397
    int qscale = ctx->thread[0]->qscale;
398

    
399
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
400
        ctx->m.last_dc[0] =
401
        ctx->m.last_dc[1] =
402
        ctx->m.last_dc[2] = 1024;
403

    
404
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
405
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
406
            int ssd     = 0;
407
            int ac_bits = 0;
408
            int dc_bits = 0;
409
            int i;
410

    
411
            dnxhd_get_blocks(ctx, mb_x, mb_y);
412

    
413
            for (i = 0; i < 8; i++) {
414
                DECLARE_ALIGNED_16(DCTELEM, block[64]);
415
                DCTELEM *src_block = ctx->blocks[i];
416
                int overflow, nbits, diff, last_index;
417
                int n = dnxhd_switch_matrix(ctx, i);
418

    
419
                memcpy(block, src_block, sizeof(block));
420
                last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
421
                ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
422

    
423
                diff = block[0] - ctx->m.last_dc[n];
424
                if (diff < 0) nbits = av_log2_16bit(-2*diff);
425
                else          nbits = av_log2_16bit( 2*diff);
426
                dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
427

    
428
                ctx->m.last_dc[n] = block[0];
429

    
430
                if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
431
                    dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
432
                    ctx->m.dsp.idct(block);
433
                    ssd += dnxhd_ssd_block(block, src_block);
434
                }
435
            }
436
            ctx->mb_rc[qscale][mb].ssd = ssd;
437
            ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
438
        }
439
    }
440
    return 0;
441
}
442

    
443
static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg)
444
{
445
    DNXHDEncContext *ctx = *(void**)arg;
446
    int mb_y, mb_x;
447

    
448
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
449
        ctx->m.last_dc[0] =
450
        ctx->m.last_dc[1] =
451
        ctx->m.last_dc[2] = 1024;
452
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
453
            unsigned mb = mb_y * ctx->m.mb_width + mb_x;
454
            int qscale = ctx->mb_qscale[mb];
455
            int i;
456

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

    
459
            dnxhd_get_blocks(ctx, mb_x, mb_y);
460

    
461
            for (i = 0; i < 8; i++) {
462
                DCTELEM *block = ctx->blocks[i];
463
                int last_index, overflow;
464
                int n = dnxhd_switch_matrix(ctx, i);
465
                last_index = ctx->m.dct_quantize((MpegEncContext*)ctx, block, i, qscale, &overflow);
466
                //START_TIMER;
467
                dnxhd_encode_block(ctx, block, last_index, n);
468
                //STOP_TIMER("encode_block");
469
            }
470
        }
471
        if (put_bits_count(&ctx->m.pb)&31)
472
            put_bits(&ctx->m.pb, 32-(put_bits_count(&ctx->m.pb)&31), 0);
473
    }
474
    flush_put_bits(&ctx->m.pb);
475
    return 0;
476
}
477

    
478
static void dnxhd_setup_threads_slices(DNXHDEncContext *ctx, uint8_t *buf)
479
{
480
    int mb_y, mb_x;
481
    int i, offset = 0;
482
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
483
        int thread_size = 0;
484
        for (mb_y = ctx->thread[i]->m.start_mb_y; mb_y < ctx->thread[i]->m.end_mb_y; mb_y++) {
485
            ctx->slice_size[mb_y] = 0;
486
            for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
487
                unsigned mb = mb_y * ctx->m.mb_width + mb_x;
488
                ctx->slice_size[mb_y] += ctx->mb_bits[mb];
489
            }
490
            ctx->slice_size[mb_y] = (ctx->slice_size[mb_y]+31)&~31;
491
            ctx->slice_size[mb_y] >>= 3;
492
            thread_size += ctx->slice_size[mb_y];
493
        }
494
        init_put_bits(&ctx->thread[i]->m.pb, buf + 640 + offset, thread_size);
495
        offset += thread_size;
496
    }
497
}
498

    
499
static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg)
500
{
501
    DNXHDEncContext *ctx = *(void**)arg;
502
    int mb_y, mb_x;
503
    for (mb_y = ctx->m.start_mb_y; mb_y < ctx->m.end_mb_y; mb_y++) {
504
        for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
505
            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;
506
            uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize) + (mb_x<<4);
507
            int sum      = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);
508
            int varc     = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)(sum*sum))>>8)+128)>>8;
509
            ctx->mb_cmp[mb].value = varc;
510
            ctx->mb_cmp[mb].mb = mb;
511
        }
512
    }
513
    return 0;
514
}
515

    
516
static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)
517
{
518
    int lambda, up_step, down_step;
519
    int last_lower = INT_MAX, last_higher = 0;
520
    int x, y, q;
521

    
522
    for (q = 1; q < avctx->qmax; q++) {
523
        ctx->qscale = q;
524
        avctx->execute(avctx, dnxhd_calc_bits_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count, sizeof(void*));
525
    }
526
    up_step = down_step = 2<<LAMBDA_FRAC_BITS;
527
    lambda = ctx->lambda;
528

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

    
589
static int dnxhd_find_qscale(DNXHDEncContext *ctx)
590
{
591
    int bits = 0;
592
    int up_step = 1;
593
    int down_step = 1;
594
    int last_higher = 0;
595
    int last_lower = INT_MAX;
596
    int qscale;
597
    int x, y;
598

    
599
    qscale = ctx->qscale;
600
    for (;;) {
601
        bits = 0;
602
        ctx->qscale = qscale;
603
        // XXX avoid recalculating bits
604
        ctx->m.avctx->execute(ctx->m.avctx, dnxhd_calc_bits_thread, (void**)&ctx->thread[0], NULL, ctx->m.avctx->thread_count, sizeof(void*));
605
        for (y = 0; y < ctx->m.mb_height; y++) {
606
            for (x = 0; x < ctx->m.mb_width; x++)
607
                bits += ctx->mb_rc[qscale][y*ctx->m.mb_width+x].bits;
608
            bits = (bits+31)&~31; // padding
609
            if (bits > ctx->frame_bits)
610
                break;
611
        }
612
        //dprintf(ctx->m.avctx, "%d, qscale %d, bits %d, frame %d, higher %d, lower %d\n",
613
        //        ctx->m.avctx->frame_number, qscale, bits, ctx->frame_bits, last_higher, last_lower);
614
        if (bits < ctx->frame_bits) {
615
            if (qscale == 1)
616
                return 1;
617
            if (last_higher == qscale - 1) {
618
                qscale = last_higher;
619
                break;
620
            }
621
            last_lower = FFMIN(qscale, last_lower);
622
            if (last_higher != 0)
623
                qscale = (qscale+last_higher)>>1;
624
            else
625
                qscale -= down_step++;
626
            if (qscale < 1)
627
                qscale = 1;
628
            up_step = 1;
629
        } else {
630
            if (last_lower == qscale + 1)
631
                break;
632
            last_higher = FFMAX(qscale, last_higher);
633
            if (last_lower != INT_MAX)
634
                qscale = (qscale+last_lower)>>1;
635
            else
636
                qscale += up_step++;
637
            down_step = 1;
638
            if (qscale >= ctx->m.avctx->qmax)
639
                return -1;
640
        }
641
    }
642
    //dprintf(ctx->m.avctx, "out qscale %d\n", qscale);
643
    ctx->qscale = qscale;
644
    return 0;
645
}
646

    
647
static int dnxhd_rc_cmp(const void *a, const void *b)
648
{
649
    return ((const RCCMPEntry *)b)->value - ((const RCCMPEntry *)a)->value;
650
}
651

    
652
static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)
653
{
654
    int max_bits = 0;
655
    int ret, x, y;
656
    if ((ret = dnxhd_find_qscale(ctx)) < 0)
657
        return -1;
658
    for (y = 0; y < ctx->m.mb_height; y++) {
659
        for (x = 0; x < ctx->m.mb_width; x++) {
660
            int mb = y*ctx->m.mb_width+x;
661
            int delta_bits;
662
            ctx->mb_qscale[mb] = ctx->qscale;
663
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale][mb].bits;
664
            max_bits += ctx->mb_rc[ctx->qscale][mb].bits;
665
            if (!RC_VARIANCE) {
666
                delta_bits = ctx->mb_rc[ctx->qscale][mb].bits-ctx->mb_rc[ctx->qscale+1][mb].bits;
667
                ctx->mb_cmp[mb].mb = mb;
668
                ctx->mb_cmp[mb].value = delta_bits ?
669
                    ((ctx->mb_rc[ctx->qscale][mb].ssd-ctx->mb_rc[ctx->qscale+1][mb].ssd)*100)/delta_bits
670
                    : INT_MIN; //avoid increasing qscale
671
            }
672
        }
673
        max_bits += 31; //worst padding
674
    }
675
    if (!ret) {
676
        if (RC_VARIANCE)
677
            avctx->execute(avctx, dnxhd_mb_var_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count, sizeof(void*));
678
        qsort(ctx->mb_cmp, ctx->m.mb_num, sizeof(RCEntry), dnxhd_rc_cmp);
679
        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {
680
            int mb = ctx->mb_cmp[x].mb;
681
            max_bits -= ctx->mb_rc[ctx->qscale][mb].bits - ctx->mb_rc[ctx->qscale+1][mb].bits;
682
            ctx->mb_qscale[mb] = ctx->qscale+1;
683
            ctx->mb_bits[mb] = ctx->mb_rc[ctx->qscale+1][mb].bits;
684
        }
685
    }
686
    return 0;
687
}
688

    
689
static void dnxhd_load_picture(DNXHDEncContext *ctx, const AVFrame *frame)
690
{
691
    int i;
692

    
693
    for (i = 0; i < 3; i++) {
694
        ctx->frame.data[i]     = frame->data[i];
695
        ctx->frame.linesize[i] = frame->linesize[i];
696
    }
697

    
698
    for (i = 0; i < ctx->m.avctx->thread_count; i++) {
699
        ctx->thread[i]->m.linesize    = ctx->frame.linesize[0]<<ctx->interlaced;
700
        ctx->thread[i]->m.uvlinesize  = ctx->frame.linesize[1]<<ctx->interlaced;
701
        ctx->thread[i]->dct_y_offset  = ctx->m.linesize  *8;
702
        ctx->thread[i]->dct_uv_offset = ctx->m.uvlinesize*8;
703
    }
704

    
705
    ctx->frame.interlaced_frame = frame->interlaced_frame;
706
    ctx->cur_field = frame->interlaced_frame && !frame->top_field_first;
707
}
708

    
709
static int dnxhd_encode_picture(AVCodecContext *avctx, unsigned char *buf, int buf_size, const void *data)
710
{
711
    DNXHDEncContext *ctx = avctx->priv_data;
712
    int first_field = 1;
713
    int offset, i, ret;
714

    
715
    if (buf_size < ctx->cid_table->frame_size) {
716
        av_log(avctx, AV_LOG_ERROR, "output buffer is too small to compress picture\n");
717
        return -1;
718
    }
719

    
720
    dnxhd_load_picture(ctx, data);
721

    
722
 encode_coding_unit:
723
    for (i = 0; i < 3; i++) {
724
        ctx->src[i] = ctx->frame.data[i];
725
        if (ctx->interlaced && ctx->cur_field)
726
            ctx->src[i] += ctx->frame.linesize[i];
727
    }
728

    
729
    dnxhd_write_header(avctx, buf);
730

    
731
    if (avctx->mb_decision == FF_MB_DECISION_RD)
732
        ret = dnxhd_encode_rdo(avctx, ctx);
733
    else
734
        ret = dnxhd_encode_fast(avctx, ctx);
735
    if (ret < 0) {
736
        av_log(avctx, AV_LOG_ERROR, "picture could not fit ratecontrol constraints\n");
737
        return -1;
738
    }
739

    
740
    dnxhd_setup_threads_slices(ctx, buf);
741

    
742
    offset = 0;
743
    for (i = 0; i < ctx->m.mb_height; i++) {
744
        AV_WB32(ctx->msip + i * 4, offset);
745
        offset += ctx->slice_size[i];
746
        assert(!(ctx->slice_size[i] & 3));
747
    }
748

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

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

    
753
    if (ctx->interlaced && first_field) {
754
        first_field     = 0;
755
        ctx->cur_field ^= 1;
756
        buf      += ctx->cid_table->coding_unit_size;
757
        buf_size -= ctx->cid_table->coding_unit_size;
758
        goto encode_coding_unit;
759
    }
760

    
761
    ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA;
762

    
763
    return ctx->cid_table->frame_size;
764
}
765

    
766
static int dnxhd_encode_end(AVCodecContext *avctx)
767
{
768
    DNXHDEncContext *ctx = avctx->priv_data;
769
    int max_level = 1<<(ctx->cid_table->bit_depth+2);
770
    int i;
771

    
772
    av_free(ctx->vlc_codes-max_level*2);
773
    av_free(ctx->vlc_bits -max_level*2);
774
    av_freep(&ctx->run_codes);
775
    av_freep(&ctx->run_bits);
776

    
777
    av_freep(&ctx->mb_bits);
778
    av_freep(&ctx->mb_qscale);
779
    av_freep(&ctx->mb_rc);
780
    av_freep(&ctx->mb_cmp);
781
    av_freep(&ctx->slice_size);
782

    
783
    av_freep(&ctx->qmatrix_c);
784
    av_freep(&ctx->qmatrix_l);
785
    av_freep(&ctx->qmatrix_c16);
786
    av_freep(&ctx->qmatrix_l16);
787

    
788
    for (i = 1; i < avctx->thread_count; i++)
789
        av_freep(&ctx->thread[i]);
790

    
791
    return 0;
792
}
793

    
794
AVCodec dnxhd_encoder = {
795
    "dnxhd",
796
    CODEC_TYPE_VIDEO,
797
    CODEC_ID_DNXHD,
798
    sizeof(DNXHDEncContext),
799
    dnxhd_encode_init,
800
    dnxhd_encode_picture,
801
    dnxhd_encode_end,
802
    .pix_fmts = (enum PixelFormat[]){PIX_FMT_YUV422P, PIX_FMT_NONE},
803
    .long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
804
};