Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ 7604246d

History | View | Annotate | Download (72.6 KB)

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

    
24
#include "mpeg12data.h"
25

    
26
#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, int f_or_b_code);    // RAL: f_code parameter added
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_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
71
static uint8_t 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_t 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_t)s->fake_picture_number * FRAME_RATE_BASE;
246
            s->gop_picture_number = s->fake_picture_number;
247
            put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
248
            put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
249
            put_bits(&s->pb, 1, 1);
250
            put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
251
            put_bits(&s->pb, 6, (uint32_t)((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_t)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
#ifdef CONFIG_ENCODERS
329
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
330
{
331
    mpeg1_encode_sequence_header(s);
332

    
333
    /* mpeg1 picture header */
334
    put_header(s, PICTURE_START_CODE);
335
    /* temporal reference */
336

    
337
    // RAL: s->picture_number instead of s->fake_picture_number
338
    put_bits(&s->pb, 10, (s->picture_number - 
339
                          s->gop_picture_number) & 0x3ff); 
340
    s->fake_picture_number++;
341
    
342
    put_bits(&s->pb, 3, s->pict_type);
343
    put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
344
    
345
    // RAL: Forward f_code also needed for B frames
346
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
347
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
348
        put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
349
    }
350
    
351
    // RAL: Backward f_code necessary for B frames
352
    if (s->pict_type == B_TYPE) {
353
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
354
        put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
355
        }
356

    
357
    put_bits(&s->pb, 1, 0); /* extra bit picture */
358
    
359
    /* only one slice */
360
    put_header(s, SLICE_MIN_START_CODE);
361
    put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
362
    put_bits(&s->pb, 1, 0); /* slice extra information */
363
}
364

    
365
void mpeg1_encode_mb(MpegEncContext *s,
366
                     DCTELEM block[6][64],
367
                     int motion_x, int motion_y)
368
{
369
    int mb_incr, i, cbp, mb_x, mb_y;
370

    
371
    mb_x = s->mb_x;
372
    mb_y = s->mb_y;
373

    
374
    /* compute cbp */
375
    cbp = 0;
376
    for(i=0;i<6;i++) {
377
        if (s->block_last_index[i] >= 0)
378
            cbp |= 1 << (5 - i);
379
    }
380

    
381
    // RAL: Skipped macroblocks for B frames...
382
    if (cbp == 0 && (!((mb_x | mb_y) == 0 || (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1))) && 
383
        ((s->pict_type == P_TYPE && (motion_x | motion_y) == 0) ||
384
        (s->pict_type == B_TYPE && s->mv_dir == s->last_mv_dir && (((s->mv_dir & MV_DIR_FORWARD) ? ((s->mv[0][0][0] - s->last_mv[0][0][0])|(s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
385
        ((s->mv_dir & MV_DIR_BACKWARD) ? ((s->mv[1][0][0] - s->last_mv[1][0][0])|(s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
386
        s->mb_incr++;
387
        s->qscale -= s->dquant;
388
        s->skip_count++;
389
        s->misc_bits++;
390
        s->last_bits++;
391
    } else {
392
        /* output mb incr */
393
        mb_incr = s->mb_incr;
394

    
395
        while (mb_incr > 33) {
396
            put_bits(&s->pb, 11, 0x008);
397
            mb_incr -= 33;
398
        }
399
        put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
400
                 mbAddrIncrTable[mb_incr - 1][0]);
401
        
402
        if (s->pict_type == I_TYPE) {
403
            if(s->dquant && cbp){
404
                put_bits(&s->pb, 2, 1); /* macroblock_type : macroblock_quant = 1 */
405
                put_bits(&s->pb, 5, s->qscale);
406
            }else{
407
                put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
408
                s->qscale -= s->dquant;
409
            }
410
            s->misc_bits+= get_bits_diff(s);
411
            s->i_count++;
412
        } else if (s->mb_intra) {
413
            if(s->dquant && cbp){
414
                put_bits(&s->pb, 6, 0x01);
415
                put_bits(&s->pb, 5, s->qscale);
416
            }else{
417
                put_bits(&s->pb, 5, 0x03);
418
                s->qscale -= s->dquant;
419
            }
420
            s->misc_bits+= get_bits_diff(s);
421
            s->i_count++;
422
            s->last_mv[0][0][0] = 
423
            s->last_mv[0][0][1] = 0;
424
        } else if (s->pict_type == P_TYPE) { 
425
                if (cbp != 0) {
426
                    if (motion_x == 0 && motion_y == 0) {
427
                        if(s->dquant){
428
                            put_bits(&s->pb, 5, 1); /* macroblock_pattern & quant */
429
                            put_bits(&s->pb, 5, s->qscale);
430
                        }else{
431
                            put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
432
                        }
433
                        s->misc_bits+= get_bits_diff(s);
434
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
435
                    } else {
436
                        if(s->dquant){
437
                            put_bits(&s->pb, 5, 2); /* motion + cbp */
438
                            put_bits(&s->pb, 5, s->qscale);
439
                        }else{
440
                            put_bits(&s->pb, 1, 1); /* motion + cbp */
441
                        }
442
                        s->misc_bits+= get_bits_diff(s);
443
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
444
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
445
                        s->mv_bits+= get_bits_diff(s);
446
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
447
                    }
448
                } else {
449
                    put_bits(&s->pb, 3, 1); /* motion only */
450
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
451
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
452
                    s->qscale -= s->dquant;
453
                    s->mv_bits+= get_bits_diff(s);
454
                }
455
                s->f_count++;
456
        } else
457
            {    // RAL: All the following bloc added for B frames:
458
                if (cbp != 0)
459
                    {    // With coded bloc pattern
460
                    if (s->mv_dir == (MV_DIR_FORWARD | MV_DIR_BACKWARD))
461
                        {    // Bi-directional motion
462
                        if (s->dquant)
463
                            {    // With QScale
464
                            put_bits(&s->pb, 5, 2);
465
                            put_bits(&s->pb, 5, s->qscale);
466
                            }
467
                        else    // Without QScale
468
                            put_bits(&s->pb, 2, 3);
469
                        s->misc_bits += get_bits_diff(s);
470
                        mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
471
                        mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
472
                        mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
473
                        mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
474
                        s->b_count++;
475
                        s->f_count++;
476
                        s->mv_bits += get_bits_diff(s);
477
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
478
                        }
479
                    else if (s->mv_dir == MV_DIR_BACKWARD)
480
                        {    // Backward motion
481
                        if (s->dquant)
482
                            {    // With QScale
483
                            put_bits(&s->pb, 6, 2);
484
                            put_bits(&s->pb, 5, s->qscale);
485
                            }
486
                        else    // Without QScale
487
                            put_bits(&s->pb, 3, 3);
488
                        s->misc_bits += get_bits_diff(s);
489
                        mpeg1_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code); 
490
                        mpeg1_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code); 
491
                        s->b_count++;
492
                        s->mv_bits += get_bits_diff(s);
493
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
494
                        }
495
                    else if (s->mv_dir == MV_DIR_FORWARD)
496
                        {    // Forward motion
497
                        if (s->dquant)
498
                            {    // With QScale
499
                            put_bits(&s->pb, 6, 3);
500
                            put_bits(&s->pb, 5, s->qscale);
501
                            }
502
                        else    // Without QScale
503
                            put_bits(&s->pb, 4, 3);
504
                        s->misc_bits += get_bits_diff(s);
505
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code); 
506
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code); 
507
                        s->f_count++;
508
                        s->mv_bits += get_bits_diff(s);
509
                        put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
510
                        }
511
                    }
512
                else
513
                    {    // No coded bloc pattern
514
                    if (s->mv_dir == (MV_DIR_FORWARD | MV_DIR_BACKWARD))
515
                        {    // Bi-directional motion 
516
                        put_bits(&s->pb, 2, 2); /* backward & forward motion */
517
                        mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
518
                        mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
519
                        mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
520
                        mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
521
                        s->b_count++;
522
                        s->f_count++;
523
                        }
524
                    else if (s->mv_dir == MV_DIR_BACKWARD)
525
                        {    // Backward motion
526
                        put_bits(&s->pb, 3, 2); /* backward motion only */
527
                        mpeg1_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code); 
528
                        mpeg1_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code); 
529
                        s->b_count++;
530
                        }
531
                    else if (s->mv_dir == MV_DIR_FORWARD)
532
                        {    // Forward motion
533
                        put_bits(&s->pb, 4, 2); /* forward motion only */
534
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code); 
535
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code); 
536
                        s->f_count++;
537
                        }
538
                    s->qscale -= s->dquant;
539
                    s->mv_bits += get_bits_diff(s);
540
                    }
541
            // End of bloc from RAL
542
            }
543
        for(i=0;i<6;i++) {
544
            if (cbp & (1 << (5 - i))) {
545
                mpeg1_encode_block(s, block[i], i);
546
            }
547
        }
548
        s->mb_incr = 1;
549
        if(s->mb_intra)
550
            s->i_tex_bits+= get_bits_diff(s);
551
        else
552
            s->p_tex_bits+= get_bits_diff(s);
553
    }
554

    
555
    // RAL: By this:
556
    if (s->mv_dir & MV_DIR_FORWARD)
557
        {
558
        s->last_mv[0][0][0]= s->mv[0][0][0];
559
        s->last_mv[0][0][1]= s->mv[0][0][1];
560
        }
561
    if (s->mv_dir & MV_DIR_BACKWARD)
562
        {
563
        s->last_mv[1][0][0]= s->mv[1][0][0];
564
        s->last_mv[1][0][1]= s->mv[1][0][1];
565
        }
566
}
567

    
568
// RAL: Parameter added: f_or_b_code
569
static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
570
{
571
    int code, bit_size, l, m, bits, range, sign;
572

    
573
    if (val == 0) {
574
        /* zero vector */
575
        code = 0;
576
        put_bits(&s->pb,
577
                 mbMotionVectorTable[0][1], 
578
                 mbMotionVectorTable[0][0]); 
579
    } else {
580
        bit_size = f_or_b_code - 1;
581
        range = 1 << bit_size;
582
        /* modulo encoding */
583
        l = 16 * range;
584
        m = 2 * l;
585
        if (val < -l) {
586
            val += m;
587
        } else if (val >= l) {
588
            val -= m;
589
        }
590

    
591
        if (val >= 0) {
592
            val--;
593
            code = (val >> bit_size) + 1;
594
            bits = val & (range - 1);
595
            sign = 0;
596
        } else {
597
            val = -val;
598
            val--;
599
            code = (val >> bit_size) + 1;
600
            bits = val & (range - 1);
601
            sign = 1;
602
        }
603

    
604
        assert(code > 0 && code <= 16);
605

    
606
        put_bits(&s->pb,
607
                 mbMotionVectorTable[code][1], 
608
                 mbMotionVectorTable[code][0]); 
609

    
610
        put_bits(&s->pb, 1, sign);
611
        if (bit_size > 0) {
612
            put_bits(&s->pb, bit_size, bits);
613
        }
614
    }
615
}
616

    
617
void ff_mpeg1_encode_init(MpegEncContext *s)
618
{
619
    static int done=0;
620

    
621
    common_init(s);
622

    
623
    if(!done){
624
        int f_code;
625
        int mv;
626
        int i;
627

    
628
        done=1;
629
        init_rl(&rl_mpeg1);
630

    
631
        for(i=0; i<64; i++)
632
        {
633
                mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
634
                mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
635
        }
636
        
637
        init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_bits, uni_mpeg1_ac_vlc_len);
638

    
639
        /* build unified dc encoding tables */
640
        for(i=-255; i<256; i++)
641
        {
642
                int adiff, index;
643
                int bits, code;
644
                int diff=i;
645

    
646
                adiff = ABS(diff);
647
                if(diff<0) diff--;
648
                index = vlc_dc_table[adiff];
649

    
650
                bits= vlc_dc_lum_bits[index] + index;
651
                code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
652
                mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
653
                
654
                bits= vlc_dc_chroma_bits[index] + index;
655
                code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
656
                mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
657
        }
658

    
659
        for(f_code=1; f_code<=MAX_FCODE; f_code++){
660
            for(mv=-MAX_MV; mv<=MAX_MV; mv++){
661
                int len;
662

    
663
                if(mv==0) len= mbMotionVectorTable[0][1];
664
                else{
665
                    int val, bit_size, range, code;
666

    
667
                    bit_size = s->f_code - 1;
668
                    range = 1 << bit_size;
669

    
670
                    val=mv;
671
                    if (val < 0) 
672
                        val = -val;
673
                    val--;
674
                    code = (val >> bit_size) + 1;
675
                    if(code<17){
676
                        len= mbMotionVectorTable[code][1] + 1 + bit_size;
677
                    }else{
678
                        len= mbMotionVectorTable[16][1] + 2 + bit_size;
679
                    }
680
                }
681

    
682
                mv_penalty[f_code][mv+MAX_MV]= len;
683
            }
684
        }
685
        
686

    
687
        for(f_code=MAX_FCODE; f_code>0; f_code--){
688
            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
689
                fcode_tab[mv+MAX_MV]= f_code;
690
            }
691
        }
692
    }
