Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg12.c @ 9ac7ecd6

History | View | Annotate | Download (55.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
/* Start codes. */
27
#define SEQ_END_CODE                0x000001b7
28
#define SEQ_START_CODE                0x000001b3
29
#define GOP_START_CODE                0x000001b8
30
#define PICTURE_START_CODE        0x00000100
31
#define SLICE_MIN_START_CODE        0x00000101
32
#define SLICE_MAX_START_CODE        0x000001af
33
#define EXT_START_CODE                0x000001b5
34
#define USER_START_CODE                0x000001b2
35

    
36
#define DC_VLC_BITS 9
37
#define MV_VLC_BITS 9
38
#define MBINCR_VLC_BITS 9
39
#define MB_PAT_VLC_BITS 9
40
#define MB_PTYPE_VLC_BITS 6
41
#define MB_BTYPE_VLC_BITS 6
42
#define TEX_VLC_BITS 9
43

    
44
static void mpeg1_encode_block(MpegEncContext *s, 
45
                         DCTELEM *block, 
46
                         int component);
47
static void mpeg1_encode_motion(MpegEncContext *s, int val);
48
static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
49
static int mpeg1_decode_block(MpegEncContext *s, 
50
                              DCTELEM *block, 
51
                              int n);
52
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
53
                                        DCTELEM *block, 
54
                                        int n);
55
static int mpeg2_decode_block_intra(MpegEncContext *s, 
56
                                    DCTELEM *block, 
57
                                    int n);
58
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
59

    
60
static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
61
static UINT8 fcode_tab[MAX_MV*2+1];
62

    
63
static void init_2d_vlc_rl(RLTable *rl)
64
{
65
    int i, q;
66
    
67
    init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
68
             &rl->table_vlc[0][1], 4, 2,
69
             &rl->table_vlc[0][0], 4, 2);
70

    
71
    
72
    rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
73
    for(i=0; i<rl->vlc.table_size; i++){
74
        int code= rl->vlc.table[i][0];
75
        int len = rl->vlc.table[i][1];
76
        int level, run;
77
    
78
        if(len==0){ // illegal code
79
            run= 65;
80
            level= MAX_LEVEL;
81
        }else if(len<0){ //more bits needed
82
            run= 0;
83
            level= code;
84
        }else{
85
            if(code==rl->n){ //esc
86
                run= 65;
87
                level= 0;
88
            }else if(code==rl->n+1){ //eob
89
                run= 192;
90
                level= 1;
91
            }else{
92
                run=   rl->table_run  [code] + 1;
93
                level= rl->table_level[code];
94
            }
95
        }
96
        rl->rl_vlc[0][i].len= len;
97
        rl->rl_vlc[0][i].level= level;
98
        rl->rl_vlc[0][i].run= run;
99
    }
100
}
101

    
102

    
103
static void put_header(MpegEncContext *s, int header)
104
{
105
    align_put_bits(&s->pb);
106
    put_bits(&s->pb, 16, header>>16);
107
    put_bits(&s->pb, 16, header&0xFFFF);
108
}
109

    
110
/* put sequence header if needed */
111
static void mpeg1_encode_sequence_header(MpegEncContext *s)
112
{
113
        unsigned int vbv_buffer_size;
114
        unsigned int fps, v;
115
        int n;
116
        UINT64 time_code;
117
        
118
        if (s->picture_in_gop_number == 0) {
119
            /* mpeg1 header repeated every gop */
120
            put_header(s, SEQ_START_CODE);
121
            
122
            /* search closest frame rate */
123
            {
124
                int i, dmin, d;
125
                s->frame_rate_index = 0;
126
                dmin = 0x7fffffff;
127
                for(i=1;i<9;i++) {
128
                    d = abs(s->frame_rate - frame_rate_tab[i]);
129
                    if (d < dmin) {
130
                        dmin = d;
131
                        s->frame_rate_index = i;
132
                    }
133
                }
134
            }
135
 
136
            put_bits(&s->pb, 12, s->width);
137
            put_bits(&s->pb, 12, s->height);
138
            put_bits(&s->pb, 4, 1); /* 1/1 aspect ratio */
139
            put_bits(&s->pb, 4, s->frame_rate_index);
140
            v = s->bit_rate / 400;
141
            if (v > 0x3ffff)
142
                v = 0x3ffff;
143
            put_bits(&s->pb, 18, v);
144
            put_bits(&s->pb, 1, 1); /* marker */
145
            /* vbv buffer size: slightly greater than an I frame. We add
146
               some margin just in case */
147
            vbv_buffer_size = (3 * s->I_frame_bits) / (2 * 8);
148
            put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
149
            put_bits(&s->pb, 1, 1); /* constrained parameter flag */
150
            put_bits(&s->pb, 1, 0); /* no custom intra matrix */
151
            put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
152

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

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

    
180
        }
181
}
182

    
183

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
382
    common_init(s);
