Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ ea937d01

History | View | Annotate | Download (66.5 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
#if 1
27
#define PRINT_QP(a, b) {}
28
#else
29
#define PRINT_QP(a, b) printf(a, b)
30
#endif
31

    
32
/* Start codes. */
33
#define SEQ_END_CODE                0x000001b7
34
#define SEQ_START_CODE                0x000001b3
35
#define GOP_START_CODE                0x000001b8
36
#define PICTURE_START_CODE        0x00000100
37
#define SLICE_MIN_START_CODE        0x00000101
38
#define SLICE_MAX_START_CODE        0x000001af
39
#define EXT_START_CODE                0x000001b5
40
#define USER_START_CODE                0x000001b2
41

    
42
#define DC_VLC_BITS 9
43
#define MV_VLC_BITS 9
44
#define MBINCR_VLC_BITS 9
45
#define MB_PAT_VLC_BITS 9
46
#define MB_PTYPE_VLC_BITS 6
47
#define MB_BTYPE_VLC_BITS 6
48
#define TEX_VLC_BITS 9
49

    
50
static void mpeg1_encode_block(MpegEncContext *s, 
51
                         DCTELEM *block, 
52
                         int component);
53
static void mpeg1_encode_motion(MpegEncContext *s, int val);
54
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
55
static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
56
                              DCTELEM *block, 
57
                              int n);
58
static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
59
                              DCTELEM *block, 
60
                              int n);
61
static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
62
                                        DCTELEM *block, 
63
                                        int n);
64
static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
65
                                    DCTELEM *block, 
66
                                    int n);
67
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
68

    
69
#ifdef CONFIG_ENCODERS
70
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
71
static UINT8 fcode_tab[MAX_MV*2+1];
72

    
73
static uint32_t uni_mpeg1_ac_vlc_bits[64*64*2];
74
static uint8_t  uni_mpeg1_ac_vlc_len [64*64*2];
75
#endif
76

    
77
static inline int get_bits_diff(MpegEncContext *s){
78
    int bits,ret;
79
    
80
    bits= get_bit_count(&s->pb);
81
    ret= bits - s->last_bits;
82
    s->last_bits=bits;
83
    
84
    return ret;
85
}
86

    
87
static void init_2d_vlc_rl(RLTable *rl)
88
{
89
    int i;
90
    
91
    init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
92
             &rl->table_vlc[0][1], 4, 2,
93
             &rl->table_vlc[0][0], 4, 2);
94

    
95
    
96
    rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
97
    for(i=0; i<rl->vlc.table_size; i++){
98
        int code= rl->vlc.table[i][0];
99
        int len = rl->vlc.table[i][1];
100
        int level, run;
101
    
102
        if(len==0){ // illegal code
103
            run= 65;
104
            level= MAX_LEVEL;
105
        }else if(len<0){ //more bits needed
106
            run= 0;
107
            level= code;
108
        }else{
109
            if(code==rl->n){ //esc
110
                run= 65;
111
                level= 0;
112
            }else if(code==rl->n+1){ //eob
113
                run= 0;
114
                level= 127;
115
            }else{
116
                run=   rl->table_run  [code] + 1;
117
                level= rl->table_level[code];
118
            }
119
        }
120
        rl->rl_vlc[0][i].len= len;
121
        rl->rl_vlc[0][i].level= level;
122
        rl->rl_vlc[0][i].run= run;
123
    }
124
}
125

    
126
static void init_uni_ac_vlc(RLTable *rl, uint32_t *uni_ac_vlc_bits, uint8_t *uni_ac_vlc_len){
127
    int i;
128

    
129
    for(i=0; i<128; i++){
130
        int level= i-64;
131
        int run;
132
        for(run=0; run<64; run++){
133
            int len, bits, code;
134
            
135
            int alevel= ABS(level);
136
            int sign= (level>>31)&1;
137

    
138
            if (alevel > rl->max_level[0][run])
139
                code= 111; /*rl->n*/
140
            else
141
                code= rl->index_run[0][run] + alevel - 1;
142

    
143
            if (code < 111 /* rl->n */) {
144
                    /* store the vlc & sign at once */
145
                len=   mpeg1_vlc[code][1]+1;
146
                bits= (mpeg1_vlc[code][0]<<1) + sign;
147
            } else {
148
                len=  mpeg1_vlc[111/*rl->n*/][1]+6;
149
                bits= mpeg1_vlc[111/*rl->n*/][0]<<6;
150

    
151
                bits|= run;
152
                if (alevel < 128) {
153
                    bits<<=8; len+=8;
154
                    bits|= level & 0xff;
155
                } else {
156
                    bits<<=16; len+=16;
157
                    bits|= level & 0xff;
158
                    if (level < 0) {
159
                        bits|= 0x8001 + level + 255;
160
                    } else {
161
                        bits|= level & 0xffff;
162
                    }
163
                }
164
            }
165

    
166
            uni_ac_vlc_bits[UNI_AC_ENC_INDEX(run, i)]= bits;
167
            uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
168
        }
169
    }
170
}
171

    
172
static void put_header(MpegEncContext *s, int header)
173
{
174
    align_put_bits(&s->pb);
175
    put_bits(&s->pb, 16, header>>16);
176
    put_bits(&s->pb, 16, header&0xFFFF);
177
}
178

    
179
/* put sequence header if needed */
180
static void mpeg1_encode_sequence_header(MpegEncContext *s)
181
{
182
        unsigned int vbv_buffer_size;
183
        unsigned int fps, v;
184
        int n, i;
185
        UINT64 time_code;
186
        float best_aspect_error= 1E10;
187
        float aspect_ratio= s->avctx->aspect_ratio;
188
        
189
        if(aspect_ratio==0.0) aspect_ratio= s->width / (float)s->height; //pixel aspect 1:1 (VGA)
190
        
191
        if (s->current_picture.key_frame) {
192
            /* mpeg1 header repeated every gop */
193
            put_header(s, SEQ_START_CODE);
194
            
195
            /* search closest frame rate */
196
            {
197
                int i, dmin, d;
198
                s->frame_rate_index = 0;
199
                dmin = 0x7fffffff;
200
                for(i=1;i<9;i++) {
201
                    d = abs(s->frame_rate - frame_rate_tab[i]);
202
                    if (d < dmin) {
203
                        dmin = d;
204
                        s->frame_rate_index = i;
205
                    }
206
                }
207
            }
208
 
209
            put_bits(&s->pb, 12, s->width);
210
            put_bits(&s->pb, 12, s->height);
211
            
212
            for(i=1; i<15; i++){
213
                float error= mpeg1_aspect[i] - s->width/(s->height*aspect_ratio);
214
                error= ABS(error);
215
                
216
                if(error < best_aspect_error){
217
                    best_aspect_error= error;
218
                    s->aspect_ratio_info= i;
219
                }
220
            }
221
            
222
            put_bits(&s->pb, 4, s->aspect_ratio_info);
223
            put_bits(&s->pb, 4, s->frame_rate_index);
224
            v = s->bit_rate / 400;
225
            if (v > 0x3ffff)
226
                v = 0x3ffff;
227
            put_bits(&s->pb, 18, v);
228
            put_bits(&s->pb, 1, 1); /* marker */
229

    
230
            if(s->avctx->rc_buffer_size)
231
                vbv_buffer_size = s->avctx->rc_buffer_size;
232
            else
233
                /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
234
                vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;         
235
            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
236
            put_bits(&s->pb, 1, 1); /* constrained parameter flag */
237
            put_bits(&s->pb, 1, 0); /* no custom intra matrix */
238
            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
239

    
240
            put_header(s, GOP_START_CODE);
241
            put_bits(&s->pb, 1, 0); /* do drop frame */
242
            /* time code : we must convert from the real frame rate to a
243
               fake mpeg frame rate in case of low frame rate */
244
            fps = frame_rate_tab[s->frame_rate_index];
245
            time_code = (INT64)s->fake_picture_number * FRAME_RATE_BASE;
246
            s->gop_picture_number = s->fake_picture_number;
247
            put_bits(&s->pb, 5, (UINT32)((time_code / (fps * 3600)) % 24));
248
            put_bits(&s->pb, 6, (UINT32)((time_code / (fps * 60)) % 60));
249
            put_bits(&s->pb, 1, 1);
250
            put_bits(&s->pb, 6, (UINT32)((time_code / fps) % 60));
251
            put_bits(&s->pb, 6, (UINT32)((time_code % fps) / FRAME_RATE_BASE));
252
            put_bits(&s->pb, 1, 1); /* closed gop */
253
            put_bits(&s->pb, 1, 0); /* broken link */
254
        }
255

    
256
        if (s->frame_rate < (24 * FRAME_RATE_BASE) && s->picture_number > 0) {
257
            /* insert empty P pictures to slow down to the desired
258
               frame rate. Each fake pictures takes about 20 bytes */
259
            fps = frame_rate_tab[s->frame_rate_index];
260
            n = (((INT64)s->picture_number * fps) / s->frame_rate) - 1;
261
            while (s->fake_picture_number < n) {
262
                mpeg1_skip_picture(s, s->fake_picture_number - 
263
                                   s->gop_picture_number); 
264
                s->fake_picture_number++;
265
            }
266

    
267
        }
268
}
269

    
270

    
271
/* insert a fake P picture */
272
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num)
273
{
274
    unsigned int mb_incr;
275

    
276
    /* mpeg1 picture header */
277
    put_header(s, PICTURE_START_CODE);
278
    /* temporal reference */
279
    put_bits(&s->pb, 10, pict_num & 0x3ff); 
280
    
281
    put_bits(&s->pb, 3, P_TYPE);
282
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
283
    
284
    put_bits(&s->pb, 1, 1); /* integer coordinates */
285
    put_bits(&s->pb, 3, 1); /* forward_f_code */
286
    
287
    put_bits(&s->pb, 1, 0); /* extra bit picture */
288
    
289
    /* only one slice */
290
    put_header(s, SLICE_MIN_START_CODE);
291
    put_bits(&s->pb, 5, 1); /* quantizer scale */
292
    put_bits(&s->pb, 1, 0); /* slice extra information */
293
    
294
    mb_incr = 1;
295
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
296
             mbAddrIncrTable[mb_incr - 1][0]);
