Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dv.c @ 4fa1c4fa

History | View | Annotate | Download (27.7 KB)

1
/*
2
 * DV decoder
3
 * Copyright (c) 2002 Fabrice Bellard.
4
 *
5
 * DV encoder 
6
 * Copyright (c) 2003 Roman Shaposhnik.
7
 *
8
 * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
9
 * of DV technical info.
10
 *
11
 * This library is free software; you can redistribute it and/or
12
 * modify it under the terms of the GNU Lesser General Public
13
 * License as published by the Free Software Foundation; either
14
 * version 2 of the License, or (at your option) any later version.
15
 *
16
 * This library is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
 * Lesser General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Lesser General Public
22
 * License along with this library; if not, write to the Free Software
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
 */
25

    
26
/**
27
 * @file dv.c
28
 * DV codec.
29
 */
30
#include "avcodec.h"
31
#include "dsputil.h"
32
#include "mpegvideo.h"
33
#include "simple_idct.h"
34
#include "dvdata.h"
35

    
36
typedef struct DVVideoDecodeContext {
37
    const DVprofile* sys;
38
    GetBitContext gb;
39
    AVFrame picture;
40
    DCTELEM block[5*6][64] __align8;
41
    
42
    /* FIXME: the following is extracted from DSP */
43
    uint8_t dv_zigzag[2][64];
44
    uint8_t idct_permutation[64];
45
    void (*get_pixels)(DCTELEM *block, const uint8_t *pixels, int line_size);
46
    void (*fdct)(DCTELEM *block);
47
    
48
    /* XXX: move it to static storage ? */
49
    uint8_t dv_shift[2][22][64];
50
    void (*idct_put[2])(uint8_t *dest, int line_size, DCTELEM *block);
51
} DVVideoDecodeContext;
52

    
53
#define TEX_VLC_BITS 9
54
/* XXX: also include quantization */
55
static RL_VLC_ELEM *dv_rl_vlc[1];
56
static VLC_TYPE dv_vlc_codes[15][23];
57

    
58
static void dv_build_unquantize_tables(DVVideoDecodeContext *s)
59
{
60
    int i, q, j;
61

    
62
    /* NOTE: max left shift is 6 */
63
    for(q = 0; q < 22; q++) {
64
        /* 88 unquant */
65
        for(i = 1; i < 64; i++) {
66
            /* 88 table */
67
            j = s->idct_permutation[i];
68
            s->dv_shift[0][q][j] =
69
                dv_quant_shifts[q][dv_88_areas[i]] + 1;
70
        }
71
        
72
        /* 248 unquant */
73
        for(i = 1; i < 64; i++) {
74
            /* 248 table */
75
            s->dv_shift[1][q][i] =  
76
                    dv_quant_shifts[q][dv_248_areas[i]] + 1;
77
        }
78
    }
79
}
80

    
81
static int dvvideo_init(AVCodecContext *avctx)
82
{
83
    DVVideoDecodeContext *s = avctx->priv_data;
84
    MpegEncContext s2;
85
    static int done=0;
86

    
87
    if (!done) {
88
        int i;
89
        VLC dv_vlc;
90

    
91
        done = 1;
92

    
93
        /* NOTE: as a trick, we use the fact the no codes are unused
94
           to accelerate the parsing of partial codes */
95
        init_vlc(&dv_vlc, TEX_VLC_BITS, NB_DV_VLC, 
96
                 dv_vlc_len, 1, 1, dv_vlc_bits, 2, 2);
97

    
98
        dv_rl_vlc[0] = av_malloc(dv_vlc.table_size * sizeof(RL_VLC_ELEM));
99
        for(i = 0; i < dv_vlc.table_size; i++){
100
            int code= dv_vlc.table[i][0];
101
            int len = dv_vlc.table[i][1];
102
            int level, run;
103
        
104
            if(len<0){ //more bits needed
105
                run= 0;
106
                level= code;
107
            } else if (code == (NB_DV_VLC - 1)) {
108
                /* EOB */
109
                run = 0;
110
                level = 256;
111
            } else {
112
                run=   dv_vlc_run[code] + 1;
113
                level= dv_vlc_level[code];
114
            }
115
            dv_rl_vlc[0][i].len = len;
116
            dv_rl_vlc[0][i].level = level;
117
            dv_rl_vlc[0][i].run = run;
118
        }
119

    
120
        memset(dv_vlc_codes, 0xff, sizeof(dv_vlc_codes));
121
        for (i = 0; i < NB_DV_VLC - 1; i++) {
122
           if (dv_vlc_run[i] < 15 && dv_vlc_level[i] < 23 && dv_vlc_len[i] < 15)
123
               dv_vlc_codes[dv_vlc_run[i]][dv_vlc_level[i]] = i;
124
        }
125
    }
126

    
127
    /* ugly way to get the idct & scantable */
128
    /* XXX: fix it */
129
    memset(&s2, 0, sizeof(MpegEncContext));
130
    s2.avctx = avctx;
131
    dsputil_init(&s2.dsp, avctx);
132
    if (DCT_common_init(&s2) < 0)
133
       return -1;
134

    
135
    s->get_pixels = s2.dsp.get_pixels;
136
    s->fdct = s2.dsp.fdct;
137
    
138
    s->idct_put[0] = s2.dsp.idct_put;
139
    memcpy(s->idct_permutation, s2.dsp.idct_permutation, 64);
140
    memcpy(s->dv_zigzag[0], s2.intra_scantable.permutated, 64);
141

    
142
    /* XXX: use MMX also for idct248 */
143
    s->idct_put[1] = simple_idct248_put;
144
    memcpy(s->dv_zigzag[1], dv_248_zigzag, 64);
145

    
146
    /* XXX: do it only for constant case */
147
    dv_build_unquantize_tables(s);
148

    
149
    /* FIXME: I really don't think this should be here */
150
    if (dv_codec_profile(avctx))
151
        avctx->pix_fmt = dv_codec_profile(avctx)->pix_fmt; 
152
    
153
    return 0;
154
}
155

    
156
// #define VLC_DEBUG
157

    
158
typedef struct BlockInfo {
159
    const uint8_t *shift_table;
160
    const uint8_t *scan_table;
161
    uint8_t pos; /* position in block */
162
    uint8_t eob_reached; /* true if EOB has been reached */
163
    uint8_t dct_mode;
164
    uint8_t partial_bit_count;
165
    uint16_t partial_bit_buffer;
166
    int shift_offset;
167
} BlockInfo;
168

    
169
/* block size in bits */
170
static const uint16_t block_sizes[6] = {
171
    112, 112, 112, 112, 80, 80
172
};
173

    
174
#ifndef ALT_BITSTREAM_READER
175
#warning only works with ALT_BITSTREAM_READER
176
#endif
177

    
178
/* decode ac coefs */
179
static void dv_decode_ac(DVVideoDecodeContext *s, 
180
                         BlockInfo *mb, DCTELEM *block, int last_index)