383

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
853
                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
854
                                                s->last_mv[i][0][0]);
855
                        s->last_mv[i][0][0] = mx;
856
                        s->last_mv[i][1][0] = mx;
857
                        dmx = get_dmv(s);
858
                        my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
859
                                                s->last_mv[i][0][1] >> 1);
860
                        dmy = get_dmv(s);
861
                        s->mv_type = MV_TYPE_DMV;
862
                        /* XXX: totally broken */
863
                        if (s->picture_structure == PICT_FRAME) {
864
                            s->last_mv[i][0][1] = my << 1;
865
                            s->last_mv[i][1][1] = my << 1;
866

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

    
894
    if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
895
        skip_bits1(&s->gb); /* marker */
896
    }
897
    
898
    if (mb_type & MB_PAT) {
899
        cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
900
        if (cbp < 0){
901
            fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
902
            return -1;
903
        }
904
        cbp++;
905
    }
906
    dprintf("cbp=%x\n", cbp);
907

    
908
    if (s->mpeg2) {
909
        if (s->mb_intra) {
910
            for(i=0;i<6;i++) {
911
                if (cbp & (1 << (5 - i))) {
912
                    if (mpeg2_decode_block_intra(s, block[i], i) < 0)
913
                        return -1;
914
                } else {
915
                    s->block_last_index[i] = -1;
916
                }
917
            }
918
        } else {
919
            for(i=0;i<6;i++) {
920
                if (cbp & (1 << (5 - i))) {
921
                    if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
922
                        return -1;
923
                } else {
924
                    s->block_last_index[i] = -1;
925
                }
926
            }
927
        }
928
    } else {
929
        for(i=0;i<6;i++) {
930
            if (cbp & (1 << (5 - i))) {
931
                if (mpeg1_decode_block(s, block[i], i) < 0)
932
                    return -1;
933
            } else {
934
                s->block_last_index[i] = -1;
935
            }
936
        }
937
    }
938
    return 0;
939
}
940

    
941
/* as h263, but only 17 codes */
942
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
943
{
944
    int code, sign, val, m, l, shift;
945

    
946
    code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
947
    if (code < 0) {
948
        return 0xffff;
949
    }
950
    if (code == 0) {
951
        return pred;
952
    }
953
    sign = get_bits1(&s->gb);
954
    shift = fcode - 1;
955
    val = (code - 1) << shift;
956
    if (shift > 0)
957
        val |= get_bits(&s->gb, shift);
958
    val++;
959
    if (sign)
960
        val = -val;
961
    val += pred;
962
    
963
    /* modulo decoding */
964
    l = (1 << shift) * 16;
965
    m = 2 * l;
966
    if (val < -l) {
967
        val += m;
968
    } else if (val >= l) {
969
        val -= m;
970
    }
971
    return val;
972
}
973

    
974
static inline int decode_dc(MpegEncContext *s, int component)
975
{
976
    int code, diff;
977

    
978
    if (component == 0) {
979
        code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
980
    } else {
981
        code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
982
    }
983
    if (code < 0){
984
        fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
985
        return 0xffff;
986
    }
987
    if (code == 0) {
988
        diff = 0;
989
    } else {
990
        diff = get_bits(&s->gb, code);
991
        if ((diff & (1 << (code - 1))) == 0) 
992
            diff = (-1 << code) | (diff + 1);
993
    }
994
    return diff;
995
}
996

    
997
static int mpeg1_decode_block(MpegEncContext *s, 
998
                               DCTELEM *block, 
999
                               int n)
1000
{
1001
    int level, dc, diff, i, j, run;
1002
    int code, component;
1003
    RLTable *rl = &rl_mpeg1;
1004

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

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

    
1071
/* Also does unquantization here, since I will never support mpeg2
1072
   encoding */
1073
static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1074
                                        DCTELEM *block, 
1075
                                        int n)