297
    
298
    /* empty macroblock */
299
    put_bits(&s->pb, 3, 1); /* motion only */
300
    
301
    /* zero motion x & y */
302
    put_bits(&s->pb, 1, 1); 
303
    put_bits(&s->pb, 1, 1); 
304

    
305
    /* output a number of empty slice */
306
    mb_incr = s->mb_width * s->mb_height - 1;
307
    while (mb_incr > 33) {
308
        put_bits(&s->pb, 11, 0x008);
309
        mb_incr -= 33;
310
    }
311
    put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
312
             mbAddrIncrTable[mb_incr - 1][0]);
313
    
314
    /* empty macroblock */
315
    put_bits(&s->pb, 3, 1); /* motion only */
316
    
317
    /* zero motion x & y */
318
    put_bits(&s->pb, 1, 1); 
319
    put_bits(&s->pb, 1, 1); 
320
}
321

    
322
static void common_init(MpegEncContext *s)
323
{
324
    s->y_dc_scale_table=
325
    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
326
}
327

    
328
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
329
{
330
    mpeg1_encode_sequence_header(s);
331

    
332
    /* mpeg1 picture header */
333
    put_header(s, PICTURE_START_CODE);
334
    /* temporal reference */
335
    put_bits(&s->pb, 10, (s->fake_picture_number - 
336
                          s->gop_picture_number) & 0x3ff); 
337
    s->fake_picture_number++;
338
    
339
    put_bits(&s->pb, 3, s->pict_type);
340
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
341
    
342
    if (s->pict_type == P_TYPE) {
343
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
344
        put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
345
    }
346
    
347
    put_bits(&s->pb, 1, 0); /* extra bit picture */
348
    
349
    /* only one slice */
350
    put_header(s, SLICE_MIN_START_CODE);
351
    put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
352
    put_bits(&s->pb, 1, 0); /* slice extra information */
353
}
354

    
355
void mpeg1_encode_mb(MpegEncContext *s,
356
                     DCTELEM block[6][64],
357
                     int motion_x, int motion_y)
358
{
359
    int mb_incr, i, cbp, mb_x, mb_y;
360

    
361
    mb_x = s->mb_x;
362
    mb_y = s->mb_y;
363

    
364
    /* compute cbp */
365
    cbp = 0;
366
    for(i=0;i<6;i++) {
367
        if (s->block_last_index[i] >= 0)
368
            cbp |= 1 << (5 - i);
369
    }
370

    
371
    /* skip macroblock, except if first or last macroblock of a slice */
372
    if ((cbp | motion_x | motion_y) == 0 &&
373
        (!((mb_x | mb_y) == 0 ||
374
           (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1)))) {
375
        s->mb_incr++;
376
        s->qscale -= s->dquant;
377
        s->skip_count++;
378
        s->misc_bits++;
379
        s->last_bits++;
380
    } else {
381
        /* output mb incr */
382
        mb_incr = s->mb_incr;
383

    
384
        while (mb_incr > 33) {
385
            put_bits(&s->pb, 11, 0x008);
386
            mb_incr -= 33;
387
        }
388
        put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
389
                 mbAddrIncrTable[mb_incr - 1][0]);
390
        
391
        if (s->pict_type == I_TYPE) {
392
            if(s->dquant && cbp){
393
                put_bits(&s->pb, 2, 1); /* macroblock_type : macroblock_quant = 1 */
394
                put_bits(&s->pb, 5, s->qscale);
395
            }else{
396
                put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
397
                s->qscale -= s->dquant;
398
            }
399
            s->misc_bits+= get_bits_diff(s);
400
            s->i_count++;
401
        } else {
402
            if (s->mb_intra) {
403
                if(s->dquant && cbp){
404
                    put_bits(&s->pb, 6, 0x01);
405
                    put_bits(&s->pb, 5, s->qscale);
406
                }else{
407
                    put_bits(&s->pb, 5, 0x03);
408
                    s->qscale -= s->dquant;
409
                }
410
                s->misc_bits+= get_bits_diff(s);
411
                s->i_count++;
412
            } else {
413
                if (cbp != 0) {
414
                    if (motion_x == 0 && motion_y == 0) {
415
                        if(s->dquant){
416
                            put_bits(&s->pb, 5, 1); /* macroblock_pattern & quant */
417
                            put_bits(&s->pb, 5, s->qscale);
418
                        }else{
419
                            put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
420
                        }
421
                        s->misc_bits+= get_bits_diff(s);
422
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
423
                    } else {
424
                        if(s->dquant){
425
                            put_bits(&s->pb, 5, 2); /* motion + cbp */
426
                            put_bits(&s->pb, 5, s->qscale);
427
                        }else{
428
                            put_bits(&s->pb, 1, 1); /* motion + cbp */
429
                        }
430
                        s->misc_bits+= get_bits_diff(s);
431
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
432
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
433
                        s->mv_bits+= get_bits_diff(s);
434
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
435
                    }
436
                } else {
437
                    put_bits(&s->pb, 3, 1); /* motion only */
438
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
439
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
440
                    s->qscale -= s->dquant;
441
                    s->mv_bits+= get_bits_diff(s);
442
                }
443
                s->f_count++;
444
            }
445
        }
446
        for(i=0;i<6;i++) {
447
            if (cbp & (1 << (5 - i))) {
448
                mpeg1_encode_block(s, block[i], i);
449
            }
450
        }
451
        s->mb_incr = 1;
452
        if(s->mb_intra)
453
            s->i_tex_bits+= get_bits_diff(s);
454
        else
455
            s->p_tex_bits+= get_bits_diff(s);
456
    }
457
    s->last_mv[0][0][0] = motion_x;
458
    s->last_mv[0][0][1] = motion_y;
459
}
460

    
461
static void mpeg1_encode_motion(MpegEncContext *s, int val)
462
{
463
    int code, bit_size, l, m, bits, range, sign;
464

    
465
    if (val == 0) {
466
        /* zero vector */
467
        code = 0;
468
        put_bits(&s->pb,
469
                 mbMotionVectorTable[0][1], 
470
                 mbMotionVectorTable[0][0]); 
471
    } else {
472
        bit_size = s->f_code - 1;
473
        range = 1 << bit_size;
474
        /* modulo encoding */
475
        l = 16 * range;
476
        m = 2 * l;
477
        if (val < -l) {
478
            val += m;
479
        } else if (val >= l) {
480
            val -= m;
481
        }
482

    
483
        if (val >= 0) {
484
            val--;
485
            code = (val >> bit_size) + 1;
486
            bits = val & (range - 1);
487
            sign = 0;
488
        } else {
489
            val = -val;
490
            val--;
491
            code = (val >> bit_size) + 1;
492
            bits = val & (range - 1);
493
            sign = 1;
494
        }
495
        put_bits(&s->pb,
496
                 mbMotionVectorTable[code][1], 
497
                 mbMotionVectorTable[code][0]); 
498
        put_bits(&s->pb, 1, sign);
499
        if (bit_size > 0) {
500
            put_bits(&s->pb, bit_size, bits);
501
        }
502
    }
503
}
504

    
505
void ff_mpeg1_encode_init(MpegEncContext *s)
506
{
507
    static int done=0;
508

    
509
    common_init(s);
510

    
511
    if(!done){
512
        int f_code;
513
        int mv;
514
        int i;
515

    
516
        done=1;
517
        init_rl(&rl_mpeg1);
518

    
519
        for(i=0; i<64; i++)
520
        {
521
                mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
522
                mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
523
        }
524
        
525
        init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_bits, uni_mpeg1_ac_vlc_len);
526

    
527
        /* build unified dc encoding tables */
528
        for(i=-255; i<256; i++)
529
        {
530
                int adiff, index;
531
                int bits, code;
532
                int diff=i;
533

    
534
                adiff = ABS(diff);
535
                if(diff<0) diff--;
536
                index = vlc_dc_table[adiff];
537

    
538
                bits= vlc_dc_lum_bits[index] + index;
539
                code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
540
                mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
541
                
542
                bits= vlc_dc_chroma_bits[index] + index;
543
                code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
544
                mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
545
        }
546

    
547
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
548
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
549
                int len;
550

    
551
                if(mv==0) len= mbMotionVectorTable[0][1];
552
                else{
553
                    int val, bit_size, range, code;
554

    
555
                    bit_size = s->f_code - 1;
556
                    range = 1 << bit_size;
557

    
558
                    val=mv;
559
                    if (val < 0) 
560
                        val = -val;
561
                    val--;
562
                    code = (val >> bit_size) + 1;
563
                    if(code<17){
564
                        len= mbMotionVectorTable[code][1] + 1 + bit_size;
565
                    }else{
566
                        len= mbMotionVectorTable[16][1] + 2 + bit_size;
567
                    }
568
                }
569

    
570
                mv_penalty[f_code][mv+MAX_MV]= len;
571
            }