181
{
182
    int last_re_index;
183
    int shift_offset = mb->shift_offset;
184
    const uint8_t *scan_table = mb->scan_table;
185
    const uint8_t *shift_table = mb->shift_table;
186
    int pos = mb->pos;
187
    int level, pos1, sign, run;
188
    int partial_bit_count;
189
#ifndef ALT_BITSTREAM_READER //FIXME
190
    int re_index=0; 
191
    int re1_index=0;
192
#endif
193
    OPEN_READER(re, &s->gb);
194
    
195
#ifdef VLC_DEBUG
196
    printf("start\n");
197
#endif
198

    
199
    /* if we must parse a partial vlc, we do it here */
200
    partial_bit_count = mb->partial_bit_count;
201
    if (partial_bit_count > 0) {
202
        uint8_t buf[4];
203
        uint32_t v;
204
        int l, l1;
205
        GetBitContext gb1;
206

    
207
        /* build the dummy bit buffer */
208
        l = 16 - partial_bit_count;
209
        UPDATE_CACHE(re, &s->gb);
210
#ifdef VLC_DEBUG
211
        printf("show=%04x\n", SHOW_UBITS(re, &s->gb, 16));
212
#endif
213
        v = (mb->partial_bit_buffer << l) | SHOW_UBITS(re, &s->gb, l);
214
        buf[0] = v >> 8;
215
        buf[1] = v;
216
#ifdef VLC_DEBUG
217
        printf("v=%04x cnt=%d %04x\n", 
218
               v, partial_bit_count, (mb->partial_bit_buffer << l));
219
#endif
220
        /* try to read the codeword */
221
        init_get_bits(&gb1, buf, 4*8);
222
        {
223
            OPEN_READER(re1, &gb1);
224
            UPDATE_CACHE(re1, &gb1);
225
            GET_RL_VLC(level, run, re1, &gb1, dv_rl_vlc[0], 
226
                       TEX_VLC_BITS, 2);
227
            l = re1_index;
228
            CLOSE_READER(re1, &gb1);
229
        }
230
#ifdef VLC_DEBUG
231
        printf("****run=%d level=%d size=%d\n", run, level, l);
232
#endif
233
        /* compute codeword length */
234
        l1 = (level != 256 && level != 0);
235
        /* if too long, we cannot parse */
236
        l -= partial_bit_count;
237
        if ((re_index + l + l1) > last_index)
238
            return;
239
        /* skip read bits */
240
        last_re_index = 0; /* avoid warning */
241
        re_index += l;
242
        /* by definition, if we can read the vlc, all partial bits
243
           will be read (otherwise we could have read the vlc before) */
244
        mb->partial_bit_count = 0;
245
        UPDATE_CACHE(re, &s->gb);
246
        goto handle_vlc;
247
    }
248

    
249
    /* get the AC coefficients until last_index is reached */
250
    for(;;) {
251
        UPDATE_CACHE(re, &s->gb);
252
#ifdef VLC_DEBUG
253
        printf("%2d: bits=%04x index=%d\n", 
254
               pos, SHOW_UBITS(re, &s->gb, 16), re_index);
255
#endif
256
        last_re_index = re_index;
257
        GET_RL_VLC(level, run, re, &s->gb, dv_rl_vlc[0], 
258
                   TEX_VLC_BITS, 2);
259
    handle_vlc:
260
#ifdef VLC_DEBUG
261
        printf("run=%d level=%d\n", run, level);
262
#endif
263
        if (level == 256) {
264
            if (re_index > last_index) {
265
            cannot_read:
266
                /* put position before read code */
267
                re_index = last_re_index;
268
                mb->eob_reached = 0;
269
                break;
270
            }
271
            /* EOB */
272
            mb->eob_reached = 1;
273
            break;
274
        } else if (level != 0) {
275
            if ((re_index + 1) > last_index)
276
                goto cannot_read;
277
            sign = SHOW_SBITS(re, &s->gb, 1);
278
            level = (level ^ sign) - sign;
279
            LAST_SKIP_BITS(re, &s->gb, 1);
280
            pos += run;
281
            /* error */
282
            if (pos >= 64) {
283
                goto read_error;
284
            }
285
            pos1 = scan_table[pos];
286
            level = level << (shift_table[pos1] + shift_offset);
287
            block[pos1] = level;
288
            //            printf("run=%d level=%d shift=%d\n", run, level, shift_table[pos1]);
289
        } else {
290
            if (re_index > last_index)
291
                goto cannot_read;
292
            /* level is zero: means run without coding. No
293
               sign is coded */
294
            pos += run;
295
            /* error */
296
            if (pos >= 64) {
297
            read_error:
298
#if defined(VLC_DEBUG) || 1
299
                fprintf(stderr, "error pos=%d\n", pos);
300
#endif
301
                /* for errors, we consider the eob is reached */
302
                mb->eob_reached = 1;
303
                break;
304
            }
305
        }
306
    }
307
    CLOSE_READER(re, &s->gb);
308
    mb->pos = pos;
309
}
310

    
311
static inline void bit_copy(PutBitContext *pb, GetBitContext *gb, int bits_left)
312
{
313
    while (bits_left >= 16) {
314
        put_bits(pb, 16, get_bits(gb, 16));
315
        bits_left -= 16;
316
    }
317
    if (bits_left > 0) {
318
        put_bits(pb, bits_left, get_bits(gb, bits_left));
319
    }
320
}
321

    
322
/* mb_x and mb_y are in units of 8 pixels */
323
static inline void dv_decode_video_segment(DVVideoDecodeContext *s, 
324
                                           uint8_t *buf_ptr1, 
325
                                           const uint16_t *mb_pos_ptr)
