Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ 8ed2ddb2

History | View | Annotate | Download (53.8 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
static void mpeg1_encode_block(MpegEncContext *s, 
37
                         DCTELEM *block, 
38
                         int component);
39
static void mpeg1_encode_motion(MpegEncContext *s, int val);
40
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
41
static int mpeg1_decode_block(MpegEncContext *s, 
42
                              DCTELEM *block, 
43
                              int n);
44
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
45
                                        DCTELEM *block, 
46
                                        int n);
47
static int mpeg2_decode_block_intra(MpegEncContext *s, 
48
                                    DCTELEM *block, 
49
                                    int n);
50
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
51

    
52
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
53
static UINT8 fcode_tab[MAX_MV*2+1];
54

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

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

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

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

    
132
        }
133
}
134

    
135

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

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

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

    
187
static void common_init(MpegEncContext *s)
188
{
189
    s->y_dc_scale_table=
190
    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
191
}
192

    
193
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
194
{
195
    mpeg1_encode_sequence_header(s);
196

    
197
    /* mpeg1 picture header */
198
    put_header(s, PICTURE_START_CODE);
199
    /* temporal reference */
200
    put_bits(&s->pb, 10, (s->fake_picture_number - 
201
                          s->gop_picture_number) & 0x3ff); 
202
    s->fake_picture_number++;
203
    
204
    put_bits(&s->pb, 3, s->pict_type);
205
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
206
    
207
    if (s->pict_type == P_TYPE) {
208
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
209
        put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
210
    }
211
    
212
    put_bits(&s->pb, 1, 0); /* extra bit picture */
213
    
214
    /* only one slice */
215
    put_header(s, SLICE_MIN_START_CODE);
216
    put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
217
    put_bits(&s->pb, 1, 0); /* slice extra information */
218
}
219

    
220
void mpeg1_encode_mb(MpegEncContext *s,
221
                     DCTELEM block[6][64],
222
                     int motion_x, int motion_y)
223
{
224
    int mb_incr, i, cbp, mb_x, mb_y;
225

    
226
    mb_x = s->mb_x;
227
    mb_y = s->mb_y;
228

    
229
    /* compute cbp */
230
    cbp = 0;
231
    for(i=0;i<6;i++) {
232
        if (s->block_last_index[i] >= 0)
233
            cbp |= 1 << (5 - i);
234
    }
235

    
236
    /* skip macroblock, except if first or last macroblock of a slice */
237
    if ((cbp | motion_x | motion_y) == 0 &&
238
        (!((mb_x | mb_y) == 0 ||
239
           (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1)))) {
240
        s->mb_incr++;
241
    } else {
242
        /* output mb incr */
243
        mb_incr = s->mb_incr;
244

    
245
        while (mb_incr > 33) {
246
            put_bits(&s->pb, 11, 0x008);
247
            mb_incr -= 33;
248
        }
249
        put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
250
                 mbAddrIncrTable[mb_incr - 1][0]);
251
        
252
        if (s->pict_type == I_TYPE) {
253
            put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
254
        } else {
255
            if (s->mb_intra) {
256
                put_bits(&s->pb, 5, 0x03);
257
            } else {
258
                if (cbp != 0) {
259
                    if (motion_x == 0 && motion_y == 0) {
260
                        put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
261
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
262
                    } else {
263
                        put_bits(&s->pb, 1, 1); /* motion + cbp */
264
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
265
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
266
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
267
                    }
268
                } else {
269
                    put_bits(&s->pb, 3, 1); /* motion only */
270
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
271
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
272
                }
273
            }
274
        }
275
        for(i=0;i<6;i++) {
276
            if (cbp & (1 << (5 - i))) {
277
                mpeg1_encode_block(s, block[i], i);
278
            }
279
        }
280
        s->mb_incr = 1;
281
    }
282
    s->last_mv[0][0][0] = motion_x;
283
    s->last_mv[0][0][1] = motion_y;
