Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ 4f68b084

History | View | Annotate | Download (54.6 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, q;
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
            /* vbv buffer size: slightly greater than an I frame. We add
146
               some margin just in case */
147
            vbv_buffer_size = (3 * s->I_frame_bits) / (2 * 8);
148
            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
149
            put_bits(&s->pb, 1, 1); /* constrained parameter flag */
150
            put_bits(&s->pb, 1, 0); /* no custom intra matrix */
151
            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
152

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

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

    
180
        }
181
}
182

    
183

    
184
/* insert a fake P picture */
185
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num)
186
{
187
    unsigned int mb_incr;
188

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

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

    
235
static void common_init(MpegEncContext *s)
236
{
237
    s->y_dc_scale_table=
238
    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
239
}
240

    
241
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
242
{
243
    mpeg1_encode_sequence_header(s);
244

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

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

    
274
    mb_x = s->mb_x;
275
    mb_y = s->mb_y;
276

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

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

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

    
334
static void mpeg1_encode_motion(MpegEncContext *s, int val)
335
{
336
    int code, bit_size, l, m, bits, range, sign;
337

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

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

    
378
void ff_mpeg1_encode_init(MpegEncContext *s)
379
{
380
    static int done=0;
381

    
382
    common_init(s);
383

    
384
    if(!done){
385
        int f_code;
386
        int mv;
387
        int i;
388

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

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

    
405
                adiff = ABS(diff);
406
                if(diff<0) diff--;
407
                index = vlc_dc_table[adiff];
408

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

    
418
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
419
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
420
                int len;
421

    
422
                if(mv==0) len= mbMotionVectorTable[0][1];
423
                else{
424
                    int val, bit_size, range, code;
425

    
426
                    bit_size = s->f_code - 1;
427
                    range = 1 << bit_size;
428

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

    
441
                mv_penalty[f_code][mv+MAX_MV]= len;
442
            }
443
        }
444
        
445

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

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

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

    
483
    last_index = s->block_last_index[n];
484

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

    
508
    /* now quantify & encode AC coefs */
509
    last_non_zero = i - 1;
510

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

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

    
573
/******************************************/
574
/* decoding */
575

    
576
static VLC dc_lum_vlc;
577
static VLC dc_chroma_vlc;
578
static VLC mv_vlc;
579
static VLC mbincr_vlc;
580
static VLC mb_ptype_vlc;
581
static VLC mb_btype_vlc;
582
static VLC mb_pat_vlc;
583

    
584
void mpeg1_init_vlc(MpegEncContext *s)
585
{
586
    static int done = 0;
587

    
588
    if (!done) {
589
        done = 1;
590

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

    
616
        init_2d_vlc_rl(&rl_mpeg1);
617
        init_2d_vlc_rl(&rl_mpeg2);
618
    }
619
}
620

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

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

    
645
/* motion type (for mpeg2) */
646
#define MT_FIELD 1
647
#define MT_FRAME 2
648
#define MT_16X8  2
649
#define MT_DMV   3
650

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

    
683
    if (--s->mb_incr != 0) {
684
        /* skip mb */
685
        s->mb_intra = 0;
686
        for(i=0;i<6;i++)
687
            s->block_last_index[i] = -1;
688
        s->mv_type = MV_TYPE_16X16;
689
        if (s->pict_type == P_TYPE) {
690
            /* if P type, zero motion vector is implied */
691
            s->mv_dir = MV_DIR_FORWARD;
692
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
693
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
694
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
695
        } else {
696
            /* if B type, reuse previous vectors and directions */
697
            s->mv[0][0][0] = s->last_mv[0][0][0];
698
            s->mv[0][0][1] = s->last_mv[0][0][1];
699
            s->mv[1][0][0] = s->last_mv[1][0][0];
700
            s->mv[1][0][1] = s->last_mv[1][0][1];
701
        }
702
        s->mb_skiped = 1;
703
        return 0;
704
    }
705

    
706
    switch(s->pict_type) {
707
    default:
708
    case I_TYPE:
709
        if (get_bits1(&s->gb) == 0) {
710
            if (get_bits1(&s->gb) == 0)
711
                return -1;
712
            mb_type = MB_QUANT | MB_INTRA;
713
        } else {
714
            mb_type = MB_INTRA;
715
        }
716
        break;
717
    case P_TYPE:
718
        mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
719
        if (mb_type < 0)
720
            return -1;
721
        break;
722
    case B_TYPE:
723
        mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
724
        if (mb_type < 0)
725
            return -1;
726
        break;
727
    }
728
    dprintf("mb_type=%x\n", mb_type);
729
    motion_type = 0; /* avoid warning */
730
    if (mb_type & (MB_FOR|MB_BACK)) {
731
        /* get additionnal motion vector type */
732
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
733
            motion_type = MT_FRAME;
734
        else
735
            motion_type = get_bits(&s->gb, 2);
736
    }
737
    /* compute dct type */
738
    if (s->picture_structure == PICT_FRAME && 
739
        !s->frame_pred_frame_dct &&
740
        (mb_type & (MB_PAT | MB_INTRA))) {
741
        s->interlaced_dct = get_bits1(&s->gb);
742
#ifdef DEBUG
743
        if (s->interlaced_dct)
744
            printf("interlaced_dct\n");
745
#endif
746
    } else {
747
        s->interlaced_dct = 0; /* frame based */
748
    }
749

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

    
847
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
848
                                                s->last_mv[i][0][0]);
849
                        s->last_mv[i][0][0] = mx;
850
                        s->last_mv[i][1][0] = mx;
851
                        dmx = get_dmv(s);
852
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
853
                                                s->last_mv[i][0][1] >> 1);
854
                        dmy = get_dmv(s);
855
                        s->mv_type = MV_TYPE_DMV;
856
                        /* XXX: totally broken */
857
                        if (s->picture_structure == PICT_FRAME) {
858
                            s->last_mv[i][0][1] = my << 1;
859
                            s->last_mv[i][1][1] = my << 1;
860

    
861
                            m = s->top_field_first ? 1 : 3;
862
                            /* top -> top pred */
863
                            s->mv[i][0][0] = mx; 
864
                            s->mv[i][0][1] = my << 1;
865
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
866
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
867
                            m = 4 - m;
868
                            s->mv[i][2][0] = mx;
869
                            s->mv[i][2][1] = my << 1;
870
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
871
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
872
                        } else {
873
                            s->last_mv[i][0][1] = my;
874
                            s->last_mv[i][1][1] = my;
875
                            s->mv[i][0][0] = mx;
876
                            s->mv[i][0][1] = my;
877
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
878
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
879
                                /* + 2 * cur_field */;
880
                        }
881
                    }
882
                    break;
883
                }