693
    s->me.mv_penalty= mv_penalty;
694
    s->fcode_tab= fcode_tab;
695
    s->min_qcoeff=-255;
696
    s->max_qcoeff= 255;
697
    s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
698
    s->inter_quant_bias= 0;
699
    s->intra_ac_vlc_length=
700
    s->inter_ac_vlc_length= uni_mpeg1_ac_vlc_len;
701
}
702

    
703
static inline void encode_dc(MpegEncContext *s, int diff, int component)
704
{
705
    if (component == 0) {
706
        put_bits(
707
            &s->pb, 
708
            mpeg1_lum_dc_uni[diff+255]&0xFF,
709
            mpeg1_lum_dc_uni[diff+255]>>8);
710
    } else {
711
        put_bits(
712
            &s->pb, 
713
            mpeg1_chr_dc_uni[diff+255]&0xFF,
714
            mpeg1_chr_dc_uni[diff+255]>>8);
715
    }
716
}
717

    
718
static void mpeg1_encode_block(MpegEncContext *s, 
719
                               DCTELEM *block, 
720
                               int n)
721
{
722
    int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
723
    int code, component;
724
//    RLTable *rl = &rl_mpeg1;
725

    
726
    last_index = s->block_last_index[n];
727

    
728
    /* DC coef */
729
    if (s->mb_intra) {
730
        component = (n <= 3 ? 0 : n - 4 + 1);
731
        dc = block[0]; /* overflow is impossible */
732
        diff = dc - s->last_dc[component];
733
        encode_dc(s, diff, component);
734
        s->last_dc[component] = dc;
735
        i = 1;
736
    } else {
737
        /* encode the first coefficient : needs to be done here because
738
           it is handled slightly differently */
739
        level = block[0];
740
        if (abs(level) == 1) {
741
                code = ((uint32_t)level >> 31); /* the sign bit */
742
                put_bits(&s->pb, 2, code | 0x02);
743
                i = 1;
744
        } else {
745
            i = 0;
746
            last_non_zero = -1;
747
            goto next_coef;
748
        }
749
    }
750

    
751
    /* now quantify & encode AC coefs */
752
    last_non_zero = i - 1;
753

    
754
    for(;i<=last_index;i++) {
755
        j = s->intra_scantable.permutated[i];
756
        level = block[j];
757
    next_coef:
758
#if 0
759
        if (level != 0)
760
            dprintf("level[%d]=%d\n", i, level);
761
#endif            
762
        /* encode using VLC */
763
        if (level != 0) {
764
            run = i - last_non_zero - 1;
765
            
766
            alevel= level;
767
            MASK_ABS(sign, alevel)
768
            sign&=1;
769

    
770
//            code = get_rl_index(rl, 0, run, alevel);
771
            if (alevel <= mpeg1_max_level[0][run]){
772
                code= mpeg1_index_run[0][run] + alevel - 1;
773
                    /* store the vlc & sign at once */
774
                put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
775
            } else {
776
                /* escape seems to be pretty rare <5% so i dont optimize it */
777
                put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
778
                /* escape: only clip in this case */
779
                put_bits(&s->pb, 6, run);
780
                if (alevel < 128) {
781
                    put_bits(&s->pb, 8, level & 0xff);
782
                } else {
783
                    if (level < 0) {
784
                        put_bits(&s->pb, 16, 0x8001 + level + 255);
785
                    } else {
786
                        put_bits(&s->pb, 16, level & 0xffff);
787
                    }
788
                }
789
            }
790
            last_non_zero = i;
791
        }
792
    }
793
    /* end of block */
794
    put_bits(&s->pb, 2, 0x2);
795
}
796
#endif //CONFIG_ENCODERS
797

    
798
/******************************************/
799
/* decoding */
800

    
801
static VLC dc_lum_vlc;
802
static VLC dc_chroma_vlc;
803
static VLC mv_vlc;
804
static VLC mbincr_vlc;
805
static VLC mb_ptype_vlc;
806
static VLC mb_btype_vlc;
807
static VLC mb_pat_vlc;
808

    
809
static void init_vlcs(MpegEncContext *s)
810
{
811
    static int done = 0;
812

    
813
    if (!done) {
814
        done = 1;
815

    
816
        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
817
                 vlc_dc_lum_bits, 1, 1,
818
                 vlc_dc_lum_code, 2, 2);
819
        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
820
                 vlc_dc_chroma_bits, 1, 1,
821
                 vlc_dc_chroma_code, 2, 2);