284
}
285

    
286
static void mpeg1_encode_motion(MpegEncContext *s, int val)
287
{
288
    int code, bit_size, l, m, bits, range, sign;
289

    
290
    if (val == 0) {
291
        /* zero vector */
292
        code = 0;
293
        put_bits(&s->pb,
294
                 mbMotionVectorTable[0][1], 
295
                 mbMotionVectorTable[0][0]); 
296
    } else {
297
        bit_size = s->f_code - 1;
298
        range = 1 << bit_size;
299
        /* modulo encoding */
300
        l = 16 * range;
301
        m = 2 * l;
302
        if (val < -l) {
303
            val += m;
304
        } else if (val >= l) {
305
            val -= m;
306
        }
307

    
308
        if (val >= 0) {
309
            val--;
310
            code = (val >> bit_size) + 1;
311
            bits = val & (range - 1);
312
            sign = 0;
313
        } else {
314
            val = -val;
315
            val--;
316
            code = (val >> bit_size) + 1;
317
            bits = val & (range - 1);
318
            sign = 1;
319
        }
320
        put_bits(&s->pb,
321
                 mbMotionVectorTable[code][1], 
322
                 mbMotionVectorTable[code][0]); 
323
        put_bits(&s->pb, 1, sign);
324
        if (bit_size > 0) {
325
            put_bits(&s->pb, bit_size, bits);
326
        }
327
    }
328
}
329

    
330
void ff_mpeg1_encode_init(MpegEncContext *s)
331
{
332
    static int done=0;
333

    
334
    common_init(s);
335

    
336
    if(!done){
337
        int f_code;
338
        int mv;
339
        int i;
340

    
341
        done=1;
342
        init_rl(&rl_mpeg1);
343
        
344
        for(i=0; i<64; i++)
345
        {
346
                mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
347
                mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
348
        }
349

    
350
        /* build unified dc encoding tables */
351
        for(i=-255; i<256; i++)
352
        {
353
                int adiff, index;
354
                int bits, code;
355
                int diff=i;
356

    
357
                adiff = ABS(diff);
358
                if(diff<0) diff--;
359
                index = vlc_dc_table[adiff];
360

    
361
                bits= vlc_dc_lum_bits[index] + index;
362
                code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
363
                mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
364
                
365
                bits= vlc_dc_chroma_bits[index] + index;
366
                code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
367
                mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
368
        }
369

    
370
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
371
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
372
                int len;
373

    
374
                if(mv==0) len= mbMotionVectorTable[0][1];
375
                else{
376
                    int val, bit_size, range, code;
377

    
378
                    bit_size = s->f_code - 1;
379
                    range = 1 << bit_size;
380

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

    
393
                mv_penalty[f_code][mv+MAX_MV]= len;
394
            }
395
        }
396
        
397

    
398
        for(f_code=MAX_FCODE; f_code>0; f_code--){
399
            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
400
                fcode_tab[mv+MAX_MV]= f_code;
401
            }
402
        }
403
    }
404
    s->mv_penalty= mv_penalty;
405
    s->fcode_tab= fcode_tab;
406
    s->min_qcoeff=-255;
407
    s->max_qcoeff= 255;
408
    s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
409
    s->inter_quant_bias= 0;
410
}
411

    
412
static inline void encode_dc(MpegEncContext *s, int diff, int component)
413
{
414
    if (component == 0) {
415
        put_bits(
416
            &s->pb, 
417
            mpeg1_lum_dc_uni[diff+255]&0xFF,
418
            mpeg1_lum_dc_uni[diff+255]>>8);
419
    } else {
420
        put_bits(
421
            &s->pb, 
422
            mpeg1_chr_dc_uni[diff+255]&0xFF,
423
            mpeg1_chr_dc_uni[diff+255]>>8);
424
    }
425
}
426

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

    
435
    last_index = s->block_last_index[n];
436

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

    
460
    /* now quantify & encode AC coefs */
461
    last_non_zero = i - 1;
462

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

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

    
525
/******************************************/
526
/* decoding */
527

    
528
static VLC dc_lum_vlc;
529
static VLC dc_chroma_vlc;
530
static VLC mv_vlc;
531
static VLC mbincr_vlc;
532
static VLC mb_ptype_vlc;
533
static VLC mb_btype_vlc;
534
static VLC mb_pat_vlc;
535

    
536
#define DC_VLC_BITS 9
537
#define MV_VLC_BITS 9
538
#define MBINCR_VLC_BITS 9
539
#define MB_PAT_VLC_BITS 9
540
#define MB_PTYPE_VLC_BITS 6
541
#define MB_BTYPE_VLC_BITS 6
542
#define TEX_VLC_BITS 9
543

    
544
void mpeg1_init_vlc(MpegEncContext *s)
545
{
546
    static int done = 0;
547

    
548
    if (!done) {
549
        done = 1;
550

    
551
        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 10/*12*/, 
552
                 vlc_dc_lum_bits, 1, 1,
553
                 vlc_dc_lum_code, 2, 2);
554
        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 10/*12*/, 
555
                 vlc_dc_chroma_bits, 1, 1,
556
                 vlc_dc_chroma_code, 2, 2);
557
        init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
558
                 &mbMotionVectorTable[0][1], 2, 1,
559
                 &mbMotionVectorTable[0][0], 2, 1);
560
        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 35, 
561
                 &mbAddrIncrTable[0][1], 2, 1,
562
                 &mbAddrIncrTable[0][0], 2, 1);
563
        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 63, 
564
                 &mbPatTable[0][1], 2, 1,
565
                 &mbPatTable[0][0], 2, 1);
566
        
567
        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 32, 
568
                 &table_mb_ptype[0][1], 2, 1,
569
                 &table_mb_ptype[0][0], 2, 1);
570
        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 32, 
571
                 &table_mb_btype[0][1], 2, 1,
572
                 &table_mb_btype[0][0], 2, 1);
573
        init_rl(&rl_mpeg1);
574
        init_rl(&rl_mpeg2);
575
        /* cannot use generic init because we must add the EOB code */
576
        init_vlc(&rl_mpeg1.vlc, TEX_VLC_BITS, rl_mpeg1.n + 2, 
577
                 &rl_mpeg1.table_vlc[0][1], 4, 2,
578
                 &rl_mpeg1.table_vlc[0][0], 4, 2);