884
            }
885
        }
886
    }
887

    
888
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
889
        skip_bits1(&s->gb); /* marker */
890
    }
891
    
892
    if (mb_type & MB_PAT) {
893
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
894
        if (cbp < 0)
895
            return -1;
896
        cbp++;
897
    }
898
    dprintf("cbp=%x\n", cbp);
899

    
900
    if (s->mpeg2) {
901
        if (s->mb_intra) {
902
            for(i=0;i<6;i++) {
903
                if (cbp & (1 << (5 - i))) {
904
                    if (mpeg2_decode_block_intra(s, block[i], i) < 0)
905
                        return -1;
906
                } else {
907
                    s->block_last_index[i] = -1;
908
                }
909
            }
910
        } else {
911
            for(i=0;i<6;i++) {
912
                if (cbp & (1 << (5 - i))) {
913
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
914
                        return -1;
915
                } else {
916
                    s->block_last_index[i] = -1;
917
                }
918
            }
919
        }
920
    } else {
921
        for(i=0;i<6;i++) {
922
            if (cbp & (1 << (5 - i))) {
923
                if (mpeg1_decode_block(s, block[i], i) < 0)
924
                    return -1;
925
            } else {
926
                s->block_last_index[i] = -1;
927
            }
928
        }
929
    }
930
    return 0;
931
}
932

    
933
/* as h263, but only 17 codes */
934
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
935
{
936
    int code, sign, val, m, l, shift;
937

    
938
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
939
    if (code < 0) {
940
        return 0xffff;
941
    }
942
    if (code == 0) {
943
        return pred;
944
    }
945
    sign = get_bits1(&s->gb);
946
    shift = fcode - 1;
947
    val = (code - 1) << shift;
948
    if (shift > 0)
949
        val |= get_bits(&s->gb, shift);
950
    val++;
951
    if (sign)
952
        val = -val;
953
    val += pred;
954
    
955
    /* modulo decoding */
956
    l = (1 << shift) * 16;
957
    m = 2 * l;
958
    if (val < -l) {
959
        val += m;
960
    } else if (val >= l) {
961
        val -= m;
962
    }
963
    return val;
964
}
965

    
966
static inline int decode_dc(MpegEncContext *s, int component)
967
{
968
    int code, diff;
969

    
970
    if (component == 0) {
971
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 1);
972
    } else {
973
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 1);
974
    }
975
    if (code < 0)
976
        return 0xffff;
977
    if (code == 0) {
978
        diff = 0;
979
    } else {
980
        diff = get_bits(&s->gb, code);
981
        if ((diff & (1 << (code - 1))) == 0) 
982
            diff = (-1 << code) | (diff + 1);
983
    }
984
    return diff;
