Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ 5bd12d12

History | View | Annotate | Download (52.8 KB)

1
/*
2
 * MPEG1 encoder / MPEG2 decoder
3
 * Copyright (c) 2000,2001 Gerard Lantau.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program 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
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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 ABS(a) ((a)<0 ? -(a) : (a))
37

    
38
static void mpeg1_encode_block(MpegEncContext *s, 
39
                         DCTELEM *block, 
40
                         int component);
41
static void mpeg1_encode_motion(MpegEncContext *s, int val);
42
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
43
static int mpeg1_decode_block(MpegEncContext *s, 
44
                              DCTELEM *block, 
45
                              int n);
46
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
47
                                        DCTELEM *block, 
48
                                        int n);
49
static int mpeg2_decode_block_intra(MpegEncContext *s, 
50
                                    DCTELEM *block, 
51
                                    int n);
52
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
53

    
54
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
55
static UINT8 fcode_tab[MAX_MV*2+1];
56

    
57
static void put_header(MpegEncContext *s, int header)
58
{
59
    align_put_bits(&s->pb);
60
    put_bits(&s->pb, 16, header>>16);
61
    put_bits(&s->pb, 16, header&0xFFFF);
62
}
63

    
64
/* put sequence header if needed */
65
static void mpeg1_encode_sequence_header(MpegEncContext *s)
66
{
67
        unsigned int vbv_buffer_size;
68
        unsigned int fps, v;
69
        int n;
70
        UINT64 time_code;
71
        
72
        if (s->picture_in_gop_number == 0) {
73
            /* mpeg1 header repeated every gop */
74
            put_header(s, SEQ_START_CODE);
75
            
76
            /* search closest frame rate */
77
            {
78
                int i, dmin, d;
79
                s->frame_rate_index = 0;
80
                dmin = 0x7fffffff;
81
                for(i=1;i<9;i++) {
82
                    d = abs(s->frame_rate - frame_rate_tab[i]);
83
                    if (d < dmin) {
84
                        dmin = d;
85
                        s->frame_rate_index = i;
86
                    }
87
                }
88
            }
89
 
90
            put_bits(&s->pb, 12, s->width);
91
            put_bits(&s->pb, 12, s->height);
92
            put_bits(&s->pb, 4, 1); /* 1/1 aspect ratio */
93
            put_bits(&s->pb, 4, s->frame_rate_index);
94
            v = s->bit_rate / 400;
95
            if (v > 0x3ffff)
96
                v = 0x3ffff;
97
            put_bits(&s->pb, 18, v);
98
            put_bits(&s->pb, 1, 1); /* marker */
99
            /* vbv buffer size: slightly greater than an I frame. We add
100
               some margin just in case */
101
            vbv_buffer_size = (3 * s->I_frame_bits) / (2 * 8);
102
            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
103
            put_bits(&s->pb, 1, 1); /* constrained parameter flag */
104
            put_bits(&s->pb, 1, 0); /* no custom intra matrix */
105
            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
106

    
107
            put_header(s, GOP_START_CODE);
108
            put_bits(&s->pb, 1, 0); /* do drop frame */
109
            /* time code : we must convert from the real frame rate to a
110
               fake mpeg frame rate in case of low frame rate */
111
            fps = frame_rate_tab[s->frame_rate_index];
112
            time_code = (INT64)s->fake_picture_number * FRAME_RATE_BASE;
113
            s->gop_picture_number = s->fake_picture_number;
114
            put_bits(&s->pb, 5, (UINT32)((time_code / (fps * 3600)) % 24));
115
            put_bits(&s->pb, 6, (UINT32)((time_code / (fps * 60)) % 60));
116
            put_bits(&s->pb, 1, 1);
117
            put_bits(&s->pb, 6, (UINT32)((time_code / fps) % 60));
118
            put_bits(&s->pb, 6, (UINT32)((time_code % fps) / FRAME_RATE_BASE));
119
            put_bits(&s->pb, 1, 1); /* closed gop */
120
            put_bits(&s->pb, 1, 0); /* broken link */
121
        }
122

    
123
        if (s->frame_rate < (24 * FRAME_RATE_BASE) && s->picture_number > 0) {
124
            /* insert empty P pictures to slow down to the desired
125
               frame rate. Each fake pictures takes about 20 bytes */
126
            fps = frame_rate_tab[s->frame_rate_index];
127
            n = (((INT64)s->picture_number * fps) / s->frame_rate) - 1;
128
            while (s->fake_picture_number < n) {
129
                mpeg1_skip_picture(s, s->fake_picture_number - 
130
                                   s->gop_picture_number); 
131
                s->fake_picture_number++;
132
            }
133

    
134
        }
135
}
136

    
137

    
138
/* insert a fake P picture */
139
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num)
140
{
141
    unsigned int mb_incr;
142

    
143
    /* mpeg1 picture header */
144
    put_header(s, PICTURE_START_CODE);
145
    /* temporal reference */
146
    put_bits(&s->pb, 10, pict_num & 0x3ff); 
147
    
148
    put_bits(&s->pb, 3, P_TYPE);
149
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
150
    
151
    put_bits(&s->pb, 1, 1); /* integer coordinates */
152
    put_bits(&s->pb, 3, 1); /* forward_f_code */
153
    
154
    put_bits(&s->pb, 1, 0); /* extra bit picture */
155
    
156
    /* only one slice */
157
    put_header(s, SLICE_MIN_START_CODE);
158
    put_bits(&s->pb, 5, 1); /* quantizer scale */
159
    put_bits(&s->pb, 1, 0); /* slice extra information */
160
    
161
    mb_incr = 1;
162
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
163
             mbAddrIncrTable[mb_incr - 1][0]);
164
    
165
    /* empty macroblock */
166
    put_bits(&s->pb, 3, 1); /* motion only */
167
    
168
    /* zero motion x & y */
169
    put_bits(&s->pb, 1, 1); 
170
    put_bits(&s->pb, 1, 1); 
171

    
172
    /* output a number of empty slice */
173
    mb_incr = s->mb_width * s->mb_height - 1;
174
    while (mb_incr > 33) {
175
        put_bits(&s->pb, 11, 0x008);
176
        mb_incr -= 33;
177
    }
178
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
179
             mbAddrIncrTable[mb_incr - 1][0]);
180
    
181
    /* empty macroblock */
182
    put_bits(&s->pb, 3, 1); /* motion only */
183
    
184
    /* zero motion x & y */
185
    put_bits(&s->pb, 1, 1); 
186
    put_bits(&s->pb, 1, 1); 
187
}
188

    
189
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
190
{
191
    static int done=0;
192

    
193
    if (!done) {
194
        int i;
195
        done = 1;
196
        init_rl(&rl_mpeg1);
197
        
198
        for(i=0; i<64; i++)
199
        {
200
                mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
201
                mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
202
        }
203

    
204
        /* build unified dc encoding tables */
205
        for(i=-255; i<256; i++)
206
        {
207
                int adiff, index;
208
                int bits, code;
209
                int diff=i;
210

    
211
                adiff = ABS(diff);
212
                if(diff<0) diff--;
213
                index = vlc_dc_table[adiff];
214

    
215
                bits= vlc_dc_lum_bits[index] + index;
216
                code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
217
                mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
218
                
219
                bits= vlc_dc_chroma_bits[index] + index;
220
                code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
221
                mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
222
        }
223
    }
224
    mpeg1_encode_sequence_header(s);
225

    
226
    /* mpeg1 picture header */
227
    put_header(s, PICTURE_START_CODE);
228
    /* temporal reference */
229
    put_bits(&s->pb, 10, (s->fake_picture_number - 
230
                          s->gop_picture_number) & 0x3ff); 
231
    s->fake_picture_number++;
232
    
233
    put_bits(&s->pb, 3, s->pict_type);
234
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
235
    
236
    if (s->pict_type == P_TYPE) {
237
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
238
        put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
239
    }
240
    
241
    put_bits(&s->pb, 1, 0); /* extra bit picture */
242
    
243
    /* only one slice */
244
    put_header(s, SLICE_MIN_START_CODE);
245
    put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
246
    put_bits(&s->pb, 1, 0); /* slice extra information */
247
}
248

    
249
void mpeg1_encode_mb(MpegEncContext *s,
250
                     DCTELEM block[6][64],
251
                     int motion_x, int motion_y)