822
        init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
823
                 &mbMotionVectorTable[0][1], 2, 1,
824
                 &mbMotionVectorTable[0][0], 2, 1);
825
        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 35, 
826
                 &mbAddrIncrTable[0][1], 2, 1,
827
                 &mbAddrIncrTable[0][0], 2, 1);
828
        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 63, 
829
                 &mbPatTable[0][1], 2, 1,
830
                 &mbPatTable[0][0], 2, 1);
831
        
832
        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 32, 
833
                 &table_mb_ptype[0][1], 2, 1,
834
                 &table_mb_ptype[0][0], 2, 1);
835
        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 32, 
836
                 &table_mb_btype[0][1], 2, 1,
837
                 &table_mb_btype[0][0], 2, 1);
838
        init_rl(&rl_mpeg1);
839
        init_rl(&rl_mpeg2);
840

    
841
        init_2d_vlc_rl(&rl_mpeg1);
842
        init_2d_vlc_rl(&rl_mpeg2);
843
    }
844
}
845

    
846
static inline int get_dmv(MpegEncContext *s)
847
{
848
    if(get_bits1(&s->gb)) 
849
        return 1 - (get_bits1(&s->gb) << 1);
850
    else
851
        return 0;
852
}
853

    
854
static inline int get_qscale(MpegEncContext *s)
855
{
856
    int qscale;
857
    if (s->mpeg2) {
858
        if (s->q_scale_type) {
859
            qscale = non_linear_qscale[get_bits(&s->gb, 5)];
860
        } else {
861
            qscale = get_bits(&s->gb, 5) << 1;
862
        }
863
    } else {
864
        /* for mpeg1, we use the generic unquant code */
865
        qscale = get_bits(&s->gb, 5);
866
    }
867
    return qscale;
868
}
869

    
870
/* motion type (for mpeg2) */
871
#define MT_FIELD 1
872
#define MT_FRAME 2
873
#define MT_16X8  2
874
#define MT_DMV   3
875

    
876
static int mpeg_decode_mb(MpegEncContext *s,
877
                          DCTELEM block[6][64])
878
{
879
    int i, j, k, cbp, val, mb_type, motion_type;
880
    
881
    dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
882

    
883
    assert(s->mb_skiped==0);
884

    
885
    if (--s->mb_incr != 0) {
886
        /* skip mb */
887
        s->mb_intra = 0;
888
        for(i=0;i<6;i++)
889
            s->block_last_index[i] = -1;
890
        s->mv_type = MV_TYPE_16X16;
891
        if (s->pict_type == P_TYPE) {
892
            /* if P type, zero motion vector is implied */
893
            s->mv_dir = MV_DIR_FORWARD;
894
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
895
            s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
896
            s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
897
            s->mb_skiped = 1;
898
        } else {
899
            /* if B type, reuse previous vectors and directions */
900
            s->mv[0][0][0] = s->last_mv[0][0][0];
901
            s->mv[0][0][1] = s->last_mv[0][0][1];
902
            s->mv[1][0][0] = s->last_mv[1][0][0];
903
            s->mv[1][0][1] = s->last_mv[1][0][1];
904

    
905
            if((s->mv[0][0][0]|s->mv[0][0][1]|s->mv[1][0][0]|s->mv[1][0][1])==0) 
906
                s->mb_skiped = 1;
907
        }
908

    
909
        return 0;
910
    }
911

    
912
    switch(s->pict_type) {
913
    default:
914
    case I_TYPE:
915
        if (get_bits1(&s->gb) == 0) {
916
            if (get_bits1(&s->gb) == 0)
917
                return -1;
918
            mb_type = MB_QUANT | MB_INTRA;
919
        } else {
920
            mb_type = MB_INTRA;
921
        }
922
        break;
923
    case P_TYPE:
924
        mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
925
        if (mb_type < 0){
926
            fprintf(stderr, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
927
            return -1;
928
        }
929
        break;
930
    case B_TYPE:
931
        mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
932
        if (mb_type < 0){
933
            fprintf(stderr, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
934
            return -1;
935
        }
936
        break;
937
    }
938
    dprintf("mb_type=%x\n", mb_type);
939
    motion_type = 0; /* avoid warning */
940
    if (mb_type & (MB_FOR|MB_BACK)) {
941
        /* get additionnal motion vector type */
942
        if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
943
            motion_type = MT_FRAME;
944
        else
945
            motion_type = get_bits(&s->gb, 2);
946
    }
947
    /* compute dct type */
948
    if (s->picture_structure == PICT_FRAME && 
949
        !s->frame_pred_frame_dct &&
950
        (mb_type & (MB_PAT | MB_INTRA))) {
951
        s->interlaced_dct = get_bits1(&s->gb);
952
#ifdef DEBUG
953
        if (s->interlaced_dct)
954
            printf("interlaced_dct\n");
955
#endif
956
    } else {
957
        s->interlaced_dct = 0; /* frame based */
958
    }
959

    
960
    if (mb_type & MB_QUANT) {
961
        s->qscale = get_qscale(s);
962
    }
963
    if (mb_type & MB_INTRA) {
964
        if (s->concealment_motion_vectors) {
965
            /* just parse them */
966
            if (s->picture_structure != PICT_FRAME) 
967
                skip_bits1(&s->gb); /* field select */
968
            mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
969
            mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
970
        }
971
        s->mb_intra = 1;
972
        cbp = 0x3f;
973
        memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
974
    } else {
975
        s->mb_intra = 0;
976
        cbp = 0;
977
    }
978
    /* special case of implicit zero motion vector */
979
    if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
980
        s->mv_dir = MV_DIR_FORWARD;
981
        s->mv_type = MV_TYPE_16X16;
982
        s->last_mv[0][0][0] = 0;
983
        s->last_mv[0][0][1] = 0;
984
        s->last_mv[0][1][0] = 0;
985
        s->last_mv[0][1][1] = 0;
986
        s->mv[0][0][0] = 0;
987
        s->mv[0][0][1] = 0;
988
    } else if (mb_type & (MB_FOR | MB_BACK)) {
989
        /* motion vectors */
990
        s->mv_dir = 0;
991
        for(i=0;i<2;i++) {
992
            if (mb_type & (MB_FOR >> i)) {
993
                s->mv_dir |= (MV_DIR_FORWARD >> i);
994
                dprintf("motion_type=%d\n", motion_type);
995
                switch(motion_type) {
996
                case MT_FRAME: /* or MT_16X8 */
997
                    if (s->picture_structure == PICT_FRAME) {
998
                        /* MT_FRAME */
999
                        s->mv_type = MV_TYPE_16X16;
1000
                        for(k=0;k<2;k++) {
1001
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
1002
                                                     s->last_mv[i][0][k]);
1003
                            s->last_mv[i][0][k] = val;
1004
                            s->last_mv[i][1][k] = val;
1005
                            /* full_pel: only for mpeg1 */
1006
                            if (s->full_pel[i])
1007
                                val = val << 1;
1008
                            s->mv[i][0][k] = val;
1009
                            dprintf("mv%d: %d\n", k, val);
1010
                        }
1011
                    } else {
1012
                        /* MT_16X8 */
1013
                        s->mv_type = MV_TYPE_16X8;
1014
                        for(j=0;j<2;j++) {
1015
                            s->field_select[i][j] = get_bits1(&s->gb);
1016
                            for(k=0;k<2;k++) {
1017
                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1018
                                                         s->last_mv[i][j][k]);
1019
                                s->last_mv[i][j][k] = val;
1020
                                s->mv[i][j][k] = val;
1021
                            }
1022
                        }
1023
                    }
1024
                    break;
1025
                case MT_FIELD:
1026
                    if (s->picture_structure == PICT_FRAME) {
1027
                        s->mv_type = MV_TYPE_FIELD;
1028
                        for(j=0;j<2;j++) {
1029
                            s->field_select[i][j] = get_bits1(&s->gb);
1030
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
1031
                                                     s->last_mv[i][j][0]);
1032
                            s->last_mv[i][j][0] = val;
1033
                            s->mv[i][j][0] = val;
1034
                            dprintf("fmx=%d\n", val);
1035
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
1036
                                                     s->last_mv[i][j][1] >> 1);
1037
                            s->last_mv[i][j][1] = val << 1;
1038
                            s->mv[i][j][1] = val;
1039
                            dprintf("fmy=%d\n", val);
1040
                        }
1041
                    } else {
1042
                        s->mv_type = MV_TYPE_16X16;
1043
                        s->field_select[i][0] = get_bits1(&s->gb);
1044
                        for(k=0;k<2;k++) {
1045
                            val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1046
                                                     s->last_mv[i][0][k]);
1047
                            s->last_mv[i][0][k] = val;
1048
                            s->last_mv[i][1][k] = val;
1049
                            s->mv[i][0][k] = val;
1050
                        }
1051
                    }
1052
                    break;
1053
                case MT_DMV:
1054
                    {
1055
                        int dmx, dmy, mx, my, m;
1056

    
1057
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
1058
                                                s->last_mv[i][0][0]);
1059
                        s->last_mv[i][0][0] = mx;
1060
                        s->last_mv[i][1][0] = mx;
1061
                        dmx = get_dmv(s);
1062
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
1063
                                                s->last_mv[i][0][1] >> 1);