985
}
986

    
987
static int mpeg1_decode_block(MpegEncContext *s, 
988
                               DCTELEM *block, 
989
                               int n)
990
{
991
    int level, dc, diff, i, j, run;
992
    int code, component;
993
    RLTable *rl = &rl_mpeg1;
994

    
995
    if (s->mb_intra) {
996
        /* DC coef */
997
        component = (n <= 3 ? 0 : n - 4 + 1);
998
        diff = decode_dc(s, component);
999
        if (diff >= 0xffff)
1000
            return -1;
1001
        dc = s->last_dc[component];
1002
        dc += diff;
1003
        s->last_dc[component] = dc;
1004
        block[0] = dc;
1005
        dprintf("dc=%d diff=%d\n", dc, diff);
1006
        i = 1;
1007
    } else {
1008
        int v;
1009
        OPEN_READER(re, &s->gb);
1010
        i = 0;
1011
        /* special case for the first coef. no need to add a second vlc table */
1012
        UPDATE_CACHE(re, &s->gb);
1013
        v= SHOW_UBITS(re, &s->gb, 2);
1014
        if (v & 2) {
1015
            run = 0;
1016
            level = 1 - ((v & 1) << 1);
1017
            SKIP_BITS(re, &s->gb, 2);
1018
            CLOSE_READER(re, &s->gb);
1019
            goto add_coef;
1020
        }
1021
        CLOSE_READER(re, &s->gb);
1022
    }
1023

    
1024
    /* now quantify & encode AC coefs */
1025
    for(;;) {
1026
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1027
        if (code < 0) {
1028
            return -1;
1029
        }
1030
        if (code == 112) {
1031
            break;
1032
        } else if (code == 111) {
1033
            /* escape */
1034
            run = get_bits(&s->gb, 6);
1035
            level = get_bits(&s->gb, 8);
1036
            level = (level << 24) >> 24;
1037
            if (level == -128) {
1038
                level = get_bits(&s->gb, 8) - 256;
1039
            } else if (level == 0) {
1040
                level = get_bits(&s->gb, 8);
1041
            }
1042
        } else {
1043
            run = rl->table_run[code];
1044
            level = rl->table_level[code];
1045
            if (get_bits1(&s->gb))
1046
                level = -level;
1047
        }
1048
        i += run;
1049
        if (i >= 64)
1050
            return -1;
1051
    add_coef:
1052
        dprintf("%d: run=%d level=%d\n", n, run, level);
1053
        j = zigzag_direct[i];
1054
        block[j] = level;
1055
        i++;
1056
    }
1057
    s->block_last_index[n] = i-1;
1058
    return 0;
1059
}
1060

    
1061
/* Also does unquantization here, since I will never support mpeg2
1062
   encoding */
1063
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1064
                                        DCTELEM *block, 
1065
                                        int n)
1066
{
1067
    int level, i, j, run;
1068
    int code;
1069
    RLTable *rl = &rl_mpeg1;
1070
    const UINT8 *scan_table;
1071
    const UINT16 *matrix;
1072
    int mismatch;
1073

    
1074
    if (s->alternate_scan)
1075
        scan_table = ff_alternate_vertical_scan;
1076
    else
1077
        scan_table = zigzag_direct;
1078
    mismatch = 1;
1079

    
1080
    {
1081
        int v;
1082
        OPEN_READER(re, &s->gb);
1083
        i = 0;
1084
        if (n < 4)
1085
            matrix = s->inter_matrix;
1086
        else
1087
            matrix = s->chroma_inter_matrix;
1088

    
1089
        /* special case for the first coef. no need to add a second vlc table */
1090
        UPDATE_CACHE(re, &s->gb);
1091
        v= SHOW_UBITS(re, &s->gb, 2);
1092
        if (v & 2) {
1093
            run = 0;
1094
            level = 1 - ((v & 1) << 1);
1095
            SKIP_BITS(re, &s->gb, 2);
1096
            CLOSE_READER(re, &s->gb);
1097
            goto add_coef;
1098
        }
1099
        CLOSE_READER(re, &s->gb);
1100
    }
1101

    
1102
    /* now quantify & encode AC coefs */
1103
    for(;;) {
1104
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1105
        if (code < 0)
1106
            return -1;
1107
        if (code == 112) {
1108
            break;
1109
        } else if (code == 111) {
1110
            /* escape */
1111
            run = get_bits(&s->gb, 6);
1112
            level = get_bits(&s->gb, 12);
1113
            level = (level << 20) >> 20;
1114
        } else {
1115
            run = rl->table_run[code];
1116
            level = rl->table_level[code];
1117
            if (get_bits1(&s->gb))
1118
                level = -level;
1119
        }
1120
        i += run;
1121
        if (i >= 64)
1122
            return -1;
1123
    add_coef:
1124
        j = scan_table[i];
1125
        dprintf("%d: run=%d level=%d\n", n, run, level);
1126
        /* XXX: optimize */
1127
        if (level > 0) {
1128
            level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1129
        } else {
1130
            level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1131
            level = -level;
1132
        }
1133
        /* XXX: is it really necessary to saturate since the encoder
1134
           knows whats going on ? */
1135
        mismatch ^= level;
1136
        block[j] = level;
1137
        i++;
1138
    }
1139
    block[63] ^= (mismatch & 1);
1140
    s->block_last_index[n] = i;
1141
    return 0;
1142
}
1143

    
1144
static int mpeg2_decode_block_intra(MpegEncContext *s, 
1145
                                    DCTELEM *block, 
1146
                                    int n)