252
{
253
    int mb_incr, i, cbp, mb_x, mb_y;
254

    
255
    mb_x = s->mb_x;
256
    mb_y = s->mb_y;
257

    
258
    /* compute cbp */
259
    cbp = 0;
260
    for(i=0;i<6;i++) {
261
        if (s->block_last_index[i] >= 0)
262
            cbp |= 1 << (5 - i);
263
    }
264

    
265
    /* skip macroblock, except if first or last macroblock of a slice */
266
    if ((cbp | motion_x | motion_y) == 0 &&
267
        (!((mb_x | mb_y) == 0 ||
268
           (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1)))) {
269
        s->mb_incr++;
270
    } else {
271
        /* output mb incr */
272
        mb_incr = s->mb_incr;
273

    
274
        while (mb_incr > 33) {
275
            put_bits(&s->pb, 11, 0x008);
276
            mb_incr -= 33;
277
        }
278
        put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
279
                 mbAddrIncrTable[mb_incr - 1][0]);
280
        
281
        if (s->pict_type == I_TYPE) {
282
            put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
283
        } else {
284
            if (s->mb_intra) {
285
                put_bits(&s->pb, 5, 0x03);
286
            } else {
287
                if (cbp != 0) {
288
                    if (motion_x == 0 && motion_y == 0) {
289
                        put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
290
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
291
                    } else {
292
                        put_bits(&s->pb, 1, 1); /* motion + cbp */
293
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
294
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
295
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
296
                    }
297
                } else {
298
                    put_bits(&s->pb, 3, 1); /* motion only */
299
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
300
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
301
                }
302
            }
303
        }
304
        for(i=0;i<6;i++) {
305
            if (cbp & (1 << (5 - i))) {
306
                mpeg1_encode_block(s, block[i], i);
307
            }
308
        }
309
        s->mb_incr = 1;
310
    }
311
    s->last_mv[0][0][0] = motion_x;
312
    s->last_mv[0][0][1] = motion_y;
313
}
314

    
315
static void mpeg1_encode_motion(MpegEncContext *s, int val)
316
{
317
    int code, bit_size, l, m, bits, range, sign;
318

    
319
    if (val == 0) {
320
        /* zero vector */
321
        code = 0;
322
        put_bits(&s->pb,
323
                 mbMotionVectorTable[0][1], 
324
                 mbMotionVectorTable[0][0]); 
325
    } else {
326
        bit_size = s->f_code - 1;
327
        range = 1 << bit_size;
328
        /* modulo encoding */
329
        l = 16 * range;
330
        m = 2 * l;
331
        if (val < -l) {
332
            val += m;
333
        } else if (val >= l) {
334
            val -= m;
335
        }
336

    
337
        if (val >= 0) {
338
            val--;
339
            code = (val >> bit_size) + 1;
340
            bits = val & (range - 1);
341
            sign = 0;
342
        } else {
343
            val = -val;
344
            val--;
345
            code = (val >> bit_size) + 1;
346
            bits = val & (range - 1);
347
            sign = 1;
348
        }
349
        put_bits(&s->pb,
350
                 mbMotionVectorTable[code][1], 
351
                 mbMotionVectorTable[code][0]); 
352
        put_bits(&s->pb, 1, sign);
353
        if (bit_size > 0) {
354
            put_bits(&s->pb, bit_size, bits);
355
        }
356
    }
357
}
358

    
359
void mpeg1_encode_init(MpegEncContext *s)
360
{
361
    static int done=0;
362
    if(!done){
363
        int f_code;
364
        int mv;
365

    
366
        done=1;
367
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
368
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
369
                int len;
370

    
371
                if(mv==0) len= mbMotionVectorTable[0][1];
372
                else{
373
                    int val, bit_size, range, code;
374

    
375
                    bit_size = s->f_code - 1;
376
                    range = 1 << bit_size;
377

    
378
                    val=mv;
379
                    if (val < 0) 
380
                        val = -val;
381
                    val--;
382
                    code = (val >> bit_size) + 1;
383
                    if(code<17){
384
                        len= mbMotionVectorTable[code][1] + 1 + bit_size;
385
                    }else{
386
                        len= mbMotionVectorTable[16][1] + 2 + bit_size;
387
                    }
388
                }
389

    
390
                mv_penalty[f_code][mv+MAX_MV]= len;
391
            }
392
        }
393
        
394

    
395
        for(f_code=MAX_FCODE; f_code>0; f_code--){
396
            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
397
                fcode_tab[mv+MAX_MV]= f_code;
398
            }
399
        }
400
    }
401
    s->mv_penalty= mv_penalty;
402
    s->fcode_tab= fcode_tab;
403
    s->min_qcoeff=-255;
404
    s->max_qcoeff= 255;
405
    s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
406
    s->inter_quant_bias= 0;
407
}
408
 
409
static inline void encode_dc(MpegEncContext *s, int diff, int component)
410
{
411
    if (component == 0) {
412
        put_bits(
413
            &s->pb, 
414
            mpeg1_lum_dc_uni[diff+255]&0xFF,
415
            mpeg1_lum_dc_uni[diff+255]>>8);
416
    } else {
417
        put_bits(
418
            &s->pb, 
419
            mpeg1_chr_dc_uni[diff+255]&0xFF,
420
            mpeg1_chr_dc_uni[diff+255]>>8);
421
    }
422
}
423

    
424
static void mpeg1_encode_block(MpegEncContext *s, 
425
                               DCTELEM *block, 
426
                               int n)