572
        }
573
        
574

    
575
        for(f_code=MAX_FCODE; f_code>0; f_code--){
576
            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
577
                fcode_tab[mv+MAX_MV]= f_code;
578
            }
579
        }
580
    }
581
    s->me.mv_penalty= mv_penalty;
582
    s->fcode_tab= fcode_tab;
583
    s->min_qcoeff=-255;
584
    s->max_qcoeff= 255;
585
    s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
586
    s->inter_quant_bias= 0;
587
    s->intra_ac_vlc_length=
588
    s->inter_ac_vlc_length= uni_mpeg1_ac_vlc_len;
589
}
590

    
591
static inline void encode_dc(MpegEncContext *s, int diff, int component)
592
{
593
    if (component == 0) {
594
        put_bits(
595
            &s->pb, 
596
            mpeg1_lum_dc_uni[diff+255]&0xFF,
597
            mpeg1_lum_dc_uni[diff+255]>>8);
598
    } else {
599
        put_bits(
600
            &s->pb, 
601
            mpeg1_chr_dc_uni[diff+255]&0xFF,
602
            mpeg1_chr_dc_uni[diff+255]>>8);
603
    }
604
}
605

    
606
static void mpeg1_encode_block(MpegEncContext *s, 
607
                               DCTELEM *block, 
608
                               int n)
609
{
610
    int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
611
    int code, component;
612
//    RLTable *rl = &rl_mpeg1;
613

    
614
    last_index = s->block_last_index[n];
615

    
616
    /* DC coef */
617
    if (s->mb_intra) {
618
        component = (n <= 3 ? 0 : n - 4 + 1);
619
        dc = block[0]; /* overflow is impossible */
620
        diff = dc - s->last_dc[component];
621
        encode_dc(s, diff, component);
622
        s->last_dc[component] = dc;
623
        i = 1;
624
    } else {
625
        /* encode the first coefficient : needs to be done here because
626
           it is handled slightly differently */
627
        level = block[0];
628
        if (abs(level) == 1) {
629
                code = ((UINT32)level >> 31); /* the sign bit */
630
                put_bits(&s->pb, 2, code | 0x02);
631
                i = 1;
632
        } else {
633
            i = 0;
634
            last_non_zero = -1;
635
            goto next_coef;
636
        }
637
    }
638

    
639
    /* now quantify & encode AC coefs */
640
    last_non_zero = i - 1;
641

    
642
    for(;i<=last_index;i++) {
643
        j = s->intra_scantable.permutated[i];
644
        level = block[j];
645
    next_coef:
646
#if 0
647
        if (level != 0)
648
            dprintf("level[%d]=%d\n", i, level);
649
#endif            
650
        /* encode using VLC */
651
        if (level != 0) {
652
            run = i - last_non_zero - 1;
653
            
654
            alevel= level;
655
            MASK_ABS(sign, alevel)
656
            sign&=1;
657

    
658
//            code = get_rl_index(rl, 0, run, alevel);
659
            if (alevel <= mpeg1_max_level[0][run]){
660
                code= mpeg1_index_run[0][run] + alevel - 1;
661
                    /* store the vlc & sign at once */
662
                put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
663
            } else {
664
                /* escape seems to be pretty rare <5% so i dont optimize it */
665
                put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
666
                /* escape: only clip in this case */
667
                put_bits(&s->pb, 6, run);
668
                if (alevel < 128) {
669
                    put_bits(&s->pb, 8, level & 0xff);
670
                } else {
671
                    if (level < 0) {
672
                        put_bits(&s->pb, 16, 0x8001 + level + 255);
673
                    } else {
674
                        put_bits(&s->pb, 16, level & 0xffff);
675
                    }
676
                }
677
            }
678
            last_non_zero = i;
679
        }
680
    }
681
    /* end of block */
682
    put_bits(&s->pb, 2, 0x2);
683
}
684

    
685
/******************************************/
686
/* decoding */
687

    
688
static VLC dc_lum_vlc;
689
static VLC dc_chroma_vlc;
690
static VLC mv_vlc;
691
static VLC mbincr_vlc;
692
static VLC mb_ptype_vlc;
693
static VLC mb_btype_vlc;
694
static VLC mb_pat_vlc;
695

    
696
static void init_vlcs(MpegEncContext *s)
697
{
698
    static int done = 0;
699

    
700
    if (!done) {
701
        done = 1;
702

    
703
        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
704
                 vlc_dc_lum_bits, 1, 1,
705
                 vlc_dc_lum_code, 2, 2);
706
        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
707
                 vlc_dc_chroma_bits, 1, 1,
708
                 vlc_dc_chroma_code, 2, 2);
709
        init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
710
                 &mbMotionVectorTable[0][1], 2, 1,
711
                 &mbMotionVectorTable[0][0], 2, 1);
712
        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 35, 
713
                 &mbAddrIncrTable[0][1], 2, 1,
714
                 &mbAddrIncrTable[0][0], 2, 1);
715
        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 63, 
716
                 &mbPatTable[0][1], 2, 1,
717
                 &mbPatTable[0][0], 2, 1);
718
        
719
        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 32, 
720
                 &table_mb_ptype[0][1], 2, 1,
721
                 &table_mb_ptype[0][0], 2, 1);
722
        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 32, 
723
                 &table_mb_btype[0][1], 2, 1,
724
                 &table_mb_btype[0][0], 2, 1);
725
        init_rl(&rl_mpeg1);
726
        init_rl(&rl_mpeg2);
727

    
728
        init_2d_vlc_rl(&rl_mpeg1);
729
        init_2d_vlc_rl(&rl_mpeg2);
730
    }
731
}
732

    
733
static inline int get_dmv(MpegEncContext *s)
734
{
735
    if(get_bits1(&s->gb)) 
736
        return 1 - (get_bits1(&s->gb) << 1);
737
    else
738
        return 0;
739
}
740

    
741
static inline int get_qscale(MpegEncContext *s)
742
{
743
    int qscale;
744
    if (s->mpeg2) {
745
        if (s->q_scale_type) {
746
            qscale = non_linear_qscale[get_bits(&s->gb, 5)];
747
        } else {
748
            qscale = get_bits(&s->gb, 5) << 1;
749
        }
750
    } else {
751
        /* for mpeg1, we use the generic unquant code */
752
        qscale = get_bits(&s->gb, 5);
753
    }
754
    return qscale;
755
}
756

    
757
/* motion type (for mpeg2) */
758
#define MT_FIELD 1
759
#define MT_FRAME 2
760
#define MT_16X8  2
761
#define MT_DMV   3
762

    
763
static int mpeg_decode_mb(MpegEncContext *s,
764
                          DCTELEM block[6][64])