1064
                        dmy = get_dmv(s);
1065
                        s->mv_type = MV_TYPE_DMV;
1066
                        /* XXX: totally broken */
1067
                        if (s->picture_structure == PICT_FRAME) {
1068
                            s->last_mv[i][0][1] = my << 1;
1069
                            s->last_mv[i][1][1] = my << 1;
1070

    
1071
                            m = s->top_field_first ? 1 : 3;
1072
                            /* top -> top pred */
1073
                            s->mv[i][0][0] = mx; 
1074
                            s->mv[i][0][1] = my << 1;
1075
                            s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1076
                            s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
1077
                            m = 4 - m;
1078
                            s->mv[i][2][0] = mx;
1079
                            s->mv[i][2][1] = my << 1;
1080
                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1081
                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
1082
                        } else {
1083
                            s->last_mv[i][0][1] = my;
1084
                            s->last_mv[i][1][1] = my;
1085
                            s->mv[i][0][0] = mx;
1086
                            s->mv[i][0][1] = my;
1087
                            s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
1088
                            s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
1089
                                /* + 2 * cur_field */;
1090
                        }
1091
                    }
1092
                    break;
1093
                }
1094
            }
1095
        }
1096
    }
1097

    
1098
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
1099
        skip_bits1(&s->gb); /* marker */
1100
    }
1101
    
1102
    if (mb_type & MB_PAT) {
1103
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1104
        if (cbp < 0){
1105
            fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
1106
            return -1;
1107
        }
1108
        cbp++;
1109
    }
1110
    dprintf("cbp=%x\n", cbp);
1111

    
1112
    if (s->mpeg2) {
1113
        if (s->mb_intra) {
1114
            for(i=0;i<6;i++) {
1115
                if (mpeg2_decode_block_intra(s, block[i], i) < 0)
1116
                    return -1;
1117
            }
1118
        } else {
1119
            for(i=0;i<6;i++) {
1120
                if (cbp & 32) {
1121
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
1122
                        return -1;
1123
                } else {
1124
                    s->block_last_index[i] = -1;
1125
                }
1126
                cbp+=cbp;
1127
            }
1128
        }
1129
    } else {
1130
        if (s->mb_intra) {
1131
            for(i=0;i<6;i++) {
1132
                if (mpeg1_decode_block_intra(s, block[i], i) < 0)
1133
                    return -1;
1134
            }
1135
        }else{
1136
            for(i=0;i<6;i++) {
1137
                if (cbp & 32) {
1138
                    if (mpeg1_decode_block_inter(s, block[i], i) < 0)
1139
                        return -1;
1140
                } else {
1141
                    s->block_last_index[i] = -1;
1142
                }
1143
                cbp+=cbp;
1144
            }
1145
        }
1146
    }
1147
    return 0;
1148
}
1149

    
1150
/* as h263, but only 17 codes */
1151
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
1152
{
1153
    int code, sign, val, m, l, shift;
1154

    
1155
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
1156
    if (code < 0) {
1157
        return 0xffff;
1158
    }
1159
    if (code == 0) {
1160
        return pred;
1161
    }
1162
    sign = get_bits1(&s->gb);
1163
    shift = fcode - 1;
1164
    val = (code - 1) << shift;
1165
    if (shift > 0)
1166
        val |= get_bits(&s->gb, shift);
1167
    val++;
1168
    if (sign)
1169
        val = -val;
1170
    val += pred;
1171
    
1172
    /* modulo decoding */
1173
    l = (1 << shift) * 16;
1174
    m = 2 * l;
1175
    if (val < -l) {
1176
        val += m;
1177
    } else if (val >= l) {
1178
        val -= m;
1179
    }
1180
    return val;
1181
}
1182

    
1183
static inline int decode_dc(MpegEncContext *s, int component)
1184
{
1185
    int code, diff;
1186

    
1187
    if (component == 0) {
1188
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
1189
    } else {
1190
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
1191
    }
1192
    if (code < 0){
1193
        fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
1194
        return 0xffff;
1195
    }
1196
    if (code == 0) {
1197
        diff = 0;
1198
    } else {
1199
        diff = get_bits(&s->gb, code);
1200
        if ((diff & (1 << (code - 1))) == 0) 
1201
            diff = (-1 << code) | (diff + 1);
1202
    }
1203
    return diff;
1204
}
1205

    
1206
static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
1207
                               DCTELEM *block, 
1208
                               int n)
1209
{
1210
    int level, dc, diff, i, j, run;
1211
    int component;
1212
    RLTable *rl = &rl_mpeg1;
1213
    uint8_t * const scantable= s->intra_scantable.permutated;
1214
    const uint16_t *quant_matrix= s->intra_matrix;
1215
    const int qscale= s->qscale;
1216

    
1217
    /* DC coef */
1218
    component = (n <= 3 ? 0 : n - 4 + 1);
1219
    diff = decode_dc(s, component);
1220
    if (diff >= 0xffff)
1221
        return -1;
1222
    dc = s->last_dc[component];
1223
    dc += diff;
1224
    s->last_dc[component] = dc;
1225
    block[0] = dc<<3;
1226
    dprintf("dc=%d diff=%d\n", dc, diff);
1227
    i = 0;
1228
    {
1229
        OPEN_READER(re, &s->gb);    
1230
        /* now quantify & encode AC coefs */
1231
        for(;;) {
1232
            UPDATE_CACHE(re, &s->gb);
1233
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1234
            
1235
            if(level == 127){
1236
                break;
1237
            } else if(level != 0) {
1238
                i += run;
1239
                j = scantable[i];
1240
                level= (level*qscale*quant_matrix[j])>>3;
1241
                level= (level-1)|1;
1242
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1243
                LAST_SKIP_BITS(re, &s->gb, 1);
1244
            } else {
1245
                /* escape */
1246
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1247
                UPDATE_CACHE(re, &s->gb);
1248
                level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1249
                if (level == -128) {
1250
                    level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1251
                } else if (level == 0) {
1252
                    level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1253
                }
1254
                i += run;
1255
                j = scantable[i];
1256
                if(level<0){
1257
                    level= -level;
1258
                    level= (level*qscale*quant_matrix[j])>>3;
1259
                    level= (level-1)|1;
1260
                    level= -level;
1261
                }else{
1262
                    level= (level*qscale*quant_matrix[j])>>3;
1263
                    level= (level-1)|1;
1264
                }
1265
            }
1266
            if (i > 63){
1267
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1268
                return -1;
1269
            }
1270

    
1271
            block[j] = level;
1272
        }
1273
        CLOSE_READER(re, &s->gb);
1274
    }
1275
    s->block_last_index[n] = i;
1276
   return 0;
1277
}
1278

    
1279
static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
1280
                               DCTELEM *block, 