579
        init_vlc(&rl_mpeg2.vlc, TEX_VLC_BITS, rl_mpeg2.n + 2, 
580
                 &rl_mpeg2.table_vlc[0][1], 4, 2,
581
                 &rl_mpeg2.table_vlc[0][0], 4, 2);
582
    }
583
}
584

    
585
static inline int get_dmv(MpegEncContext *s)
586
{
587
    if(get_bits1(&s->gb)) 
588
        return 1 - (get_bits1(&s->gb) << 1);
589
    else
590
        return 0;
591
}
592

    
593
static inline int get_qscale(MpegEncContext *s)
594
{
595
    int qscale;
596
    if (s->mpeg2) {
597
        if (s->q_scale_type) {
598
            qscale = non_linear_qscale[get_bits(&s->gb, 5)];
599
        } else {
600
            qscale = get_bits(&s->gb, 5) << 1;
601
        }
602
    } else {
603
        /* for mpeg1, we use the generic unquant code */
604
        qscale = get_bits(&s->gb, 5);
605
    }
606
    return qscale;
607
}
608

    
609
/* motion type (for mpeg2) */
610
#define MT_FIELD 1
611
#define MT_FRAME 2
612
#define MT_16X8  2
613
#define MT_DMV   3
614

    
615
static int mpeg_decode_mb(MpegEncContext *s,
616
                          DCTELEM block[6][64])
617
{
618
    int i, j, k, cbp, val, code, mb_type, motion_type;
619
    
620
    /* skip mb handling */
621
    if (s->mb_incr == 0) {
622
        /* read again increment */
623
        s->mb_incr = 1;
624
        for(;;) {
625
            code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
626
            if (code < 0)
627
                return 1; /* error = end of slice */
628
            if (code >= 33) {
629
                if (code == 33) {
630
                    s->mb_incr += 33;
631
                }
632
                /* otherwise, stuffing, nothing to do */
633
            } else {
634
                s->mb_incr += code;
635
                break;
636
            }
637
        }
638
    }
639
    if (++s->mb_x >= s->mb_width) {
640
        s->mb_x = 0;
641
        if (s->mb_y >= (s->mb_height - 1))
642
            return -1;
643
        s->mb_y++;
644
    }
645
    dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
646

    
647
    if (--s->mb_incr != 0) {
648
        /* skip mb */
649
        s->mb_intra = 0;
650
        for(i=0;i<6;i++)
651
            s->block_last_index[i] = -1;
652
        s->mv_type = MV_TYPE_16X16;
653
        if (s->pict_type == P_TYPE) {
654
            /* if P type, zero motion vector is implied */
655
            s->mv_dir = MV_DIR_FORWARD;
656
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
657
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
658
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
659
        } else {
660
            /* if B type, reuse previous vectors and directions */
661
            s->mv[0][0][0] = s->last_mv[0][0][0];
662
            s->mv[0][0][1] = s->last_mv[0][0][1];
663
            s->mv[1][0][0] = s->last_mv[1][0][0];
664
            s->mv[1][0][1] = s->last_mv[1][0][1];
665
        }
666
        s->mb_skiped = 1;
667
        return 0;
668
    }
669

    
670
    switch(s->pict_type) {
671
    default:
672
    case I_TYPE:
673
        if (get_bits1(&s->gb) == 0) {
674
            if (get_bits1(&s->gb) == 0)
675
                return -1;
676
            mb_type = MB_QUANT | MB_INTRA;
677
        } else {
678
            mb_type = MB_INTRA;
679
        }
680
        break;
681
    case P_TYPE:
682
        mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
683
        if (mb_type < 0)
684
            return -1;
685
        break;
686
    case B_TYPE:
687
        mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
688
        if (mb_type < 0)
689
            return -1;
690
        break;
691
    }
692
    dprintf("mb_type=%x\n", mb_type);
693
    motion_type = 0; /* avoid warning */
694
    if (mb_type & (MB_FOR|MB_BACK)) {
695
        /* get additionnal motion vector type */
696
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
697
            motion_type = MT_FRAME;
698
        else
699
            motion_type = get_bits(&s->gb, 2);
700
    }
701
    /* compute dct type */
702
    if (s->picture_structure == PICT_FRAME && 
703
        !s->frame_pred_frame_dct &&
704
        (mb_type & (MB_PAT | MB_INTRA))) {
705
        s->interlaced_dct = get_bits1(&s->gb);
706
#ifdef DEBUG
707
        if (s->interlaced_dct)
708
            printf("interlaced_dct\n");
709
#endif
710
    } else {
711
        s->interlaced_dct = 0; /* frame based */
712
    }
713

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

    
811
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
812
                                                s->last_mv[i][0][0]);
813
                        s->last_mv[i][0][0] = mx;
814
                        s->last_mv[i][1][0] = mx;
815
                        dmx = get_dmv(s);
816
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
817
                                                s->last_mv[i][0][1] >> 1);
818
                        dmy = get_dmv(s);
819
                        s->mv_type = MV_TYPE_DMV;
820
                        /* XXX: totally broken */