765
{
766
    int i, j, k, cbp, val, mb_type, motion_type;
767
    
768
    dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
769

    
770
    assert(s->mb_skiped==0);
771

    
772
    if (--s->mb_incr != 0) {
773
        /* skip mb */
774
        s->mb_intra = 0;
775
        for(i=0;i<6;i++)
776
            s->block_last_index[i] = -1;
777
        s->mv_type = MV_TYPE_16X16;
778
        if (s->pict_type == P_TYPE) {
779
            /* if P type, zero motion vector is implied */
780
            s->mv_dir = MV_DIR_FORWARD;
781
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
782
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
783
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
784
            s->mb_skiped = 1;
785
        } else {
786
            /* if B type, reuse previous vectors and directions */
787
            s->mv[0][0][0] = s->last_mv[0][0][0];
788
            s->mv[0][0][1] = s->last_mv[0][0][1];
789
            s->mv[1][0][0] = s->last_mv[1][0][0];
790
            s->mv[1][0][1] = s->last_mv[1][0][1];
791

    
792
            if((s->mv[0][0][0]|s->mv[0][0][1]|s->mv[1][0][0]|s->mv[1][0][1])==0) 
793
                s->mb_skiped = 1;
794
        }
795

    
796
        return 0;
797
    }
798

    
799
    switch(s->pict_type) {
800
    default:
801
    case I_TYPE:
802
        if (get_bits1(&s->gb) == 0) {
803
            if (get_bits1(&s->gb) == 0)
804
                return -1;
805
            mb_type = MB_QUANT | MB_INTRA;
806
        } else {
807
            mb_type = MB_INTRA;
808
        }
809
        break;
810
    case P_TYPE:
811
        mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
812
        if (mb_type < 0){
813
            fprintf(stderr, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
814
            return -1;
815
        }
816
        break;
817
    case B_TYPE:
818
        mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
819
        if (mb_type < 0){
820
            fprintf(stderr, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
821
            return -1;
822
        }
823
        break;
824
    }
825
    dprintf("mb_type=%x\n", mb_type);
826
    motion_type = 0; /* avoid warning */
827
    if (mb_type & (MB_FOR|MB_BACK)) {
828
        /* get additionnal motion vector type */
829
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
830
            motion_type = MT_FRAME;
831
        else
832
            motion_type = get_bits(&s->gb, 2);
833
    }
834
    /* compute dct type */
835
    if (s->picture_structure == PICT_FRAME && 
836
        !s->frame_pred_frame_dct &&
837
        (mb_type & (MB_PAT | MB_INTRA))) {
838
        s->interlaced_dct = get_bits1(&s->gb);
839
#ifdef DEBUG
840
        if (s->interlaced_dct)
841
            printf("interlaced_dct\n");
842
#endif
843
    } else {
844
        s->interlaced_dct = 0; /* frame based */
845
    }
846

    
847
    if (mb_type & MB_QUANT) {
848
        s->qscale = get_qscale(s);
849
    }
850
    if (mb_type & MB_INTRA) {
851
        if (s->concealment_motion_vectors) {
852
            /* just parse them */
853
            if (s->picture_structure != PICT_FRAME) 
854
                skip_bits1(&s->gb); /* field select */
855
            mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
856
            mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
857
        }
858
        s->mb_intra = 1;
859
        cbp = 0x3f;
860
        memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
861
    } else {
862
        s->mb_intra = 0;
863
        cbp = 0;
864
    }
865
    /* special case of implicit zero motion vector */
866
    if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
867
        s->mv_dir = MV_DIR_FORWARD;
868
        s->mv_type = MV_TYPE_16X16;
869
        s->last_mv[0][0][0] = 0;
870
        s->last_mv[0][0][1] = 0;
871
        s->last_mv[0][1][0] = 0;
872
        s->last_mv[0][1][1] = 0;
873
        s->mv[0][0][0] = 0;
874
        s->mv[0][0][1] = 0;
875
    } else if (mb_type & (MB_FOR | MB_BACK)) {
876
        /* motion vectors */
877
        s->mv_dir = 0;
878
        for(i=0;i<2;i++) {
879
            if (mb_type & (MB_FOR >> i)) {
880
                s->mv_dir |= (MV_DIR_FORWARD >> i);
881
                dprintf("motion_type=%d\n", motion_type);
882
                switch(motion_type) {
883
                case MT_FRAME: /* or MT_16X8 */
884
                    if (s->picture_structure == PICT_FRAME) {
885
                        /* MT_FRAME */
886
                        s->mv_type = MV_TYPE_16X16;
887
                        for(k=0;k<2;k++) {
888
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
889
                                                     s->last_mv[i][0][k]);
890
                            s->last_mv[i][0][k] = val;
891
                            s->last_mv[i][1][k] = val;
892
                            /* full_pel: only for mpeg1 */
893
                            if (s->full_pel[i])
894
                                val = val << 1;
895
                            s->mv[i][0][k] = val;
896
                            dprintf("mv%d: %d\n", k, val);
897
                        }
898
                    } else {
899
                        /* MT_16X8 */
900
                        s->mv_type = MV_TYPE_16X8;
901
                        for(j=0;j<2;j++) {
902
                            s->field_select[i][j] = get_bits1(&s->gb);
903
                            for(k=0;k<2;k++) {
904
                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
905
                                                         s->last_mv[i][j][k]);
906
                                s->last_mv[i][j][k] = val;
907
                                s->mv[i][j][k] = val;
908
                            }
909
                        }
910
                    }
911
                    break;
912
                case MT_FIELD:
913
                    if (s->picture_structure == PICT_FRAME) {
914
                        s->mv_type = MV_TYPE_FIELD;
915
                        for(j=0;j<2;j++) {
916
                            s->field_select[i][j] = get_bits1(&s->gb);
917
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
918
                                                     s->last_mv[i][j][0]);
919
                            s->last_mv[i][j][0] = val;
920
                            s->mv[i][j][0] = val;
921
                            dprintf("fmx=%d\n", val);
922
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
923
                                                     s->last_mv[i][j][1] >> 1);
924
                            s->last_mv[i][j][1] = val << 1;
925
                            s->mv[i][j][1] = val;
926
                            dprintf("fmy=%d\n", val);
927
                        }
928
                    } else {
929
                        s->mv_type = MV_TYPE_16X16;
930
                        s->field_select[i][0] = get_bits1(&s->gb);
931
                        for(k=0;k<2;k++) {
932
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
933
                                                     s->last_mv[i][0][k]);
934
                            s->last_mv[i][0][k] = val;
935
                            s->last_mv[i][1][k] = val;
936
                            s->mv[i][0][k] = val;
937
                        }
938
                    }
939
                    break;
940
                case MT_DMV:
941
                    {
942
                        int dmx, dmy, mx, my, m;
943

    
944
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
945
                                                s->last_mv[i][0][0]);
946
                        s->last_mv[i][0][0] = mx;
947
                        s->last_mv[i][1][0] = mx;
948
                        dmx = get_dmv(s);
949
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
950
                                                s->last_mv[i][0][1] >> 1);
951
                        dmy = get_dmv(s);
952
                        s->mv_type = MV_TYPE_DMV;
953
                        /* XXX: totally broken */
954
                        if (s->picture_structure == PICT_FRAME) {
955
                            s->last_mv[i][0][1] = my << 1;
956
                            s->last_mv[i][1][1] = my << 1;
957

    
958
                            m = s->top_field_first ? 1 : 3;
959
                            /* top -> top pred */
960
                            s->mv[i][0][0] = mx; 
961
                            s->mv[i][0][1] = my << 1;
962
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
963
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
964
                            m = 4 - m;
965
                            s->mv[i][2][0] = mx;
966
                            s->mv[i][2][1] = my << 1;
967
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
968
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
969
                        } else {
970
                            s->last_mv[i][0][1] = my;
971
                            s->last_mv[i][1][1] = my;
972
                            s->mv[i][0][0] = mx;
973
                            s->mv[i][0][1] = my;
974
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
975
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
976
                                /* + 2 * cur_field */;
977
                        }
978
                    }
979
                    break;
980
                }
981
            }
982
        }
983
    }
984

    
985
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
986
        skip_bits1(&s->gb); /* marker */
987
    }
988
    
989
    if (mb_type & MB_PAT) {
990
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
991
        if (cbp < 0){
992
            fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
993
            return -1;
994
        }
995
        cbp++;
996
    }
997
    dprintf("cbp=%x\n", cbp);
998

    
999
    if (s->mpeg2) {
1000
        if (s->mb_intra) {
1001
            for(i=0;i<6;i++) {
1002
                if (mpeg2_decode_block_intra(s, block[i], i) < 0)
1003
                    return -1;
1004
            }
1005
        } else {
1006
            for(i=0;i<6;i++) {
1007
                if (cbp & 32) {
1008
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
1009
                        return -1;
1010
                } else {
1011
                    s->block_last_index[i] = -1;
1012
                }
1013
                cbp+=cbp;
1014
            }
1015
        }
1016
    } else {
1017
        if (s->mb_intra) {
1018
            for(i=0;i<6;i++) {
1019
                if (mpeg1_decode_block_intra(s, block[i], i) < 0)
1020
                    return -1;
1021
            }
1022
        }else{
1023
            for(i=0;i<6;i++) {
1024
                if (cbp & 32) {
1025
                    if (mpeg1_decode_block_inter(s, block[i], i) < 0)
1026
                        return -1;
1027
                } else {
1028
                    s->block_last_index[i] = -1;
1029
                }
1030
                cbp+=cbp;
1031
            }
1032
        }
1033
    }
1034
    return 0;