1147
{
1148
    int level, dc, diff, i, j, run;
1149
    int code, component;
1150
    RLTable *rl;
1151
    const UINT8 *scan_table;
1152
    const UINT16 *matrix;
1153
    int mismatch;
1154

    
1155
    if (s->alternate_scan)
1156
        scan_table = ff_alternate_vertical_scan;
1157
    else
1158
        scan_table = zigzag_direct;
1159

    
1160
    /* DC coef */
1161
    component = (n <= 3 ? 0 : n - 4 + 1);
1162
    diff = decode_dc(s, component);
1163
    if (diff >= 0xffff)
1164
        return -1;
1165
    dc = s->last_dc[component];
1166
    dc += diff;
1167
    s->last_dc[component] = dc;
1168
    block[0] = dc << (3 - s->intra_dc_precision);
1169
    dprintf("dc=%d\n", block[0]);
1170
    mismatch = block[0] ^ 1;
1171
    i = 1;
1172
    if (s->intra_vlc_format)
1173
        rl = &rl_mpeg2;
1174
    else
1175
        rl = &rl_mpeg1;
1176
    if (n < 4) 
1177
        matrix = s->intra_matrix;
1178
    else
1179
        matrix = s->chroma_intra_matrix;
1180

    
1181
    /* now quantify & encode AC coefs */
1182
    for(;;) {
1183
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1184
        if (code < 0)
1185
            return -1;
1186
        if (code == 112) {
1187
            break;
1188
        } else if (code == 111) {
1189
            /* escape */
1190
            run = get_bits(&s->gb, 6);
1191
            level = get_bits(&s->gb, 12);
1192
            level = (level << 20) >> 20;
1193
        } else {
1194
            run = rl->table_run[code];
1195
            level = rl->table_level[code];
1196
            if (get_bits1(&s->gb))
1197
                level = -level;
1198
        }
1199
        i += run;
1200
        if (i >= 64)
1201
            return -1;
1202
        j = scan_table[i];
1203
        dprintf("%d: run=%d level=%d\n", n, run, level);
1204
        level = (level * s->qscale * matrix[j]) / 16;
1205
        /* XXX: is it really necessary to saturate since the encoder
1206
           knows whats going on ? */
1207
        mismatch ^= level;
1208
        block[j] = level;
1209
        i++;
1210
    }
1211
    block[63] ^= (mismatch & 1);
1212
    s->block_last_index[n] = i;
1213
    return 0;
1214
}
1215

    
1216
/* compressed picture size */
1217
#define PICTURE_BUFFER_SIZE 100000
1218

    
1219
typedef struct Mpeg1Context {
1220
    MpegEncContext mpeg_enc_ctx;
1221
    UINT32 header_state;
1222
    int start_code; /* current start code */
1223
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1224
    UINT8 *buf_ptr;
1225
    int buffer_size;
1226
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1227
    int repeat_field; /* true if we must repeat the field */
1228
} Mpeg1Context;
1229

    
1230
static int mpeg_decode_init(AVCodecContext *avctx)
1231
{
1232
    Mpeg1Context *s = avctx->priv_data;
1233
    
1234
    common_init(&s->mpeg_enc_ctx);
1235

    
1236
    s->header_state = 0xff;
1237
    s->mpeg_enc_ctx_allocated = 0;
1238
    s->buffer_size = PICTURE_BUFFER_SIZE;
1239
    s->start_code = -1;
1240
    s->buf_ptr = s->buffer;
1241
    s->mpeg_enc_ctx.picture_number = 0;
1242
    s->repeat_field = 0;
1243
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1244
    avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1245
    s->mpeg_enc_ctx.flags= avctx->flags;
1246
    return 0;
1247
}
1248

    
1249
/* return the 8 bit start code value and update the search
1250
   state. Return -1 if no start code found */
1251
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1252
                           UINT32 *header_state)
