Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ ecfd40b3

History | View | Annotate | Download (55.9 KB)

1
/*
2
 * MPEG1 encoder / MPEG2 decoder
3
 * Copyright (c) 2000,2001 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
//#define DEBUG
20
#include "avcodec.h"
21
#include "dsputil.h"
22
#include "mpegvideo.h"
23

    
24
#include "mpeg12data.h"
25

    
26
/* Start codes. */
27
#define SEQ_END_CODE                0x000001b7
28
#define SEQ_START_CODE                0x000001b3
29
#define GOP_START_CODE                0x000001b8
30
#define PICTURE_START_CODE        0x00000100
31
#define SLICE_MIN_START_CODE        0x00000101
32
#define SLICE_MAX_START_CODE        0x000001af
33
#define EXT_START_CODE                0x000001b5
34
#define USER_START_CODE                0x000001b2
35

    
36
#define DC_VLC_BITS 9
37
#define MV_VLC_BITS 9
38
#define MBINCR_VLC_BITS 9
39
#define MB_PAT_VLC_BITS 9
40
#define MB_PTYPE_VLC_BITS 6
41
#define MB_BTYPE_VLC_BITS 6
42
#define TEX_VLC_BITS 9
43

    
44
static void mpeg1_encode_block(MpegEncContext *s, 
45
                         DCTELEM *block, 
46
                         int component);
47
static void mpeg1_encode_motion(MpegEncContext *s, int val);
48
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
49
static int mpeg1_decode_block(MpegEncContext *s, 
50
                              DCTELEM *block, 
51
                              int n);
52
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
53
                                        DCTELEM *block, 
54
                                        int n);
55
static int mpeg2_decode_block_intra(MpegEncContext *s, 
56
                                    DCTELEM *block, 
57
                                    int n);
58
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
59

    
60
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
61
static UINT8 fcode_tab[MAX_MV*2+1];
62

    
63
static void init_2d_vlc_rl(RLTable *rl)
64
{
65
    int i;
66
    
67
    init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
68
             &rl->table_vlc[0][1], 4, 2,
69
             &rl->table_vlc[0][0], 4, 2);
70

    
71
    
72
    rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
73
    for(i=0; i<rl->vlc.table_size; i++){
74
        int code= rl->vlc.table[i][0];
75
        int len = rl->vlc.table[i][1];
76
        int level, run;
77
    
78
        if(len==0){ // illegal code
79
            run= 65;
80
            level= MAX_LEVEL;
81
        }else if(len<0){ //more bits needed
82
            run= 0;
83
            level= code;
84
        }else{
85
            if(code==rl->n){ //esc
86
                run= 65;
87
                level= 0;
88
            }else if(code==rl->n+1){ //eob
89
                run= 192;
90
                level= 1;
91
            }else{
92
                run=   rl->table_run  [code] + 1;
93
                level= rl->table_level[code];
94
            }
95
        }
96
        rl->rl_vlc[0][i].len= len;
97
        rl->rl_vlc[0][i].level= level;
98
        rl->rl_vlc[0][i].run= run;
99
    }
100
}
101

    
102

    
103
static void put_header(MpegEncContext *s, int header)
104
{
105
    align_put_bits(&s->pb);
106
    put_bits(&s->pb, 16, header>>16);
107
    put_bits(&s->pb, 16, header&0xFFFF);
108
}
109

    
110
/* put sequence header if needed */
111
static void mpeg1_encode_sequence_header(MpegEncContext *s)
112
{
113
        unsigned int vbv_buffer_size;
114
        unsigned int fps, v;
115
        int n;
116
        UINT64 time_code;
117
        
118
        if (s->picture_in_gop_number == 0) {
119
            /* mpeg1 header repeated every gop */
120
            put_header(s, SEQ_START_CODE);
121
            
122
            /* search closest frame rate */
123
            {
124
                int i, dmin, d;
125
                s->frame_rate_index = 0;
126
                dmin = 0x7fffffff;
127
                for(i=1;i<9;i++) {
128
                    d = abs(s->frame_rate - frame_rate_tab[i]);
129
                    if (d < dmin) {
130
                        dmin = d;
131
                        s->frame_rate_index = i;
132
                    }
133
                }
134
            }
135
 
136
            put_bits(&s->pb, 12, s->width);
137
            put_bits(&s->pb, 12, s->height);
138
            put_bits(&s->pb, 4, 1); /* 1/1 aspect ratio */
139
            put_bits(&s->pb, 4, s->frame_rate_index);
140
            v = s->bit_rate / 400;
141
            if (v > 0x3ffff)
142
                v = 0x3ffff;
143
            put_bits(&s->pb, 18, v);
144
            put_bits(&s->pb, 1, 1); /* marker */
145

    
146
            if(s->avctx->rc_buffer_size)
147
                vbv_buffer_size = s->avctx->rc_buffer_size;
148
            else
149
                /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
150
                vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;         
151
            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
152
            put_bits(&s->pb, 1, 1); /* constrained parameter flag */
153
            put_bits(&s->pb, 1, 0); /* no custom intra matrix */
154
            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
155

    
156
            put_header(s, GOP_START_CODE);
157
            put_bits(&s->pb, 1, 0); /* do drop frame */
158
            /* time code : we must convert from the real frame rate to a
159
               fake mpeg frame rate in case of low frame rate */
160
            fps = frame_rate_tab[s->frame_rate_index];
161
            time_code = (INT64)s->fake_picture_number * FRAME_RATE_BASE;
162
            s->gop_picture_number = s->fake_picture_number;
163
            put_bits(&s->pb, 5, (UINT32)((time_code / (fps * 3600)) % 24));
164
            put_bits(&s->pb, 6, (UINT32)((time_code / (fps * 60)) % 60));
165
            put_bits(&s->pb, 1, 1);
166
            put_bits(&s->pb, 6, (UINT32)((time_code / fps) % 60));
167
            put_bits(&s->pb, 6, (UINT32)((time_code % fps) / FRAME_RATE_BASE));
168
            put_bits(&s->pb, 1, 1); /* closed gop */
169
            put_bits(&s->pb, 1, 0); /* broken link */
170
        }
171

    
172
        if (s->frame_rate < (24 * FRAME_RATE_BASE) && s->picture_number > 0) {
173
            /* insert empty P pictures to slow down to the desired
174
               frame rate. Each fake pictures takes about 20 bytes */
175
            fps = frame_rate_tab[s->frame_rate_index];
176
            n = (((INT64)s->picture_number * fps) / s->frame_rate) - 1;
177
            while (s->fake_picture_number < n) {
178
                mpeg1_skip_picture(s, s->fake_picture_number - 
179
                                   s->gop_picture_number); 
180
                s->fake_picture_number++;
181
            }
182

    
183
        }
184
}
185

    
186

    
187
/* insert a fake P picture */
188
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num)
189
{
190
    unsigned int mb_incr;
191

    
192
    /* mpeg1 picture header */
193
    put_header(s, PICTURE_START_CODE);
194
    /* temporal reference */
195
    put_bits(&s->pb, 10, pict_num & 0x3ff); 
196
    
197
    put_bits(&s->pb, 3, P_TYPE);
198
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
199
    
200
    put_bits(&s->pb, 1, 1); /* integer coordinates */
201
    put_bits(&s->pb, 3, 1); /* forward_f_code */
202
    
203
    put_bits(&s->pb, 1, 0); /* extra bit picture */
204
    
205
    /* only one slice */
206
    put_header(s, SLICE_MIN_START_CODE);
207
    put_bits(&s->pb, 5, 1); /* quantizer scale */
208
    put_bits(&s->pb, 1, 0); /* slice extra information */
209
    
210
    mb_incr = 1;
211
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
212
             mbAddrIncrTable[mb_incr - 1][0]);
213
    
214
    /* empty macroblock */