427
{
428
    int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
429
    int code, component;
430
//    RLTable *rl = &rl_mpeg1;
431

    
432
    last_index = s->block_last_index[n];
433

    
434
    /* DC coef */
435
    if (s->mb_intra) {
436
        component = (n <= 3 ? 0 : n - 4 + 1);
437
        dc = block[0]; /* overflow is impossible */
438
        diff = dc - s->last_dc[component];
439
        encode_dc(s, diff, component);
440
        s->last_dc[component] = dc;
441
        i = 1;
442
    } else {
443
        /* encode the first coefficient : needs to be done here because
444
           it is handled slightly differently */
445
        level = block[0];
446
        if (abs(level) == 1) {
447
                code = ((UINT32)level >> 31); /* the sign bit */
448
                put_bits(&s->pb, 2, code | 0x02);
449
                i = 1;
450
        } else {
451
            i = 0;
452
            last_non_zero = -1;
453
            goto next_coef;
454
        }
455
    }
456

    
457
    /* now quantify & encode AC coefs */
458
    last_non_zero = i - 1;
459

    
460
    for(;i<=last_index;i++) {
461
        j = zigzag_direct[i];
462
        level = block[j];
463
    next_coef:
464
#if 0
465
        if (level != 0)
466
            dprintf("level[%d]=%d\n", i, level);
467
#endif            
468
        /* encode using VLC */
469
        if (level != 0) {
470
            run = i - last_non_zero - 1;
471
#ifdef ARCH_X86
472
            asm volatile(
473
                "movl %2, %1                \n\t"
474
                "movl %1, %0                \n\t"
475
                "addl %1, %1                \n\t"
476
                "sbbl %1, %1                \n\t"
477
                "xorl %1, %0                \n\t"
478
                "subl %1, %0                \n\t"
479
                "andl $1, %1                \n\t"
480
                : "=&r" (alevel), "=&r" (sign)
481
                : "g" (level)
482
            );
483
#else
484
            sign = 0;
485
            alevel = level;
486
            if (alevel < 0) {
487
                sign = 1;
488
                alevel = -alevel;
489
            }
490
#endif
491
//            code = get_rl_index(rl, 0, run, alevel);
492
            if (alevel > mpeg1_max_level[0][run])
493
                code= 111; /*rl->n*/
494
            else
495
                code= mpeg1_index_run[0][run] + alevel - 1;
496

    
497
            if (code < 111 /* rl->n */) {
498
                    /* store the vlc & sign at once */
499
                put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
500
            } else {
501
                /* escape seems to be pretty rare <5% so i dont optimize it */
502
                put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
503
                /* escape: only clip in this case */
504
                put_bits(&s->pb, 6, run);
505
                if (alevel < 128) {
506
                    put_bits(&s->pb, 8, level & 0xff);
507
                } else {
508
                    if (level < 0) {
509
                        put_bits(&s->pb, 16, 0x8001 + level + 255);
510
                    } else {
511
                        put_bits(&s->pb, 16, level & 0xffff);
512
                    }
513
                }
514
            }
515
            last_non_zero = i;
516
        }
517
    }
518
    /* end of block */
519
    put_bits(&s->pb, 2, 0x2);
520
}
521

    
522
/******************************************/
523
/* decoding */
524

    
525
static VLC dc_lum_vlc;
526
static VLC dc_chroma_vlc;
527
static VLC mv_vlc;
528
static VLC mbincr_vlc;
529
static VLC mb_ptype_vlc;
530
static VLC mb_btype_vlc;
531
static VLC mb_pat_vlc;
532

    
533
void mpeg1_init_vlc(MpegEncContext *s)
534
{
535
    static int done = 0;
536

    
537
    if (!done) {
538

    
539
        init_vlc(&dc_lum_vlc, 9, 12, 
540
                 vlc_dc_lum_bits, 1, 1,
541
                 vlc_dc_lum_code, 2, 2);
542
        init_vlc(&dc_chroma_vlc, 9, 12, 
543
                 vlc_dc_chroma_bits, 1, 1,
544
                 vlc_dc_chroma_code, 2, 2);
545
        init_vlc(&mv_vlc, 9, 17, 
546
                 &mbMotionVectorTable[0][1], 2, 1,
547
                 &mbMotionVectorTable[0][0], 2, 1);
548
        init_vlc(&mbincr_vlc, 9, 35, 
549
                 &mbAddrIncrTable[0][1], 2, 1,
550
                 &mbAddrIncrTable[0][0], 2, 1);
551
        init_vlc(&mb_pat_vlc, 9, 63, 
552
                 &mbPatTable[0][1], 2, 1,
553
                 &mbPatTable[0][0], 2, 1);
554
        
555
        init_vlc(&mb_ptype_vlc, 6, 32, 
556
                 &table_mb_ptype[0][1], 2, 1,
557
                 &table_mb_ptype[0][0], 2, 1);
558
        init_vlc(&mb_btype_vlc, 6, 32, 
559
                 &table_mb_btype[0][1], 2, 1,
560
                 &table_mb_btype[0][0], 2, 1);
561
        init_rl(&rl_mpeg1);
562
        init_rl(&rl_mpeg2);
563
        /* cannot use generic init because we must add the EOB code */
564
        init_vlc(&rl_mpeg1.vlc, 9, rl_mpeg1.n + 2, 
565
                 &rl_mpeg1.table_vlc[0][1], 4, 2,
566
                 &rl_mpeg1.table_vlc[0][0], 4, 2);
567
        init_vlc(&rl_mpeg2.vlc, 9, rl_mpeg2.n + 2, 
568
                 &rl_mpeg2.table_vlc[0][1], 4, 2,
569
                 &rl_mpeg2.table_vlc[0][0], 4, 2);
570
    }
571
}
572

    
573
static inline int get_dmv(MpegEncContext *s)
574
{
575
    if(get_bits1(&s->gb)) 
576
        return 1 - (get_bits1(&s->gb) << 1);
577
    else
578
        return 0;
579
}
580

    
581
static inline int get_qscale(MpegEncContext *s)
582
{
583
    int qscale;
584
    if (s->mpeg2) {
585
        if (s->q_scale_type) {
586
            qscale = non_linear_qscale[get_bits(&s->gb, 5)];
587
        } else {
588
            qscale = get_bits(&s->gb, 5) << 1;
589
        }
590
    } else {
591
        /* for mpeg1, we use the generic unquant code */
592
        qscale = get_bits(&s->gb, 5);
593
    }
594
    return qscale;
595
}
596

    
597
/* motion type (for mpeg2) */
598
#define MT_FIELD 1
599
#define MT_FRAME 2
600
#define MT_16X8  2
601
#define MT_DMV   3
602

    
603
static int mpeg_decode_mb(MpegEncContext *s,
604
                          DCTELEM block[6][64])