821
                        if (s->picture_structure == PICT_FRAME) {
822
                            s->last_mv[i][0][1] = my << 1;
823
                            s->last_mv[i][1][1] = my << 1;
824

    
825
                            m = s->top_field_first ? 1 : 3;
826
                            /* top -> top pred */
827
                            s->mv[i][0][0] = mx; 
828
                            s->mv[i][0][1] = my << 1;
829
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
830
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
831
                            m = 4 - m;
832
                            s->mv[i][2][0] = mx;
833
                            s->mv[i][2][1] = my << 1;
834
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
835
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
836
                        } else {
837
                            s->last_mv[i][0][1] = my;
838
                            s->last_mv[i][1][1] = my;
839
                            s->mv[i][0][0] = mx;
840
                            s->mv[i][0][1] = my;
841
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
842
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
843
                                /* + 2 * cur_field */;
844
                        }
845
                    }
846
                    break;
847
                }
848
            }
849
        }
850
    }
851

    
852
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
853
        skip_bits1(&s->gb); /* marker */
854
    }
855
    
856
    if (mb_type & MB_PAT) {
857
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
858
        if (cbp < 0)
859
            return -1;
860
        cbp++;
861
    }
862
    dprintf("cbp=%x\n", cbp);
863

    
864
    if (s->mpeg2) {
865
        if (s->mb_intra) {
866
            for(i=0;i<6;i++) {
867
                if (cbp & (1 << (5 - i))) {
868
                    if (mpeg2_decode_block_intra(s, block[i], i) < 0)
869
                        return -1;
870
                } else {
871
                    s->block_last_index[i] = -1;
872
                }
873
            }
874
        } else {
875
            for(i=0;i<6;i++) {
876
                if (cbp & (1 << (5 - i))) {
877
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
878
                        return -1;
879
                } else {
880
                    s->block_last_index[i] = -1;
881
                }
882
            }
883
        }
884
    } else {
885
        for(i=0;i<6;i++) {
886
            if (cbp & (1 << (5 - i))) {
887
                if (mpeg1_decode_block(s, block[i], i) < 0)
888
                    return -1;
889
            } else {
890
                s->block_last_index[i] = -1;
891
            }
892
        }
893
    }
894
    return 0;
895
}
896

    
897
/* as h263, but only 17 codes */
898
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
899
{
900
    int code, sign, val, m, l, shift;
901

    
902
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
903
    if (code < 0) {
904
        return 0xffff;
905
    }
906
    if (code == 0) {
907
        return pred;
908
    }
909
    sign = get_bits1(&s->gb);
910
    shift = fcode - 1;
911
    val = (code - 1) << shift;
912
    if (shift > 0)
913
        val |= get_bits(&s->gb, shift);
914
    val++;
915
    if (sign)
916
        val = -val;
917
    val += pred;
918
    
919
    /* modulo decoding */
920
    l = (1 << shift) * 16;
921
    m = 2 * l;
922
    if (val < -l) {
923
        val += m;
924
    } else if (val >= l) {
925
        val -= m;
926
    }
927
    return val;
928
}
929

    
930
static inline int decode_dc(MpegEncContext *s, int component)
931
{
932
    int code, diff;
933

    
934
    if (component == 0) {
935
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 1);
936
    } else {
937
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 1);
938
    }
939
    if (code < 0)
940
        return 0xffff;
941
    if (code == 0) {
942
        diff = 0;
943
    } else {
944
        diff = get_bits(&s->gb, code);
945
        if ((diff & (1 << (code - 1))) == 0) 
946
            diff = (-1 << code) | (diff + 1);
947
    }
948
    return diff;
949
}
950

    
951
static int mpeg1_decode_block(MpegEncContext *s, 
952
                               DCTELEM *block, 
953
                               int n)
954
{
955
    int level, dc, diff, i, j, run;
956
    int code, component;
957
    RLTable *rl = &rl_mpeg1;
958

    
959
    if (s->mb_intra) {
960
        /* DC coef */
961
        component = (n <= 3 ? 0 : n - 4 + 1);
962
        diff = decode_dc(s, component);
963
        if (diff >= 0xffff)
964
            return -1;
965
        dc = s->last_dc[component];
966
        dc += diff;
967
        s->last_dc[component] = dc;
968
        block[0] = dc;
969
        dprintf("dc=%d diff=%d\n", dc, diff);
970
        i = 1;
971
    } else {
972
        int v;
973
        OPEN_READER(re, &s->gb);
974
        i = 0;
975
        /* special case for the first coef. no need to add a second vlc table */
976
        UPDATE_CACHE(re, &s->gb);
977
        v= SHOW_UBITS(re, &s->gb, 2);
978
        if (v & 2) {
979
            run = 0;
980
            level = 1 - ((v & 1) << 1);
981
            SKIP_BITS(re, &s->gb, 2);
982
            CLOSE_READER(re, &s->gb);
983
            goto add_coef;
984
        }
985
        CLOSE_READER(re, &s->gb);
986
    }
987

    
988
    /* now quantify & encode AC coefs */
989
    for(;;) {
990
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
991
        if (code < 0) {
992
            return -1;
993
        }
994
        if (code == 112) {
995
            break;
996
        } else if (code == 111) {
997
            /* escape */
998
            run = get_bits(&s->gb, 6);
999
            level = get_bits(&s->gb, 8);
1000
            level = (level << 24) >> 24;
1001
            if (level == -128) {
1002
                level = get_bits(&s->gb, 8) - 256;
1003
            } else if (level == 0) {
1004
                level = get_bits(&s->gb, 8);
1005
            }
1006
        } else {
1007
            run = rl->table_run[code];
1008
            level = rl->table_level[code];
1009
            if (get_bits1(&s->gb))
1010
                level = -level;
1011
        }
1012
        i += run;
1013
        if (i >= 64)
1014
            return -1;
1015
    add_coef:
1016
        dprintf("%d: run=%d level=%d\n", n, run, level);
1017
        j = zigzag_direct[i];
1018
        block[j] = level;
1019
        i++;
1020
    }
1021
    s->block_last_index[n] = i-1;
1022
    return 0;
1023
}
1024

    
1025
/* Also does unquantization here, since I will never support mpeg2
1026
   encoding */