1076
{
1077
    int level, i, j, run;
1078
    int code;
1079
    RLTable *rl = &rl_mpeg1;
1080
    const UINT8 *scan_table;
1081
    const UINT16 *matrix;
1082
    int mismatch;
1083

    
1084
    if (s->alternate_scan)
1085
        scan_table = ff_alternate_vertical_scan;
1086
    else
1087
        scan_table = zigzag_direct;
1088
    mismatch = 1;
1089

    
1090
    {
1091
        int v;
1092
        OPEN_READER(re, &s->gb);
1093
        i = 0;
1094
        if (n < 4)
1095
            matrix = s->inter_matrix;
1096
        else
1097
            matrix = s->chroma_inter_matrix;
1098

    
1099
        /* special case for the first coef. no need to add a second vlc table */
1100
        UPDATE_CACHE(re, &s->gb);
1101
        v= SHOW_UBITS(re, &s->gb, 2);
1102
        if (v & 2) {
1103
            run = 0;
1104
            level = 1 - ((v & 1) << 1);
1105
            SKIP_BITS(re, &s->gb, 2);
1106
            CLOSE_READER(re, &s->gb);
1107
            goto add_coef;
1108
        }
1109
        CLOSE_READER(re, &s->gb);
1110
    }
1111

    
1112
    /* now quantify & encode AC coefs */
1113
    for(;;) {
1114
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1115
        if (code < 0){
1116
            fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1117
            return -1;
1118
        }
1119
        if (code == 112) {
1120
            break;
1121
        } else if (code == 111) {
1122
            /* escape */
1123
            run = get_bits(&s->gb, 6);
1124
            level = get_bits(&s->gb, 12);
1125
            level = (level << 20) >> 20;
1126
        } else {
1127
            run = rl->table_run[code];
1128
            level = rl->table_level[code];
1129
            if (get_bits1(&s->gb))
1130
                level = -level;
1131
        }
1132
        i += run;
1133
        if (i >= 64){
1134
            fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1135
            return -1;
1136
        }
1137
    add_coef:
1138
        j = scan_table[i];
1139
        dprintf("%d: run=%d level=%d\n", n, run, level);
1140
        /* XXX: optimize */
1141
        if (level > 0) {
1142
            level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1143
        } else {
1144
            level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1145
            level = -level;
1146
        }
1147
        /* XXX: is it really necessary to saturate since the encoder
1148
           knows whats going on ? */
1149
        mismatch ^= level;
1150
        block[j] = level;
1151
        i++;
1152
    }
1153
    block[63] ^= (mismatch & 1);
1154
    s->block_last_index[n] = i;
1155
    return 0;
1156
}
1157

    
1158
static int mpeg2_decode_block_intra(MpegEncContext *s, 
1159
                                    DCTELEM *block, 
1160
                                    int n)