605
{
606
    int i, j, k, cbp, val, code, mb_type, motion_type;
607
    
608
    /* skip mb handling */
609
    if (s->mb_incr == 0) {
610
        /* read again increment */
611
        s->mb_incr = 1;
612
        for(;;) {
613
            code = get_vlc(&s->gb, &mbincr_vlc);
614
            if (code < 0)
615
                return 1; /* error = end of slice */
616
            if (code >= 33) {
617
                if (code == 33) {
618
                    s->mb_incr += 33;
619
                }
620
                /* otherwise, stuffing, nothing to do */
621
            } else {
622
                s->mb_incr += code;
623
                break;
624
            }
625
        }
626
    }
627
    if (++s->mb_x >= s->mb_width) {
628
        s->mb_x = 0;
629
        if (s->mb_y >= (s->mb_height - 1))
630
            return -1;
631
        s->mb_y++;
632
    }
633
    dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
634

    
635
    if (--s->mb_incr != 0) {
636
        /* skip mb */
637
        s->mb_intra = 0;
638
        for(i=0;i<6;i++)
639
            s->block_last_index[i] = -1;
640
        s->mv_type = MV_TYPE_16X16;
641
        if (s->pict_type == P_TYPE) {
642
            /* if P type, zero motion vector is implied */
643
            s->mv_dir = MV_DIR_FORWARD;
644
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
645
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
646
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
647
        } else {
648
            /* if B type, reuse previous vectors and directions */
649
            s->mv[0][0][0] = s->last_mv[0][0][0];
650
            s->mv[0][0][1] = s->last_mv[0][0][1];
651
            s->mv[1][0][0] = s->last_mv[1][0][0];
652
            s->mv[1][0][1] = s->last_mv[1][0][1];
653
        }
654
        s->mb_skiped = 1;
655
        return 0;
656
    }
657

    
658
    switch(s->pict_type) {
659
    default:
660
    case I_TYPE:
661
        if (get_bits1(&s->gb) == 0) {
662
            if (get_bits1(&s->gb) == 0)
663
                return -1;
664
            mb_type = MB_QUANT | MB_INTRA;
665
        } else {
666
            mb_type = MB_INTRA;
667
        }
668
        break;
669
    case P_TYPE:
670
        mb_type = get_vlc(&s->gb, &mb_ptype_vlc);
671
        if (mb_type < 0)
672
            return -1;
673
        break;
674
    case B_TYPE:
675
        mb_type = get_vlc(&s->gb, &mb_btype_vlc);
676
        if (mb_type < 0)
677
            return -1;
678
        break;
679
    }
680
    dprintf("mb_type=%x\n", mb_type);
681
    motion_type = 0; /* avoid warning */
682
    if (mb_type & (MB_FOR|MB_BACK)) {
683
        /* get additionnal motion vector type */
684
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
685
            motion_type = MT_FRAME;
686
        else
687
            motion_type = get_bits(&s->gb, 2);
688
    }
689
    /* compute dct type */
690
    if (s->picture_structure == PICT_FRAME && 
691
        !s->frame_pred_frame_dct &&
692
        (mb_type & (MB_PAT | MB_INTRA))) {
693
        s->interlaced_dct = get_bits1(&s->gb);
694
#ifdef DEBUG
695
        if (s->interlaced_dct)
696
            printf("interlaced_dct\n");
697
#endif
698
    } else {
699
        s->interlaced_dct = 0; /* frame based */
700
    }
701

    
702
    if (mb_type & MB_QUANT) {
703
        s->qscale = get_qscale(s);
704
    }
705
    if (mb_type & MB_INTRA) {
706
        if (s->concealment_motion_vectors) {
707
            /* just parse them */
708
            if (s->picture_structure != PICT_FRAME) 
709
                skip_bits1(&s->gb); /* field select */
710
            mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
711
            mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
712
        }
713
        s->mb_intra = 1;
714
        cbp = 0x3f;
715
        memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
716
    } else {
717
        s->mb_intra = 0;
718
        cbp = 0;
719
    }
720
    /* special case of implicit zero motion vector */
721
    if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
722
        s->mv_dir = MV_DIR_FORWARD;
723
        s->mv_type = MV_TYPE_16X16;
724
        s->last_mv[0][0][0] = 0;
725
        s->last_mv[0][0][1] = 0;
726
        s->last_mv[0][1][0] = 0;
727
        s->last_mv[0][1][1] = 0;
728
        s->mv[0][0][0] = 0;
729
        s->mv[0][0][1] = 0;
730
    } else if (mb_type & (MB_FOR | MB_BACK)) {
731
        /* motion vectors */
732
        s->mv_dir = 0;
733
        for(i=0;i<2;i++) {
734
            if (mb_type & (MB_FOR >> i)) {
735
                s->mv_dir |= (MV_DIR_FORWARD >> i);
736
                dprintf("motion_type=%d\n", motion_type);
737
                switch(motion_type) {
738
                case MT_FRAME: /* or MT_16X8 */
739
                    if (s->picture_structure == PICT_FRAME) {
740
                        /* MT_FRAME */
741
                        s->mv_type = MV_TYPE_16X16;
742
                        for(k=0;k<2;k++) {
743
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
744
                                                     s->last_mv[i][0][k]);
745
                            s->last_mv[i][0][k] = val;
746
                            s->last_mv[i][1][k] = val;
747
                            /* full_pel: only for mpeg1 */
748
                            if (s->full_pel[i])
749
                                val = val << 1;
750
                            s->mv[i][0][k] = val;
751
                            dprintf("mv%d: %d\n", k, val);
752
                        }
753
                    } else {
754
                        /* MT_16X8 */
755
                        s->mv_type = MV_TYPE_16X8;
756
                        for(j=0;j<2;j++) {
757
                            s->field_select[i][j] = get_bits1(&s->gb);
758
                            for(k=0;k<2;k++) {
759
                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
760
                                                         s->last_mv[i][j][k]);
761
                                s->last_mv[i][j][k] = val;
762
                                s->mv[i][j][k] = val;
763
                            }
764
                        }
765
                    }
766
                    break;
767
                case MT_FIELD:
768
                    if (s->picture_structure == PICT_FRAME) {
769
                        s->mv_type = MV_TYPE_FIELD;
770
                        for(j=0;j<2;j++) {
771
                            s->field_select[i][j] = get_bits1(&s->gb);
772
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
773
                                                     s->last_mv[i][j][0]);
774
                            s->last_mv[i][j][0] = val;
775
                            s->mv[i][j][0] = val;
776
                            dprintf("fmx=%d\n", val);
777
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
778
                                                     s->last_mv[i][j][1] >> 1);
779
                            s->last_mv[i][j][1] = val << 1;
780
                            s->mv[i][j][1] = val;
781
                            dprintf("fmy=%d\n", val);
782
                        }
783
                    } else {
784
                        s->mv_type = MV_TYPE_16X16;
785
                        s->field_select[i][0] = get_bits1(&s->gb);
786
                        for(k=0;k<2;k++) {
787
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
788
                                                     s->last_mv[i][0][k]);
789
                            s->last_mv[i][0][k] = val;
790
                            s->last_mv[i][1][k] = val;
791
                            s->mv[i][0][k] = val;
792
                        }
793
                    }
794
                    break;
795
                case MT_DMV:
796
                    {
797
                        int dmx, dmy, mx, my, m;
798

    
799
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
800
                                                s->last_mv[i][0][0]);
801
                        s->last_mv[i][0][0] = mx;
802
                        s->last_mv[i][1][0] = mx;
803
                        dmx = get_dmv(s);
804
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
805
                                                s->last_mv[i][0][1] >> 1);
806
                        dmy = get_dmv(s);
807
                        s->mv_type = MV_TYPE_DMV;
808
                        /* XXX: totally broken */
809
                        if (s->picture_structure == PICT_FRAME) {
810
                            s->last_mv[i][0][1] = my << 1;
811
                            s->last_mv[i][1][1] = my << 1;
812

    
813
                            m = s->top_field_first ? 1 : 3;
814
                            /* top -> top pred */
815
                            s->mv[i][0][0] = mx; 
816
                            s->mv[i][0][1] = my << 1;
817
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
818
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
819
                            m = 4 - m;
820
                            s->mv[i][2][0] = mx;
821
                            s->mv[i][2][1] = my << 1;
822
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
823
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
824
                        } else {
825
                            s->last_mv[i][0][1] = my;
826
                            s->last_mv[i][1][1] = my;
827
                            s->mv[i][0][0] = mx;
828
                            s->mv[i][0][1] = my;
829
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
830
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
831
                                /* + 2 * cur_field */;
832
                        }
833
                    }
834
                    break;
835
                }
836
            }
837
        }
838
    }
839

    
840
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
841
        skip_bits1(&s->gb); /* marker */
842
    }
843
    
844
    if (mb_type & MB_PAT) {
845
        cbp = get_vlc(&s->gb, &mb_pat_vlc);
846
        if (cbp < 0)
847
            return -1;
848
        cbp++;
849
    }
850
    dprintf("cbp=%x\n", cbp);