326
{
327
    int quant, dc, dct_mode, class1, j;
328
    int mb_index, mb_x, mb_y, v, last_index;
329
    DCTELEM *block, *block1;
330
    int c_offset, bits_left;
331
    uint8_t *y_ptr;
332
    BlockInfo mb_data[5 * 6], *mb, *mb1;
333
    void (*idct_put)(uint8_t *dest, int line_size, DCTELEM *block);
334
    uint8_t *buf_ptr;
335
    PutBitContext pb, vs_pb;
336
    uint8_t mb_bit_buffer[80 + 4]; /* allow some slack */
337
    int mb_bit_count;
338
    uint8_t vs_bit_buffer[5 * 80 + 4]; /* allow some slack */
339
    int vs_bit_count;
340
    
341
    memset(s->block, 0, sizeof(s->block));
342

    
343
    /* pass 1 : read DC and AC coefficients in blocks */
344
    buf_ptr = buf_ptr1;
345
    block1 = &s->block[0][0];
346
    mb1 = mb_data;
347
    init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80, NULL, NULL);
348
    vs_bit_count = 0;
349
    for(mb_index = 0; mb_index < 5; mb_index++) {
350
        /* skip header */
351
        quant = buf_ptr[3] & 0x0f;
352
        buf_ptr += 4;
353
        init_put_bits(&pb, mb_bit_buffer, 80, NULL, NULL);
354
        mb_bit_count = 0;
355
        mb = mb1;
356
        block = block1;
357
        for(j = 0;j < 6; j++) {
358
            /* NOTE: size is not important here */
359
            init_get_bits(&s->gb, buf_ptr, 14*8);
360
            
361
            /* get the dc */
362
            dc = get_bits(&s->gb, 9);
363
            dc = (dc << (32 - 9)) >> (32 - 9);
364
            dct_mode = get_bits1(&s->gb);
365
            mb->dct_mode = dct_mode;
366
            mb->scan_table = s->dv_zigzag[dct_mode];
367
            class1 = get_bits(&s->gb, 2);
368
            mb->shift_offset = (class1 == 3);
369
            mb->shift_table = s->dv_shift[dct_mode]
370
                [quant + dv_quant_offset[class1]];
371
            dc = dc << 2;
372
            /* convert to unsigned because 128 is not added in the
373
               standard IDCT */
374
            dc += 1024;
375
            block[0] = dc;
376
            last_index = block_sizes[j];
377
            buf_ptr += last_index >> 3;
378
            mb->pos = 0;
379
            mb->partial_bit_count = 0;
380

    
381
#ifdef VLC_DEBUG
382
            printf("MB block: %d, %d ", mb_index, j);
383
#endif
384
            dv_decode_ac(s, mb, block, last_index);
385

    
386
            /* write the remaining bits  in a new buffer only if the
387
               block is finished */
388
            bits_left = last_index - get_bits_count(&s->gb);
389
            if (mb->eob_reached) {
390
                mb->partial_bit_count = 0;
391
                mb_bit_count += bits_left;
392
                bit_copy(&pb, &s->gb, bits_left);
393
            } else {
394
                /* should be < 16 bits otherwise a codeword could have
395
                   been parsed */
396
                mb->partial_bit_count = bits_left;
397
                mb->partial_bit_buffer = get_bits(&s->gb, bits_left);
398
            }
399
            block += 64;
400
            mb++;
401
        }
402
        
403
        flush_put_bits(&pb);
404

    
405
        /* pass 2 : we can do it just after */
406
#ifdef VLC_DEBUG
407
        printf("***pass 2 size=%d MB#=%d\n", mb_bit_count, mb_index);
408
#endif
409
        block = block1;
410
        mb = mb1;
411
        init_get_bits(&s->gb, mb_bit_buffer, 80*8);
412
        for(j = 0;j < 6; j++) {
413
            if (!mb->eob_reached && get_bits_count(&s->gb) < mb_bit_count) {
414
                dv_decode_ac(s, mb, block, mb_bit_count);
415
                /* if still not finished, no need to parse other blocks */
416
                if (!mb->eob_reached) {
417
                    /* we could not parse the current AC coefficient,
418
                       so we add the remaining bytes */
419
                    bits_left = mb_bit_count - get_bits_count(&s->gb);
420
                    if (bits_left > 0) {
421
                        mb->partial_bit_count += bits_left;
422
                        mb->partial_bit_buffer = 
423
                            (mb->partial_bit_buffer << bits_left) | 
424
                            get_bits(&s->gb, bits_left);
425
                    }
426
                    goto next_mb;
427
                }
428
            }
429
            block += 64;
430
            mb++;
431
        }
432
        /* all blocks are finished, so the extra bytes can be used at
433
           the video segment level */
434
        bits_left = mb_bit_count - get_bits_count(&s->gb);
435
        vs_bit_count += bits_left;
436
        bit_copy(&vs_pb, &s->gb, bits_left);
437
    next_mb:
438
        mb1 += 6;
439
        block1 += 6 * 64;
440
    }