1035
}
1036

    
1037
/* as h263, but only 17 codes */
1038
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
1039
{
1040
    int code, sign, val, m, l, shift;
1041

    
1042
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
1043
    if (code < 0) {
1044
        return 0xffff;
1045
    }
1046
    if (code == 0) {
1047
        return pred;
1048
    }
1049
    sign = get_bits1(&s->gb);
1050
    shift = fcode - 1;
1051
    val = (code - 1) << shift;
1052
    if (shift > 0)
1053
        val |= get_bits(&s->gb, shift);
1054
    val++;
1055
    if (sign)
1056
        val = -val;
1057
    val += pred;
1058
    
1059
    /* modulo decoding */
1060
    l = (1 << shift) * 16;
1061
    m = 2 * l;
1062
    if (val < -l) {
1063
        val += m;
1064
    } else if (val >= l) {
1065
        val -= m;
1066
    }
1067
    return val;
1068
}
1069

    
1070
static inline int decode_dc(MpegEncContext *s, int component)
1071
{
1072
    int code, diff;
1073

    
1074
    if (component == 0) {
1075
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
1076
    } else {
1077
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
1078
    }
1079
    if (code < 0){
1080
        fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
1081
        return 0xffff;
1082
    }
1083
    if (code == 0) {
1084
        diff = 0;
1085
    } else {
1086
        diff = get_bits(&s->gb, code);
1087
        if ((diff & (1 << (code - 1))) == 0) 
1088
            diff = (-1 << code) | (diff + 1);
1089
    }
1090
    return diff;
1091
}
1092

    
1093
static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
1094
                               DCTELEM *block, 
1095
                               int n)
1096
{
1097
    int level, dc, diff, i, j, run;
1098
    int component;
1099
    RLTable *rl = &rl_mpeg1;
1100
    UINT8 * const scantable= s->intra_scantable.permutated;
1101
    const UINT16 *quant_matrix= s->intra_matrix;
1102
    const int qscale= s->qscale;
1103

    
1104
    /* DC coef */
1105
    component = (n <= 3 ? 0 : n - 4 + 1);
1106
    diff = decode_dc(s, component);
1107
    if (diff >= 0xffff)
1108
        return -1;
1109
    dc = s->last_dc[component];
1110
    dc += diff;
1111
    s->last_dc[component] = dc;
1112
    block[0] = dc<<3;
1113
    dprintf("dc=%d diff=%d\n", dc, diff);
1114
    i = 0;
1115
    {
1116
        OPEN_READER(re, &s->gb);    
1117
        /* now quantify & encode AC coefs */
1118
        for(;;) {
1119
            UPDATE_CACHE(re, &s->gb);
1120
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1121
            
1122
            if(level == 127){
1123
                break;
1124
            } else if(level != 0) {
1125
                i += run;
1126
                j = scantable[i];
1127
                level= (level*qscale*quant_matrix[j])>>3;
1128
                level= (level-1)|1;
1129
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1130
                LAST_SKIP_BITS(re, &s->gb, 1);
1131
            } else {
1132
                /* escape */
1133
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1134
                UPDATE_CACHE(re, &s->gb);
1135
                level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1136
                if (level == -128) {
1137
                    level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1138
                } else if (level == 0) {
1139
                    level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1140
                }
1141
                i += run;
1142
                j = scantable[i];
1143
                if(level<0){
1144
                    level= -level;
1145
                    level= (level*qscale*quant_matrix[j])>>3;
1146
                    level= (level-1)|1;
1147
                    level= -level;
1148
                }else{
1149
                    level= (level*qscale*quant_matrix[j])>>3;
1150
                    level= (level-1)|1;
1151
                }
1152
            }
1153
            if (i > 63){
1154
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1155
                return -1;
1156
            }
1157

    
1158
            block[j] = level;
1159
        }
1160
        CLOSE_READER(re, &s->gb);
1161
    }
1162
    s->block_last_index[n] = i;
1163
   return 0;
1164
}
1165

    
1166
static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
1167
                               DCTELEM *block, 
1168
                               int n)
1169
{
1170
    int level, i, j, run;
1171
    RLTable *rl = &rl_mpeg1;
1172
    UINT8 * const scantable= s->intra_scantable.permutated;
1173
    const UINT16 *quant_matrix= s->inter_matrix;
1174
    const int qscale= s->qscale;
1175

    
1176
    {
1177
        int v;
1178
        OPEN_READER(re, &s->gb);
1179
        i = -1;
1180
        /* special case for the first coef. no need to add a second vlc table */
1181
        UPDATE_CACHE(re, &s->gb);
1182
        v= SHOW_UBITS(re, &s->gb, 2);
1183
        if (v & 2) {
1184
            LAST_SKIP_BITS(re, &s->gb, 2);
1185
            level= (3*qscale*quant_matrix[0])>>4;
1186
            level= (level-1)|1;
1187
            if(v&1)
1188
                level= -level;
1189
            block[0] = level;
1190
            i++;
1191
        }
1192

    
1193
        /* now quantify & encode AC coefs */
1194
        for(;;) {
1195
            UPDATE_CACHE(re, &s->gb);
1196
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1197
            
1198
            if(level == 127){
1199
                break;
1200
            } else if(level != 0) {
1201
                i += run;
1202
                j = scantable[i];
1203
                level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1204
                level= (level-1)|1;
1205
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1206
                LAST_SKIP_BITS(re, &s->gb, 1);
1207
            } else {
1208
                /* escape */
1209
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1210
                UPDATE_CACHE(re, &s->gb);
1211
                level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1212
                if (level == -128) {
1213
                    level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1214
                } else if (level == 0) {
1215
                    level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1216
                }
1217
                i += run;
1218
                j = scantable[i];
1219
                if(level<0){
1220
                    level= -level;
1221
                    level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1222
                    level= (level-1)|1;
1223
                    level= -level;
1224
                }else{
1225
                    level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1226
                    level= (level-1)|1;
1227
                }
1228
            }
1229
            if (i > 63){
1230
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1231
                return -1;
1232
            }
1233

    
1234
            block[j] = level;
1235
        }
1236
        CLOSE_READER(re, &s->gb);
1237
    }
1238
    s->block_last_index[n] = i;
1239
    return 0;
1240
}
1241

    
1242
/* Also does unquantization here, since I will never support mpeg2
1243
   encoding */
1244
static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1245
                               DCTELEM *block, 
1246
                               int n)
1247
{
1248
    int level, i, j, run;
1249
    RLTable *rl = &rl_mpeg1;
1250
    UINT8 * const scantable= s->intra_scantable.permutated;
1251
    const UINT16 *quant_matrix;
1252
    const int qscale= s->qscale;
1253
    int mismatch;
1254

    
1255
    mismatch = 1;
1256

    
1257
    {
1258
        int v;
1259
        OPEN_READER(re, &s->gb);
1260
        i = -1;
1261
        if (n < 4)
1262
            quant_matrix = s->inter_matrix;
1263
        else
1264
            quant_matrix = s->chroma_inter_matrix;
1265

    
1266
        /* special case for the first coef. no need to add a second vlc table */
1267
        UPDATE_CACHE(re, &s->gb);
1268
        v= SHOW_UBITS(re, &s->gb, 2);
1269
        if (v & 2) {
1270
            LAST_SKIP_BITS(re, &s->gb, 2);
1271
            level= (3*qscale*quant_matrix[0])>>5;
1272
            if(v&1)
1273
                level= -level;
1274
            block[0] = level;
1275
            mismatch ^= level;
1276
            i++;
1277
        }
1278

    
1279
        /* now quantify & encode AC coefs */
1280
        for(;;) {
1281
            UPDATE_CACHE(re, &s->gb);
1282
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1283
            
1284
            if(level == 127){
1285
                break;
1286
            } else if(level != 0) {
1287
                i += run;
1288
                j = scantable[i];
1289
                level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1290
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1291
                LAST_SKIP_BITS(re, &s->gb, 1);
1292
            } else {
1293
                /* escape */
1294
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1295
                UPDATE_CACHE(re, &s->gb);
1296
                level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1297

    
1298
                i += run;
1299
                j = scantable[i];
1300
                if(level<0){
1301
                    level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
1302
                    level= -level;
1303
                }else{
1304
                    level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1305
                }
1306
            }
1307
            if (i > 63){
1308
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1309
                return -1;
1310
            }
1311
            
1312
            mismatch ^= level;
1313
            block[j] = level;
1314
        }
1315
        CLOSE_READER(re, &s->gb);
1316
    }
1317
    block[63] ^= (mismatch & 1);
1318
    
1319
    s->block_last_index[n] = i;
1320
    return 0;
1321
}
1322

    
1323
static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
1324
                               DCTELEM *block, 
1325
                               int n)