1161
{
1162
    int level, dc, diff, i, j, run;
1163
    int code, component;
1164
    RLTable *rl;
1165
    const UINT8 *scan_table;
1166
    const UINT16 *matrix;
1167
    int mismatch;
1168

    
1169
    if (s->alternate_scan)
1170
        scan_table = ff_alternate_vertical_scan;
1171
    else
1172
        scan_table = zigzag_direct;
1173

    
1174
    /* DC coef */
1175
    component = (n <= 3 ? 0 : n - 4 + 1);
1176
    diff = decode_dc(s, component);
1177
    if (diff >= 0xffff)
1178
        return -1;
1179
    dc = s->last_dc[component];
1180
    dc += diff;
1181
    s->last_dc[component] = dc;
1182
    block[0] = dc << (3 - s->intra_dc_precision);
1183
    dprintf("dc=%d\n", block[0]);
1184
    mismatch = block[0] ^ 1;
1185
    i = 1;
1186
    if (s->intra_vlc_format)
1187
        rl = &rl_mpeg2;
1188
    else
1189
        rl = &rl_mpeg1;
1190
    if (n < 4) 
1191
        matrix = s->intra_matrix;
1192
    else
1193
        matrix = s->chroma_intra_matrix;
1194

    
1195
    /* now quantify & encode AC coefs */
1196
    for(;;) {
1197
        code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1198
        if (code < 0){
1199
            fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1200
            return -1;
1201
        }
1202
        if (code == 112) {
1203
            break;
1204
        } else if (code == 111) {
1205
            /* escape */
1206
            run = get_bits(&s->gb, 6);
1207
            level = get_bits(&s->gb, 12);
1208
            level = (level << 20) >> 20;
1209
        } else {
1210
            run = rl->table_run[code];
1211
            level = rl->table_level[code];
1212
            if (get_bits1(&s->gb))
1213
                level = -level;
1214
        }
1215
        i += run;
1216
        if (i >= 64){
1217
            fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1218
            return -1;
1219
        }
1220
        j = scan_table[i];
1221
        dprintf("%d: run=%d level=%d\n", n, run, level);
1222
        level = (level * s->qscale * matrix[j]) / 16;
1223
        /* XXX: is it really necessary to saturate since the encoder
1224
           knows whats going on ? */
1225
        mismatch ^= level;
1226
        block[j] = level;
1227
        i++;
1228
    }
1229
    block[63] ^= (mismatch & 1);
1230
    s->block_last_index[n] = i;
1231
    return 0;
1232
}
1233

    
1234
/* compressed picture size */
1235
#define PICTURE_BUFFER_SIZE 100000
1236

    
1237
typedef struct Mpeg1Context {
1238
    MpegEncContext mpeg_enc_ctx;
1239
    UINT32 header_state;
1240
    int start_code; /* current start code */
1241
    UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1242
    UINT8 *buf_ptr;
1243
    int buffer_size;
1244
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1245
    int repeat_field; /* true if we must repeat the field */
1246
} Mpeg1Context;
1247

    
1248
static int mpeg_decode_init(AVCodecContext *avctx)
1249
{
1250
    Mpeg1Context *s = avctx->priv_data;
1251
    
1252
    s->mpeg_enc_ctx.flags= avctx->flags;
1253
    common_init(&s->mpeg_enc_ctx);
1254

    
1255
    s->header_state = 0xff;
1256
    s->mpeg_enc_ctx_allocated = 0;
1257
    s->buffer_size = PICTURE_BUFFER_SIZE;
1258
    s->start_code = -1;
1259
    s->buf_ptr = s->buffer;
1260
    s->mpeg_enc_ctx.picture_number = 0;
1261
    s->repeat_field = 0;
1262
    s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1263
    avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1264
    return 0;
1265
}
1266

    
1267
/* return the 8 bit start code value and update the search
1268
   state. Return -1 if no start code found */
1269
static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1270
                           UINT32 *header_state)
1271
{
1272
    UINT8 *buf_ptr;
1273
    unsigned int state, v;
1274
    int val;
1275

    
1276
    state = *header_state;
1277
    buf_ptr = *pbuf_ptr;
1278
    while (buf_ptr < buf_end) {
1279
        v = *buf_ptr++;
1280
        if (state == 0x000001) {
1281
            state = ((state << 8) | v) & 0xffffff;
1282
            val = state;
1283
            goto found;
1284
        }
1285
        state = ((state << 8) | v) & 0xffffff;
1286
    }
1287
    val = -1;
1288
 found:
1289
    *pbuf_ptr = buf_ptr;
1290
    *header_state = state;
1291
    return val;
1292
}
1293

    
1294
static int mpeg1_decode_picture(AVCodecContext *avctx, 
1295
                                UINT8 *buf, int buf_size)
1296
{
1297
    Mpeg1Context *s1 = avctx->priv_data;
1298
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1299
    int ref, f_code;
1300

    
1301
    init_get_bits(&s->gb, buf, buf_size);
1302

    
1303
    ref = get_bits(&s->gb, 10); /* temporal ref */
1304
    s->pict_type = get_bits(&s->gb, 3);
1305
    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1306
    skip_bits(&s->gb, 16);
1307
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1308
        s->full_pel[0] = get_bits1(&s->gb);
1309
        f_code = get_bits(&s->gb, 3);
1310
        if (f_code == 0)
1311
            return -1;
1312
        s->mpeg_f_code[0][0] = f_code;
1313
        s->mpeg_f_code[0][1] = f_code;
1314
    }
1315
    if (s->pict_type == B_TYPE) {
1316
        s->full_pel[1] = get_bits1(&s->gb);
1317
        f_code = get_bits(&s->gb, 3);
1318
        if (f_code == 0)
1319
            return -1;
1320
        s->mpeg_f_code[1][0] = f_code;
1321
        s->mpeg_f_code[1][1] = f_code;
1322
    }
1323
    s->y_dc_scale = 8;
1324
    s->c_dc_scale = 8;
1325
    s->first_slice = 1;
1326
    return 0;