1027
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1028
                                        DCTELEM *block, 
1029
                                        int n)
1030
{
1031
    int level, i, j, run;
1032
    int code;
1033
    RLTable *rl = &rl_mpeg1;
1034
    const UINT8 *scan_table;
1035
    const UINT16 *matrix;
1036
    int mismatch;
1037

    
1038
    if (s->alternate_scan)
1039
        scan_table = ff_alternate_vertical_scan;
1040
    else
1041
        scan_table = zigzag_direct;
1042
    mismatch = 1;
1043

    
1044
    {
1045
        int v;
1046
        OPEN_READER(re, &s->gb);
1047
        i = 0;
1048
        if (n < 4)
1049
            matrix = s->inter_matrix;
1050
        else
1051
            matrix = s->chroma_inter_matrix;
1052

    
1053
        /* special case for the first coef. no need to add a second vlc table */
1054
        UPDATE_CACHE(re, &s->gb);
1055
        v= SHOW_UBITS(re, &s->gb, 2);
1056
        if (v & 2) {
1057
            run = 0;
1058
            level = 1 - ((v & 1) << 1);
1059
            SKIP_BITS(re, &s->gb, 2);
1060
            CLOSE_READER(re, &s->gb);
1061
            goto add_coef;
1062
        }
1063
        CLOSE_READER(re, &s->gb);
1064
    }
1065

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

    
1108
static int mpeg2_decode_block_intra(MpegEncContext *s, 
1109
                                    DCTELEM *block, 
1110
                                    int n)
1111
{
1112
    int level, dc, diff, i, j, run;
1113
    int code, component;
1114
    RLTable *rl;
1115
    const UINT8 *scan_table;
1116
    const UINT16 *matrix;
1117
    int mismatch;
1118

    
1119
    if (s->alternate_scan)
1120
        scan_table = ff_alternate_vertical_scan;
1121
    else
1122
        scan_table = zigzag_direct;
1123

    
1124
    /* DC coef */
1125
    component = (n <= 3 ? 0 : n - 4 + 1);
1126
    diff = decode_dc(s, component);
1127
    if (diff >= 0xffff)
1128
        return -1;
1129
    dc = s->last_dc[component];
1130
    dc += diff;
1131
    s->last_dc[component] = dc;
1132
    block[0] = dc << (3 - s->intra_dc_precision);
1133
    dprintf("dc=%d\n", block[0]);
1134
    mismatch = block[0] ^ 1;
1135
    i = 1;
1136
    if (s->intra_vlc_format)
1137
        rl = &rl_mpeg2;
1138
    else
1139
        rl = &rl_mpeg1;
1140
    if (n < 4) 
1141
        matrix = s->intra_matrix;
1142
    else
1143
        matrix = s->chroma_intra_matrix;
1144

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

    
1180
/* compressed picture size */
1181
#define PICTURE_BUFFER_SIZE 100000
1182

    
1183
typedef struct Mpeg1Context {
1184
    MpegEncContext mpeg_enc_ctx;
1185
    UINT32 header_state;
1186
    int start_code; /* current start code */
1187
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1188
    UINT8 *buf_ptr;
1189
    int buffer_size;
1190
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1191
    int repeat_field; /* true if we must repeat the field */
1192
} Mpeg1Context;
1193

    
1194
static int mpeg_decode_init(AVCodecContext *avctx)
1195
{
1196
    Mpeg1Context *s = avctx->priv_data;
1197
    
1198
    common_init(&s->mpeg_enc_ctx);
1199

    
1200
    s->header_state = 0xff;
1201
    s->mpeg_enc_ctx_allocated = 0;
1202
    s->buffer_size = PICTURE_BUFFER_SIZE;
1203
    s->start_code = -1;
1204
    s->buf_ptr = s->buffer;
1205
    s->mpeg_enc_ctx.picture_number = 0;
1206
    s->repeat_field = 0;
1207
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1208
    avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1209
    s->mpeg_enc_ctx.flags= avctx->flags;
1210
    return 0;
1211
}
1212

    
1213
/* return the 8 bit start code value and update the search
1214
   state. Return -1 if no start code found */
1215
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1216
                           UINT32 *header_state)
1217
{
1218
    UINT8 *buf_ptr;
1219
    unsigned int state, v;
1220
    int val;
1221

    
1222
    state = *header_state;
1223
    buf_ptr = *pbuf_ptr;
1224
    while (buf_ptr < buf_end) {
1225
        v = *buf_ptr++;
1226
        if (state == 0x000001) {
1227
            state = ((state << 8) | v) & 0xffffff;
1228
            val = state;
1229
            goto found;
1230
        }
1231
        state = ((state << 8) | v) & 0xffffff;
1232
    }
1233
    val = -1;
1234
 found:
1235
    *pbuf_ptr = buf_ptr;
1236
    *header_state = state;
1237
    return val;
1238
}
1239

    
1240
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1241
                                UINT8 *buf, int buf_size)