1253
{
1254
    UINT8 *buf_ptr;
1255
    unsigned int state, v;
1256
    int val;
1257

    
1258
    state = *header_state;
1259
    buf_ptr = *pbuf_ptr;
1260
    while (buf_ptr < buf_end) {
1261
        v = *buf_ptr++;
1262
        if (state == 0x000001) {
1263
            state = ((state << 8) | v) & 0xffffff;
1264
            val = state;
1265
            goto found;
1266
        }
1267
        state = ((state << 8) | v) & 0xffffff;
1268
    }
1269
    val = -1;
1270
 found:
1271
    *pbuf_ptr = buf_ptr;
1272
    *header_state = state;
1273
    return val;
1274
}
1275

    
1276
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1277
                                UINT8 *buf, int buf_size)
1278
{
1279
    Mpeg1Context *s1 = avctx->priv_data;
1280
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1281
    int ref, f_code;
1282

    
1283
    init_get_bits(&s->gb, buf, buf_size);
1284

    
1285
    ref = get_bits(&s->gb, 10); /* temporal ref */
1286
    s->pict_type = get_bits(&s->gb, 3);
1287
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1288
    skip_bits(&s->gb, 16);
1289
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1290
        s->full_pel[0] = get_bits1(&s->gb);
1291
        f_code = get_bits(&s->gb, 3);
1292
        if (f_code == 0)
1293
            return -1;
1294
        s->mpeg_f_code[0][0] = f_code;
1295
        s->mpeg_f_code[0][1] = f_code;
1296
    }
1297
    if (s->pict_type == B_TYPE) {
1298
        s->full_pel[1] = get_bits1(&s->gb);
1299
        f_code = get_bits(&s->gb, 3);
1300
        if (f_code == 0)
1301
            return -1;
1302
        s->mpeg_f_code[1][0] = f_code;
1303
        s->mpeg_f_code[1][1] = f_code;
1304
    }
1305
    s->y_dc_scale = 8;
1306
    s->c_dc_scale = 8;
1307
    s->first_slice = 1;
1308
    return 0;
1309
}
1310

    
1311
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1312
{
1313
    int horiz_size_ext, vert_size_ext;
1314
    int bit_rate_ext, vbv_buf_ext, low_delay;
1315
    int frame_rate_ext_n, frame_rate_ext_d;
1316

    
1317
    skip_bits(&s->gb, 8); /* profil and level */
1318
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1319
    skip_bits(&s->gb, 2); /* chroma_format */
1320
    horiz_size_ext = get_bits(&s->gb, 2);
1321
    vert_size_ext = get_bits(&s->gb, 2);
1322
    s->width |= (horiz_size_ext << 12);
1323
    s->height |= (vert_size_ext << 12);
1324
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1325
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1326
    skip_bits1(&s->gb); /* marker */
1327
    vbv_buf_ext = get_bits(&s->gb, 8);
1328
    low_delay = get_bits1(&s->gb);
1329
    frame_rate_ext_n = get_bits(&s->gb, 2);
1330
    frame_rate_ext_d = get_bits(&s->gb, 5);
1331
    if (frame_rate_ext_d >= 1)
1332
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1333
    dprintf("sequence extension\n");
1334
    s->mpeg2 = 1;
1335
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1336
}
1337

    
1338
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1339
{
1340
    int i, v, j;
1341

    
1342
    dprintf("matrix extension\n");
1343

    
1344
    if (get_bits1(&s->gb)) {
1345
        for(i=0;i<64;i++) {
1346
            v = get_bits(&s->gb, 8);
1347
            j = zigzag_direct[i];
1348
            s->intra_matrix[j] = v;
1349
            s->chroma_intra_matrix[j] = v;
1350
        }
1351
    }
1352
    if (get_bits1(&s->gb)) {
1353
        for(i=0;i<64;i++) {
1354
            v = get_bits(&s->gb, 8);
1355
            j = zigzag_direct[i];
1356
            s->inter_matrix[j] = v;
1357
            s->chroma_inter_matrix[j] = v;
1358
        }
1359
    }
1360
    if (get_bits1(&s->gb)) {
1361
        for(i=0;i<64;i++) {
1362
            v = get_bits(&s->gb, 8);
1363
            j = zigzag_direct[i];
1364
            s->chroma_intra_matrix[j] = v;
1365
        }
1366
    }
1367
    if (get_bits1(&s->gb)) {
1368
        for(i=0;i<64;i++) {
1369
            v = get_bits(&s->gb, 8);
1370
            j = zigzag_direct[i];
1371
            s->chroma_inter_matrix[j] = v;
1372
        }
1373
    }
1374
}
1375

    
1376
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1377
{
1378
    s->full_pel[0] = s->full_pel[1] = 0;
1379
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1380
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1381
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1382
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1383
    s->intra_dc_precision = get_bits(&s->gb, 2);
1384
    s->picture_structure = get_bits(&s->gb, 2);
1385
    s->top_field_first = get_bits1(&s->gb);
1386
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1387
    s->concealment_motion_vectors = get_bits1(&s->gb);
1388
    s->q_scale_type = get_bits1(&s->gb);
1389
    s->intra_vlc_format = get_bits1(&s->gb);
1390
    s->alternate_scan = get_bits1(&s->gb);
1391
    s->repeat_first_field = get_bits1(&s->gb);
1392
    s->chroma_420_type = get_bits1(&s->gb);
1393
    s->progressive_frame = get_bits1(&s->gb);
1394
    /* composite display not parsed */
1395
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1396
    dprintf("picture_structure=%d\n", s->picture_structure);
1397
    dprintf("top field first=%d\n", s->top_field_first);
1398
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1399
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1400
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1401
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1402
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1403
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1404
}
1405

    
1406
static void mpeg_decode_extension(AVCodecContext *avctx, 
1407
                                  UINT8 *buf, int buf_size)