1327
}
1328

    
1329
static void mpeg_decode_sequence_extension(MpegEncContext *s)
1330
{
1331
    int horiz_size_ext, vert_size_ext;
1332
    int bit_rate_ext, vbv_buf_ext, low_delay;
1333
    int frame_rate_ext_n, frame_rate_ext_d;
1334

    
1335
    skip_bits(&s->gb, 8); /* profil and level */
1336
    s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1337
    skip_bits(&s->gb, 2); /* chroma_format */
1338
    horiz_size_ext = get_bits(&s->gb, 2);
1339
    vert_size_ext = get_bits(&s->gb, 2);
1340
    s->width |= (horiz_size_ext << 12);
1341
    s->height |= (vert_size_ext << 12);
1342
    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1343
    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1344
    skip_bits1(&s->gb); /* marker */
1345
    vbv_buf_ext = get_bits(&s->gb, 8);
1346
    low_delay = get_bits1(&s->gb);
1347
    frame_rate_ext_n = get_bits(&s->gb, 2);
1348
    frame_rate_ext_d = get_bits(&s->gb, 5);
1349
    if (frame_rate_ext_d >= 1)
1350
        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1351
    dprintf("sequence extension\n");
1352
    s->mpeg2 = 1;
1353
    s->avctx->sub_id = 2; /* indicates mpeg2 found */
1354
}
1355

    
1356
static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1357
{
1358
    int i, v, j;
1359

    
1360
    dprintf("matrix extension\n");
1361

    
1362
    if (get_bits1(&s->gb)) {
1363
        for(i=0;i<64;i++) {
1364
            v = get_bits(&s->gb, 8);
1365
            j = zigzag_direct[i];
1366
            s->intra_matrix[j] = v;
1367
            s->chroma_intra_matrix[j] = v;
1368
        }
1369
    }
1370
    if (get_bits1(&s->gb)) {
1371
        for(i=0;i<64;i++) {
1372
            v = get_bits(&s->gb, 8);
1373
            j = zigzag_direct[i];
1374
            s->inter_matrix[j] = v;
1375
            s->chroma_inter_matrix[j] = v;
1376
        }
1377
    }
1378
    if (get_bits1(&s->gb)) {
1379
        for(i=0;i<64;i++) {
1380
            v = get_bits(&s->gb, 8);
1381
            j = zigzag_direct[i];
1382
            s->chroma_intra_matrix[j] = v;
1383
        }
1384
    }
1385
    if (get_bits1(&s->gb)) {
1386
        for(i=0;i<64;i++) {
1387
            v = get_bits(&s->gb, 8);
1388
            j = zigzag_direct[i];
1389
            s->chroma_inter_matrix[j] = v;
1390
        }
1391
    }
1392
}
1393

    
1394
static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1395
{
1396
    s->full_pel[0] = s->full_pel[1] = 0;
1397
    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1398
    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1399
    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1400
    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1401
    s->intra_dc_precision = get_bits(&s->gb, 2);
1402
    s->picture_structure = get_bits(&s->gb, 2);
1403
    s->top_field_first = get_bits1(&s->gb);
1404
    s->frame_pred_frame_dct = get_bits1(&s->gb);
1405
    s->concealment_motion_vectors = get_bits1(&s->gb);
1406
    s->q_scale_type = get_bits1(&s->gb);
1407
    s->intra_vlc_format = get_bits1(&s->gb);
1408
    s->alternate_scan = get_bits1(&s->gb);
1409
    s->repeat_first_field = get_bits1(&s->gb);
1410
    s->chroma_420_type = get_bits1(&s->gb);
1411
    s->progressive_frame = get_bits1(&s->gb);
1412
    /* composite display not parsed */
1413
    dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1414
    dprintf("picture_structure=%d\n", s->picture_structure);
1415
    dprintf("top field first=%d\n", s->top_field_first);
1416
    dprintf("repeat first field=%d\n", s->repeat_first_field);
1417
    dprintf("conceal=%d\n", s->concealment_motion_vectors);
1418
    dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1419
    dprintf("alternate_scan=%d\n", s->alternate_scan);
1420
    dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1421
    dprintf("progressive_frame=%d\n", s->progressive_frame);
1422
}
1423

    
1424
static void mpeg_decode_extension(AVCodecContext *avctx, 
1425
                                  UINT8 *buf, int buf_size)