851

    
852
    if (s->mpeg2) {
853
        if (s->mb_intra) {
854
            for(i=0;i<6;i++) {
855
                if (cbp & (1 << (5 - i))) {
856
                    if (mpeg2_decode_block_intra(s, block[i], i) < 0)
857
                        return -1;
858
                } else {
859
                    s->block_last_index[i] = -1;
860
                }
861
            }
862
        } else {
863
            for(i=0;i<6;i++) {
864
                if (cbp & (1 << (5 - i))) {
865
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
866
                        return -1;
867
                } else {
868
                    s->block_last_index[i] = -1;
869
                }
870
            }
871
        }
872
    } else {
873
        for(i=0;i<6;i++) {
874
            if (cbp & (1 << (5 - i))) {
875
                if (mpeg1_decode_block(s, block[i], i) < 0)
876
                    return -1;
877
            } else {
878
                s->block_last_index[i] = -1;
879
            }
880
        }
881
    }
882
    return 0;
883
}
884

    
885
/* as h263, but only 17 codes */
886
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
887
{
888
    int code, sign, val, m, l, shift;
889

    
890
    code = get_vlc(&s->gb, &mv_vlc);
891
    if (code < 0) {
892
        return 0xffff;
893
    }
894
    if (code == 0) {
895
        return pred;
896
    }
897
    sign = get_bits1(&s->gb);
898
    shift = fcode - 1;
899
    val = (code - 1) << shift;
900
    if (shift > 0)
901
        val |= get_bits(&s->gb, shift);
902
    val++;
903
    if (sign)
904
        val = -val;
905
    val += pred;
906
    
907
    /* modulo decoding */
908
    l = (1 << shift) * 16;
909
    m = 2 * l;
910
    if (val < -l) {
911
        val += m;
912
    } else if (val >= l) {
913
        val -= m;
914
    }
915
    return val;
916
}
917

    
918
static inline int decode_dc(MpegEncContext *s, int component)
919
{
920
    int code, diff;
921

    
922
    if (component == 0) {
923
        code = get_vlc(&s->gb, &dc_lum_vlc);
924
    } else {
925
        code = get_vlc(&s->gb, &dc_chroma_vlc);
926
    }
927
    if (code < 0)
928
        return 0xffff;
929
    if (code == 0) {
930
        diff = 0;
931
    } else {
932
        diff = get_bits(&s->gb, code);
933
        if ((diff & (1 << (code - 1))) == 0) 
934
            diff = (-1 << code) | (diff + 1);
935
    }
936
    return diff;
937
}
938

    
939
static int mpeg1_decode_block(MpegEncContext *s, 
940
                               DCTELEM *block, 
941
                               int n)
942
{
943
    int level, dc, diff, i, j, run;
944
    int code, component;
945
    RLTable *rl = &rl_mpeg1;
946

    
947
    if (s->mb_intra) {
948
        /* DC coef */
949
        component = (n <= 3 ? 0 : n - 4 + 1);
950
        diff = decode_dc(s, component);
951
        if (diff >= 0xffff)
952
            return -1;
953
        dc = s->last_dc[component];
954
        dc += diff;
955
        s->last_dc[component] = dc;
956
        block[0] = dc;
957
        dprintf("dc=%d diff=%d\n", dc, diff);
958
        i = 1;
959
    } else {
960
        int bit_cnt, v;
961
        UINT32 bit_buf;
962
        UINT8 *buf_ptr;
963
        i = 0;
964
        /* special case for the first coef. no need to add a second vlc table */
965
        SAVE_BITS(&s->gb);
966
        SHOW_BITS(&s->gb, v, 2);
967
        if (v & 2) {
968
            run = 0;
969
            level = 1 - ((v & 1) << 1);
970
            FLUSH_BITS(2);
971
            RESTORE_BITS(&s->gb);
972
            goto add_coef;
973
        }
974
        RESTORE_BITS(&s->gb);
975
    }
976

    
977
    /* now quantify & encode AC coefs */
978
    for(;;) {
979
        code = get_vlc(&s->gb, &rl->vlc);
980
        if (code < 0) {
981
            return -1;
982
        }
983
        if (code == 112) {
984
            break;
985
        } else if (code == 111) {
986
            /* escape */
987
            run = get_bits(&s->gb, 6);
988
            level = get_bits(&s->gb, 8);
989
            level = (level << 24) >> 24;
990
            if (level == -128) {
991
                level = get_bits(&s->gb, 8) - 256;
992
            } else if (level == 0) {
993
                level = get_bits(&s->gb, 8);
994
            }
995
        } else {
996
            run = rl->table_run[code];
997
            level = rl->table_level[code];
998
            if (get_bits1(&s->gb))
999
                level = -level;
1000
        }
1001
        i += run;
1002
        if (i >= 64)
1003
            return -1;
1004
    add_coef:
1005
        dprintf("%d: run=%d level=%d\n", n, run, level);
1006
        j = zigzag_direct[i];
1007
        block[j] = level;
1008
        i++;
1009
    }
1010
    s->block_last_index[n] = i-1;
1011
    return 0;
1012
}
1013

    
1014
/* Also does unquantization here, since I will never support mpeg2
1015
   encoding */
1016
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1017
                                        DCTELEM *block, 
1018
                                        int n)
1019
{
1020
    int level, i, j, run;
1021
    int code;
1022
    RLTable *rl = &rl_mpeg1;
1023
    const UINT8 *scan_table;
1024
    const UINT16 *matrix;
1025
    int mismatch;
1026

    
1027
    if (s->alternate_scan)
1028
        scan_table = ff_alternate_vertical_scan;
1029
    else
1030
        scan_table = zigzag_direct;
1031
    mismatch = 1;
1032

    
1033
    {
1034
        int bit_cnt, v;
1035
        UINT32 bit_buf;
1036
        UINT8 *buf_ptr;
1037
        i = 0;
1038
        if (n < 4) 
1039
            matrix = s->inter_matrix;
1040
        else
1041
            matrix = s->chroma_inter_matrix;
1042
            
1043
        /* special case for the first coef. no need to add a second vlc table */
1044
        SAVE_BITS(&s->gb);
1045
        SHOW_BITS(&s->gb, v, 2);
1046
        if (v & 2) {
1047
            run = 0;
1048
            level = 1 - ((v & 1) << 1);
1049
            FLUSH_BITS(2);
1050
            RESTORE_BITS(&s->gb);
1051
            goto add_coef;
1052
        }
1053
        RESTORE_BITS(&s->gb);
1054
    }
1055

    
1056
    /* now quantify & encode AC coefs */
1057
    for(;;) {
1058
        code = get_vlc(&s->gb, &rl->vlc);
1059
        if (code < 0)
1060
            return -1;
1061
        if (code == 112) {
1062
            break;
1063
        } else if (code == 111) {
1064
            /* escape */
1065
            run = get_bits(&s->gb, 6);
1066
            level = get_bits(&s->gb, 12);
1067
            level = (level << 20) >> 20;
1068
        } else {
1069
            run = rl->table_run[code];
1070
            level = rl->table_level[code];
1071
            if (get_bits1(&s->gb))
1072
                level = -level;
1073
        }
1074
        i += run;
1075
        if (i >= 64)
1076
            return -1;
1077
    add_coef:
1078
        j = scan_table[i];
1079
        dprintf("%d: run=%d level=%d\n", n, run, level);
1080
        /* XXX: optimize */
1081
        if (level > 0) {
1082
            level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1083
        } else {
1084
            level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1085
            level = -level;
1086
        }
1087
        /* XXX: is it really necessary to saturate since the encoder
1088
           knows whats going on ? */
1089
        mismatch ^= level;
1090
        block[j] = level;
1091
        i++;
1092
    }
1093
    block[63] ^= (mismatch & 1);
1094
    s->block_last_index[n] = i;
1095
    return 0;
1096
}
1097

    
1098
static int mpeg2_decode_block_intra(MpegEncContext *s, 
1099
                                    DCTELEM *block, 
1100
                                    int n)