1408
{
1409
    Mpeg1Context *s1 = avctx->priv_data;
1410
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1411
    int ext_type;
1412

    
1413
    init_get_bits(&s->gb, buf, buf_size);
1414
    
1415
    ext_type = get_bits(&s->gb, 4);
1416
    switch(ext_type) {
1417
    case 0x1:
1418
        /* sequence ext */
1419
        mpeg_decode_sequence_extension(s);
1420
        break;
1421
    case 0x3:
1422
        /* quant matrix extension */
1423
        mpeg_decode_quant_matrix_extension(s);
1424
        break;
1425
    case 0x8:
1426
        /* picture extension */
1427
        mpeg_decode_picture_coding_extension(s);
1428
        break;
1429
    }
1430
}
1431

    
1432
/* return 1 if end of frame */
1433
static int mpeg_decode_slice(AVCodecContext *avctx, 
1434
                              AVPicture *pict,
1435
                              int start_code,
1436
                              UINT8 *buf, int buf_size)
1437
{
1438
    Mpeg1Context *s1 = avctx->priv_data;
1439
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1440
    int ret;
1441

    
1442
    start_code = (start_code - 1) & 0xff;
1443
    if (start_code >= s->mb_height)
1444
        return -1;
1445
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1446
    s->last_dc[1] = s->last_dc[0];
1447
    s->last_dc[2] = s->last_dc[0];
1448
    memset(s->last_mv, 0, sizeof(s->last_mv));
1449
    s->mb_x = -1;
1450
    s->mb_y = start_code;
1451
    s->mb_incr = 0;
1452
    /* start frame decoding */
1453
    if (s->first_slice) {
1454
        s->first_slice = 0;
1455
        MPV_frame_start(s, avctx);
1456
    }
1457

    
1458
    init_get_bits(&s->gb, buf, buf_size);
1459

    
1460
    s->qscale = get_qscale(s);
1461
    /* extra slice info */
1462
    while (get_bits1(&s->gb) != 0) {
1463
        skip_bits(&s->gb, 8);
1464
    }
1465

    
1466
    for(;;) {
1467
        clear_blocks(s->block[0]);
1468
        emms_c();
1469
        ret = mpeg_decode_mb(s, s->block);
1470
        dprintf("ret=%d\n", ret);
1471
        if (ret < 0)
1472
            return -1;
1473
        if (ret == 1)
1474
            break;
1475
        MPV_decode_mb(s, s->block);
1476
    }
1477
    emms_c();
1478

    
1479
    /* end of slice reached */
1480
    if (s->mb_x == (s->mb_width - 1) &&
1481
        s->mb_y == (s->mb_height - 1)) {
1482
        /* end of image */
1483
        UINT8 **picture;
1484

    
1485
        MPV_frame_end(s);
1486

    
1487
        /* XXX: incorrect reported qscale for mpeg2 */
1488
        if (s->pict_type == B_TYPE) {
1489
            picture = s->current_picture;
1490
            avctx->quality = s->qscale;
1491
        } else {
1492
            /* latency of 1 frame for I and P frames */
1493
            /* XXX: use another variable than picture_number */
1494
            if (s->picture_number == 0) {
1495
                picture = NULL;
1496
            } else {
1497
                picture = s->last_picture;
1498
                avctx->quality = s->last_qscale;
1499
            }
1500
            s->last_qscale = s->qscale;
1501
            s->picture_number++;
1502
        }
1503
        if (picture) {
1504
            pict->data[0] = picture[0];
1505
            pict->data[1] = picture[1];
1506
            pict->data[2] = picture[2];
1507
            pict->linesize[0] = s->linesize;
1508
            pict->linesize[1] = s->linesize / 2;
1509
            pict->linesize[2] = s->linesize / 2;
1510
            return 1;
1511
        } else {
1512
            return 0;
1513
        }
1514
    } else {
1515
        return 0;
1516
    }
1517
}
1518

    
1519
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1520
                                 UINT8 *buf, int buf_size)