1426
{
1427
    Mpeg1Context *s1 = avctx->priv_data;
1428
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1429
    int ext_type;
1430

    
1431
    init_get_bits(&s->gb, buf, buf_size);
1432
    
1433
    ext_type = get_bits(&s->gb, 4);
1434
    switch(ext_type) {
1435
    case 0x1:
1436
        /* sequence ext */
1437
        mpeg_decode_sequence_extension(s);
1438
        break;
1439
    case 0x3:
1440
        /* quant matrix extension */
1441
        mpeg_decode_quant_matrix_extension(s);
1442
        break;
1443
    case 0x8:
1444
        /* picture extension */
1445
        mpeg_decode_picture_coding_extension(s);
1446
        break;
1447
    }
1448
}
1449

    
1450
/* return 1 if end of frame */
1451
static int mpeg_decode_slice(AVCodecContext *avctx, 
1452
                              AVPicture *pict,
1453
                              int start_code,
1454
                              UINT8 *buf, int buf_size)
1455
{
1456
    Mpeg1Context *s1 = avctx->priv_data;
1457
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1458
    int ret;
1459

    
1460
    start_code = (start_code - 1) & 0xff;
1461
    if (start_code >= s->mb_height){
1462
        fprintf(stderr, "slice below image\n");
1463
        return -1;
1464
    }
1465
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1466
    s->last_dc[1] = s->last_dc[0];
1467
    s->last_dc[2] = s->last_dc[0];
1468
    memset(s->last_mv, 0, sizeof(s->last_mv));
1469
    s->mb_x = -1;
1470
    s->mb_y = start_code;
1471
    s->mb_incr = 0;
1472
    /* start frame decoding */
1473
    if (s->first_slice) {
1474
        s->first_slice = 0;
1475
        MPV_frame_start(s, avctx);
1476
    }
1477

    
1478
    init_get_bits(&s->gb, buf, buf_size);
1479

    
1480
    s->qscale = get_qscale(s);
1481
    /* extra slice info */
1482
    while (get_bits1(&s->gb) != 0) {
1483
        skip_bits(&s->gb, 8);
1484
    }
1485

    
1486
    for(;;) {
1487
        clear_blocks(s->block[0]);
1488
        emms_c();
1489
        ret = mpeg_decode_mb(s, s->block);
1490
        dprintf("ret=%d\n", ret);
1491
        if (ret < 0)
1492
            return -1;
1493
        if (ret == 1)
1494
            break;
1495
        MPV_decode_mb(s, s->block);
1496
    }
1497
    emms_c();
1498

    
1499
    /* end of slice reached */
1500
    if (s->mb_x == (s->mb_width - 1) &&
1501
        s->mb_y == (s->mb_height - 1)) {
1502
        /* end of image */
1503
        UINT8 **picture;
1504

    
1505
        MPV_frame_end(s);
1506

    
1507
        /* XXX: incorrect reported qscale for mpeg2 */
1508
        if (s->pict_type == B_TYPE) {
1509
            picture = s->current_picture;
1510
            avctx->quality = s->qscale;
1511
        } else {
1512
            /* latency of 1 frame for I and P frames */
1513
            /* XXX: use another variable than picture_number */
1514
            if (s->picture_number == 0) {
1515
                picture = NULL;
1516
            } else {
1517
                picture = s->last_picture;
1518
                avctx->quality = s->last_qscale;
1519
            }
1520
            s->last_qscale = s->qscale;
1521
            s->picture_number++;
1522
        }
1523
        if (picture) {
1524
            pict->data[0] = picture[0];
1525
            pict->data[1] = picture[1];
1526
            pict->data[2] = picture[2];
1527
            pict->linesize[0] = s->linesize;
1528
            pict->linesize[1] = s->uvlinesize;
1529
            pict->linesize[2] = s->uvlinesize;
1530
            return 1;
1531
        } else {
1532
            return 0;
1533
        }
1534
    } else {
1535
        return 0;
1536
    }
1537
}
1538

    
1539
static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1540
                                 UINT8 *buf, int buf_size)