1101
{
1102
    int level, dc, diff, i, j, run;
1103
    int code, component;
1104
    RLTable *rl;
1105
    const UINT8 *scan_table;
1106
    const UINT16 *matrix;
1107
    int mismatch;
1108

    
1109
    if (s->alternate_scan)
1110
        scan_table = ff_alternate_vertical_scan;
1111
    else
1112
        scan_table = zigzag_direct;
1113

    
1114
    /* DC coef */
1115
    component = (n <= 3 ? 0 : n - 4 + 1);
1116
    diff = decode_dc(s, component);
1117
    if (diff >= 0xffff)
1118
        return -1;
1119
    dc = s->last_dc[component];
1120
    dc += diff;
1121
    s->last_dc[component] = dc;
1122
    block[0] = dc << (3 - s->intra_dc_precision);
1123
    dprintf("dc=%d\n", block[0]);
1124
    mismatch = block[0] ^ 1;
1125
    i = 1;
1126
    if (s->intra_vlc_format)
1127
        rl = &rl_mpeg2;
1128
    else
1129
        rl = &rl_mpeg1;
1130
    if (n < 4) 
1131
        matrix = s->intra_matrix;
1132
    else
1133
        matrix = s->chroma_intra_matrix;
1134

    
1135
    /* now quantify & encode AC coefs */
1136
    for(;;) {
1137
        code = get_vlc(&s->gb, &rl->vlc);
1138
        if (code < 0)
1139
            return -1;
1140
        if (code == 112) {
1141
            break;
1142
        } else if (code == 111) {
1143
            /* escape */
1144
            run = get_bits(&s->gb, 6);
1145
            level = get_bits(&s->gb, 12);
1146
            level = (level << 20) >> 20;
1147
        } else {
1148
            run = rl->table_run[code];
1149
            level = rl->table_level[code];
1150
            if (get_bits1(&s->gb))
1151
                level = -level;
1152
        }
1153
        i += run;
1154
        if (i >= 64)
1155
            return -1;
1156
        j = scan_table[i];
1157
        dprintf("%d: run=%d level=%d\n", n, run, level);
1158
        level = (level * s->qscale * matrix[j]) / 16;
1159
        /* XXX: is it really necessary to saturate since the encoder
1160
           knows whats going on ? */
1161
        mismatch ^= level;
1162
        block[j] = level;
1163
        i++;
1164
    }
1165
    block[63] ^= (mismatch & 1);
1166
    s->block_last_index[n] = i;
1167
    return 0;
1168
}
1169

    
1170
/* compressed picture size */
1171
#define PICTURE_BUFFER_SIZE 100000
1172

    
1173
typedef struct Mpeg1Context {
1174
    MpegEncContext mpeg_enc_ctx;
1175
    UINT32 header_state;
1176
    int start_code; /* current start code */
1177
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1178
    UINT8 *buf_ptr;
1179
    int buffer_size;
1180
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1181
    int repeat_field; /* true if we must repeat the field */
1182
} Mpeg1Context;
1183

    
1184
static int mpeg_decode_init(AVCodecContext *avctx)
1185
{
1186
    Mpeg1Context *s = avctx->priv_data;
1187

    
1188
    s->header_state = 0xff;
1189
    s->mpeg_enc_ctx_allocated = 0;
1190
    s->buffer_size = PICTURE_BUFFER_SIZE;
1191
    s->start_code = -1;
1192
    s->buf_ptr = s->buffer;
1193
    s->mpeg_enc_ctx.picture_number = 0;
1194
    s->repeat_field = 0;
1195
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1196
    avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1197
    return 0;
1198
}
1199

    
1200
/* return the 8 bit start code value and update the search
1201
   state. Return -1 if no start code found */
1202
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1203
                           UINT32 *header_state)
1204
{
1205
    UINT8 *buf_ptr;
1206
    unsigned int state, v;
1207
    int val;
1208

    
1209
    state = *header_state;
1210
    buf_ptr = *pbuf_ptr;
1211
    while (buf_ptr < buf_end) {
1212
        v = *buf_ptr++;
1213
        if (state == 0x000001) {
1214
            state = ((state << 8) | v) & 0xffffff;
1215
            val = state;
1216
            goto found;
1217
        }
1218
        state = ((state << 8) | v) & 0xffffff;
1219
    }
1220
    val = -1;
1221
 found:
1222
    *pbuf_ptr = buf_ptr;
1223
    *header_state = state;
1224
    return val;
1225
}
1226

    
1227
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1228
                                UINT8 *buf, int buf_size)
1229
{
1230
    Mpeg1Context *s1 = avctx->priv_data;
1231
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1232
    int ref, f_code;
1233

    
1234
    init_get_bits(&s->gb, buf, buf_size);
1235

    
1236
    ref = get_bits(&s->gb, 10); /* temporal ref */
1237
    s->pict_type = get_bits(&s->gb, 3);
1238
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1239
    skip_bits(&s->gb, 16);
1240
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1241
        s->full_pel[0] = get_bits1(&s->gb);
1242
        f_code = get_bits(&s->gb, 3);
1243
        if (f_code == 0)
1244
            return -1;
1245
        s->mpeg_f_code[0][0] = f_code;
1246
        s->mpeg_f_code[0][1] = f_code;
1247
    }
1248
    if (s->pict_type == B_TYPE) {
1249
        s->full_pel[1] = get_bits1(&s->gb);
1250
        f_code = get_bits(&s->gb, 3);
1251
        if (f_code == 0)
1252
            return -1;
1253
        s->mpeg_f_code[1][0] = f_code;
1254
        s->mpeg_f_code[1][1] = f_code;
1255
    }
1256
    s->y_dc_scale = 8;
1257
    s->c_dc_scale = 8;
1258
    s->first_slice = 1;
1259
    return 0;