1326
{
1327
    int level, dc, diff, i, j, run;
1328
    int component;
1329
    RLTable *rl;
1330
    UINT8 * const scantable= s->intra_scantable.permutated;
1331
    const UINT16 *quant_matrix;
1332
    const int qscale= s->qscale;
1333
    int mismatch;
1334

    
1335
    /* DC coef */
1336
    if (n < 4){
1337
        quant_matrix = s->intra_matrix;
1338
        component = 0; 
1339
    }else{
1340
        quant_matrix = s->chroma_intra_matrix;
1341
        component = n - 3;
1342
    }
1343
    diff = decode_dc(s, component);
1344
    if (diff >= 0xffff)
1345
        return -1;
1346
    dc = s->last_dc[component];
1347
    dc += diff;
1348
    s->last_dc[component] = dc;
1349
    block[0] = dc << (3 - s->intra_dc_precision);
1350
    dprintf("dc=%d\n", block[0]);
1351
    mismatch = block[0] ^ 1;
1352
    i = 0;
1353
    if (s->intra_vlc_format)
1354
        rl = &rl_mpeg2;
1355
    else
1356
        rl = &rl_mpeg1;
1357

    
1358
    {
1359
        OPEN_READER(re, &s->gb);    
1360
        /* now quantify & encode AC coefs */
1361
        for(;;) {
1362
            UPDATE_CACHE(re, &s->gb);
1363
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1364
            
1365
            if(level == 127){
1366
                break;
1367
            } else if(level != 0) {
1368
                i += run;
1369
                j = scantable[i];
1370
                level= (level*qscale*quant_matrix[j])>>4;
1371
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1372
                LAST_SKIP_BITS(re, &s->gb, 1);
1373
            } else {
1374
                /* escape */
1375
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1376
                UPDATE_CACHE(re, &s->gb);
1377
                level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1378
                i += run;
1379
                j = scantable[i];
1380
                if(level<0){
1381
                    level= (-level*qscale*quant_matrix[j])>>4;
1382
                    level= -level;
1383
                }else{
1384
                    level= (level*qscale*quant_matrix[j])>>4;
1385
                }
1386
            }
1387
            if (i > 63){
1388
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1389
                return -1;
1390
            }
1391
            
1392
            mismatch^= level;
1393
            block[j] = level;
1394
        }
1395
        CLOSE_READER(re, &s->gb);
1396
    }
1397
    block[63]^= mismatch&1;
1398
    
1399
    s->block_last_index[n] = i;
1400
    return 0;
1401
}
1402

    
1403
/* compressed picture size */
1404
#define PICTURE_BUFFER_SIZE 100000
1405

    
1406
typedef struct Mpeg1Context {
1407
    MpegEncContext mpeg_enc_ctx;
1408
    UINT32 header_state;
1409
    int start_code; /* current start code */
1410
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1411
    UINT8 *buf_ptr;
1412
    int buffer_size;
1413
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1414
    int repeat_field; /* true if we must repeat the field */
1415
} Mpeg1Context;
1416

    
1417
static int mpeg_decode_init(AVCodecContext *avctx)
1418
{
1419
    Mpeg1Context *s = avctx->priv_data;
1420
    
1421
    s->mpeg_enc_ctx.flags= avctx->flags;
1422
    common_init(&s->mpeg_enc_ctx);
1423
    init_vlcs(&s->mpeg_enc_ctx);
1424

    
1425
    s->header_state = 0xff;
1426
    s->mpeg_enc_ctx_allocated = 0;
1427
    s->buffer_size = PICTURE_BUFFER_SIZE;
1428
    s->start_code = -1;
1429
    s->buf_ptr = s->buffer;
1430
    s->mpeg_enc_ctx.picture_number = 0;
1431
    s->repeat_field = 0;
1432
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1433
    return 0;
1434
}
1435

    
1436
/* return the 8 bit start code value and update the search
1437
   state. Return -1 if no start code found */
1438
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1439
                           UINT32 *header_state)
1440
{
1441
    UINT8 *buf_ptr;
1442
    unsigned int state, v;
1443
    int val;
1444

    
1445
    state = *header_state;
1446
    buf_ptr = *pbuf_ptr;
1447
    while (buf_ptr < buf_end) {
1448
        v = *buf_ptr++;
1449
        if (state == 0x000001) {
1450
            state = ((state << 8) | v) & 0xffffff;
1451
            val = state;
1452
            goto found;
1453
        }
1454
        state = ((state << 8) | v) & 0xffffff;
1455
    }
1456
    val = -1;
1457
 found:
1458
    *pbuf_ptr = buf_ptr;
1459
    *header_state = state;
1460
    return val;
1461
}
1462

    
1463
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1464
                                UINT8 *buf, int buf_size)
1465
{
1466
    Mpeg1Context *s1 = avctx->priv_data;
1467
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1468
    int ref, f_code;
1469

    
1470
    init_get_bits(&s->gb, buf, buf_size*8);
1471

    
1472
    ref = get_bits(&s->gb, 10); /* temporal ref */
1473
    s->pict_type = get_bits(&s->gb, 3);
1474
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1475

    
1476
    skip_bits(&s->gb, 16);
1477
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1478
        s->full_pel[0] = get_bits1(&s->gb);
1479
        f_code = get_bits(&s->gb, 3);
1480
        if (f_code == 0)
1481
            return -1;
1482
        s->mpeg_f_code[0][0] = f_code;
1483
        s->mpeg_f_code[0][1] = f_code;
1484
    }
1485
    if (s->pict_type == B_TYPE) {
1486
        s->full_pel[1] = get_bits1(&s->gb);
1487
        f_code = get_bits(&s->gb, 3);
1488
        if (f_code == 0)
1489
            return -1;
1490
        s->mpeg_f_code[1][0] = f_code;
1491
        s->mpeg_f_code[1][1] = f_code;
1492
    }
1493
    s->current_picture.pict_type= s->pict_type;
1494
    s->current_picture.key_frame= s->pict_type == I_TYPE;
1495
    
1496
    s->y_dc_scale = 8;
1497
    s->c_dc_scale = 8;
1498
    s->first_slice = 1;
1499
    return 0;
1500
}
1501

    
1502
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1503
{
1504
    int horiz_size_ext, vert_size_ext;
1505
    int bit_rate_ext, vbv_buf_ext;
1506
    int frame_rate_ext_n, frame_rate_ext_d;
1507
    float aspect;
1508

    
1509
    skip_bits(&s->gb, 8); /* profil and level */
1510
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1511
    skip_bits(&s->gb, 2); /* chroma_format */
1512
    horiz_size_ext = get_bits(&s->gb, 2);
1513
    vert_size_ext = get_bits(&s->gb, 2);
1514
    s->width |= (horiz_size_ext << 12);
1515
    s->height |= (vert_size_ext << 12);
1516
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1517
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1518
    skip_bits1(&s->gb); /* marker */
1519
    vbv_buf_ext = get_bits(&s->gb, 8);
1520
    s->low_delay = get_bits1(&s->gb);
1521
    frame_rate_ext_n = get_bits(&s->gb, 2);
1522
    frame_rate_ext_d = get_bits(&s->gb, 5);
1523
    if (frame_rate_ext_d >= 1)
1524
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1525
    dprintf("sequence extension\n");
1526
    s->mpeg2 = 1;
1527
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1528

    
1529
    aspect= mpeg2_aspect[s->aspect_ratio_info];
1530
    if(aspect>0.0)      s->avctx->aspect_ratio= s->width/(aspect*s->height);
1531
    else if(aspect<0.0) s->avctx->aspect_ratio= -1.0/aspect;
1532
}
1533

    
1534
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1535
{
1536
    int i, v, j;
1537

    
1538
    dprintf("matrix extension\n");
1539

    
1540
    if (get_bits1(&s->gb)) {
1541
        for(i=0;i<64;i++) {
1542
            v = get_bits(&s->gb, 8);
1543
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1544
            s->intra_matrix[j] = v;
1545
            s->chroma_intra_matrix[j] = v;
1546
        }
1547
    }
1548
    if (get_bits1(&s->gb)) {
1549
        for(i=0;i<64;i++) {
1550
            v = get_bits(&s->gb, 8);
1551
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1552
            s->inter_matrix[j] = v;
1553
            s->chroma_inter_matrix[j] = 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= s->idct_permutation[ ff_zigzag_direct[i] ];
1560
            s->chroma_intra_matrix[j] = v;
1561
        }
1562
    }
1563
    if (get_bits1(&s->gb)) {
1564
        for(i=0;i<64;i++) {
1565
            v = get_bits(&s->gb, 8);
1566
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1567
            s->chroma_inter_matrix[j] = v;
1568
        }
1569
    }
1570
}
1571

    
1572
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1573
{
1574
    s->full_pel[0] = s->full_pel[1] = 0;
1575
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1576
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1577
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1578
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1579
    s->intra_dc_precision = get_bits(&s->gb, 2);
1580
    s->picture_structure = get_bits(&s->gb, 2);
1581
    s->top_field_first = get_bits1(&s->gb);
1582
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1583
    s->concealment_motion_vectors = get_bits1(&s->gb);
1584
    s->q_scale_type = get_bits1(&s->gb);
1585
    s->intra_vlc_format = get_bits1(&s->gb);
1586
    s->alternate_scan = get_bits1(&s->gb);
1587
    s->repeat_first_field = get_bits1(&s->gb);
1588
    s->chroma_420_type = get_bits1(&s->gb);
1589
    s->progressive_frame = get_bits1(&s->gb);
1590
    
1591
    if(s->alternate_scan){
1592
        ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
1593
        ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
1594
        ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
1595
        ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1596
    }else{
1597
        ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
1598
        ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
1599
        ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
1600
        ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1601
    }
1602
    
1603
    /* composite display not parsed */
1604
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1605
    dprintf("picture_structure=%d\n", s->picture_structure);
1606
    dprintf("top field first=%d\n", s->top_field_first);
1607
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1608
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1609
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1610
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1611
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1612
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1613
}
1614

    
1615
static void mpeg_decode_extension(AVCodecContext *avctx, 
1616
                                  UINT8 *buf, int buf_size)