1541
{
1542
    Mpeg1Context *s1 = avctx->priv_data;
1543
    MpegEncContext *s = &s1->mpeg_enc_ctx;
1544
    int width, height, i, v, j;
1545

    
1546
    init_get_bits(&s->gb, buf, buf_size);
1547

    
1548
    width = get_bits(&s->gb, 12);
1549
    height = get_bits(&s->gb, 12);
1550
    skip_bits(&s->gb, 4);
1551
    s->frame_rate_index = get_bits(&s->gb, 4);
1552
    if (s->frame_rate_index == 0)
1553
        return -1;
1554
    s->bit_rate = get_bits(&s->gb, 18) * 400;
1555
    if (get_bits1(&s->gb) == 0) /* marker */
1556
        return -1;
1557
    if (width <= 0 || height <= 0 ||
1558
        (width % 2) != 0 || (height % 2) != 0)
1559
        return -1;
1560
    if (width != s->width ||
1561
        height != s->height) {
1562
        /* start new mpeg1 context decoding */
1563
        s->out_format = FMT_MPEG1;
1564
        if (s1->mpeg_enc_ctx_allocated) {
1565
            MPV_common_end(s);
1566
        }
1567
        s->width = width;
1568
        s->height = height;
1569
        avctx->has_b_frames= s->has_b_frames = 1;
1570
        s->avctx = avctx;
1571
        avctx->width = width;
1572
        avctx->height = height;
1573
        if (s->frame_rate_index >= 9) {
1574
            /* at least give a valid frame rate (some old mpeg1 have this) */
1575
            avctx->frame_rate = 25 * FRAME_RATE_BASE;
1576
        } else {
1577
            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1578
        }
1579
        s->frame_rate = avctx->frame_rate;
1580
        avctx->bit_rate = s->bit_rate;
1581
        
1582
        if (MPV_common_init(s) < 0)
1583
            return -1;
1584
        mpeg1_init_vlc(s);
1585
        s1->mpeg_enc_ctx_allocated = 1;
1586
    }
1587

    
1588
    skip_bits(&s->gb, 10); /* vbv_buffer_size */
1589
    skip_bits(&s->gb, 1);
1590

    
1591
    /* get matrix */
1592
    if (get_bits1(&s->gb)) {
1593
        for(i=0;i<64;i++) {
1594
            v = get_bits(&s->gb, 8);
1595
            j = zigzag_direct[i];
1596
            s->intra_matrix[j] = v;
1597
            s->chroma_intra_matrix[j] = v;
1598
        }
1599
#ifdef DEBUG
1600
        dprintf("intra matrix present\n");
1601
        for(i=0;i<64;i++)
1602
            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1603
        printf("\n");
1604
#endif
1605
    } else {
1606
        for(i=0;i<64;i++) {
1607
            v = ff_mpeg1_default_intra_matrix[i];
1608
            s->intra_matrix[i] = v;
1609
            s->chroma_intra_matrix[i] = v;
1610
        }
1611
    }
1612
    if (get_bits1(&s->gb)) {
1613
        for(i=0;i<64;i++) {
1614
            v = get_bits(&s->gb, 8);
1615
            j = zigzag_direct[i];
1616
            s->inter_matrix[j] = v;
1617
            s->chroma_inter_matrix[j] = v;
1618
        }
1619
#ifdef DEBUG
1620
        dprintf("non intra matrix present\n");
1621
        for(i=0;i<64;i++)
1622
            dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1623
        printf("\n");
1624
#endif
1625
    } else {
1626
        for(i=0;i<64;i++) {
1627
            v = ff_mpeg1_default_non_intra_matrix[i];
1628
            s->inter_matrix[i] = v;
1629
            s->chroma_inter_matrix[i] = v;
1630
        }
1631
    }
1632

    
1633
    /* we set mpeg2 parameters so that it emulates mpeg1 */
1634
    s->progressive_sequence = 1;
1635
    s->progressive_frame = 1;
1636
    s->picture_structure = PICT_FRAME;
1637
    s->frame_pred_frame_dct = 1;
1638
    s->mpeg2 = 0;
1639
    avctx->sub_id = 1; /* indicates mpeg1 */
1640
    return 0;
1641
}
1642

    
1643
/* handle buffering and image synchronisation */
1644
static int mpeg_decode_frame(AVCodecContext *avctx, 
1645
                             void *data, int *data_size,
1646
                             UINT8 *buf, int buf_size)
1647
{
1648
    Mpeg1Context *s = avctx->priv_data;
1649
    UINT8 *buf_end, *buf_ptr, *buf_start;
1650
    int len, start_code_found, ret, code, start_code, input_size;
1651
    AVPicture *picture = data;
1652
    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1653
            
1654
    dprintf("fill_buffer\n");
1655

    
1656
    *data_size = 0;
1657

    
1658
    /* special case for last picture */
1659
    if (buf_size == 0) {
1660
        if (s2->picture_number > 0) {
1661
            picture->data[0] = s2->next_picture[0];
1662
            picture->data[1] = s2->next_picture[1];
1663
            picture->data[2] = s2->next_picture[2];
1664
            picture->linesize[0] = s2->linesize;
1665
            picture->linesize[1] = s2->uvlinesize;
1666
            picture->linesize[2] = s2->uvlinesize;
1667
            *data_size = sizeof(AVPicture);
1668
        }
1669
        return 0;
1670
    }
1671

    
1672
    buf_ptr = buf;
1673
    buf_end = buf + buf_size;
1674

    
1675
#if 0    
1676
    if (s->repeat_field % 2 == 1) { 
1677
        s->repeat_field++;
1678
        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1679
        //        s2->picture_number, s->repeat_field);
1680
        if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1681
            *data_size = sizeof(AVPicture);
1682
            goto the_end;
1683
        }
1684
    }