215
    put_bits(&s->pb, 3, 1); /* motion only */
216
    
217
    /* zero motion x & y */
218
    put_bits(&s->pb, 1, 1); 
219
    put_bits(&s->pb, 1, 1); 
220

    
221
    /* output a number of empty slice */
222
    mb_incr = s->mb_width * s->mb_height - 1;
223
    while (mb_incr > 33) {
224
        put_bits(&s->pb, 11, 0x008);
225
        mb_incr -= 33;
226
    }
227
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
228
             mbAddrIncrTable[mb_incr - 1][0]);
229
    
230
    /* empty macroblock */
231
    put_bits(&s->pb, 3, 1); /* motion only */
232
    
233
    /* zero motion x & y */
234
    put_bits(&s->pb, 1, 1); 
235
    put_bits(&s->pb, 1, 1); 
236
}
237

    
238
static void common_init(MpegEncContext *s)
239
{
240
    s->y_dc_scale_table=
241
    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
242
}
243

    
244
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
245
{
246
    mpeg1_encode_sequence_header(s);
247

    
248
    /* mpeg1 picture header */
249
    put_header(s, PICTURE_START_CODE);
250
    /* temporal reference */
251
    put_bits(&s->pb, 10, (s->fake_picture_number - 
252
                          s->gop_picture_number) & 0x3ff); 
253
    s->fake_picture_number++;
254
    
255
    put_bits(&s->pb, 3, s->pict_type);
256
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
257
    
258
    if (s->pict_type == P_TYPE) {
259
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
260
        put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
261
    }
262
    
263
    put_bits(&s->pb, 1, 0); /* extra bit picture */
264
    
265
    /* only one slice */
266
    put_header(s, SLICE_MIN_START_CODE);
267
    put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
268
    put_bits(&s->pb, 1, 0); /* slice extra information */
269
}
270

    
271
void mpeg1_encode_mb(MpegEncContext *s,
272
                     DCTELEM block[6][64],
273
                     int motion_x, int motion_y)
274
{
275
    int mb_incr, i, cbp, mb_x, mb_y;
276

    
277
    mb_x = s->mb_x;
278
    mb_y = s->mb_y;
279

    
280
    /* compute cbp */
281
    cbp = 0;
282
    for(i=0;i<6;i++) {
283
        if (s->block_last_index[i] >= 0)
284
            cbp |= 1 << (5 - i);
285
    }
286

    
287
    /* skip macroblock, except if first or last macroblock of a slice */
288
    if ((cbp | motion_x | motion_y) == 0 &&
289
        (!((mb_x | mb_y) == 0 ||
290
           (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1)))) {
291
        s->mb_incr++;
292
    } else {
293
        /* output mb incr */
294
        mb_incr = s->mb_incr;
295

    
296
        while (mb_incr > 33) {
297
            put_bits(&s->pb, 11, 0x008);
298
            mb_incr -= 33;
299
        }
300
        put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
301
                 mbAddrIncrTable[mb_incr - 1][0]);
302
        
303
        if (s->pict_type == I_TYPE) {
304
            put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
305
        } else {
306
            if (s->mb_intra) {
307
                put_bits(&s->pb, 5, 0x03);
308
            } else {
309
                if (cbp != 0) {
310
                    if (motion_x == 0 && motion_y == 0) {
311
                        put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
312
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
313
                    } else {
314
                        put_bits(&s->pb, 1, 1); /* motion + cbp */
315
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
316
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
317
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
318
                    }
319
                } else {
320
                    put_bits(&s->pb, 3, 1); /* motion only */
321
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
322
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
323
                }
324
            }
325
        }
326
        for(i=0;i<6;i++) {
327
            if (cbp & (1 << (5 - i))) {
328
                mpeg1_encode_block(s, block[i], i);
329
            }
330
        }
331
        s->mb_incr = 1;
332
    }
333
    s->last_mv[0][0][0] = motion_x;
334
    s->last_mv[0][0][1] = motion_y;
335
}
336

    
337
static void mpeg1_encode_motion(MpegEncContext *s, int val)
338
{
339
    int code, bit_size, l, m, bits, range, sign;
340

    
341
    if (val == 0) {
342
        /* zero vector */
343
        code = 0;
344
        put_bits(&s->pb,
345
                 mbMotionVectorTable[0][1], 
346
                 mbMotionVectorTable[0][0]); 
347
    } else {
348
        bit_size = s->f_code - 1;
349
        range = 1 << bit_size;
350
        /* modulo encoding */
351
        l = 16 * range;
352
        m = 2 * l;
353
        if (val < -l) {
354
            val += m;
355
        } else if (val >= l) {
356
            val -= m;
357
        }
358

    
359
        if (val >= 0) {
360
            val--;
361
            code = (val >> bit_size) + 1;
362
            bits = val & (range - 1);
363
            sign = 0;
364
        } else {
365
            val = -val;
366
            val--;
367
            code = (val >> bit_size) + 1;
368
            bits = val & (range - 1);
369
            sign = 1;
370
        }
371
        put_bits(&s->pb,
372
                 mbMotionVectorTable[code][1], 
373
                 mbMotionVectorTable[code][0]); 
374
        put_bits(&s->pb, 1, sign);
375
        if (bit_size > 0) {
376
            put_bits(&s->pb, bit_size, bits);
377
        }
378
    }
379
}
380

    
381
void ff_mpeg1_encode_init(MpegEncContext *s)
382
{
383
    static int done=0;
384

    
385
    common_init(s);
386

    
387
    if(!done){
388
        int f_code;
389
        int mv;
390
        int i;
391

    
392
        done=1;
393
        init_rl(&rl_mpeg1);
394
        
395
        for(i=0; i<64; i++)
396
        {
397
                mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
398
                mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
399
        }
400

    
401
        /* build unified dc encoding tables */
402
        for(i=-255; i<256; i++)
403
        {
404
                int adiff, index;
405
                int bits, code;
406
                int diff=i;
407

    
408
                adiff = ABS(diff);
409
                if(diff<0) diff--;
410
                index = vlc_dc_table[adiff];
411

    
412
                bits= vlc_dc_lum_bits[index] + index;
413
                code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
414
                mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
415
                
416
                bits= vlc_dc_chroma_bits[index] + index;
417
                code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
418
                mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
419
        }
420

    
421
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
422
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
423
                int len;
424

    
425
                if(mv==0) len= mbMotionVectorTable[0][1];
426
                else{
427
                    int val, bit_size, range, code;
428

    
429
                    bit_size = s->f_code - 1;
430
                    range = 1 << bit_size;
431

    
432
                    val=mv;
433
                    if (val < 0) 
434
                        val = -val;
435
                    val--;
436
                    code = (val >> bit_size) + 1;
437
                    if(code<17){
438
                        len= mbMotionVectorTable[code][1] + 1 + bit_size;
439
                    }else{
440
                        len= mbMotionVectorTable[16][1] + 2 + bit_size;
441
                    }
442
                }
443

    
444
                mv_penalty[f_code][mv+MAX_MV]= len;
445
            }
446
        }
447
        
448

    
449
        for(f_code=MAX_FCODE; f_code>0; f_code--){
450
            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
451
                fcode_tab[mv+MAX_MV]= f_code;
452
            }
453
        }
454
    }
455
    s->mv_penalty= mv_penalty;
456
    s->fcode_tab= fcode_tab;
457
    s->min_qcoeff=-255;
458
    s->max_qcoeff= 255;
459
    s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
460
    s->inter_quant_bias= 0;