1281
                               int n)
1282
{
1283
    int level, i, j, run;
1284
    RLTable *rl = &rl_mpeg1;
1285
    uint8_t * const scantable= s->intra_scantable.permutated;
1286
    const uint16_t *quant_matrix= s->inter_matrix;
1287
    const int qscale= s->qscale;
1288

    
1289
    {
1290
        int v;
1291
        OPEN_READER(re, &s->gb);
1292
        i = -1;
1293
        /* special case for the first coef. no need to add a second vlc table */
1294
        UPDATE_CACHE(re, &s->gb);
1295
        v= SHOW_UBITS(re, &s->gb, 2);
1296
        if (v & 2) {
1297
            LAST_SKIP_BITS(re, &s->gb, 2);
1298
            level= (3*qscale*quant_matrix[0])>>4;
1299
            level= (level-1)|1;
1300
            if(v&1)
1301
                level= -level;
1302
            block[0] = level;
1303
            i++;
1304
        }
1305

    
1306
        /* now quantify & encode AC coefs */
1307
        for(;;) {
1308
            UPDATE_CACHE(re, &s->gb);
1309
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1310
            
1311
            if(level == 127){
1312
                break;
1313
            } else if(level != 0) {
1314
                i += run;
1315
                j = scantable[i];
1316
                level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1317
                level= (level-1)|1;
1318
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1319
                LAST_SKIP_BITS(re, &s->gb, 1);
1320
            } else {
1321
                /* escape */
1322
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1323
                UPDATE_CACHE(re, &s->gb);
1324
                level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1325
                if (level == -128) {
1326
                    level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1327
                } else if (level == 0) {
1328
                    level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1329
                }
1330
                i += run;
1331
                j = scantable[i];
1332
                if(level<0){
1333
                    level= -level;
1334
                    level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1335
                    level= (level-1)|1;
1336
                    level= -level;
1337
                }else{
1338
                    level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1339
                    level= (level-1)|1;
1340
                }
1341
            }
1342
            if (i > 63){
1343
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1344
                return -1;
1345
            }
1346

    
1347
            block[j] = level;
1348
        }
1349
        CLOSE_READER(re, &s->gb);
1350
    }
1351
    s->block_last_index[n] = i;
1352
    return 0;
1353
}
1354

    
1355
/* Also does unquantization here, since I will never support mpeg2
1356
   encoding */
1357
static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1358
                               DCTELEM *block, 
1359
                               int n)
1360
{
1361
    int level, i, j, run;
1362
    RLTable *rl = &rl_mpeg1;
1363
    uint8_t * const scantable= s->intra_scantable.permutated;
1364
    const uint16_t *quant_matrix;
1365
    const int qscale= s->qscale;
1366
    int mismatch;
1367

    
1368
    mismatch = 1;
1369

    
1370
    {
1371
        int v;
1372
        OPEN_READER(re, &s->gb);
1373
        i = -1;
1374
        if (n < 4)
1375
            quant_matrix = s->inter_matrix;
1376
        else
1377
            quant_matrix = s->chroma_inter_matrix;
1378

    
1379
        /* special case for the first coef. no need to add a second vlc table */
1380
        UPDATE_CACHE(re, &s->gb);
1381
        v= SHOW_UBITS(re, &s->gb, 2);
1382
        if (v & 2) {
1383
            LAST_SKIP_BITS(re, &s->gb, 2);
1384
            level= (3*qscale*quant_matrix[0])>>5;
1385
            if(v&1)
1386
                level= -level;
1387
            block[0] = level;
1388
            mismatch ^= level;
1389
            i++;
1390
        }
1391

    
1392
        /* now quantify & encode AC coefs */
1393
        for(;;) {
1394
            UPDATE_CACHE(re, &s->gb);
1395
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1396
            
1397
            if(level == 127){
1398
                break;
1399
            } else if(level != 0) {
1400
                i += run;
1401
                j = scantable[i];
1402
                level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1403
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1404
                LAST_SKIP_BITS(re, &s->gb, 1);
1405
            } else {
1406
                /* escape */
1407
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1408
                UPDATE_CACHE(re, &s->gb);
1409
                level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1410

    
1411
                i += run;
1412
                j = scantable[i];
1413
                if(level<0){
1414
                    level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
1415
                    level= -level;
1416
                }else{
1417
                    level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1418
                }
1419
            }
1420
            if (i > 63){
1421
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1422
                return -1;
1423
            }
1424
            
1425
            mismatch ^= level;
1426
            block[j] = level;
1427
        }
1428
        CLOSE_READER(re, &s->gb);
1429
    }
1430
    block[63] ^= (mismatch & 1);
1431
    
1432
    s->block_last_index[n] = i;
1433
    return 0;
1434
}
1435

    
1436
static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
1437
                               DCTELEM *block, 
1438
                               int n)
1439
{
1440
    int level, dc, diff, i, j, run;
1441
    int component;
1442
    RLTable *rl;
1443
    uint8_t * const scantable= s->intra_scantable.permutated;
1444
    const uint16_t *quant_matrix;
1445
    const int qscale= s->qscale;
1446
    int mismatch;
1447

    
1448
    /* DC coef */
1449
    if (n < 4){
1450
        quant_matrix = s->intra_matrix;
1451
        component = 0; 
1452
    }else{
1453
        quant_matrix = s->chroma_intra_matrix;
1454
        component = n - 3;
1455
    }
1456
    diff = decode_dc(s, component);
1457
    if (diff >= 0xffff)
1458
        return -1;
1459
    dc = s->last_dc[component];
1460
    dc += diff;
1461
    s->last_dc[component] = dc;
1462
    block[0] = dc << (3 - s->intra_dc_precision);
1463
    dprintf("dc=%d\n", block[0]);
1464
    mismatch = block[0] ^ 1;
1465
    i = 0;
1466
    if (s->intra_vlc_format)
1467
        rl = &rl_mpeg2;
1468
    else
1469
        rl = &rl_mpeg1;
1470

    
1471
    {
1472
        OPEN_READER(re, &s->gb);    
1473
        /* now quantify & encode AC coefs */
1474
        for(;;) {
1475
            UPDATE_CACHE(re, &s->gb);
1476
            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1477
            
1478
            if(level == 127){
1479
                break;
1480
            } else if(level != 0) {
1481
                i += run;
1482
                j = scantable[i];
1483
                level= (level*qscale*quant_matrix[j])>>4;
1484
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1485
                LAST_SKIP_BITS(re, &s->gb, 1);
1486
            } else {
1487
                /* escape */
1488
                run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1489
                UPDATE_CACHE(re, &s->gb);
1490
                level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1491
                i += run;
1492
                j = scantable[i];
1493
                if(level<0){
1494
                    level= (-level*qscale*quant_matrix[j])>>4;
1495
                    level= -level;
1496
                }else{
1497
                    level= (level*qscale*quant_matrix[j])>>4;
1498
                }
1499
            }
1500
            if (i > 63){
1501
                fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1502
                return -1;
1503
            }
1504
            
1505
            mismatch^= level;
1506
            block[j] = level;
1507
        }
1508
        CLOSE_READER(re, &s->gb);
1509
    }
1510
    block[63]^= mismatch&1;
1511
    
1512
    s->block_last_index[n] = i;
1513
    return 0;
1514
}
1515

    
1516
/* compressed picture size */
1517
#define PICTURE_BUFFER_SIZE 100000
1518

    
1519
typedef struct Mpeg1Context {
1520
    MpegEncContext mpeg_enc_ctx;
1521
    uint32_t header_state;
1522
    int start_code; /* current start code */
1523
    uint8_t buffer[PICTURE_BUFFER_SIZE]; 
1524
    uint8_t *buf_ptr;
1525
    int buffer_size;
1526
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1527
    int repeat_field; /* true if we must repeat the field */
1528
} Mpeg1Context;
1529

    
1530
static int mpeg_decode_init(AVCodecContext *avctx)
1531
{
1532
    Mpeg1Context *s = avctx->priv_data;
1533
    
1534
    s->mpeg_enc_ctx.flags= avctx->flags;
1535
    common_init(&s->mpeg_enc_ctx);
1536
    init_vlcs(&s->mpeg_enc_ctx);
1537

    
1538
    s->header_state = 0xff;
1539
    s->mpeg_enc_ctx_allocated = 0;
1540
    s->buffer_size = PICTURE_BUFFER_SIZE;
1541
    s->start_code = -1;
1542
    s->buf_ptr = s->buffer;
1543
    s->mpeg_enc_ctx.picture_number = 0;
1544
    s->repeat_field = 0;
1545
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1546
    return 0;
1547
}
1548

    
1549
/* return the 8 bit start code value and update the search
1550
   state. Return -1 if no start code found */