441

    
442
    /* we need a pass other the whole video segment */
443
    flush_put_bits(&vs_pb);
444
        
445
#ifdef VLC_DEBUG
446
    printf("***pass 3 size=%d\n", vs_bit_count);
447
#endif
448
    block = &s->block[0][0];
449
    mb = mb_data;
450
    init_get_bits(&s->gb, vs_bit_buffer, 5 * 80*8);
451
    for(mb_index = 0; mb_index < 5; mb_index++) {
452
        for(j = 0;j < 6; j++) {
453
            if (!mb->eob_reached) {
454
#ifdef VLC_DEBUG
455
                printf("start %d:%d\n", mb_index, j);
456
#endif
457
                dv_decode_ac(s, mb, block, vs_bit_count);
458
            }
459
            block += 64;
460
            mb++;
461
        }
462
    }
463
    
464
    /* compute idct and place blocks */
465
    block = &s->block[0][0];
466
    mb = mb_data;
467
    for(mb_index = 0; mb_index < 5; mb_index++) {
468
        v = *mb_pos_ptr++;
469
        mb_x = v & 0xff;
470
        mb_y = v >> 8;
471
        y_ptr = s->picture.data[0] + (mb_y * s->picture.linesize[0] * 8) + (mb_x * 8);
472
        if (s->sys->pix_fmt == PIX_FMT_YUV411P)
473
            c_offset = (mb_y * s->picture.linesize[1] * 8) + ((mb_x >> 2) * 8);
474
        else
475
            c_offset = ((mb_y >> 1) * s->picture.linesize[1] * 8) + ((mb_x >> 1) * 8);
476
        for(j = 0;j < 6; j++) {
477
            idct_put = s->idct_put[mb->dct_mode];
478
            if (j < 4) {
479
                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {
480
                    /* NOTE: at end of line, the macroblock is handled as 420 */
481
                    idct_put(y_ptr + (j * 8), s->picture.linesize[0], block);
482
                } else {
483
                    idct_put(y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->picture.linesize[0]),
484
                             s->picture.linesize[0], block);
485
                }
486
            } else {
487
                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
488
                    uint8_t pixels[64], *c_ptr, *c_ptr1, *ptr;
489
                    int y, linesize;
490
                    /* NOTE: at end of line, the macroblock is handled as 420 */
491
                    idct_put(pixels, 8, block);
492
                    linesize = s->picture.linesize[6 - j];
493
                    c_ptr = s->picture.data[6 - j] + c_offset;
494
                    ptr = pixels;
495
                    for(y = 0;y < 8; y++) {
496
                        /* convert to 411P */
497
                        c_ptr1 = c_ptr + 8*linesize;
498
                        c_ptr[0]= ptr[0]; c_ptr1[0]= ptr[4];
499
                        c_ptr[1]= ptr[1]; c_ptr1[1]= ptr[5];
500
                        c_ptr[2]= ptr[2]; c_ptr1[2]= ptr[6];
501
                        c_ptr[3]= ptr[3]; c_ptr1[3]= ptr[7];
502
                        c_ptr += linesize;
503
                        ptr += 8;
504
                    }
505
                } else {
506
                    /* don't ask me why they inverted Cb and Cr ! */
507
                    idct_put(s->picture.data[6 - j] + c_offset, 
508
                             s->picture.linesize[6 - j], block);
509
                }
510
            }