461
}
462

    
463
static inline void encode_dc(MpegEncContext *s, int diff, int component)
464
{
465
    if (component == 0) {
466
        put_bits(
467
            &s->pb, 
468
            mpeg1_lum_dc_uni[diff+255]&0xFF,
469
            mpeg1_lum_dc_uni[diff+255]>>8);
470
    } else {
471
        put_bits(
472
            &s->pb, 
473
            mpeg1_chr_dc_uni[diff+255]&0xFF,
474
            mpeg1_chr_dc_uni[diff+255]>>8);
475
    }
476
}
477

    
478
static void mpeg1_encode_block(MpegEncContext *s, 
479
                               DCTELEM *block, 
480
                               int n)
481
{
482
    int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
483
    int code, component;
484
//    RLTable *rl = &rl_mpeg1;
485

    
486
    last_index = s->block_last_index[n];
487

    
488
    /* DC coef */
489
    if (s->mb_intra) {
490
        component = (n <= 3 ? 0 : n - 4 + 1);
491
        dc = block[0]; /* overflow is impossible */
492
        diff = dc - s->last_dc[component];
493
        encode_dc(s, diff, component);
494
        s->last_dc[component] = dc;
495
        i = 1;
496
    } else {
497
        /* encode the first coefficient : needs to be done here because
498
           it is handled slightly differently */
499
        level = block[0];
500
        if (abs(level) == 1) {
501
                code = ((UINT32)level >> 31); /* the sign bit */
502
                put_bits(&s->pb, 2, code | 0x02);
503
                i = 1;
504
        } else {
505
            i = 0;
506
            last_non_zero = -1;
507
            goto next_coef;
508
        }
509
    }
510

    
511
    /* now quantify & encode AC coefs */
512
    last_non_zero = i - 1;
513

    
514
    for(;i<=last_index;i++) {
515
        j = zigzag_direct[i];
516
        level = block[j];
517
    next_coef:
518
#if 0
519
        if (level != 0)
520
            dprintf("level[%d]=%d\n", i, level);
521
#endif            
522
        /* encode using VLC */
523
        if (level != 0) {
524
            run = i - last_non_zero - 1;
525
#ifdef ARCH_X86
526
            asm volatile(
527
                "movl %2, %1                \n\t"
528
                "movl %1, %0                \n\t"
529
                "addl %1, %1                \n\t"
530
                "sbbl %1, %1                \n\t"
531
                "xorl %1, %0                \n\t"
532
                "subl %1, %0                \n\t"
533
                "andl $1, %1                \n\t"
534
                : "=&r" (alevel), "=&r" (sign)
535
                : "g" (level)
536
            );
537
#else
538
            sign = 0;
539
            alevel = level;
540
            if (alevel < 0) {
541
                sign = 1;
542
                alevel = -alevel;
543
            }
544
#endif
545
//            code = get_rl_index(rl, 0, run, alevel);
546
            if (alevel > mpeg1_max_level[0][run])
547
                code= 111; /*rl->n*/
548
            else
549
                code= mpeg1_index_run[0][run] + alevel - 1;
550

    
551
            if (code < 111 /* rl->n */) {
552
                    /* store the vlc & sign at once */
553
                put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
554
            } else {
555
                /* escape seems to be pretty rare <5% so i dont optimize it */
556
                put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
557
                /* escape: only clip in this case */
558
                put_bits(&s->pb, 6, run);
559
                if (alevel < 128) {
560
                    put_bits(&s->pb, 8, level & 0xff);
561
                } else {
562
                    if (level < 0) {
563
                        put_bits(&s->pb, 16, 0x8001 + level + 255);
564
                    } else {
565
                        put_bits(&s->pb, 16, level & 0xffff);
566
                    }
567
                }
568
            }
569
            last_non_zero = i;
570
        }
571
    }
572
    /* end of block */
573
    put_bits(&s->pb, 2, 0x2);
574
}
575

    
576
/******************************************/
577
/* decoding */
578

    
579
static VLC dc_lum_vlc;
580
static VLC dc_chroma_vlc;
581
static VLC mv_vlc;
582
static VLC mbincr_vlc;
583
static VLC mb_ptype_vlc;
584
static VLC mb_btype_vlc;
585
static VLC mb_pat_vlc;
586

    
587
void mpeg1_init_vlc(MpegEncContext *s)
588
{
589
    static int done = 0;
590

    
591
    if (!done) {
592
        done = 1;
593

    
594
        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
595
                 vlc_dc_lum_bits, 1, 1,
596
                 vlc_dc_lum_code, 2, 2);
597
        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
598
                 vlc_dc_chroma_bits, 1, 1,
599
                 vlc_dc_chroma_code, 2, 2);
600
        init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
601
                 &mbMotionVectorTable[0][1], 2, 1,
602
                 &mbMotionVectorTable[0][0], 2, 1);
603
        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 35, 
604
                 &mbAddrIncrTable[0][1], 2, 1,
605
                 &mbAddrIncrTable[0][0], 2, 1);
606
        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 63, 
607
                 &mbPatTable[0][1], 2, 1,
608
                 &mbPatTable[0][0], 2, 1);
609
        
610
        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 32, 
611
                 &table_mb_ptype[0][1], 2, 1,
612
                 &table_mb_ptype[0][0], 2, 1);
613
        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 32, 
614
                 &table_mb_btype[0][1], 2, 1,
615
                 &table_mb_btype[0][0], 2, 1);
616
        init_rl(&rl_mpeg1);
617
        init_rl(&rl_mpeg2);
618

    
619
        init_2d_vlc_rl(&rl_mpeg1);
620
        init_2d_vlc_rl(&rl_mpeg2);
621
    }
622
}
623

    
624
static inline int get_dmv(MpegEncContext *s)
625
{
626
    if(get_bits1(&s->gb)) 
627
        return 1 - (get_bits1(&s->gb) << 1);
628
    else
629
        return 0;
630
}
631

    
632
static inline int get_qscale(MpegEncContext *s)
633
{
634
    int qscale;
635
    if (s->mpeg2) {
636
        if (s->q_scale_type) {
637
            qscale = non_linear_qscale[get_bits(&s->gb, 5)];
638
        } else {
639
            qscale = get_bits(&s->gb, 5) << 1;
640
        }
641
    } else {
642
        /* for mpeg1, we use the generic unquant code */
643
        qscale = get_bits(&s->gb, 5);
644
    }
645
    return qscale;
646
}
647

    
648
/* motion type (for mpeg2) */
649
#define MT_FIELD 1
650
#define MT_FRAME 2
651
#define MT_16X8  2
652
#define MT_DMV   3
653

    
654
static int mpeg_decode_mb(MpegEncContext *s,
655
                          DCTELEM block[6][64])