1521
{
1522
    Mpeg1Context *s1 = avctx->priv_data;
1523
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1524
    int width, height, i, v, j;
1525

    
1526
    init_get_bits(&s->gb, buf, buf_size);
1527

    
1528
    width = get_bits(&s->gb, 12);
1529
    height = get_bits(&s->gb, 12);
1530
    skip_bits(&s->gb, 4);
1531
    s->frame_rate_index = get_bits(&s->gb, 4);
1532
    if (s->frame_rate_index == 0)
1533
        return -1;
1534
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1535
    if (get_bits1(&s->gb) == 0) /* marker */
1536
        return -1;
1537
    if (width <= 0 || height <= 0 ||
1538
        (width % 2) != 0 || (height % 2) != 0)
1539
        return -1;
1540
    if (width != s->width ||
1541
        height != s->height) {
1542
        /* start new mpeg1 context decoding */
1543
        s->out_format = FMT_MPEG1;
1544
        if (s1->mpeg_enc_ctx_allocated) {
1545
            MPV_common_end(s);
1546
        }
1547
        s->width = width;
1548
        s->height = height;
1549
        s->has_b_frames = 1;
1550
        s->avctx = avctx;
1551
        avctx->width = width;
1552
        avctx->height = height;
1553
        if (s->frame_rate_index >= 9) {
1554
            /* at least give a valid frame rate (some old mpeg1 have this) */
1555
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1556
        } else {
1557
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1558
        }
1559
        s->frame_rate = avctx->frame_rate;
1560
        avctx->bit_rate = s->bit_rate;
1561
        
1562
        if (MPV_common_init(s) < 0)
1563
            return -1;
1564
        mpeg1_init_vlc(s);
1565
        s1->mpeg_enc_ctx_allocated = 1;
1566
    }
1567

    
1568
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1569
    skip_bits(&s->gb, 1);
1570

    
1571
    /* get matrix */
1572
    if (get_bits1(&s->gb)) {
1573
        for(i=0;i<64;i++) {
1574
            v = get_bits(&s->gb, 8);
1575
            j = zigzag_direct[i];
1576
            s->intra_matrix[j] = v;
1577
            s->chroma_intra_matrix[j] = v;
1578
        }
1579
#ifdef DEBUG
1580
        dprintf("intra matrix present\n");
1581
        for(i=0;i<64;i++)
1582
            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1583
        printf("\n");
1584
#endif
1585
    } else {
1586
        for(i=0;i<64;i++) {
1587
            v = ff_mpeg1_default_intra_matrix[i];
1588
            s->intra_matrix[i] = v;
1589
            s->chroma_intra_matrix[i] = v;
1590
        }
1591
    }
1592
    if (get_bits1(&s->gb)) {
1593
        for(i=0;i<64;i++) {
1594
            v = get_bits(&s->gb, 8);
1595
            j = zigzag_direct[i];
1596
            s->inter_matrix[j] = v;
1597
            s->chroma_inter_matrix[j] = v;
1598
        }
1599
#ifdef DEBUG
1600
        dprintf("non intra matrix present\n");
1601
        for(i=0;i<64;i++)
1602
            dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1603
        printf("\n");
1604
#endif
1605
    } else {
1606
        for(i=0;i<64;i++) {
1607
            v = ff_mpeg1_default_non_intra_matrix[i];
1608
            s->inter_matrix[i] = v;
1609
            s->chroma_inter_matrix[i] = v;
1610
        }
1611
    }
1612

    
1613
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1614
    s->progressive_sequence = 1;
1615
    s->progressive_frame = 1;
1616
    s->picture_structure = PICT_FRAME;
1617
    s->frame_pred_frame_dct = 1;
1618
    s->mpeg2 = 0;
1619
    avctx->sub_id = 1; /* indicates mpeg1 */
1620
    return 0;
1621
}
1622

    
1623
/* handle buffering and image synchronisation */
1624
static int mpeg_decode_frame(AVCodecContext *avctx, 
1625
                             void *data, int *data_size,
1626
                             UINT8 *buf, int buf_size)