511
            block += 64;
512
            mb++;
513
        }
514
    }
515
}
516

    
517
/* Converts run and level (where level != 0) pair into vlc, returning bit size */
518
static inline int dv_rl2vlc(int run, int l, uint32_t* vlc)
519
{
520
    int sign = l >> 8;
521
    int level = (l ^ sign) - sign;
522
    int size;
523
    
524
    sign = (sign & 1);
525

    
526
    if (run < 15 && level < 23 && dv_vlc_codes[run][level] != -1) {
527
        *vlc = (dv_vlc_bits[dv_vlc_codes[run][level]] << 1) | sign; 
528
        size = dv_vlc_len[dv_vlc_codes[run][level]] + 1;
529
    }
530
    else { 
531
        if (level < 23) {
532
            *vlc = (dv_vlc_bits[dv_vlc_codes[0][level]] << 1) | sign; 
533
            size = dv_vlc_len[dv_vlc_codes[0][level]] + 1;
534
        } else {
535
            *vlc = 0xfe00 | (level << 1) | sign;
536
            size = 16;
537
        }
538

    
539
        switch(run) {
540
        case 0:
541
            break;
542
        case 1:
543
        case 2:
544
            *vlc |= ((0x7ce | (run - 1)) << size);
545
            size += 11;
546
            break;
547
        case 3:
548
        case 4:
549
        case 5:
550
        case 6:
551
            *vlc |= ((0xfac | (run - 3)) << size);
552
            size += 12;
553
            break;
554
        default:
555
            *vlc |= ((0x1f80 | (run - 1)) << size);
556
            size += 13;
557
            break;
558
        }
559
    }
560
    
561
    return size;
562
}
563

    
564
typedef struct EncBlockInfo {
565
    int qno;
566
    int cno;
567
    int dct_mode;
568
    int block_size;
569
    DCTELEM *mb;
570
    PutBitContext pb;
571
} EncBlockInfo;
572

    
573
static inline int dv_bits_left(EncBlockInfo* bi)
574
{
575
    return (bi->block_size - get_bit_count(&bi->pb));
576
}
577

    
578
static inline void dv_encode_ac(EncBlockInfo* bi, PutBitContext* heap)
579
{
580
    int i, level, size, run = 0;
581
    uint32_t vlc;
582
    PutBitContext* cpb = &bi->pb;
583
    
584
    for (i=1; i<64; i++) {
585
       level = bi->mb[ff_zigzag_direct[i]] / 
586
               (1<<(dv_quant_shifts[bi->qno + dv_quant_offset[bi->cno]]
587
                               [dv_88_areas[ff_zigzag_direct[i]]] + 4 + (bi->cno == 3)));
588
       if (level != 0) {
589
           size = dv_rl2vlc(run, level, &vlc);
590
put_vlc:
591

    
592
#ifdef VLC_DEBUG
593
           printf(" %3d:%3d", run, level);
594
#endif
595
           if (cpb == &bi->pb && size > dv_bits_left(bi)) {
596
               size -= dv_bits_left(bi);
597
               put_bits(cpb, dv_bits_left(bi), vlc >> size);
598
               vlc = vlc & ((1<<size)-1);
599
               cpb = heap;
600
           }
601
           put_bits(cpb, size, vlc);
602
           run = 0;
603
       } else
604
           run++;
605
    }
606
   
607
    if (i == 64) {
608
        size = 4; vlc = 6; /* End Of Block stamp */
609
        goto put_vlc;
610
    }
611
}
612

    
613
static inline void dv_redistr_bits(EncBlockInfo* bi, int count, uint8_t* extra_data, int extra_bits, PutBitContext* heap)
614
{
615
    int i;
616
    GetBitContext gb;
617
    
618
    init_get_bits(&gb, extra_data, extra_bits);
619
    
620
    for (i=0; i<count; i++) {
621
       int bits_left = dv_bits_left(bi);
622
#ifdef VLC_DEBUG
623
       if (bits_left)
624
           printf("------------> inserting %d bytes in %d:%d\n", bits_left, i/6, i%6);
625
#endif
626
       if (bits_left > extra_bits) {
627
           bit_copy(&bi->pb, &gb, extra_bits); 
628
           extra_bits = 0;
629
           break;
630
       } else
631
           bit_copy(&bi->pb, &gb, bits_left);
632
           
633
       extra_bits -= bits_left;
634
       bi++;
635
    }
636
    
637
    if (extra_bits > 0 && heap)
638
        bit_copy(heap, &gb, extra_bits);
639
}
640

    
641
static inline void dv_set_class_number(EncBlockInfo* bi, int j)
642
{
643
    int i, max_ac = 0;
644

    
645
    for (i=1; i<64; i++) {
646
       int ac = abs(bi->mb[ff_zigzag_direct[i]]) / 4;
647
       if (max_ac < ac)
648
           max_ac = ac;
649
    }
650
    if (max_ac < 12)
651
        bi->cno = j;
652
    else if (max_ac < 24)
653
        bi->cno = j + 1;
654
    else if (max_ac < 36)
655
        bi->cno = j + 2;
656
    else
657
        bi->cno = j + 3;
658
    
659
    if (bi->cno > 3)
660
        bi->cno = 3;
661
}
662

    
663
/*
664
 * This is a very rough initial implementaion. The performance is
665
 * horrible and some features are missing, mainly 2-4-8 DCT encoding.
666
 * The weighting is missing as well, but it's missing from the decoding
667
 * step also -- so at least we're on the same page with decoder ;-)
668
 */