656
{
657
    int i, j, k, cbp, val, code, mb_type, motion_type;
658
    
659
    /* skip mb handling */
660
    if (s->mb_incr == 0) {
661
        /* read again increment */
662
        s->mb_incr = 1;
663
        for(;;) {
664
            code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
665
            if (code < 0)
666
                return 1; /* error = end of slice */
667
            if (code >= 33) {
668
                if (code == 33) {
669
                    s->mb_incr += 33;
670
                }
671
                /* otherwise, stuffing, nothing to do */
672
            } else {
673
                s->mb_incr += code;
674
                break;
675
            }
676
        }
677
    }
678
    if(s->mb_x==-1 /* first MB in a slice */ && s->mb_incr>1){
679
        s->mb_x+= (s->mb_incr - 1) % s->mb_width;
680
        s->mb_y+= (s->mb_incr - 1) / s->mb_width;
681
        s->mb_incr= 1;
682
    }
683

    
684
    if (++s->mb_x >= s->mb_width) {
685
        s->mb_x = 0;
686
        if (s->mb_y >= (s->mb_height - 1)){
687
            fprintf(stderr, "slice too long\n");
688
            return -1;
689
        }
690
        s->mb_y++;
691
    }
692
    dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
693

    
694
    if (--s->mb_incr != 0) {
695
        /* skip mb */
696
        s->mb_intra = 0;
697
        for(i=0;i<6;i++)
698
            s->block_last_index[i] = -1;
699
        s->mv_type = MV_TYPE_16X16;
700
        if (s->pict_type == P_TYPE) {
701
            /* if P type, zero motion vector is implied */
702
            s->mv_dir = MV_DIR_FORWARD;
703
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
704
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
705
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
706
        } else {
707
            /* if B type, reuse previous vectors and directions */
708
            s->mv[0][0][0] = s->last_mv[0][0][0];
709
            s->mv[0][0][1] = s->last_mv[0][0][1];
710
            s->mv[1][0][0] = s->last_mv[1][0][0];
711
            s->mv[1][0][1] = s->last_mv[1][0][1];
712
        }
713
        s->mb_skiped = 1;
714
        return 0;
715
    }
716

    
717
    switch(s->pict_type) {
718
    default:
719
    case I_TYPE:
720
        if (get_bits1(&s->gb) == 0) {
721
            if (get_bits1(&s->gb) == 0)
722
                return -1;
723
            mb_type = MB_QUANT | MB_INTRA;
724
        } else {
725
            mb_type = MB_INTRA;
726
        }
727
        break;
728
    case P_TYPE:
729
        mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
730
        if (mb_type < 0){
731
            fprintf(stderr, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
732
            return -1;
733
        }
734
        break;
735
    case B_TYPE:
736
        mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
737
        if (mb_type < 0){
738
            fprintf(stderr, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
739
            return -1;
740
        }
741
        break;
742
    }
743
    dprintf("mb_type=%x\n", mb_type);
744
    motion_type = 0; /* avoid warning */
745
    if (mb_type & (MB_FOR|MB_BACK)) {
746
        /* get additionnal motion vector type */
747
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
748
            motion_type = MT_FRAME;
749
        else
750
            motion_type = get_bits(&s->gb, 2);
751
    }
752
    /* compute dct type */
753
    if (s->picture_structure == PICT_FRAME && 
754
        !s->frame_pred_frame_dct &&
755
        (mb_type & (MB_PAT | MB_INTRA))) {
756
        s->interlaced_dct = get_bits1(&s->gb);
757
#ifdef DEBUG
758
        if (s->interlaced_dct)
759
            printf("interlaced_dct\n");
760
#endif
761
    } else {
762
        s->interlaced_dct = 0; /* frame based */
763
    }
764

    
765
    if (mb_type & MB_QUANT) {
766
        s->qscale = get_qscale(s);
767
    }
768
    if (mb_type & MB_INTRA) {
769
        if (s->concealment_motion_vectors) {
770
            /* just parse them */
771
            if (s->picture_structure != PICT_FRAME) 
772
                skip_bits1(&s->gb); /* field select */
773
            mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
774
            mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
775
        }
776
        s->mb_intra = 1;
777
        cbp = 0x3f;
778
        memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
779
    } else {
780
        s->mb_intra = 0;
781
        cbp = 0;
782
    }
783
    /* special case of implicit zero motion vector */
784
    if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
785
        s->mv_dir = MV_DIR_FORWARD;
786
        s->mv_type = MV_TYPE_16X16;
787
        s->last_mv[0][0][0] = 0;
788
        s->last_mv[0][0][1] = 0;
789
        s->last_mv[0][1][0] = 0;
790
        s->last_mv[0][1][1] = 0;
791
        s->mv[0][0][0] = 0;
792
        s->mv[0][0][1] = 0;
793
    } else if (mb_type & (MB_FOR | MB_BACK)) {
794
        /* motion vectors */
795
        s->mv_dir = 0;
796
        for(i=0;i<2;i++) {
797
            if (mb_type & (MB_FOR >> i)) {
798
                s->mv_dir |= (MV_DIR_FORWARD >> i);
799
                dprintf("motion_type=%d\n", motion_type);
800
                switch(motion_type) {
801
                case MT_FRAME: /* or MT_16X8 */
802
                    if (s->picture_structure == PICT_FRAME) {
803
                        /* MT_FRAME */
804
                        s->mv_type = MV_TYPE_16X16;
805
                        for(k=0;k<2;k++) {
806
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
807
                                                     s->last_mv[i][0][k]);
808
                            s->last_mv[i][0][k] = val;
809
                            s->last_mv[i][1][k] = val;
810
                            /* full_pel: only for mpeg1 */
811
                            if (s->full_pel[i])
812
                                val = val << 1;
813
                            s->mv[i][0][k] = val;
814
                            dprintf("mv%d: %d\n", k, val);
815
                        }
816
                    } else {
817
                        /* MT_16X8 */
818
                        s->mv_type = MV_TYPE_16X8;
819
                        for(j=0;j<2;j++) {
820
                            s->field_select[i][j] = get_bits1(&s->gb);
821
                            for(k=0;k<2;k++) {
822
                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
823
                                                         s->last_mv[i][j][k]);
824
                                s->last_mv[i][j][k] = val;
825
                                s->mv[i][j][k] = val;
826
                            }
827
                        }
828
                    }
829
                    break;
830
                case MT_FIELD:
831
                    if (s->picture_structure == PICT_FRAME) {
832
                        s->mv_type = MV_TYPE_FIELD;
833
                        for(j=0;j<2;j++) {
834
                            s->field_select[i][j] = get_bits1(&s->gb);
835
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
836
                                                     s->last_mv[i][j][0]);
837
                            s->last_mv[i][j][0] = val;
838
                            s->mv[i][j][0] = val;
839
                            dprintf("fmx=%d\n", val);
840
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
841
                                                     s->last_mv[i][j][1] >> 1);
842
                            s->last_mv[i][j][1] = val << 1;
843
                            s->mv[i][j][1] = val;
844
                            dprintf("fmy=%d\n", val);
845
                        }
846
                    } else {
847
                        s->mv_type = MV_TYPE_16X16;
848
                        s->field_select[i][0] = get_bits1(&s->gb);
849
                        for(k=0;k<2;k++) {
850
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
851
                                                     s->last_mv[i][0][k]);
852
                            s->last_mv[i][0][k] = val;
853
                            s->last_mv[i][1][k] = val;
854
                            s->mv[i][0][k] = val;
855
                        }
856
                    }
857
                    break;
858
                case MT_DMV:
859
                    {
860
                        int dmx, dmy, mx, my, m;
861

    
862
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
863
                                                s->last_mv[i][0][0]);
864
                        s->last_mv[i][0][0] = mx;
865
                        s->last_mv[i][1][0] = mx;
866
                        dmx = get_dmv(s);
867
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
868
                                                s->last_mv[i][0][1] >> 1);
869
                        dmy = get_dmv(s);
870
                        s->mv_type = MV_TYPE_DMV;
871
                        /* XXX: totally broken */
872
                        if (s->picture_structure == PICT_FRAME) {
873
                            s->last_mv[i][0][1] = my << 1;
874
                            s->last_mv[i][1][1] = my << 1;
875

    
876
                            m = s->top_field_first ? 1 : 3;
877
                            /* top -> top pred */
878
                            s->mv[i][0][0] = mx; 
879
                            s->mv[i][0][1] = my << 1;
880
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
881
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
882
                            m = 4 - m;
883
                            s->mv[i][2][0] = mx;
884
                            s->mv[i][2][1] = my << 1;
885
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
886
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
887
                        } else {
888
                            s->last_mv[i][0][1] = my;
889
                            s->last_mv[i][1][1] = my;
890
                            s->mv[i][0][0] = mx;
891
                            s->mv[i][0][1] = my;
892
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
893
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
894
                                /* + 2 * cur_field */;
895
                        }
896
                    }
897
                    break;
898
                }
899
            }
900
        }
901
    }
902

    
903
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
904
        skip_bits1(&s->gb); /* marker */
905
    }
906
    