1242
{
1243
    Mpeg1Context *s1 = avctx->priv_data;
1244
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1245
    int ref, f_code;
1246

    
1247
    init_get_bits(&s->gb, buf, buf_size);
1248

    
1249
    ref = get_bits(&s->gb, 10); /* temporal ref */
1250
    s->pict_type = get_bits(&s->gb, 3);
1251
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1252
    skip_bits(&s->gb, 16);
1253
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1254
        s->full_pel[0] = get_bits1(&s->gb);
1255
        f_code = get_bits(&s->gb, 3);
1256
        if (f_code == 0)
1257
            return -1;
1258
        s->mpeg_f_code[0][0] = f_code;
1259
        s->mpeg_f_code[0][1] = f_code;
1260
    }
1261
    if (s->pict_type == B_TYPE) {
1262
        s->full_pel[1] = get_bits1(&s->gb);
1263
        f_code = get_bits(&s->gb, 3);
1264
        if (f_code == 0)
1265
            return -1;
1266
        s->mpeg_f_code[1][0] = f_code;
1267
        s->mpeg_f_code[1][1] = f_code;
1268
    }
1269
    s->y_dc_scale = 8;
1270
    s->c_dc_scale = 8;
1271
    s->first_slice = 1;
1272
    return 0;
1273
}
1274

    
1275
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1276
{
1277
    int horiz_size_ext, vert_size_ext;
1278
    int bit_rate_ext, vbv_buf_ext, low_delay;
1279
    int frame_rate_ext_n, frame_rate_ext_d;
1280

    
1281
    skip_bits(&s->gb, 8); /* profil and level */
1282
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1283
    skip_bits(&s->gb, 2); /* chroma_format */
1284
    horiz_size_ext = get_bits(&s->gb, 2);
1285
    vert_size_ext = get_bits(&s->gb, 2);
1286
    s->width |= (horiz_size_ext << 12);
1287
    s->height |= (vert_size_ext << 12);
1288
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1289
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1290
    skip_bits1(&s->gb); /* marker */
1291
    vbv_buf_ext = get_bits(&s->gb, 8);
1292
    low_delay = get_bits1(&s->gb);
1293
    frame_rate_ext_n = get_bits(&s->gb, 2);
1294
    frame_rate_ext_d = get_bits(&s->gb, 5);
1295
    if (frame_rate_ext_d >= 1)
1296
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1297
    dprintf("sequence extension\n");
1298
    s->mpeg2 = 1;
1299
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1300
}
1301

    
1302
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1303
{
1304
    int i, v, j;
1305

    
1306
    dprintf("matrix extension\n");
1307

    
1308
    if (get_bits1(&s->gb)) {
1309
        for(i=0;i<64;i++) {
1310
            v = get_bits(&s->gb, 8);
1311
            j = zigzag_direct[i];
1312
            s->intra_matrix[j] = v;
1313
            s->chroma_intra_matrix[j] = v;
1314
        }
1315
    }
1316
    if (get_bits1(&s->gb)) {
1317
        for(i=0;i<64;i++) {
1318
            v = get_bits(&s->gb, 8);
1319
            j = zigzag_direct[i];
1320
            s->inter_matrix[j] = v;
1321
            s->chroma_inter_matrix[j] = v;
1322
        }
1323
    }
1324
    if (get_bits1(&s->gb)) {
1325
        for(i=0;i<64;i++) {
1326
            v = get_bits(&s->gb, 8);
1327
            j = zigzag_direct[i];
1328
            s->chroma_intra_matrix[j] = v;
1329
        }
1330
    }
1331
    if (get_bits1(&s->gb)) {
1332
        for(i=0;i<64;i++) {
1333
            v = get_bits(&s->gb, 8);
1334
            j = zigzag_direct[i];
1335
            s->chroma_inter_matrix[j] = v;
1336
        }
1337
    }
1338
}
1339

    
1340
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1341
{
1342
    s->full_pel[0] = s->full_pel[1] = 0;
1343
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1344
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1345
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1346
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1347
    s->intra_dc_precision = get_bits(&s->gb, 2);
1348
    s->picture_structure = get_bits(&s->gb, 2);
1349
    s->top_field_first = get_bits1(&s->gb);
1350
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1351
    s->concealment_motion_vectors = get_bits1(&s->gb);
1352
    s->q_scale_type = get_bits1(&s->gb);
1353
    s->intra_vlc_format = get_bits1(&s->gb);
1354
    s->alternate_scan = get_bits1(&s->gb);
1355
    s->repeat_first_field = get_bits1(&s->gb);
1356
    s->chroma_420_type = get_bits1(&s->gb);
1357
    s->progressive_frame = get_bits1(&s->gb);
1358
    /* composite display not parsed */
1359
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1360
    dprintf("picture_structure=%d\n", s->picture_structure);
1361
    dprintf("top field first=%d\n", s->top_field_first);
1362
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1363
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1364
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1365
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1366
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1367
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1368
}
1369

    
1370
static void mpeg_decode_extension(AVCodecContext *avctx, 
1371
                                  UINT8 *buf, int buf_size)