1551
static int find_start_code(uint8_t **pbuf_ptr, uint8_t *buf_end, 
1552
                           uint32_t *header_state)
1553
{
1554
    uint8_t *buf_ptr;
1555
    unsigned int state, v;
1556
    int val;
1557

    
1558
    state = *header_state;
1559
    buf_ptr = *pbuf_ptr;
1560
    while (buf_ptr < buf_end) {
1561
        v = *buf_ptr++;
1562
        if (state == 0x000001) {
1563
            state = ((state << 8) | v) & 0xffffff;
1564
            val = state;
1565
            goto found;
1566
        }
1567
        state = ((state << 8) | v) & 0xffffff;
1568
    }
1569
    val = -1;
1570
 found:
1571
    *pbuf_ptr = buf_ptr;
1572
    *header_state = state;
1573
    return val;
1574
}
1575

    
1576
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1577
                                uint8_t *buf, int buf_size)
1578
{
1579
    Mpeg1Context *s1 = avctx->priv_data;
1580
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1581
    int ref, f_code;
1582

    
1583
    init_get_bits(&s->gb, buf, buf_size*8);
1584

    
1585
    ref = get_bits(&s->gb, 10); /* temporal ref */
1586
    s->pict_type = get_bits(&s->gb, 3);
1587
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1588

    
1589
    skip_bits(&s->gb, 16);
1590
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1591
        s->full_pel[0] = get_bits1(&s->gb);
1592
        f_code = get_bits(&s->gb, 3);
1593
        if (f_code == 0)
1594
            return -1;
1595
        s->mpeg_f_code[0][0] = f_code;
1596
        s->mpeg_f_code[0][1] = f_code;
1597
    }
1598
    if (s->pict_type == B_TYPE) {
1599
        s->full_pel[1] = get_bits1(&s->gb);
1600
        f_code = get_bits(&s->gb, 3);
1601
        if (f_code == 0)
1602
            return -1;
1603
        s->mpeg_f_code[1][0] = f_code;
1604
        s->mpeg_f_code[1][1] = f_code;
1605
    }
1606
    s->current_picture.pict_type= s->pict_type;
1607
    s->current_picture.key_frame= s->pict_type == I_TYPE;
1608
    
1609
    s->y_dc_scale = 8;
1610
    s->c_dc_scale = 8;
1611
    s->first_slice = 1;
1612
    return 0;
1613
}
1614

    
1615
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1616
{
1617
    int horiz_size_ext, vert_size_ext;
1618
    int bit_rate_ext, vbv_buf_ext;
1619
    int frame_rate_ext_n, frame_rate_ext_d;
1620
    float aspect;
1621

    
1622
    skip_bits(&s->gb, 8); /* profil and level */
1623
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1624
    skip_bits(&s->gb, 2); /* chroma_format */
1625
    horiz_size_ext = get_bits(&s->gb, 2);
1626
    vert_size_ext = get_bits(&s->gb, 2);
1627
    s->width |= (horiz_size_ext << 12);
1628
    s->height |= (vert_size_ext << 12);
1629
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1630
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1631
    skip_bits1(&s->gb); /* marker */
1632
    vbv_buf_ext = get_bits(&s->gb, 8);
1633
    s->low_delay = get_bits1(&s->gb);
1634
    frame_rate_ext_n = get_bits(&s->gb, 2);
1635
    frame_rate_ext_d = get_bits(&s->gb, 5);
1636
    if (frame_rate_ext_d >= 1)
1637
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1638
    dprintf("sequence extension\n");
1639
    s->mpeg2 = 1;
1640
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1641

    
1642
    aspect= mpeg2_aspect[s->aspect_ratio_info];
1643
    if(aspect>0.0)      s->avctx->aspect_ratio= s->width/(aspect*s->height);
1644
    else if(aspect<0.0) s->avctx->aspect_ratio= -1.0/aspect;
1645
}
1646

    
1647
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1648
{
1649
    int i, v, j;
1650

    
1651
    dprintf("matrix extension\n");
1652

    
1653
    if (get_bits1(&s->gb)) {
1654
        for(i=0;i<64;i++) {
1655
            v = get_bits(&s->gb, 8);
1656
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1657
            s->intra_matrix[j] = v;
1658
            s->chroma_intra_matrix[j] = v;
1659
        }
1660
    }
1661
    if (get_bits1(&s->gb)) {
1662
        for(i=0;i<64;i++) {
1663
            v = get_bits(&s->gb, 8);
1664
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1665
            s->inter_matrix[j] = v;
1666
            s->chroma_inter_matrix[j] = v;
1667
        }
1668
    }
1669
    if (get_bits1(&s->gb)) {
1670
        for(i=0;i<64;i++) {
1671
            v = get_bits(&s->gb, 8);
1672
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1673
            s->chroma_intra_matrix[j] = v;
1674
        }
1675
    }
1676
    if (get_bits1(&s->gb)) {
1677
        for(i=0;i<64;i++) {
1678
            v = get_bits(&s->gb, 8);
1679
            j= s->idct_permutation[ ff_zigzag_direct[i] ];
1680
            s->chroma_inter_matrix[j] = v;
1681
        }
1682
    }
1683
}
1684

    
1685
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1686
{
1687
    s->full_pel[0] = s->full_pel[1] = 0;
1688
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1689
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1690
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1691
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1692
    s->intra_dc_precision = get_bits(&s->gb, 2);
1693
    s->picture_structure = get_bits(&s->gb, 2);
1694
    s->top_field_first = get_bits1(&s->gb);
1695
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1696
    s->concealment_motion_vectors = get_bits1(&s->gb);
1697
    s->q_scale_type = get_bits1(&s->gb);
1698
    s->intra_vlc_format = get_bits1(&s->gb);
1699
    s->alternate_scan = get_bits1(&s->gb);
1700
    s->repeat_first_field = get_bits1(&s->gb);
1701
    s->chroma_420_type = get_bits1(&s->gb);
1702
    s->progressive_frame = get_bits1(&s->gb);
1703
    
1704
    if(s->alternate_scan){
1705
        ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
1706
        ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
1707
        ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
1708
        ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1709
    }else{
1710
        ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
1711
        ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
1712
        ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
1713
        ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1714
    }
1715
    
1716
    /* composite display not parsed */
1717
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1718
    dprintf("picture_structure=%d\n", s->picture_structure);
1719
    dprintf("top field first=%d\n", s->top_field_first);
1720
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1721
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1722
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1723
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1724
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1725
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1726
}
1727

    
1728
static void mpeg_decode_extension(AVCodecContext *avctx, 
1729
                                  uint8_t *buf, int buf_size)