907
    if (mb_type & MB_PAT) {
908
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
909
        if (cbp < 0){
910
            fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
911
            return -1;
912
        }
913
        cbp++;
914
    }
915
    dprintf("cbp=%x\n", cbp);
916

    
917
    if (s->mpeg2) {
918
        if (s->mb_intra) {
919
            for(i=0;i<6;i++) {
920
                if (cbp & (1 << (5 - i))) {
921
                    if (mpeg2_decode_block_intra(s, block[i], i) < 0)
922
                        return -1;
923
                } else {
924
                    s->block_last_index[i] = -1;
925
                }
926
            }
927
        } else {
928
            for(i=0;i<6;i++) {
929
                if (cbp & (1 << (5 - i))) {
930
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
931
                        return -1;
932
                } else {
933
                    s->block_last_index[i] = -1;
934
                }
935
            }
936
        }
937
    } else {
938
        for(i=0;i<6;i++) {
939
            if (cbp & (1 << (5 - i))) {
940
                if (mpeg1_decode_block(s, block[i], i) < 0)
941
                    return -1;
942
            } else {
943
                s->block_last_index[i] = -1;
944
            }
945
        }
946
    }
947
    return 0;
948
}
949

    
950
/* as h263, but only 17 codes */
951
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
952
{
953
    int code, sign, val, m, l, shift;
954

    
955
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
956
    if (code < 0) {
957
        return 0xffff;
958
    }
959
    if (code == 0) {
960
        return pred;
961
    }
962
    sign = get_bits1(&s->gb);
963
    shift = fcode - 1;
964
    val = (code - 1) << shift;
965
    if (shift > 0)
966
        val |= get_bits(&s->gb, shift);
967
    val++;
968
    if (sign)
969
        val = -val;
970
    val += pred;
971
    
972
    /* modulo decoding */
973
    l = (1 << shift) * 16;
974
    m = 2 * l;
975
    if (val < -l) {
976
        val += m;
977
    } else if (val >= l) {
978
        val -= m;
979
    }
980
    return val;
981
}
982

    
983
static inline int decode_dc(MpegEncContext *s, int component)
984
{
985
    int code, diff;
986

    
987
    if (component == 0) {
988
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
989
    } else {
990
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
991
    }
992
    if (code < 0){
993
        fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
994
        return 0xffff;
995
    }
996
    if (code == 0) {
997
        diff = 0;
998
    } else {
999
        diff = get_bits(&s->gb, code);
1000
        if ((diff & (1 << (code - 1))) == 0) 
1001
            diff = (-1 << code) | (diff + 1);
1002
    }
1003
    return diff;
1004
}
1005

    
1006
static int mpeg1_decode_block(MpegEncContext *s, 
1007
                               DCTELEM *block, 
1008
                               int n)
1009
{
1010
    int level, dc, diff, i, j, run;
1011
    int code, component;
1012
    RLTable *rl = &rl_mpeg1;
1013

    
1014
    if (s->mb_intra) {
1015
        /* DC coef */
1016
        component = (n <= 3 ? 0 : n - 4 + 1);
1017
        diff = decode_dc(s, component);
1018
        if (diff >= 0xffff)
1019
            return -1;
1020
        dc = s->last_dc[component];
1021
        dc += diff;
1022
        s->last_dc[component] = dc;
1023
        block[0] = dc;
1024
        dprintf("dc=%d diff=%d\n", dc, diff);
1025
        i = 1;
1026
    } else {
1027
        int v;
1028
        OPEN_READER(re, &s->gb);
1029
        i = 0;
1030
        /* special case for the first coef. no need to add a second vlc table */
1031
        UPDATE_CACHE(re, &s->gb);
1032
        v= SHOW_UBITS(re, &s->gb, 2);
1033
        if (v & 2) {
1034
            run = 0;
1035
            level = 1 - ((v & 1) << 1);
1036
            SKIP_BITS(re, &s->gb, 2);
1037
            CLOSE_READER(re, &s->gb);
1038
            goto add_coef;
1039
        }
1040
        CLOSE_READER(re, &s->gb);
1041
    }
1042

    
1043
    /* now quantify & encode AC coefs */
1044
    for(;;) {
1045
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1046
        if (code < 0) {
1047
            return -1;
1048
        }
1049
        if (code == 112) {
1050
            break;
1051
        } else if (code == 111) {
1052
            /* escape */
1053
            run = get_bits(&s->gb, 6);
1054
            level = get_bits(&s->gb, 8);
1055
            level= (level + ((-1)<<7)) ^ ((-1)<<7); //sign extension
1056
            if (level == -128) {
1057
                level = get_bits(&s->gb, 8) - 256;
1058
            } else if (level == 0) {
1059
                level = get_bits(&s->gb, 8);
1060
            }
1061
        } else {
1062
            run = rl->table_run[code];
1063
            level = rl->table_level[code];
1064
            if (get_bits1(&s->gb))
1065
                level = -level;
1066
        }
1067
        i += run;
1068
        if (i >= 64)
1069
            return -1;
1070
    add_coef:
1071
        dprintf("%d: run=%d level=%d\n", n, run, level);
1072
        j = zigzag_direct[i];
1073
        block[j] = level;
1074
        i++;
1075
    }
1076
    s->block_last_index[n] = i-1;
1077
    return 0;
1078
}
1079

    
1080
/* Also does unquantization here, since I will never support mpeg2
1081
   encoding */
1082
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1083
                                        DCTELEM *block, 
1084
                                        int n)
1085
{
1086
    int level, i, j, run;
1087
    int code;
1088
    RLTable *rl = &rl_mpeg1;
1089
    const UINT8 *scan_table;
1090
    const UINT16 *matrix;
1091
    int mismatch;
1092

    
1093
    if (s->alternate_scan)
1094
        scan_table = ff_alternate_vertical_scan;
1095
    else
1096
        scan_table = zigzag_direct;
1097
    mismatch = 1;
1098

    
1099
    {
1100
        int v;
1101
        OPEN_READER(re, &s->gb);
1102
        i = 0;
1103
        if (n < 4)
1104
            matrix = s->inter_matrix;
1105
        else
1106
            matrix = s->chroma_inter_matrix;
1107

    
1108
        /* special case for the first coef. no need to add a second vlc table */
1109
        UPDATE_CACHE(re, &s->gb);
1110
        v= SHOW_UBITS(re, &s->gb, 2);
1111
        if (v & 2) {
1112
            run = 0;
1113
            level = 1 - ((v & 1) << 1);
1114
            SKIP_BITS(re, &s->gb, 2);
1115
            CLOSE_READER(re, &s->gb);
1116
            goto add_coef;
1117
        }
1118
        CLOSE_READER(re, &s->gb);
1119
    }
1120

    
1121
    /* now quantify & encode AC coefs */
1122
    for(;;) {
1123
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1124
        if (code < 0){
1125
            fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1126
            return -1;
1127
        }
1128
        if (code == 112) {
1129
            break;
1130
        } else if (code == 111) {
1131
            /* escape */
1132
            run = get_bits(&s->gb, 6);
1133
            level = get_bits(&s->gb, 12);
1134
            level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
1135
        } else {
1136
            run = rl->table_run[code];
1137
            level = rl->table_level[code];
1138
            if (get_bits1(&s->gb))
1139
                level = -level;
1140
        }
1141
        i += run;
1142
        if (i >= 64){
1143
            fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1144
            return -1;
1145
        }
1146
    add_coef:
1147
        j = scan_table[i];
1148
        dprintf("%d: run=%d level=%d\n", n, run, level);
1149
        /* XXX: optimize */
1150
        if (level > 0) {
1151
            level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1152
        } else {
1153
            level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1154
            level = -level;
1155
        }
1156
        /* XXX: is it really necessary to saturate since the encoder
1157
           knows whats going on ? */
1158
        mismatch ^= level;
1159
        block[j] = level;
1160
        i++;
1161
    }
1162
    block[63] ^= (mismatch & 1);
1163
    s->block_last_index[n] = i;
1164
    return 0;
1165
}
1166

    
1167
static int mpeg2_decode_block_intra(MpegEncContext *s, 
1168
                                    DCTELEM *block, 
1169
                                    int n)