1372
{
1373
    Mpeg1Context *s1 = avctx->priv_data;
1374
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1375
    int ext_type;
1376

    
1377
    init_get_bits(&s->gb, buf, buf_size);
1378
    
1379
    ext_type = get_bits(&s->gb, 4);
1380
    switch(ext_type) {
1381
    case 0x1:
1382
        /* sequence ext */
1383
        mpeg_decode_sequence_extension(s);
1384
        break;
1385
    case 0x3:
1386
        /* quant matrix extension */
1387
        mpeg_decode_quant_matrix_extension(s);
1388
        break;
1389
    case 0x8:
1390
        /* picture extension */
1391
        mpeg_decode_picture_coding_extension(s);
1392
        break;
1393
    }
1394
}
1395

    
1396
/* return 1 if end of frame */
1397
static int mpeg_decode_slice(AVCodecContext *avctx, 
1398
                              AVPicture *pict,
1399
                              int start_code,
1400
                              UINT8 *buf, int buf_size)
1401
{
1402
    Mpeg1Context *s1 = avctx->priv_data;
1403
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1404
    int ret;
1405

    
1406
    start_code = (start_code - 1) & 0xff;
1407
    if (start_code >= s->mb_height)
1408
        return -1;
1409
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1410
    s->last_dc[1] = s->last_dc[0];
1411
    s->last_dc[2] = s->last_dc[0];
1412
    memset(s->last_mv, 0, sizeof(s->last_mv));
1413
    s->mb_x = -1;
1414
    s->mb_y = start_code;
1415
    s->mb_incr = 0;
1416
    /* start frame decoding */
1417
    if (s->first_slice) {
1418
        s->first_slice = 0;
1419
        MPV_frame_start(s);
1420
    }
1421

    
1422
    init_get_bits(&s->gb, buf, buf_size);
1423

    
1424
    s->qscale = get_qscale(s);
1425
    /* extra slice info */
1426
    while (get_bits1(&s->gb) != 0) {
1427
        skip_bits(&s->gb, 8);
1428
    }
1429

    
1430
    for(;;) {
1431
        clear_blocks(s->block[0]);
1432
        emms_c();
1433
        ret = mpeg_decode_mb(s, s->block);
1434
        dprintf("ret=%d\n", ret);
1435
        if (ret < 0)
1436
            return -1;
1437
        if (ret == 1)
1438
            break;
1439
        MPV_decode_mb(s, s->block);
1440
    }
1441
    emms_c();
1442

    
1443
    /* end of slice reached */
1444
    if (s->mb_x == (s->mb_width - 1) &&
1445
        s->mb_y == (s->mb_height - 1)) {
1446
        /* end of image */
1447
        UINT8 **picture;
1448

    
1449
        MPV_frame_end(s);
1450

    
1451
        /* XXX: incorrect reported qscale for mpeg2 */
1452
        if (s->pict_type == B_TYPE) {
1453
            picture = s->current_picture;
1454
            avctx->quality = s->qscale;
1455
        } else {
1456
            /* latency of 1 frame for I and P frames */
1457
            /* XXX: use another variable than picture_number */
1458
            if (s->picture_number == 0) {
1459
                picture = NULL;
1460
            } else {
1461
                picture = s->last_picture;
1462
                avctx->quality = s->last_qscale;
1463
            }
1464
            s->last_qscale = s->qscale;
1465
            s->picture_number++;
1466
        }
1467
        if (picture) {
1468
            pict->data[0] = picture[0];
1469
            pict->data[1] = picture[1];
1470
            pict->data[2] = picture[2];
1471
            pict->linesize[0] = s->linesize;
1472
            pict->linesize[1] = s->linesize / 2;
1473
            pict->linesize[2] = s->linesize / 2;
1474
            return 1;
1475
        } else {
1476
            return 0;
1477
        }
1478
    } else {
1479
        return 0;
1480
    }
1481
}
1482

    
1483
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1484
                                 UINT8 *buf, int buf_size)