1617
{
1618
    Mpeg1Context *s1 = avctx->priv_data;
1619
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1620
    int ext_type;
1621

    
1622
    init_get_bits(&s->gb, buf, buf_size*8);
1623
    
1624
    ext_type = get_bits(&s->gb, 4);
1625
    switch(ext_type) {
1626
    case 0x1:
1627
        /* sequence ext */
1628
        mpeg_decode_sequence_extension(s);
1629
        break;
1630
    case 0x3:
1631
        /* quant matrix extension */
1632
        mpeg_decode_quant_matrix_extension(s);
1633
        break;
1634
    case 0x8:
1635
        /* picture extension */
1636
        mpeg_decode_picture_coding_extension(s);
1637
        break;
1638
    }
1639
}
1640

    
1641
#define DECODE_SLICE_FATAL_ERROR -2
1642
#define DECODE_SLICE_ERROR -1
1643
#define DECODE_SLICE_OK 0
1644
#define DECODE_SLICE_EOP 1
1645

    
1646
/**
1647
 * decodes a slice.
1648
 * @return DECODE_SLICE_FATAL_ERROR if a non recoverable error occured<br>
1649
 *         DECODE_SLICE_ERROR if the slice is damaged<br>
1650
 *         DECODE_SLICE_OK if this slice is ok<br>
1651
 *         DECODE_SLICE_EOP if the end of the picture is reached
1652
 */
1653
static int mpeg_decode_slice(AVCodecContext *avctx, 
1654
                              AVFrame *pict,
1655
                              int start_code,
1656
                              UINT8 *buf, int buf_size)
1657
{
1658
    Mpeg1Context *s1 = avctx->priv_data;
1659
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1660
    int ret;
1661

    
1662
    start_code = (start_code - 1) & 0xff;
1663
    if (start_code >= s->mb_height){
1664
        fprintf(stderr, "slice below image (%d >= %d)\n", start_code, s->mb_height);
1665
        return DECODE_SLICE_ERROR;
1666
    }
1667
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1668
    s->last_dc[1] = s->last_dc[0];
1669
    s->last_dc[2] = s->last_dc[0];
1670
    memset(s->last_mv, 0, sizeof(s->last_mv));
1671
    /* start frame decoding */
1672
    if (s->first_slice) {
1673
        s->first_slice = 0;
1674
        if(MPV_frame_start(s, avctx) < 0)
1675
            return DECODE_SLICE_FATAL_ERROR;
1676
            
1677
        if(s->avctx->debug&FF_DEBUG_PICT_INFO){
1678
             printf("qp:%d fc:%2d%2d%2d%2d %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n", 
1679
                 s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1],
1680
                 s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
1681
                 s->progressive_sequence ? "pro" :"", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", 
1682
                 s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
1683
                 s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
1684
        }
1685
    }
1686

    
1687
    init_get_bits(&s->gb, buf, buf_size*8);
1688

    
1689
    s->qscale = get_qscale(s);
1690
    /* extra slice info */
1691
    while (get_bits1(&s->gb) != 0) {
1692
        skip_bits(&s->gb, 8);
1693
    }
1694

    
1695
    s->mb_x=0;
1696
    for(;;) {
1697
        int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1698
        if (code < 0)
1699
            return -1; /* error = end of slice, but empty slice is bad or?*/
1700
        if (code >= 33) {
1701
            if (code == 33) {
1702
                s->mb_x += 33;
1703
            }
1704
            /* otherwise, stuffing, nothing to do */
1705
        } else {
1706
            s->mb_x += code;
1707
            break;
1708
        }
1709
    }
1710
    s->mb_y = start_code;
1711
    s->mb_incr= 1;
1712

    
1713
    for(;;) {
1714
        s->dsp.clear_blocks(s->block[0]);
1715
        
1716
        ret = mpeg_decode_mb(s, s->block);
1717
        dprintf("ret=%d\n", ret);
1718
        if (ret < 0)
1719
            return -1;
1720
    
1721
        MPV_decode_mb(s, s->block);
1722

    
1723
        if (++s->mb_x >= s->mb_width) {
1724
            ff_draw_horiz_band(s);
1725

    
1726
            s->mb_x = 0;
1727
            s->mb_y++;
1728
            PRINT_QP("%s", "\n");
1729
        }
1730
        PRINT_QP("%2d", s->qscale);
1731

    
1732
        /* skip mb handling */
1733
        if (s->mb_incr == 0) {
1734
            /* read again increment */
1735
            s->mb_incr = 1;
1736
            for(;;) {
1737
                int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1738
                if (code < 0)
1739
                    goto eos; /* error = end of slice */
1740
                if (code >= 33) {
1741
                    if (code == 33) {
1742
                        s->mb_incr += 33;
1743
                    }
1744
                    /* otherwise, stuffing, nothing to do */
1745
                } else {
1746
                    s->mb_incr += code;
1747
                    break;
1748
                }
1749
            }
1750
        }
1751
        if(s->mb_y >= s->mb_height){
1752
            fprintf(stderr, "slice too long\n");
1753
            return DECODE_SLICE_ERROR;
1754
        }
1755
    }
1756
eos: //end of slice
1757
    
1758
    emms_c();
1759

    
1760
    /* end of slice reached */
1761
    if (/*s->mb_x == 0 &&*/
1762
        s->mb_y == s->mb_height) {
1763
        /* end of image */
1764

    
1765
        if(s->mpeg2)
1766
            s->qscale >>=1;
1767

    
1768
        MPV_frame_end(s);
1769

    
1770
        if (s->pict_type == B_TYPE || s->low_delay) {
1771
            *pict= *(AVFrame*)&s->current_picture;
1772
        } else {
1773
            s->picture_number++;
1774
            /* latency of 1 frame for I and P frames */
1775
            /* XXX: use another variable than picture_number */
1776
            if (s->last_picture.data[0] == NULL) {
1777
                return DECODE_SLICE_OK;
1778
            } else {
1779
                *pict= *(AVFrame*)&s->last_picture;
1780
            }
1781
        }
1782
        return DECODE_SLICE_EOP;
1783
    } else {
1784
        return DECODE_SLICE_OK;
1785
    }
1786
}
1787

    
1788
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1789
                                 UINT8 *buf, int buf_size)