1170
{
1171
    int level, dc, diff, i, j, run;
1172
    int code, component;
1173
    RLTable *rl;
1174
    const UINT8 *scan_table;
1175
    const UINT16 *matrix;
1176
    int mismatch;
1177

    
1178
    if (s->alternate_scan)
1179
        scan_table = ff_alternate_vertical_scan;
1180
    else
1181
        scan_table = zigzag_direct;
1182

    
1183
    /* DC coef */
1184
    component = (n <= 3 ? 0 : n - 4 + 1);
1185
    diff = decode_dc(s, component);
1186
    if (diff >= 0xffff)
1187
        return -1;
1188
    dc = s->last_dc[component];
1189
    dc += diff;
1190
    s->last_dc[component] = dc;
1191
    block[0] = dc << (3 - s->intra_dc_precision);
1192
    dprintf("dc=%d\n", block[0]);
1193
    mismatch = block[0] ^ 1;
1194
    i = 1;
1195
    if (s->intra_vlc_format)
1196
        rl = &rl_mpeg2;
1197
    else
1198
        rl = &rl_mpeg1;
1199
    if (n < 4) 
1200
        matrix = s->intra_matrix;
1201
    else
1202
        matrix = s->chroma_intra_matrix;
1203

    
1204
    /* now quantify & encode AC coefs */
1205
    for(;;) {
1206
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1207
        if (code < 0){
1208
            fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1209
            return -1;
1210
        }
1211
        if (code == 112) {
1212
            break;
1213
        } else if (code == 111) {
1214
            /* escape */
1215
            run = get_bits(&s->gb, 6);
1216
            level = get_bits(&s->gb, 12);
1217
            level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
1218
        } else {
1219
            run = rl->table_run[code];
1220
            level = rl->table_level[code];
1221
            if (get_bits1(&s->gb))
1222
                level = -level;
1223
        }
1224
        i += run;
1225
        if (i >= 64){
1226
            fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1227
            return -1;
1228
        }
1229
        j = scan_table[i];
1230
        dprintf("%d: run=%d level=%d\n", n, run, level);
1231
        level = (level * s->qscale * matrix[j]) / 16;
1232
        /* XXX: is it really necessary to saturate since the encoder
1233
           knows whats going on ? */
1234
        mismatch ^= level;
1235
        block[j] = level;
1236
        i++;
1237
    }
1238
    block[63] ^= (mismatch & 1);
1239
    s->block_last_index[n] = i;
1240
    return 0;
1241
}
1242

    
1243
/* compressed picture size */
1244
#define PICTURE_BUFFER_SIZE 100000
1245

    
1246
typedef struct Mpeg1Context {
1247
    MpegEncContext mpeg_enc_ctx;
1248
    UINT32 header_state;
1249
    int start_code; /* current start code */
1250
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1251
    UINT8 *buf_ptr;
1252
    int buffer_size;
1253
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1254
    int repeat_field; /* true if we must repeat the field */
1255
} Mpeg1Context;
1256

    
1257
static int mpeg_decode_init(AVCodecContext *avctx)
1258
{
1259
    Mpeg1Context *s = avctx->priv_data;
1260
    
1261
    s->mpeg_enc_ctx.flags= avctx->flags;
1262
    common_init(&s->mpeg_enc_ctx);
1263

    
1264
    s->header_state = 0xff;
1265
    s->mpeg_enc_ctx_allocated = 0;
1266
    s->buffer_size = PICTURE_BUFFER_SIZE;
1267
    s->start_code = -1;
1268
    s->buf_ptr = s->buffer;
1269
    s->mpeg_enc_ctx.picture_number = 0;
1270
    s->repeat_field = 0;
1271
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1272
    avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1273
    return 0;
1274
}
1275

    
1276
/* return the 8 bit start code value and update the search
1277
   state. Return -1 if no start code found */
1278
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1279
                           UINT32 *header_state)
1280
{
1281
    UINT8 *buf_ptr;
1282
    unsigned int state, v;
1283
    int val;
1284

    
1285
    state = *header_state;
1286
    buf_ptr = *pbuf_ptr;
1287
    while (buf_ptr < buf_end) {
1288
        v = *buf_ptr++;
1289
        if (state == 0x000001) {
1290
            state = ((state << 8) | v) & 0xffffff;
1291
            val = state;
1292
            goto found;
1293
        }
1294
        state = ((state << 8) | v) & 0xffffff;
1295
    }
1296
    val = -1;
1297
 found:
1298
    *pbuf_ptr = buf_ptr;
1299
    *header_state = state;
1300
    return val;
1301
}
1302

    
1303
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1304
                                UINT8 *buf, int buf_size)
1305
{
1306
    Mpeg1Context *s1 = avctx->priv_data;
1307
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1308
    int ref, f_code;
1309

    
1310
    init_get_bits(&s->gb, buf, buf_size);
1311

    
1312
    ref = get_bits(&s->gb, 10); /* temporal ref */
1313
    s->pict_type = get_bits(&s->gb, 3);
1314
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1315
    skip_bits(&s->gb, 16);
1316
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1317
        s->full_pel[0] = get_bits1(&s->gb);
1318
        f_code = get_bits(&s->gb, 3);
1319
        if (f_code == 0)
1320
            return -1;
1321
        s->mpeg_f_code[0][0] = f_code;
1322
        s->mpeg_f_code[0][1] = f_code;
1323
    }
1324
    if (s->pict_type == B_TYPE) {
1325
        s->full_pel[1] = get_bits1(&s->gb);
1326
        f_code = get_bits(&s->gb, 3);
1327
        if (f_code == 0)
1328
            return -1;
1329
        s->mpeg_f_code[1][0] = f_code;
1330
        s->mpeg_f_code[1][1] = f_code;
1331
    }
1332
    s->y_dc_scale = 8;
1333
    s->c_dc_scale = 8;
1334
    s->first_slice = 1;
1335
    return 0;