1685
#endif
1686
    while (buf_ptr < buf_end) {
1687
        buf_start = buf_ptr;
1688
        /* find start next code */
1689
        code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1690
        if (code >= 0) {
1691
            start_code_found = 1;
1692
        } else {
1693
            start_code_found = 0;
1694
        }
1695
        /* copy to buffer */
1696
        len = buf_ptr - buf_start;
1697
        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1698
            /* data too big : flush */
1699
            s->buf_ptr = s->buffer;
1700
            if (start_code_found)
1701
                s->start_code = code;
1702
        } else {
1703
            memcpy(s->buf_ptr, buf_start, len);
1704
            s->buf_ptr += len;
1705
            
1706
            if (start_code_found) {
1707
                /* prepare data for next start code */
1708
                input_size = s->buf_ptr - s->buffer;
1709
                start_code = s->start_code;
1710
                s->buf_ptr = s->buffer;
1711
                s->start_code = code;
1712
                switch(start_code) {
1713
                case SEQ_START_CODE:
1714
                    mpeg1_decode_sequence(avctx, s->buffer, 
1715
                                          input_size);
1716
                    break;
1717
                            
1718
                case PICTURE_START_CODE:
1719
                    /* we have a complete image : we try to decompress it */
1720
                    mpeg1_decode_picture(avctx, 
1721
                                         s->buffer, input_size);
1722
                    break;
1723
                case EXT_START_CODE:
1724
                    mpeg_decode_extension(avctx,
1725
                                          s->buffer, input_size);
1726
                    break;
1727
                default:
1728
                    if (start_code >= SLICE_MIN_START_CODE &&
1729
                        start_code <= SLICE_MAX_START_CODE) {
1730
                        ret = mpeg_decode_slice(avctx, picture,
1731
                                                start_code, s->buffer, input_size);
1732
                        if (ret == 1) {
1733
                            /* got a picture: exit */
1734
                            /* first check if we must repeat the frame */
1735
                            avctx->repeat_pict = 0;
1736
#if 0
1737
                            if (s2->progressive_frame && s2->repeat_first_field) {
1738
                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1739
                                //s2->repeat_first_field = 0;
1740
                                //s2->progressive_frame = 0;
1741
                                if (++s->repeat_field > 2)
1742
                                    s->repeat_field = 0;
1743
                                avctx->repeat_pict = 1;
1744
                            }
1745
#endif                      
1746
                            if (s2->repeat_first_field) {
1747
                                if (s2->progressive_sequence) {
1748
                                    if (s2->top_field_first)
1749
                                        avctx->repeat_pict = 4;
1750
                                    else
1751
                                        avctx->repeat_pict = 2;
1752
                                } else if (s2->progressive_frame) {
1753
                                    avctx->repeat_pict = 1;
1754
                                }
1755
                            }         
1756
                            *data_size = sizeof(AVPicture);
1757
                            goto the_end;
1758
                        }else if(ret==-1){
1759
                            printf("Error while decoding slice\n");
1760
                        }
1761
                    }
1762
                    break;
1763
                }
1764
            }
1765
        }
1766
    }
1767
 the_end:
1768
    return buf_ptr - buf;
1769
}
1770

    
1771
static int mpeg_decode_end(AVCodecContext *avctx)
1772
{
1773
    Mpeg1Context *s = avctx->priv_data;
1774

    
1775
    if (s->mpeg_enc_ctx_allocated)
1776
        MPV_common_end(&s->mpeg_enc_ctx);
1777
    return 0;
1778
}
1779

    
1780
AVCodec mpeg_decoder = {
1781
    "mpegvideo",
1782
    CODEC_TYPE_VIDEO,
1783
    CODEC_ID_MPEG1VIDEO,
1784
    sizeof(Mpeg1Context),
1785
    mpeg_decode_init,
1786
    NULL,
1787
    mpeg_decode_end,
1788
    mpeg_decode_frame,
1789
    CODEC_CAP_DR1,
1790
};