1730
{
1731
    Mpeg1Context *s1 = avctx->priv_data;
1732
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1733
    int ext_type;
1734

    
1735
    init_get_bits(&s->gb, buf, buf_size*8);
1736
    
1737
    ext_type = get_bits(&s->gb, 4);
1738
    switch(ext_type) {
1739
    case 0x1:
1740
        /* sequence ext */
1741
        mpeg_decode_sequence_extension(s);
1742
        break;
1743
    case 0x3:
1744
        /* quant matrix extension */
1745
        mpeg_decode_quant_matrix_extension(s);
1746
        break;
1747
    case 0x8:
1748
        /* picture extension */
1749
        mpeg_decode_picture_coding_extension(s);
1750
        break;
1751
    }
1752
}
1753

    
1754
#define DECODE_SLICE_FATAL_ERROR -2
1755
#define DECODE_SLICE_ERROR -1
1756
#define DECODE_SLICE_OK 0
1757
#define DECODE_SLICE_EOP 1
1758

    
1759
/**
1760
 * decodes a slice.
1761
 * @return DECODE_SLICE_FATAL_ERROR if a non recoverable error occured<br>
1762
 *         DECODE_SLICE_ERROR if the slice is damaged<br>
1763
 *         DECODE_SLICE_OK if this slice is ok<br>
1764
 *         DECODE_SLICE_EOP if the end of the picture is reached
1765
 */
1766
static int mpeg_decode_slice(AVCodecContext *avctx, 
1767
                              AVFrame *pict,
1768
                              int start_code,
1769
                              uint8_t *buf, int buf_size)
1770
{
1771
    Mpeg1Context *s1 = avctx->priv_data;
1772
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1773
    int ret;
1774

    
1775
    start_code = (start_code - 1) & 0xff;
1776
    if (start_code >= s->mb_height){
1777
        fprintf(stderr, "slice below image (%d >= %d)\n", start_code, s->mb_height);
1778
        return DECODE_SLICE_ERROR;
1779
    }
1780
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1781
    s->last_dc[1] = s->last_dc[0];
1782
    s->last_dc[2] = s->last_dc[0];
1783
    memset(s->last_mv, 0, sizeof(s->last_mv));
1784
    /* start frame decoding */
1785
    if (s->first_slice) {
1786
        s->first_slice = 0;
1787
        if(MPV_frame_start(s, avctx) < 0)
1788
            return DECODE_SLICE_FATAL_ERROR;
1789
            
1790
        if(s->avctx->debug&FF_DEBUG_PICT_INFO){
1791
             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", 
1792
                 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],
1793
                 s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
1794
                 s->progressive_sequence ? "pro" :"", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", 
1795
                 s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
1796
                 s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
1797
        }
1798
    }
1799

    
1800
    init_get_bits(&s->gb, buf, buf_size*8);
1801

    
1802
    s->qscale = get_qscale(s);
1803
    /* extra slice info */
1804
    while (get_bits1(&s->gb) != 0) {
1805
        skip_bits(&s->gb, 8);
1806
    }
1807

    
1808
    s->mb_x=0;
1809
    for(;;) {
1810
        int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1811
        if (code < 0)
1812
            return -1; /* error = end of slice, but empty slice is bad or?*/
1813
        if (code >= 33) {
1814
            if (code == 33) {
1815
                s->mb_x += 33;
1816
            }
1817
            /* otherwise, stuffing, nothing to do */
1818
        } else {
1819
            s->mb_x += code;
1820
            break;
1821
        }
1822
    }
1823
    s->mb_y = start_code;
1824
    s->mb_incr= 1;
1825

    
1826
    for(;;) {
1827
        s->dsp.clear_blocks(s->block[0]);
1828
        
1829
        ret = mpeg_decode_mb(s, s->block);
1830
        dprintf("ret=%d\n", ret);
1831
        if (ret < 0)
1832
            return -1;
1833
    
1834
        MPV_decode_mb(s, s->block);
1835

    
1836
        if (++s->mb_x >= s->mb_width) {
1837
            ff_draw_horiz_band(s);
1838

    
1839
            s->mb_x = 0;
1840
            s->mb_y++;
1841
            PRINT_QP("%s", "\n");
1842
        }
1843
        PRINT_QP("%2d", s->qscale);
1844

    
1845
        /* skip mb handling */
1846
        if (s->mb_incr == 0) {
1847
            /* read again increment */
1848
            s->mb_incr = 1;
1849
            for(;;) {
1850
                int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1851
                if (code < 0)
1852
                    goto eos; /* error = end of slice */
1853
                if (code >= 33) {
1854
                    if (code == 33) {
1855
                        s->mb_incr += 33;
1856
                    }
1857
                    /* otherwise, stuffing, nothing to do */
1858
                } else {
1859
                    s->mb_incr += code;
1860
                    break;
1861
                }
1862
            }
1863
        }
1864
        if(s->mb_y >= s->mb_height){
1865
            fprintf(stderr, "slice too long\n");
1866
            return DECODE_SLICE_ERROR;
1867
        }
1868
    }
1869
eos: //end of slice
1870
    
1871
    emms_c();
1872

    
1873
    /* end of slice reached */
1874
    if (/*s->mb_x == 0 &&*/
1875
        s->mb_y == s->mb_height) {
1876
        /* end of image */
1877

    
1878
        if(s->mpeg2)
1879
            s->qscale >>=1;
1880

    
1881
        MPV_frame_end(s);
1882

    
1883
        if (s->pict_type == B_TYPE || s->low_delay) {
1884
            *pict= *(AVFrame*)&s->current_picture;
1885
        } else {
1886
            s->picture_number++;
1887
            /* latency of 1 frame for I and P frames */
1888
            /* XXX: use another variable than picture_number */
1889
            if (s->last_picture.data[0] == NULL) {
1890
                return DECODE_SLICE_OK;
1891
            } else {
1892
                *pict= *(AVFrame*)&s->last_picture;
1893
            }
1894
        }
1895
        return DECODE_SLICE_EOP;
1896
    } else {
1897
        return DECODE_SLICE_OK;
1898
    }
1899
}
1900

    
1901
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1902
                                 uint8_t *buf, int buf_size)
1903
{
1904
    Mpeg1Context *s1 = avctx->priv_data;
1905
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1906
    int width, height, i, v, j;
1907
    float aspect;
1908

    
1909
    init_get_bits(&s->gb, buf, buf_size*8);
1910

    
1911
    width = get_bits(&s->gb, 12);
1912
    height = get_bits(&s->gb, 12);
1913
    s->aspect_ratio_info= get_bits(&s->gb, 4);
1914
    if(!s->mpeg2){
1915
        aspect= mpeg1_aspect[s->aspect_ratio_info];
1916
        if(aspect!=0.0) avctx->aspect_ratio= width/(aspect*height);
1917
    }
1918

    
1919
    s->frame_rate_index = get_bits(&s->gb, 4);
1920
    if (s->frame_rate_index == 0)
1921
        return -1;
1922
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1923
    if (get_bits1(&s->gb) == 0) /* marker */
1924
        return -1;
1925
    if (width <= 0 || height <= 0 ||
1926
        (width % 2) != 0 || (height % 2) != 0)
1927
        return -1;
1928
    if (width != s->width ||
1929
        height != s->height) {
1930
        /* start new mpeg1 context decoding */
1931
        s->out_format = FMT_MPEG1;
1932
        if (s1->mpeg_enc_ctx_allocated) {
1933
            MPV_common_end(s);
1934
        }
1935
        s->width = width;
1936
        s->height = height;
1937
        avctx->has_b_frames= 1;
1938
        s->avctx = avctx;
1939
        avctx->width = width;
1940
        avctx->height = height;
1941
        if (s->frame_rate_index >= 9) {
1942
            /* at least give a valid frame rate (some old mpeg1 have this) */
1943
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1944
        } else {
1945
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1946
        }
1947
        s->frame_rate = avctx->frame_rate;
1948
        avctx->bit_rate = s->bit_rate;
1949
        
1950
        if (MPV_common_init(s) < 0)
1951
            return -1;
1952
        s1->mpeg_enc_ctx_allocated = 1;
1953
    }
1954

    
1955
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1956
    skip_bits(&s->gb, 1);
1957

    
1958
    /* get matrix */
1959
    if (get_bits1(&s->gb)) {
1960
        for(i=0;i<64;i++) {
1961
            v = get_bits(&s->gb, 8);
1962
            j = s->intra_scantable.permutated[i];
1963
            s->intra_matrix[j] = v;
1964
            s->chroma_intra_matrix[j] = v;
1965
        }
1966
#ifdef DEBUG
1967
        dprintf("intra matrix present\n");
1968
        for(i=0;i<64;i++)
1969
            dprintf(" %d", s->intra_matrix[s->intra_scantable.permutated[i]]);
1970
        printf("\n");
1971
#endif
1972
    } else {
1973
        for(i=0;i<64;i++) {
1974
            int j= s->idct_permutation[i];
1975
            v = ff_mpeg1_default_intra_matrix[i];
1976
            s->intra_matrix[j] = v;
1977
            s->chroma_intra_matrix[j] = v;
1978
        }
1979
    }
1980
    if (get_bits1(&s->gb)) {
1981
        for(i=0;i<64;i++) {
1982
            v = get_bits(&s->gb, 8);
1983
            j = s->intra_scantable.permutated[i];
1984
            s->inter_matrix[j] = v;
1985
            s->chroma_inter_matrix[j] = v;
1986
        }
1987
#ifdef DEBUG
1988
        dprintf("non intra matrix present\n");
1989
        for(i=0;i<64;i++)
1990
            dprintf(" %d", s->inter_matrix[s->intra_scantable.permutated[i]]);
1991
        printf("\n");
1992
#endif
1993
    } else {
1994
        for(i=0;i<64;i++) {
1995
            int j= s->idct_permutation[i];
1996
            v = ff_mpeg1_default_non_intra_matrix[i];
1997
            s->inter_matrix[j] = v;
1998
            s->chroma_inter_matrix[j] = v;
1999
        }
2000
    }
2001

    
2002
    /* we set mpeg2 parameters so that it emulates mpeg1 */
2003
    s->progressive_sequence = 1;
2004
    s->progressive_frame = 1;
2005
    s->picture_structure = PICT_FRAME;
2006
    s->frame_pred_frame_dct = 1;
2007
    s->mpeg2 = 0;
2008
    avctx->sub_id = 1; /* indicates mpeg1 */
2009
    return 0;
2010
}
2011

    
2012
/* handle buffering and image synchronisation */
2013
static int mpeg_decode_frame(AVCodecContext *avctx, 
2014
                             void *data, int *data_size,
2015
                             uint8_t *buf, int buf_size)