1790
{
1791
    Mpeg1Context *s1 = avctx->priv_data;
1792
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1793
    int width, height, i, v, j;
1794
    float aspect;
1795

    
1796
    init_get_bits(&s->gb, buf, buf_size*8);
1797

    
1798
    width = get_bits(&s->gb, 12);
1799
    height = get_bits(&s->gb, 12);
1800
    s->aspect_ratio_info= get_bits(&s->gb, 4);
1801
    if(!s->mpeg2){
1802
        aspect= mpeg1_aspect[s->aspect_ratio_info];
1803
        if(aspect!=0.0) avctx->aspect_ratio= width/(aspect*height);
1804
    }
1805

    
1806
    s->frame_rate_index = get_bits(&s->gb, 4);
1807
    if (s->frame_rate_index == 0)
1808
        return -1;
1809
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1810
    if (get_bits1(&s->gb) == 0) /* marker */
1811
        return -1;
1812
    if (width <= 0 || height <= 0 ||
1813
        (width % 2) != 0 || (height % 2) != 0)
1814
        return -1;
1815
    if (width != s->width ||
1816
        height != s->height) {
1817
        /* start new mpeg1 context decoding */
1818
        s->out_format = FMT_MPEG1;
1819
        if (s1->mpeg_enc_ctx_allocated) {
1820
            MPV_common_end(s);
1821
        }
1822
        s->width = width;
1823
        s->height = height;
1824
        avctx->has_b_frames= 1;
1825
        s->avctx = avctx;
1826
        avctx->width = width;
1827
        avctx->height = height;
1828
        if (s->frame_rate_index >= 9) {
1829
            /* at least give a valid frame rate (some old mpeg1 have this) */
1830
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1831
        } else {
1832
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1833
        }
1834
        s->frame_rate = avctx->frame_rate;
1835
        avctx->bit_rate = s->bit_rate;
1836
        
1837
        if (MPV_common_init(s) < 0)
1838
            return -1;
1839
        s1->mpeg_enc_ctx_allocated = 1;
1840
    }
1841

    
1842
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1843
    skip_bits(&s->gb, 1);
1844

    
1845
    /* get matrix */
1846
    if (get_bits1(&s->gb)) {
1847
        for(i=0;i<64;i++) {
1848
            v = get_bits(&s->gb, 8);
1849
            j = s->intra_scantable.permutated[i];
1850
            s->intra_matrix[j] = v;
1851
            s->chroma_intra_matrix[j] = v;
1852
        }
1853
#ifdef DEBUG
1854
        dprintf("intra matrix present\n");
1855
        for(i=0;i<64;i++)
1856
            dprintf(" %d", s->intra_matrix[s->intra_scantable.permutated[i]]);
1857
        printf("\n");
1858
#endif
1859
    } else {
1860
        for(i=0;i<64;i++) {
1861
            int j= s->idct_permutation[i];
1862
            v = ff_mpeg1_default_intra_matrix[i];
1863
            s->intra_matrix[j] = v;
1864
            s->chroma_intra_matrix[j] = v;
1865
        }
1866
    }
1867
    if (get_bits1(&s->gb)) {
1868
        for(i=0;i<64;i++) {
1869
            v = get_bits(&s->gb, 8);
1870
            j = s->intra_scantable.permutated[i];
1871
            s->inter_matrix[j] = v;
1872
            s->chroma_inter_matrix[j] = v;
1873
        }
1874
#ifdef DEBUG
1875
        dprintf("non intra matrix present\n");
1876
        for(i=0;i<64;i++)
1877
            dprintf(" %d", s->inter_matrix[s->intra_scantable.permutated[i]]);
1878
        printf("\n");
1879
#endif
1880
    } else {
1881
        for(i=0;i<64;i++) {
1882
            int j= s->idct_permutation[i];
1883
            v = ff_mpeg1_default_non_intra_matrix[i];
1884
            s->inter_matrix[j] = v;
1885
            s->chroma_inter_matrix[j] = v;
1886
        }
1887
    }
1888

    
1889
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1890
    s->progressive_sequence = 1;
1891
    s->progressive_frame = 1;
1892
    s->picture_structure = PICT_FRAME;
1893
    s->frame_pred_frame_dct = 1;
1894
    s->mpeg2 = 0;
1895
    avctx->sub_id = 1; /* indicates mpeg1 */
1896
    return 0;
1897
}
1898

    
1899
/* handle buffering and image synchronisation */
1900
static int mpeg_decode_frame(AVCodecContext *avctx, 
1901
                             void *data, int *data_size,
1902
                             UINT8 *buf, int buf_size)
1903
{
1904
    Mpeg1Context *s = avctx->priv_data;
1905
    UINT8 *buf_end, *buf_ptr, *buf_start;
1906
    int len, start_code_found, ret, code, start_code, input_size;
1907
    AVFrame *picture = data;
1908
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1909
            
1910
    dprintf("fill_buffer\n");
1911

    
1912
    *data_size = 0;
1913

    
1914
    /* special case for last picture */
1915
    if (buf_size == 0) {
1916
        if (s2->picture_number > 0) {
1917
            *picture= *(AVFrame*)&s2->next_picture;
1918

    
1919
            *data_size = sizeof(AVFrame);
1920
        }
1921
        return 0;
1922
    }
1923

    
1924
    buf_ptr = buf;
1925
    buf_end = buf + buf_size;
1926

    
1927
#if 0    
1928
    if (s->repeat_field % 2 == 1) { 
1929
        s->repeat_field++;
1930
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1931
        //        s2->picture_number, s->repeat_field);
1932
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1933
            *data_size = sizeof(AVPicture);
1934
            goto the_end;
1935
        }
1936
    }
1937
#endif
1938
    while (buf_ptr < buf_end) {
1939
        buf_start = buf_ptr;
1940
        /* find start next code */
1941
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1942
        if (code >= 0) {
1943
            start_code_found = 1;
1944
        } else {
1945
            start_code_found = 0;
1946
        }
1947
        /* copy to buffer */
1948
        len = buf_ptr - buf_start;
1949
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1950
            /* data too big : flush */
1951
            s->buf_ptr = s->buffer;
1952
            if (start_code_found)
1953
                s->start_code = code;
1954
        } else {
1955
            memcpy(s->buf_ptr, buf_start, len);
1956
            s->buf_ptr += len;
1957
            if(   (!(s2->flags&CODEC_FLAG_TRUNCATED)) && (!start_code_found) 
1958
               && s->buf_ptr+4<s->buffer+s->buffer_size){
1959
                start_code_found= 1;
1960
                code= 0x1FF;
1961
                s->header_state=0xFF;
1962
                s->buf_ptr[0]=0;
1963
                s->buf_ptr[1]=0;
1964
                s->buf_ptr[2]=1;
1965
                s->buf_ptr[3]=0xFF;
1966
                s->buf_ptr+=4;
1967
            }
1968
            if (start_code_found) {
1969
                /* prepare data for next start code */
1970
                input_size = s->buf_ptr - s->buffer;
1971
                start_code = s->start_code;
1972
                s->buf_ptr = s->buffer;
1973
                s->start_code = code;
1974
                switch(start_code) {
1975
                case SEQ_START_CODE:
1976
                    mpeg1_decode_sequence(avctx, s->buffer, 
1977
                                          input_size);
1978
                    break;
1979
                            
1980
                case PICTURE_START_CODE:
1981
                    /* we have a complete image : we try to decompress it */
1982
                    mpeg1_decode_picture(avctx, 
1983
                                         s->buffer, input_size);
1984
                    break;
1985
                case EXT_START_CODE:
1986
                    mpeg_decode_extension(avctx,
1987
                                          s->buffer, input_size);
1988
                    break;
1989
                default:
1990
                    if (start_code >= SLICE_MIN_START_CODE &&
1991
                        start_code <= SLICE_MAX_START_CODE) {
1992
                        
1993
                        /* skip b frames if we dont have reference frames */
1994
                        if(s2->last_picture.data[0]==NULL && s2->pict_type==B_TYPE) break;
1995
                        /* skip b frames if we are in a hurry */
1996
                        if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
1997
                        /* skip everything if we are in a hurry>=5 */
1998
                        if(avctx->hurry_up>=5) break;
1999

    
2000
                        ret = mpeg_decode_slice(avctx, picture,
2001
                                                start_code, s->buffer, input_size);
2002
                        if (ret == DECODE_SLICE_EOP) {
2003
                            /* got a picture: exit */
2004
                            /* first check if we must repeat the frame */
2005
                            avctx->repeat_pict = 0;
2006
#if 0
2007
                            if (s2->progressive_frame && s2->repeat_first_field) {
2008
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
2009
                                //s2->repeat_first_field = 0;
2010
                                //s2->progressive_frame = 0;
2011
                                if (++s->repeat_field > 2)
2012
                                    s->repeat_field = 0;
2013
                                avctx->repeat_pict = 1;
2014
                            }
2015
#endif                      
2016
                            if (s2->repeat_first_field) {
2017
                                if (s2->progressive_sequence) {
2018
                                    if (s2->top_field_first)
2019
                                        avctx->repeat_pict = 4;
2020
                                    else
2021
                                        avctx->repeat_pict = 2;
2022
                                } else if (s2->progressive_frame) {
2023
                                    avctx->repeat_pict = 1;
2024
                                }
2025
                            }         
2026
                            *data_size = sizeof(AVPicture);
2027
                            goto the_end;
2028
                        }else if(ret<0){
2029
                            fprintf(stderr,"Error while decoding slice\n");
2030
                            if(ret==DECODE_SLICE_FATAL_ERROR) return -1;
2031
                        }
2032
                    }
2033
                    break;
2034
                }
2035
            }
2036
        }
2037
    }
2038
 the_end:
2039
    return buf_ptr - buf;
2040
}
2041

    
2042
static int mpeg_decode_end(AVCodecContext *avctx)
2043
{
2044
    Mpeg1Context *s = avctx->priv_data;
2045

    
2046
    if (s->mpeg_enc_ctx_allocated)
2047
        MPV_common_end(&s->mpeg_enc_ctx);
2048
    return 0;
2049
}
2050

    
2051
AVCodec mpeg_decoder = {
2052
    "mpegvideo",
2053
    CODEC_TYPE_VIDEO,
2054
    CODEC_ID_MPEG1VIDEO,
2055
    sizeof(Mpeg1Context),
2056
    mpeg_decode_init,
2057
    NULL,
2058
    mpeg_decode_end,
2059
    mpeg_decode_frame,
2060
    CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED,
2061
};