669
static inline void dv_encode_video_segment(DVVideoDecodeContext *s, 
670
                                           uint8_t *dif, 
671
                                           const uint16_t *mb_pos_ptr)
672
{
673
    int mb_index, i, j, v;
674
    int mb_x, mb_y, c_offset, linesize; 
675
    uint8_t*  y_ptr;
676
    uint8_t*  data;
677
    int       do_edge_wrap;
678
    DCTELEM  *block;
679
    EncBlockInfo  enc_blks[5*6];
680
    EncBlockInfo* enc_blk;
681
    int       free_vs_bits;
682
    int extra_bits;
683
    PutBitContext extra_vs;
684
    uint8_t   extra_vs_data[5*6*128];
685
    uint8_t   extra_mb_data[6*128];
686

    
687
    int       QNO = 15;
688
   
689
    /* Stage 1 -- doing DCT on 5 MBs */
690
    block = &s->block[0][0];
691
    for(mb_index = 0; mb_index < 5; mb_index++) {
692
        v = *mb_pos_ptr++;
693
        mb_x = v & 0xff;
694
        mb_y = v >> 8;
695
        y_ptr = s->picture.data[0] + (mb_y * s->picture.linesize[0] * 8) + (mb_x * 8);
696
        c_offset = (s->sys->pix_fmt == PIX_FMT_YUV411P) ?
697
                   ((mb_y * s->picture.linesize[1] * 8) + ((mb_x >> 2) * 8)) :
698
                   (((mb_y >> 1) * s->picture.linesize[1] * 8) + ((mb_x >> 1) * 8));
699
        do_edge_wrap = 0;
700
        for(j = 0;j < 6; j++) {
701
            if (j < 4) {  /* Four Y blocks */
702
                /* NOTE: at end of line, the macroblock is handled as 420 */
703
                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {
704
                    data = y_ptr + (j * 8);
705
                } else {
706
                    data = y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->picture.linesize[0]);
707
                }
708
                linesize = s->picture.linesize[0];
709
            } else {      /* Cr and Cb blocks */
710
                /* don't ask Fabrice why they inverted Cb and Cr ! */
711
                data = s->picture.data[6 - j] + c_offset;
712
                linesize = s->picture.linesize[6 - j];
713
                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8))
714
                    do_edge_wrap = 1;
715
            }        