2016
{
2017
    Mpeg1Context *s = avctx->priv_data;
2018
    uint8_t *buf_end, *buf_ptr, *buf_start;
2019
    int len, start_code_found, ret, code, start_code, input_size;
2020
    AVFrame *picture = data;
2021
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
2022
            
2023
    dprintf("fill_buffer\n");
2024

    
2025
    *data_size = 0;
2026

    
2027
    /* special case for last picture */
2028
    if (buf_size == 0) {
2029
        if (s2->picture_number > 0) {
2030
            *picture= *(AVFrame*)&s2->next_picture;
2031

    
2032
            *data_size = sizeof(AVFrame);
2033
        }
2034
        return 0;
2035
    }
2036

    
2037
    buf_ptr = buf;
2038
    buf_end = buf + buf_size;
2039

    
2040
#if 0    
2041
    if (s->repeat_field % 2 == 1) { 
2042
        s->repeat_field++;
2043
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
2044
        //        s2->picture_number, s->repeat_field);
2045
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
2046
            *data_size = sizeof(AVPicture);
2047
            goto the_end;
2048
        }
2049
    }
2050
#endif
2051
    while (buf_ptr < buf_end) {
2052
        buf_start = buf_ptr;
2053
        /* find start next code */
2054
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
2055
        if (code >= 0) {
2056
            start_code_found = 1;
2057
        } else {
2058
            start_code_found = 0;
2059
        }
2060
        /* copy to buffer */
2061
        len = buf_ptr - buf_start;
2062
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
2063
            /* data too big : flush */
2064
            s->buf_ptr = s->buffer;
2065
            if (start_code_found)
2066
                s->start_code = code;
2067
        } else {
2068
            memcpy(s->buf_ptr, buf_start, len);
2069
            s->buf_ptr += len;
2070
            if(   (!(s2->flags&CODEC_FLAG_TRUNCATED)) && (!start_code_found) 
2071
               && s->buf_ptr+4<s->buffer+s->buffer_size){
2072
                start_code_found= 1;
2073
                code= 0x1FF;
2074
                s->header_state=0xFF;
2075
                s->buf_ptr[0]=0;
2076
                s->buf_ptr[1]=0;
2077
                s->buf_ptr[2]=1;
2078
                s->buf_ptr[3]=0xFF;
2079
                s->buf_ptr+=4;
2080
            }
2081
            if (start_code_found) {
2082
                /* prepare data for next start code */
2083
                input_size = s->buf_ptr - s->buffer;
2084
                start_code = s->start_code;
2085
                s->buf_ptr = s->buffer;
2086
                s->start_code = code;
2087
                switch(start_code) {
2088
                case SEQ_START_CODE:
2089
                    mpeg1_decode_sequence(avctx, s->buffer, 
2090
                                          input_size);
2091
                    break;
2092
                            
2093
                case PICTURE_START_CODE:
2094
                    /* we have a complete image : we try to decompress it */
2095
                    mpeg1_decode_picture(avctx, 
2096
                                         s->buffer, input_size);
2097
                    break;
2098
                case EXT_START_CODE:
2099
                    mpeg_decode_extension(avctx,
2100
                                          s->buffer, input_size);
2101
                    break;
2102
                default:
2103
                    if (start_code >= SLICE_MIN_START_CODE &&
2104
                        start_code <= SLICE_MAX_START_CODE) {
2105
                        
2106
                        /* skip b frames if we dont have reference frames */
2107
                        if(s2->last_picture.data[0]==NULL && s2->pict_type==B_TYPE) break;
2108
                        /* skip b frames if we are in a hurry */
2109
                        if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
2110
                        /* skip everything if we are in a hurry>=5 */
2111
                        if(avctx->hurry_up>=5) break;
2112

    
2113
                        ret = mpeg_decode_slice(avctx, picture,
2114
                                                start_code, s->buffer, input_size);
2115
                        if (ret == DECODE_SLICE_EOP) {
2116
                            /* got a picture: exit */
2117
                            /* first check if we must repeat the frame */
2118
                            avctx->repeat_pict = 0;
2119
#if 0
2120
                            if (s2->progressive_frame && s2->repeat_first_field) {
2121
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
2122
                                //s2->repeat_first_field = 0;
2123
                                //s2->progressive_frame = 0;
2124
                                if (++s->repeat_field > 2)
2125
                                    s->repeat_field = 0;
2126
                                avctx->repeat_pict = 1;
2127
                            }
2128
#endif                      
2129
                            if (s2->repeat_first_field) {
2130
                                if (s2->progressive_sequence) {
2131
                                    if (s2->top_field_first)
2132
                                        avctx->repeat_pict = 4;
2133
                                    else
2134
                                        avctx->repeat_pict = 2;
2135
                                } else if (s2->progressive_frame) {
2136
                                    avctx->repeat_pict = 1;
2137
                                }
2138
                            }         
2139
                            *data_size = sizeof(AVPicture);
2140
                            goto the_end;
2141
                        }else if(ret<0){
2142
                            fprintf(stderr,"Error while decoding slice\n");
2143
                            if(ret==DECODE_SLICE_FATAL_ERROR) return -1;
2144
                        }
2145
                    }
2146
                    break;
2147
                }
2148
            }
2149
        }
2150
    }
2151
 the_end:
2152
    return buf_ptr - buf;
2153
}
2154

    
2155
static int mpeg_decode_end(AVCodecContext *avctx)
2156
{
2157
    Mpeg1Context *s = avctx->priv_data;
2158

    
2159
    if (s->mpeg_enc_ctx_allocated)
2160
        MPV_common_end(&s->mpeg_enc_ctx);
2161
    return 0;
2162
}
2163

    
2164
AVCodec mpeg_decoder = {
2165
    "mpegvideo",
2166
    CODEC_TYPE_VIDEO,
2167
    CODEC_ID_MPEG1VIDEO,
2168
    sizeof(Mpeg1Context),
2169
    mpeg_decode_init,
2170
    NULL,
2171
    mpeg_decode_end,
2172
    mpeg_decode_frame,
2173
    CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED,
2174
};