1336
}
1337

    
1338
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1339
{
1340
    int horiz_size_ext, vert_size_ext;
1341
    int bit_rate_ext, vbv_buf_ext, low_delay;
1342
    int frame_rate_ext_n, frame_rate_ext_d;
1343

    
1344
    skip_bits(&s->gb, 8); /* profil and level */
1345
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1346
    skip_bits(&s->gb, 2); /* chroma_format */
1347
    horiz_size_ext = get_bits(&s->gb, 2);
1348
    vert_size_ext = get_bits(&s->gb, 2);
1349
    s->width |= (horiz_size_ext << 12);
1350
    s->height |= (vert_size_ext << 12);
1351
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1352
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1353
    skip_bits1(&s->gb); /* marker */
1354
    vbv_buf_ext = get_bits(&s->gb, 8);
1355
    low_delay = get_bits1(&s->gb);
1356
    frame_rate_ext_n = get_bits(&s->gb, 2);
1357
    frame_rate_ext_d = get_bits(&s->gb, 5);
1358
    if (frame_rate_ext_d >= 1)
1359
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1360
    dprintf("sequence extension\n");
1361
    s->mpeg2 = 1;
1362
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1363
}
1364

    
1365
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1366
{
1367
    int i, v, j;
1368

    
1369
    dprintf("matrix extension\n");
1370

    
1371
    if (get_bits1(&s->gb)) {
1372
        for(i=0;i<64;i++) {
1373
            v = get_bits(&s->gb, 8);
1374
            j = zigzag_direct[i];
1375
            s->intra_matrix[j] = v;
1376
            s->chroma_intra_matrix[j] = v;
1377
        }
1378
    }
1379
    if (get_bits1(&s->gb)) {
1380
        for(i=0;i<64;i++) {
1381
            v = get_bits(&s->gb, 8);
1382
            j = zigzag_direct[i];
1383
            s->inter_matrix[j] = v;
1384
            s->chroma_inter_matrix[j] = v;
1385
        }
1386
    }
1387
    if (get_bits1(&s->gb)) {
1388
        for(i=0;i<64;i++) {
1389
            v = get_bits(&s->gb, 8);
1390
            j = zigzag_direct[i];
1391
            s->chroma_intra_matrix[j] = v;
1392
        }
1393
    }
1394
    if (get_bits1(&s->gb)) {
1395
        for(i=0;i<64;i++) {
1396
            v = get_bits(&s->gb, 8);
1397
            j = zigzag_direct[i];
1398
            s->chroma_inter_matrix[j] = v;
1399
        }
1400
    }
1401
}
1402

    
1403
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1404
{
1405
    s->full_pel[0] = s->full_pel[1] = 0;
1406
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1407
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1408
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1409
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1410
    s->intra_dc_precision = get_bits(&s->gb, 2);
1411
    s->picture_structure = get_bits(&s->gb, 2);
1412
    s->top_field_first = get_bits1(&s->gb);
1413
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1414
    s->concealment_motion_vectors = get_bits1(&s->gb);
1415
    s->q_scale_type = get_bits1(&s->gb);
1416
    s->intra_vlc_format = get_bits1(&s->gb);
1417
    s->alternate_scan = get_bits1(&s->gb);
1418
    s->repeat_first_field = get_bits1(&s->gb);
1419
    s->chroma_420_type = get_bits1(&s->gb);
1420
    s->progressive_frame = get_bits1(&s->gb);
1421
    /* composite display not parsed */
1422
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1423
    dprintf("picture_structure=%d\n", s->picture_structure);
1424
    dprintf("top field first=%d\n", s->top_field_first);
1425
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1426
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1427
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1428
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1429
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1430
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1431
}
1432

    
1433
static void mpeg_decode_extension(AVCodecContext *avctx, 
1434
                                  UINT8 *buf, int buf_size)
1435
{
1436
    Mpeg1Context *s1 = avctx->priv_data;
1437
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1438
    int ext_type;
1439

    
1440
    init_get_bits(&s->gb, buf, buf_size);
1441
    
1442
    ext_type = get_bits(&s->gb, 4);
1443
    switch(ext_type) {
1444
    case 0x1:
1445
        /* sequence ext */
1446
        mpeg_decode_sequence_extension(s);
1447
        break;
1448
    case 0x3:
1449
        /* quant matrix extension */
1450
        mpeg_decode_quant_matrix_extension(s);
1451
        break;
1452
    case 0x8:
1453
        /* picture extension */
1454
        mpeg_decode_picture_coding_extension(s);
1455
        break;
1456
    }
1457
}
1458

    
1459
/* return 1 if end of frame */
1460
static int mpeg_decode_slice(AVCodecContext *avctx, 
1461
                              AVPicture *pict,
1462
                              int start_code,
1463
                              UINT8 *buf, int buf_size)
1464
{
1465
    Mpeg1Context *s1 = avctx->priv_data;
1466
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1467
    int ret;
1468

    
1469
    start_code = (start_code - 1) & 0xff;
1470
    if (start_code >= s->mb_height){
1471
        fprintf(stderr, "slice below image\n");
1472
        return -1;
1473
    }
1474
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1475
    s->last_dc[1] = s->last_dc[0];
1476
    s->last_dc[2] = s->last_dc[0];
1477
    memset(s->last_mv, 0, sizeof(s->last_mv));
1478
    s->mb_x = -1;
1479
    s->mb_y = start_code;
1480
    s->mb_incr = 0;
1481
    /* start frame decoding */
1482
    if (s->first_slice) {
1483
        s->first_slice = 0;
1484
        MPV_frame_start(s, avctx);
1485
    }
1486

    
1487
    init_get_bits(&s->gb, buf, buf_size);
1488

    
1489
    s->qscale = get_qscale(s);
1490
    /* extra slice info */
1491
    while (get_bits1(&s->gb) != 0) {
1492
        skip_bits(&s->gb, 8);
1493
    }
1494

    
1495
    for(;;) {
1496
        clear_blocks(s->block[0]);
1497
        emms_c();
1498
        ret = mpeg_decode_mb(s, s->block);
1499
        dprintf("ret=%d\n", ret);
1500
        if (ret < 0)
1501
            return -1;
1502
        if (ret == 1)
1503
            break;
1504
        MPV_decode_mb(s, s->block);
1505
    }
1506
    emms_c();
1507

    
1508
    /* end of slice reached */
1509
    if (s->mb_x == (s->mb_width - 1) &&
1510
        s->mb_y == (s->mb_height - 1)) {
1511
        /* end of image */
1512
        UINT8 **picture;
1513

    
1514
        MPV_frame_end(s);
1515

    
1516
        /* XXX: incorrect reported qscale for mpeg2 */
1517
        if (s->pict_type == B_TYPE) {
1518
            picture = s->current_picture;
1519
            avctx->quality = s->qscale;
1520
        } else {
1521
            /* latency of 1 frame for I and P frames */
1522
            /* XXX: use another variable than picture_number */
1523
            if (s->picture_number == 0) {
1524
                picture = NULL;
1525
            } else {
1526
                picture = s->last_picture;
1527
                avctx->quality = s->last_qscale;
1528
            }
1529
            s->last_qscale = s->qscale;
1530
            s->picture_number++;
1531
        }
1532
        if (picture) {
1533
            pict->data[0] = picture[0];
1534
            pict->data[1] = picture[1];
1535
            pict->data[2] = picture[2];
1536
            pict->linesize[0] = s->linesize;
1537
            pict->linesize[1] = s->uvlinesize;
1538
            pict->linesize[2] = s->uvlinesize;
1539
            return 1;
1540
        } else {
1541
            return 0;
1542
        }
1543
    } else {
1544
        return 0;
1545
    }
1546
}
1547

    
1548
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1549
                                 UINT8 *buf, int buf_size)