1260
}
1261

    
1262
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1263
{
1264
    int horiz_size_ext, vert_size_ext;
1265
    int bit_rate_ext, vbv_buf_ext, low_delay;
1266
    int frame_rate_ext_n, frame_rate_ext_d;
1267

    
1268
    skip_bits(&s->gb, 8); /* profil and level */
1269
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1270
    skip_bits(&s->gb, 2); /* chroma_format */
1271
    horiz_size_ext = get_bits(&s->gb, 2);
1272
    vert_size_ext = get_bits(&s->gb, 2);
1273
    s->width |= (horiz_size_ext << 12);
1274
    s->height |= (vert_size_ext << 12);
1275
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1276
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1277
    skip_bits1(&s->gb); /* marker */
1278
    vbv_buf_ext = get_bits(&s->gb, 8);
1279
    low_delay = get_bits1(&s->gb);
1280
    frame_rate_ext_n = get_bits(&s->gb, 2);
1281
    frame_rate_ext_d = get_bits(&s->gb, 5);
1282
    if (frame_rate_ext_d >= 1)
1283
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1284
    dprintf("sequence extension\n");
1285
    s->mpeg2 = 1;
1286
}
1287

    
1288
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1289
{
1290
    int i, v, j;
1291

    
1292
    dprintf("matrix extension\n");
1293

    
1294
    if (get_bits1(&s->gb)) {
1295
        for(i=0;i<64;i++) {
1296
            v = get_bits(&s->gb, 8);
1297
            j = zigzag_direct[i];
1298
            s->intra_matrix[j] = v;
1299
            s->chroma_intra_matrix[j] = v;
1300
        }
1301
    }
1302
    if (get_bits1(&s->gb)) {
1303
        for(i=0;i<64;i++) {
1304
            v = get_bits(&s->gb, 8);
1305
            j = zigzag_direct[i];
1306
            s->inter_matrix[j] = v;
1307
            s->chroma_inter_matrix[j] = v;
1308
        }
1309
    }
1310
    if (get_bits1(&s->gb)) {
1311
        for(i=0;i<64;i++) {
1312
            v = get_bits(&s->gb, 8);
1313
            j = zigzag_direct[i];
1314
            s->chroma_intra_matrix[j] = v;
1315
        }
1316
    }
1317
    if (get_bits1(&s->gb)) {
1318
        for(i=0;i<64;i++) {
1319
            v = get_bits(&s->gb, 8);
1320
            j = zigzag_direct[i];
1321
            s->chroma_inter_matrix[j] = v;
1322
        }
1323
    }
1324
}
1325

    
1326
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1327
{
1328
    s->full_pel[0] = s->full_pel[1] = 0;
1329
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1330
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1331
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1332
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1333
    s->intra_dc_precision = get_bits(&s->gb, 2);
1334
    s->picture_structure = get_bits(&s->gb, 2);
1335
    s->top_field_first = get_bits1(&s->gb);
1336
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1337
    s->concealment_motion_vectors = get_bits1(&s->gb);
1338
    s->q_scale_type = get_bits1(&s->gb);
1339
    s->intra_vlc_format = get_bits1(&s->gb);
1340
    s->alternate_scan = get_bits1(&s->gb);
1341
    s->repeat_first_field = get_bits1(&s->gb);
1342
    s->chroma_420_type = get_bits1(&s->gb);
1343
    s->progressive_frame = get_bits1(&s->gb);
1344
    /* composite display not parsed */
1345
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1346
    dprintf("picture_structure=%d\n", s->picture_structure);
1347
    dprintf("top field first=%d\n", s->top_field_first);
1348
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1349
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1350
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1351
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1352
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1353
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1354
}
1355

    
1356
static void mpeg_decode_extension(AVCodecContext *avctx, 
1357
                                  UINT8 *buf, int buf_size)
1358
{
1359
    Mpeg1Context *s1 = avctx->priv_data;
1360
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1361
    int ext_type;
1362

    
1363
    init_get_bits(&s->gb, buf, buf_size);
1364
    
1365
    ext_type = get_bits(&s->gb, 4);
1366
    switch(ext_type) {
1367
    case 0x1:
1368
        /* sequence ext */
1369
        mpeg_decode_sequence_extension(s);
1370
        break;
1371
    case 0x3:
1372
        /* quant matrix extension */
1373
        mpeg_decode_quant_matrix_extension(s);
1374
        break;
1375
    case 0x8:
1376
        /* picture extension */
1377
        mpeg_decode_picture_coding_extension(s);
1378
        break;
1379
    }
1380
}
1381

    
1382
/* return 1 if end of frame */
1383
static int mpeg_decode_slice(AVCodecContext *avctx, 
1384
                              AVPicture *pict,
1385
                              int start_code,
1386
                              UINT8 *buf, int buf_size)
1387
{
1388
    Mpeg1Context *s1 = avctx->priv_data;
1389
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1390
    int ret;
1391

    
1392
    start_code = (start_code - 1) & 0xff;
1393
    if (start_code >= s->mb_height)
1394
        return -1;
1395
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1396
    s->last_dc[1] = s->last_dc[0];
1397
    s->last_dc[2] = s->last_dc[0];
1398
    memset(s->last_mv, 0, sizeof(s->last_mv));
1399
    s->mb_x = -1;
1400
    s->mb_y = start_code;
1401
    s->mb_incr = 0;
1402
    /* start frame decoding */
1403
    if (s->first_slice) {
1404
        s->first_slice = 0;
1405
        MPV_frame_start(s);
1406
    }
1407

    
1408
    init_get_bits(&s->gb, buf, buf_size);
1409

    
1410
    s->qscale = get_qscale(s);
1411
    /* extra slice info */
1412
    while (get_bits1(&s->gb) != 0) {
1413
        skip_bits(&s->gb, 8);
1414
    }
1415

    
1416
    for(;;) {
1417
        clear_blocks(s->block[0]);
1418
        emms_c();
1419
        ret = mpeg_decode_mb(s, s->block);
1420
        dprintf("ret=%d\n", ret);
1421
        if (ret < 0)
1422
            return -1;
1423
        if (ret == 1)
1424
            break;
1425
        MPV_decode_mb(s, s->block);
1426
    }
1427
    emms_c();
1428

    
1429
    /* end of slice reached */
1430
    if (s->mb_x == (s->mb_width - 1) &&
1431
        s->mb_y == (s->mb_height - 1)) {
1432
        /* end of image */
1433
        UINT8 **picture;
1434

    
1435
        MPV_frame_end(s);
1436

    
1437
        /* XXX: incorrect reported qscale for mpeg2 */
1438
        if (s->pict_type == B_TYPE) {
1439
            picture = s->current_picture;
1440
            avctx->quality = s->qscale;
1441
        } else {
1442
            /* latency of 1 frame for I and P frames */
1443
            /* XXX: use another variable than picture_number */
1444
            if (s->picture_number == 0) {
1445
                picture = NULL;
1446
            } else {
1447
                picture = s->last_picture;
1448
                avctx->quality = s->last_qscale;
1449
            }
1450
            s->last_qscale = s->qscale;
1451
            s->picture_number++;
1452
        }
1453
        if (picture) {
1454
            pict->data[0] = picture[0];
1455
            pict->data[1] = picture[1];
1456
            pict->data[2] = picture[2];
1457
            pict->linesize[0] = s->linesize;
1458
            pict->linesize[1] = s->linesize / 2;
1459
            pict->linesize[2] = s->linesize / 2;
1460
            return 1;
1461
        } else {
1462
            return 0;
1463
        }
1464
    } else {
1465
        return 0;
1466
    }
1467
}
1468

    
1469
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1470
                                 UINT8 *buf, int buf_size)