1627
{
1628
    Mpeg1Context *s = avctx->priv_data;
1629
    UINT8 *buf_end, *buf_ptr, *buf_start;
1630
    int len, start_code_found, ret, code, start_code, input_size;
1631
    AVPicture *picture = data;
1632
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1633
            
1634
    dprintf("fill_buffer\n");
1635

    
1636
    *data_size = 0;
1637

    
1638
    /* special case for last picture */
1639
    if (buf_size == 0) {
1640
        if (s2->picture_number > 0) {
1641
            picture->data[0] = s2->next_picture[0];
1642
            picture->data[1] = s2->next_picture[1];
1643
            picture->data[2] = s2->next_picture[2];
1644
            picture->linesize[0] = s2->linesize;
1645
            picture->linesize[1] = s2->linesize / 2;
1646
            picture->linesize[2] = s2->linesize / 2;
1647
            *data_size = sizeof(AVPicture);
1648
        }
1649
        return 0;
1650
    }
1651

    
1652
    buf_ptr = buf;
1653
    buf_end = buf + buf_size;
1654

    
1655
#if 0    
1656
    if (s->repeat_field % 2 == 1) { 
1657
        s->repeat_field++;
1658
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1659
        //        s2->picture_number, s->repeat_field);
1660
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1661
            *data_size = sizeof(AVPicture);
1662
            goto the_end;
1663
        }
1664
    }
1665
#endif
1666
    while (buf_ptr < buf_end) {
1667
        buf_start = buf_ptr;
1668
        /* find start next code */
1669
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1670
        if (code >= 0) {
1671
            start_code_found = 1;
1672
        } else {
1673
            start_code_found = 0;
1674
        }
1675
        /* copy to buffer */
1676
        len = buf_ptr - buf_start;
1677
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1678
            /* data too big : flush */
1679
            s->buf_ptr = s->buffer;
1680
            if (start_code_found)
1681
                s->start_code = code;
1682
        } else {
1683
            memcpy(s->buf_ptr, buf_start, len);
1684
            s->buf_ptr += len;
1685
            
1686
            if (start_code_found) {
1687
                /* prepare data for next start code */
1688
                input_size = s->buf_ptr - s->buffer;
1689
                start_code = s->start_code;
1690
                s->buf_ptr = s->buffer;
1691
                s->start_code = code;
1692
                switch(start_code) {
1693
                case SEQ_START_CODE:
1694
                    mpeg1_decode_sequence(avctx, s->buffer, 
1695
                                          input_size);
1696
                    break;
1697
                            
1698
                case PICTURE_START_CODE:
1699
                    /* we have a complete image : we try to decompress it */
1700
                    mpeg1_decode_picture(avctx, 
1701
                                         s->buffer, input_size);
1702
                    break;
1703
                case EXT_START_CODE:
1704
                    mpeg_decode_extension(avctx,
1705
                                          s->buffer, input_size);
1706
                    break;
1707
                default:
1708
                    if (start_code >= SLICE_MIN_START_CODE &&
1709
                        start_code <= SLICE_MAX_START_CODE) {
1710
                        ret = mpeg_decode_slice(avctx, picture,
1711
                                                start_code, s->buffer, input_size);
1712
                        if (ret == 1) {
1713
                            /* got a picture: exit */
1714
                            /* first check if we must repeat the frame */
1715
                            avctx->repeat_pict = 0;
1716
#if 0
1717
                            if (s2->progressive_frame && s2->repeat_first_field) {
1718
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1719
                                //s2->repeat_first_field = 0;
1720
                                //s2->progressive_frame = 0;
1721
                                if (++s->repeat_field > 2)
1722
                                    s->repeat_field = 0;
1723
                                avctx->repeat_pict = 1;
1724
                            }
1725
#endif                      
1726
                            if (s2->repeat_first_field) {
1727
                                if (s2->progressive_sequence) {
1728
                                    if (s2->top_field_first)
1729
                                        avctx->repeat_pict = 4;
1730
                                    else
1731
                                        avctx->repeat_pict = 2;
1732
                                } else if (s2->progressive_frame) {
1733
                                    avctx->repeat_pict = 1;
1734
                                }
1735
                            }         
1736
                            *data_size = sizeof(AVPicture);
1737
                            goto the_end;
1738
                        }
1739
                    }
1740
                    break;
1741
                }
1742
            }
1743
        }
1744
    }
1745
 the_end:
1746
    return buf_ptr - buf;
1747
}
1748

    
1749
static int mpeg_decode_end(AVCodecContext *avctx)
1750
{
1751
    Mpeg1Context *s = avctx->priv_data;
1752

    
1753
    if (s->mpeg_enc_ctx_allocated)
1754
        MPV_common_end(&s->mpeg_enc_ctx);
1755
    return 0;
1756
}
1757

    
1758
AVCodec mpeg_decoder = {
1759
    "mpegvideo",
1760
    CODEC_TYPE_VIDEO,
1761
    CODEC_ID_MPEG1VIDEO,
1762
    sizeof(Mpeg1Context),
1763
    mpeg_decode_init,
1764
    NULL,
1765
    mpeg_decode_end,
1766
    mpeg_decode_frame,
1767
};