1485
{
1486
    Mpeg1Context *s1 = avctx->priv_data;
1487
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1488
    int width, height, i, v, j;
1489

    
1490
    init_get_bits(&s->gb, buf, buf_size);
1491

    
1492
    width = get_bits(&s->gb, 12);
1493
    height = get_bits(&s->gb, 12);
1494
    skip_bits(&s->gb, 4);
1495
    s->frame_rate_index = get_bits(&s->gb, 4);
1496
    if (s->frame_rate_index == 0)
1497
        return -1;
1498
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1499
    if (get_bits1(&s->gb) == 0) /* marker */
1500
        return -1;
1501
    if (width <= 0 || height <= 0 ||
1502
        (width % 2) != 0 || (height % 2) != 0)
1503
        return -1;
1504
    if (width != s->width ||
1505
        height != s->height) {
1506
        /* start new mpeg1 context decoding */
1507
        s->out_format = FMT_MPEG1;
1508
        if (s1->mpeg_enc_ctx_allocated) {
1509
            MPV_common_end(s);
1510
        }
1511
        s->width = width;
1512
        s->height = height;
1513
        s->has_b_frames = 1;
1514
        s->avctx = avctx;
1515
        avctx->width = width;
1516
        avctx->height = height;
1517
        if (s->frame_rate_index >= 9) {
1518
            /* at least give a valid frame rate (some old mpeg1 have this) */
1519
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1520
        } else {
1521
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1522
        }
1523
        s->frame_rate = avctx->frame_rate;
1524
        avctx->bit_rate = s->bit_rate;
1525
        
1526
        if (MPV_common_init(s) < 0)
1527
            return -1;
1528
        mpeg1_init_vlc(s);
1529
        s1->mpeg_enc_ctx_allocated = 1;
1530
    }
1531

    
1532
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1533
    skip_bits(&s->gb, 1);
1534

    
1535
    /* get matrix */
1536
    if (get_bits1(&s->gb)) {
1537
        for(i=0;i<64;i++) {
1538
            v = get_bits(&s->gb, 8);
1539
            j = zigzag_direct[i];
1540
            s->intra_matrix[j] = v;
1541
            s->chroma_intra_matrix[j] = v;
1542
        }
1543
#ifdef DEBUG
1544
        dprintf("intra matrix present\n");
1545
        for(i=0;i<64;i++)
1546
            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1547
        printf("\n");
1548
#endif
1549
    } else {
1550
        for(i=0;i<64;i++) {
1551
            v = ff_mpeg1_default_intra_matrix[i];
1552
            s->intra_matrix[i] = v;
1553
            s->chroma_intra_matrix[i] = v;
1554
        }
1555
    }
1556
    if (get_bits1(&s->gb)) {
1557
        for(i=0;i<64;i++) {
1558
            v = get_bits(&s->gb, 8);
1559
            j = zigzag_direct[i];
1560
            s->inter_matrix[j] = v;
1561
            s->chroma_inter_matrix[j] = v;
1562
        }
1563
#ifdef DEBUG
1564
        dprintf("non intra matrix present\n");
1565
        for(i=0;i<64;i++)
1566
            dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1567
        printf("\n");
1568
#endif
1569
    } else {
1570
        for(i=0;i<64;i++) {
1571
            v = ff_mpeg1_default_non_intra_matrix[i];
1572
            s->inter_matrix[i] = v;
1573
            s->chroma_inter_matrix[i] = v;
1574
        }
1575
    }
1576

    
1577
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1578
    s->progressive_sequence = 1;
1579
    s->progressive_frame = 1;
1580
    s->picture_structure = PICT_FRAME;
1581
    s->frame_pred_frame_dct = 1;
1582
    s->mpeg2 = 0;
1583
    avctx->sub_id = 1; /* indicates mpeg1 */
1584
    return 0;
1585
}
1586

    
1587
/* handle buffering and image synchronisation */
1588
static int mpeg_decode_frame(AVCodecContext *avctx, 
1589
                             void *data, int *data_size,
1590
                             UINT8 *buf, int buf_size)
1591
{
1592
    Mpeg1Context *s = avctx->priv_data;
1593
    UINT8 *buf_end, *buf_ptr, *buf_start;
1594
    int len, start_code_found, ret, code, start_code, input_size;
1595
    AVPicture *picture = data;
1596
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1597
            
1598
    dprintf("fill_buffer\n");
1599

    
1600
    *data_size = 0;
1601

    
1602
    /* special case for last picture */
1603
    if (buf_size == 0) {
1604
        if (s2->picture_number > 0) {
1605
            picture->data[0] = s2->next_picture[0];
1606
            picture->data[1] = s2->next_picture[1];
1607
            picture->data[2] = s2->next_picture[2];
1608
            picture->linesize[0] = s2->linesize;
1609
            picture->linesize[1] = s2->linesize / 2;
1610
            picture->linesize[2] = s2->linesize / 2;
1611
            *data_size = sizeof(AVPicture);
1612
        }
1613
        return 0;
1614
    }
1615

    
1616
    buf_ptr = buf;
1617
    buf_end = buf + buf_size;
1618

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

    
1713
static int mpeg_decode_end(AVCodecContext *avctx)
1714
{
1715
    Mpeg1Context *s = avctx->priv_data;
1716

    
1717
    if (s->mpeg_enc_ctx_allocated)
1718
        MPV_common_end(&s->mpeg_enc_ctx);
1719
    return 0;
1720
}
1721

    
1722
AVCodec mpeg_decoder = {
1723
    "mpegvideo",
1724
    CODEC_TYPE_VIDEO,
1725
    CODEC_ID_MPEG1VIDEO,
1726
    sizeof(Mpeg1Context),
1727
    mpeg_decode_init,
1728
    NULL,
1729
    mpeg_decode_end,
1730
    mpeg_decode_frame,
1731
};