1471
{
1472
    Mpeg1Context *s1 = avctx->priv_data;
1473
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1474
    int width, height, i, v, j;
1475
    
1476
    init_get_bits(&s->gb, buf, buf_size);
1477

    
1478
    width = get_bits(&s->gb, 12);
1479
    height = get_bits(&s->gb, 12);
1480
    skip_bits(&s->gb, 4);
1481
    s->frame_rate_index = get_bits(&s->gb, 4);
1482
    if (s->frame_rate_index == 0)
1483
        return -1;
1484
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1485
    if (get_bits1(&s->gb) == 0) /* marker */
1486
        return -1;
1487
    if (width <= 0 || height <= 0 ||
1488
        (width % 2) != 0 || (height % 2) != 0)
1489
        return -1;
1490
    if (width != s->width ||
1491
        height != s->height) {
1492
        /* start new mpeg1 context decoding */
1493
        s->out_format = FMT_MPEG1;
1494
        if (s1->mpeg_enc_ctx_allocated) {
1495
            MPV_common_end(s);
1496
        }
1497
        s->width = width;
1498
        s->height = height;
1499
        s->has_b_frames = 1;
1500
        s->avctx = avctx;
1501
        avctx->width = width;
1502
        avctx->height = height;
1503
        avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1504
        s->frame_rate = avctx->frame_rate;
1505
        avctx->bit_rate = s->bit_rate;
1506
        
1507
        if (MPV_common_init(s) < 0)
1508
            return -1;
1509
        mpeg1_init_vlc(s);
1510
        s1->mpeg_enc_ctx_allocated = 1;
1511
    }
1512

    
1513
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1514
    skip_bits(&s->gb, 1);
1515

    
1516
    /* get matrix */
1517
    if (get_bits1(&s->gb)) {
1518
        for(i=0;i<64;i++) {
1519
            v = get_bits(&s->gb, 8);
1520
            j = zigzag_direct[i];
1521
            s->intra_matrix[j] = v;
1522
            s->chroma_intra_matrix[j] = v;
1523
        }
1524
#ifdef DEBUG
1525
        dprintf("intra matrix present\n");
1526
        for(i=0;i<64;i++)
1527
            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1528
        printf("\n");
1529
#endif
1530
    } else {
1531
        for(i=0;i<64;i++) {
1532
            v = default_intra_matrix[i];
1533
            s->intra_matrix[i] = v;
1534
            s->chroma_intra_matrix[i] = v;
1535
        }
1536
    }
1537
    if (get_bits1(&s->gb)) {
1538
        for(i=0;i<64;i++) {
1539
            v = get_bits(&s->gb, 8);
1540
            j = zigzag_direct[i];
1541
            s->inter_matrix[j] = v;
1542
            s->chroma_inter_matrix[j] = v;
1543
        }
1544
#ifdef DEBUG
1545
        dprintf("non intra matrix present\n");
1546
        for(i=0;i<64;i++)
1547
            dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1548
        printf("\n");
1549
#endif
1550
    } else {
1551
        for(i=0;i<64;i++) {
1552
            v = default_non_intra_matrix[i];
1553
            s->inter_matrix[i] = v;
1554
            s->chroma_inter_matrix[i] = v;
1555
        }
1556
    }
1557

    
1558
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1559
    s->progressive_sequence = 1;
1560
    s->progressive_frame = 1;
1561
    s->picture_structure = PICT_FRAME;
1562
    s->frame_pred_frame_dct = 1;
1563
    s->mpeg2 = 0;
1564
    return 0;
1565
}
1566

    
1567
/* handle buffering and image synchronisation */
1568
static int mpeg_decode_frame(AVCodecContext *avctx, 
1569
                             void *data, int *data_size,
1570
                             UINT8 *buf, int buf_size)
1571
{
1572
    Mpeg1Context *s = avctx->priv_data;
1573
    UINT8 *buf_end, *buf_ptr, *buf_start;
1574
    int len, start_code_found, ret, code, start_code, input_size;
1575
    AVPicture *picture = data;
1576
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1577
            
1578
    dprintf("fill_buffer\n");
1579

    
1580
    *data_size = 0;
1581

    
1582
    /* special case for last picture */
1583
    if (buf_size == 0) {
1584
        if (s2->picture_number > 0) {
1585
            picture->data[0] = s2->next_picture[0];
1586
            picture->data[1] = s2->next_picture[1];
1587
            picture->data[2] = s2->next_picture[2];
1588
            picture->linesize[0] = s2->linesize;
1589
            picture->linesize[1] = s2->linesize / 2;
1590
            picture->linesize[2] = s2->linesize / 2;
1591
            *data_size = sizeof(AVPicture);
1592
        }
1593
        return 0;
1594
    }
1595

    
1596
    buf_ptr = buf;
1597
    buf_end = buf + buf_size;
1598

    
1599
#if 0    
1600
    if (s->repeat_field % 2 == 1) { 
1601
        s->repeat_field++;
1602
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1603
        //        s2->picture_number, s->repeat_field);
1604
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1605
            *data_size = sizeof(AVPicture);
1606
            goto the_end;
1607
        }
1608
    }
1609
#endif
1610
    while (buf_ptr < buf_end) {
1611
        buf_start = buf_ptr;
1612
        /* find start next code */
1613
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1614
        if (code >= 0) {
1615
            start_code_found = 1;
1616
        } else {
1617
            start_code_found = 0;
1618
        }
1619
        /* copy to buffer */
1620
        len = buf_ptr - buf_start;
1621
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1622
            /* data too big : flush */
1623
            s->buf_ptr = s->buffer;
1624
            if (start_code_found)
1625
                s->start_code = code;
1626
        } else {
1627
            memcpy(s->buf_ptr, buf_start, len);
1628
            s->buf_ptr += len;
1629
            
1630
            if (start_code_found) {
1631
                /* prepare data for next start code */
1632
                input_size = s->buf_ptr - s->buffer;
1633
                start_code = s->start_code;
1634
                s->buf_ptr = s->buffer;
1635
                s->start_code = code;
1636
                switch(start_code) {
1637
                case SEQ_START_CODE:
1638
                    mpeg1_decode_sequence(avctx, s->buffer, 
1639
                                          input_size);
1640
                    break;
1641
                            
1642
                case PICTURE_START_CODE:
1643
                    /* we have a complete image : we try to decompress it */
1644
                    mpeg1_decode_picture(avctx, 
1645
                                         s->buffer, input_size);
1646
                    break;
1647
                case EXT_START_CODE:
1648
                    mpeg_decode_extension(avctx,
1649
                                          s->buffer, input_size);
1650
                    break;
1651
                default:
1652
                    if (start_code >= SLICE_MIN_START_CODE &&
1653
                        start_code <= SLICE_MAX_START_CODE) {
1654
                        ret = mpeg_decode_slice(avctx, picture,
1655
                                                start_code, s->buffer, input_size);
1656
                        if (ret == 1) {
1657
                            /* got a picture: exit */
1658
                            /* first check if we must repeat the frame */
1659
                            avctx->repeat_pict = 0;
1660
#if 0
1661
                            if (s2->progressive_frame && s2->repeat_first_field) {
1662
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1663
                                //s2->repeat_first_field = 0;
1664
                                //s2->progressive_frame = 0;
1665
                                if (++s->repeat_field > 2)
1666
                                    s->repeat_field = 0;
1667
                                avctx->repeat_pict = 1;
1668
                            }
1669
#endif                      
1670
                            if (s2->repeat_first_field) {
1671
                                if (s2->progressive_sequence) {
1672
                                    if (s2->top_field_first)
1673
                                        avctx->repeat_pict = 4;
1674
                                    else
1675
                                        avctx->repeat_pict = 2;
1676
                                } else if (s2->progressive_frame) {
1677
                                    avctx->repeat_pict = 1;
1678
                                }
1679
                            }         
1680
                            *data_size = sizeof(AVPicture);
1681
                            goto the_end;
1682
                        }
1683
                    }
1684
                    break;
1685
                }
1686
            }
1687
        }
1688
    }
1689
 the_end:
1690
    return buf_ptr - buf;
1691
}
1692

    
1693
static int mpeg_decode_end(AVCodecContext *avctx)
1694
{
1695
    Mpeg1Context *s = avctx->priv_data;
1696

    
1697
    if (s->mpeg_enc_ctx_allocated)
1698
        MPV_common_end(&s->mpeg_enc_ctx);
1699
    return 0;
1700
}
1701

    
1702
AVCodec mpeg_decoder = {
1703
    "mpegvideo",
1704
    CODEC_TYPE_VIDEO,
1705
    CODEC_ID_MPEG1VIDEO,
1706
    sizeof(Mpeg1Context),
1707
    mpeg_decode_init,
1708
    NULL,
1709
    mpeg_decode_end,
1710
    mpeg_decode_frame,
1711
};