716
            
717
            /* Everything is set up -- now just copy data -> DCT block */
718
            if (do_edge_wrap) {  /* Edge wrap copy: 4x16 -> 8x8 */
719
                uint8_t* d;
720
                DCTELEM *b = block;
721
                for (i=0;i<8;i++) {
722
                   d = data + 8 * linesize;
723
                   b[0] = data[0]; b[1] = data[1]; b[2] = data[2]; b[3] = data[3];
724
                   b[4] =    d[0]; b[5] =    d[1]; b[6] =    d[2]; b[7] =    d[3];
725
                   data += linesize;
726
                   b += 8;
727
                }
728
            } else {             /* Simple copy: 8x8 -> 8x8 */
729
                s->get_pixels(block, data, linesize);
730
            }
731
            
732
            s->fdct(block);
733
            
734
            block += 64;
735
        }
736
    }
737

    
738
    /* Stage 2 -- setup for encoding phase */
739
    enc_blk = &enc_blks[0];
740
    block = &s->block[0][0];
741
    for (i=0; i<5; i++) {
742
       for (j=0; j<6; j++) {
743
          enc_blk->mb = block;
744
          enc_blk->dct_mode = 0;
745
          enc_blk->block_size = block_sizes[j];
746
          
747
          dv_set_class_number(enc_blk, j/4*(j%2));
748
          
749
          block += 64;
750
          enc_blk++;
751
       }
752
    }
753
   
754
    /* Stage 3 -- encoding by trial-and-error */
755
encode_vs:
756
    enc_blk = &enc_blks[0];
757
    for (i=0; i<5; i++) {
758
       uint8_t* p = dif + i*80 + 4;
759
       for (j=0; j<6; j++) {
760
          enc_blk->qno = QNO;
761
          init_put_bits(&enc_blk->pb, p, block_sizes[j]/8, NULL, NULL);
762
          enc_blk++;
763
          p += block_sizes[j]/8;
764
       }
765
    }
766

    
767
    init_put_bits(&extra_vs, extra_vs_data, sizeof(extra_vs_data), NULL, NULL);
768
    free_vs_bits = 0;
769
    enc_blk = &enc_blks[0];
770
    for (i=0; i<5; i++) {
771
       PutBitContext extra_mb;
772
       EncBlockInfo* enc_blk2 = enc_blk;
773
       int free_mb_bits = 0;
774

    
775
       init_put_bits(&extra_mb, extra_mb_data, sizeof(extra_mb_data), NULL, NULL);
776
       dif[i*80 + 3] = enc_blk->qno;
777
       
778
       for (j=0; j<6; j++) {
779
          uint16_t dc = ((enc_blk->mb[0] >> 3) - 1024) >> 2;
780

    
781
          put_bits(&enc_blk->pb, 9, dc);
782
          put_bits(&enc_blk->pb, 1, enc_blk->dct_mode);
783
          put_bits(&enc_blk->pb, 2, enc_blk->cno);
784

    
785
#ifdef VLC_DEBUG
786
          printf("[%d, %d]: ", i, j);
787
#endif
788
          dv_encode_ac(enc_blk, &extra_mb);
789
#ifdef VLC_DEBUG
790
          printf("\n");
791
#endif
792
          
793
          free_mb_bits += dv_bits_left(enc_blk);
794
          enc_blk++;
795
       }
796
       
797
       /* We can't flush extra_mb just yet -- since it'll round up bit number */
798
       extra_bits = get_bit_count(&extra_mb);
799
       if (free_mb_bits > extra_bits)
800
           free_vs_bits += free_mb_bits - extra_bits;
801
    
802
       if (extra_bits) {  /* FIXME: speed up things when free_mb_bits == 0 */
803
           flush_put_bits(&extra_mb);
804
           dv_redistr_bits(enc_blk2, 6, extra_mb_data, extra_bits, &extra_vs);
805
       }
806
    }
807
    
808
    /* We can't flush extra_mb just yet -- since it'll round up bit number */