1550
{
1551
    Mpeg1Context *s1 = avctx->priv_data;
1552
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1553
    int width, height, i, v, j;
1554

    
1555
    init_get_bits(&s->gb, buf, buf_size);
1556

    
1557
    width = get_bits(&s->gb, 12);
1558
    height = get_bits(&s->gb, 12);
1559
    skip_bits(&s->gb, 4);
1560
    s->frame_rate_index = get_bits(&s->gb, 4);
1561
    if (s->frame_rate_index == 0)
1562
        return -1;
1563
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1564
    if (get_bits1(&s->gb) == 0) /* marker */
1565
        return -1;
1566
    if (width <= 0 || height <= 0 ||
1567
        (width % 2) != 0 || (height % 2) != 0)
1568
        return -1;
1569
    if (width != s->width ||
1570
        height != s->height) {
1571
        /* start new mpeg1 context decoding */
1572
        s->out_format = FMT_MPEG1;
1573
        if (s1->mpeg_enc_ctx_allocated) {
1574
            MPV_common_end(s);
1575
        }
1576
        s->width = width;
1577
        s->height = height;
1578
        avctx->has_b_frames= s->has_b_frames = 1;
1579
        s->avctx = avctx;
1580
        avctx->width = width;
1581
        avctx->height = height;
1582
        if (s->frame_rate_index >= 9) {
1583
            /* at least give a valid frame rate (some old mpeg1 have this) */
1584
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1585
        } else {
1586
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1587
        }
1588
        s->frame_rate = avctx->frame_rate;
1589
        avctx->bit_rate = s->bit_rate;
1590
        
1591
        if (MPV_common_init(s) < 0)
1592
            return -1;
1593
        mpeg1_init_vlc(s);
1594
        s1->mpeg_enc_ctx_allocated = 1;
1595
    }
1596

    
1597
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1598
    skip_bits(&s->gb, 1);
1599

    
1600
    /* get matrix */
1601
    if (get_bits1(&s->gb)) {
1602
        for(i=0;i<64;i++) {
1603
            v = get_bits(&s->gb, 8);
1604
            j = zigzag_direct[i];
1605
            s->intra_matrix[j] = v;
1606
            s->chroma_intra_matrix[j] = v;
1607
        }
1608
#ifdef DEBUG
1609
        dprintf("intra matrix present\n");
1610
        for(i=0;i<64;i++)
1611
            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1612
        printf("\n");
1613
#endif
1614
    } else {
1615
        for(i=0;i<64;i++) {
1616
            v = ff_mpeg1_default_intra_matrix[i];
1617
            s->intra_matrix[i] = v;
1618
            s->chroma_intra_matrix[i] = v;
1619
        }
1620
    }
1621
    if (get_bits1(&s->gb)) {
1622
        for(i=0;i<64;i++) {
1623
            v = get_bits(&s->gb, 8);
1624
            j = zigzag_direct[i];
1625
            s->inter_matrix[j] = v;
1626
            s->chroma_inter_matrix[j] = v;
1627
        }
1628
#ifdef DEBUG
1629
        dprintf("non intra matrix present\n");
1630
        for(i=0;i<64;i++)
1631
            dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1632
        printf("\n");
1633
#endif
1634
    } else {
1635
        for(i=0;i<64;i++) {
1636
            v = ff_mpeg1_default_non_intra_matrix[i];
1637
            s->inter_matrix[i] = v;
1638
            s->chroma_inter_matrix[i] = v;
1639
        }
1640
    }
1641

    
1642
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1643
    s->progressive_sequence = 1;
1644
    s->progressive_frame = 1;
1645
    s->picture_structure = PICT_FRAME;
1646
    s->frame_pred_frame_dct = 1;
1647
    s->mpeg2 = 0;
1648
    avctx->sub_id = 1; /* indicates mpeg1 */
1649
    return 0;
1650
}
1651

    
1652
/* handle buffering and image synchronisation */
1653
static int mpeg_decode_frame(AVCodecContext *avctx, 
1654
                             void *data, int *data_size,
1655
                             UINT8 *buf, int buf_size)
1656
{
1657
    Mpeg1Context *s = avctx->priv_data;
1658
    UINT8 *buf_end, *buf_ptr, *buf_start;
1659
    int len, start_code_found, ret, code, start_code, input_size;
1660
    AVPicture *picture = data;
1661
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1662
            
1663
    dprintf("fill_buffer\n");
1664

    
1665
    *data_size = 0;
1666

    
1667
    /* special case for last picture */
1668
    if (buf_size == 0) {
1669
        if (s2->picture_number > 0) {
1670
            picture->data[0] = s2->next_picture[0];
1671
            picture->data[1] = s2->next_picture[1];
1672
            picture->data[2] = s2->next_picture[2];
1673
            picture->linesize[0] = s2->linesize;
1674
            picture->linesize[1] = s2->uvlinesize;
1675
            picture->linesize[2] = s2->uvlinesize;
1676
            *data_size = sizeof(AVPicture);
1677
        }
1678
        return 0;
1679
    }
1680

    
1681
    buf_ptr = buf;
1682
    buf_end = buf + buf_size;
1683

    
1684
#if 0    
1685
    if (s->repeat_field % 2 == 1) { 
1686
        s->repeat_field++;
1687
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1688
        //        s2->picture_number, s->repeat_field);
1689
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1690
            *data_size = sizeof(AVPicture);
1691
            goto the_end;
1692
        }
1693
    }
1694
#endif
1695
    while (buf_ptr < buf_end) {
1696
        buf_start = buf_ptr;
1697
        /* find start next code */
1698
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1699
        if (code >= 0) {
1700
            start_code_found = 1;
1701
        } else {
1702
            start_code_found = 0;
1703
        }
1704
        /* copy to buffer */
1705
        len = buf_ptr - buf_start;
1706
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1707
            /* data too big : flush */
1708
            s->buf_ptr = s->buffer;
1709
            if (start_code_found)
1710
                s->start_code = code;
1711
        } else {
1712
            memcpy(s->buf_ptr, buf_start, len);
1713
            s->buf_ptr += len;
1714
            
1715
            if (start_code_found) {
1716
                /* prepare data for next start code */
1717
                input_size = s->buf_ptr - s->buffer;
1718
                start_code = s->start_code;
1719
                s->buf_ptr = s->buffer;
1720
                s->start_code = code;
1721
                switch(start_code) {
1722
                case SEQ_START_CODE:
1723
                    mpeg1_decode_sequence(avctx, s->buffer, 
1724
                                          input_size);
1725
                    break;
1726
                            
1727
                case PICTURE_START_CODE:
1728
                    /* we have a complete image : we try to decompress it */
1729
                    mpeg1_decode_picture(avctx, 
1730
                                         s->buffer, input_size);
1731
                    break;
1732
                case EXT_START_CODE:
1733
                    mpeg_decode_extension(avctx,
1734
                                          s->buffer, input_size);
1735
                    break;
1736
                default:
1737
                    if (start_code >= SLICE_MIN_START_CODE &&
1738
                        start_code <= SLICE_MAX_START_CODE) {
1739
                        ret = mpeg_decode_slice(avctx, picture,
1740
                                                start_code, s->buffer, input_size);
1741
                        if (ret == 1) {
1742
                            /* got a picture: exit */
1743
                            /* first check if we must repeat the frame */
1744
                            avctx->repeat_pict = 0;
1745
#if 0
1746
                            if (s2->progressive_frame && s2->repeat_first_field) {
1747
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1748
                                //s2->repeat_first_field = 0;
1749
                                //s2->progressive_frame = 0;
1750
                                if (++s->repeat_field > 2)
1751
                                    s->repeat_field = 0;
1752
                                avctx->repeat_pict = 1;
1753
                            }
1754
#endif                      
1755
                            if (s2->repeat_first_field) {
1756
                                if (s2->progressive_sequence) {
1757
                                    if (s2->top_field_first)
1758
                                        avctx->repeat_pict = 4;
1759
                                    else
1760
                                        avctx->repeat_pict = 2;
1761
                                } else if (s2->progressive_frame) {
1762
                                    avctx->repeat_pict = 1;
1763
                                }
1764
                            }         
1765
                            *data_size = sizeof(AVPicture);
1766
                            goto the_end;
1767
                        }else if(ret==-1){
1768
                            printf("Error while decoding slice\n");
1769
                        }
1770
                    }
1771
                    break;
1772
                }
1773
            }
1774
        }
1775
    }
1776
 the_end:
1777
    return buf_ptr - buf;
1778
}
1779

    
1780
static int mpeg_decode_end(AVCodecContext *avctx)
1781
{
1782
    Mpeg1Context *s = avctx->priv_data;
1783

    
1784
    if (s->mpeg_enc_ctx_allocated)
1785
        MPV_common_end(&s->mpeg_enc_ctx);
1786
    return 0;
1787
}
1788

    
1789
AVCodec mpeg_decoder = {
1790
    "mpegvideo",
1791
    CODEC_TYPE_VIDEO,
1792
    CODEC_ID_MPEG1VIDEO,
1793
    sizeof(Mpeg1Context),
1794
    mpeg_decode_init,
1795
    NULL,
1796
    mpeg_decode_end,
1797
    mpeg_decode_frame,
1798
    CODEC_CAP_DR1,
1799
};