809
    extra_bits = get_bit_count(&extra_vs);
810
    if (extra_bits > free_vs_bits && QNO) { /* FIXME: very crude trial-and-error */
811
        QNO--;
812
        goto encode_vs;
813
    }
814
    
815
    if (extra_bits) {
816
        flush_put_bits(&extra_vs);
817
        dv_redistr_bits(&enc_blks[0], 5*6, extra_vs_data, extra_bits, NULL);
818
    }
819

    
820
    for (i=0; i<6*5; i++) {
821
       flush_put_bits(&enc_blks[i].pb);
822
#ifdef VLC_DEBUG
823
       printf("[%d:%d] qno=%d cno=%d\n", i/6, i%6, enc_blks[i].qno, enc_blks[i].cno);
824
#endif
825
    }
826
}
827

    
828
/* NOTE: exactly one frame must be given (120000 bytes for NTSC,
829
   144000 bytes for PAL) */
830
static int dvvideo_decode_frame(AVCodecContext *avctx, 
831
                                 void *data, int *data_size,
832
                                 uint8_t *buf, int buf_size)
833
{
834
    DVVideoDecodeContext *s = avctx->priv_data;
835
    int ds, vs;
836
    const uint16_t *mb_pos_ptr;
837
    
838
    s->sys = dv_frame_profile(buf);
839
    if (!s->sys || buf_size < s->sys->frame_size)
840
        return -1; /* NOTE: we only accept several full frames */
841

    
842
        
843
    if(s->picture.data[0])
844
        avctx->release_buffer(avctx, &s->picture);
845
    
846
    s->picture.reference = 0;
847
    avctx->pix_fmt = s->sys->pix_fmt;
848
    if(avctx->get_buffer(avctx, &s->picture) < 0) {
849
        fprintf(stderr, "get_buffer() failed\n");
850
        return -1;
851
    }
852

    
853
    /* for each DIF segment */
854
    mb_pos_ptr = s->sys->video_place;
855
    for (ds = 0; ds < s->sys->difseg_size; ds++) {
856
        buf += 6 * 80; /* skip DIF segment header */
857
        
858
        for(vs = 0; vs < 27; vs++) {
859
            if ((vs % 3) == 0)
860
                buf += 80; /* skip audio block */
861
            
862
#ifdef VLC_DEBUG
863
            printf("********************* %d, %d **********************\n", ds, vs);
864
#endif
865
            dv_decode_video_segment(s, buf, mb_pos_ptr);
866
            buf += 5 * 80;
867
            mb_pos_ptr += 5;
868
        }
869
    }
870

    
871
    emms_c();
872

    
873
    /* return image */
874
    *data_size = sizeof(AVFrame);
875
    *(AVFrame*)data= s->picture;
876
    
877
    return s->sys->frame_size;
878
}
879

    
880
static int dvvideo_encode_frame(AVCodecContext *c, uint8_t *buf, int buf_size, 
881
                                void *data)
882
{
883
    DVVideoDecodeContext *s = c->priv_data;
884
    const uint16_t *mb_pos_ptr;
885
    int ds, vs;
886

    
887
    s->sys = dv_codec_profile(c);
888
    if (!s->sys)
889
        return -1;
890
    
891
    c->pix_fmt = s->sys->pix_fmt;
892
    s->picture = *((AVFrame *)data);
893

    
894
    /* for each DIF segment */
895
    mb_pos_ptr = s->sys->video_place;
896
    for (ds = 0; ds < s->sys->difseg_size; ds++) {
897
        buf += 6 * 80; /* skip DIF segment header */
898
        
899
        for(vs = 0; vs < 27; vs++) {
900
            if ((vs % 3) == 0)
901
                buf += 80; /* skip audio block */
902

    
903
#ifdef VLC_DEBUG
904
            printf("********************* %d, %d **********************\n", ds, vs);
905
#endif
906
            dv_encode_video_segment(s, buf, mb_pos_ptr);
907
            buf += 5 * 80;
908
            mb_pos_ptr += 5;
909
        }
910
    }
911

    
912
    emms_c();
913
    return s->sys->frame_size;
914
}
915

    
916
static int dvvideo_end(AVCodecContext *avctx)
917
{
918
    avcodec_default_free_buffers(avctx);    
919
    return 0;
920
}
921

    
922
AVCodec dvvideo_decoder = {
923
    "dvvideo",
924
    CODEC_TYPE_VIDEO,
925
    CODEC_ID_DVVIDEO,
926
    sizeof(DVVideoDecodeContext),
927
    dvvideo_init,
928
    dvvideo_encode_frame,
929
    dvvideo_end,
930
    dvvideo_decode_frame,
931
    CODEC_CAP_DR1,
932
    NULL
933
};