]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg12.c
fixing some 64bit bugs
[ffmpeg] / libavcodec / mpeg12.c
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==-1 /* first MB in a slice */ && s->mb_incr>1){
676         s->mb_x+= (s->mb_incr - 1) % s->mb_width;
677         s->mb_y+= (s->mb_incr - 1) / s->mb_width;
678         s->mb_incr= 1;
679     }
680
681     if (++s->mb_x >= s->mb_width) {
682         s->mb_x = 0;
683         if (s->mb_y >= (s->mb_height - 1)){
684             fprintf(stderr, "slice too long\n");
685             return -1;
686         }
687         s->mb_y++;
688     }
689     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
690
691     if (--s->mb_incr != 0) {
692         /* skip mb */
693         s->mb_intra = 0;
694         for(i=0;i<6;i++)
695             s->block_last_index[i] = -1;
696         s->mv_type = MV_TYPE_16X16;
697         if (s->pict_type == P_TYPE) {
698             /* if P type, zero motion vector is implied */
699             s->mv_dir = MV_DIR_FORWARD;
700             s->mv[0][0][0] = s->mv[0][0][1] = 0;
701             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
702             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
703         } else {
704             /* if B type, reuse previous vectors and directions */
705             s->mv[0][0][0] = s->last_mv[0][0][0];
706             s->mv[0][0][1] = s->last_mv[0][0][1];
707             s->mv[1][0][0] = s->last_mv[1][0][0];
708             s->mv[1][0][1] = s->last_mv[1][0][1];
709         }
710         s->mb_skiped = 1;
711         return 0;
712     }
713
714     switch(s->pict_type) {
715     default:
716     case I_TYPE:
717         if (get_bits1(&s->gb) == 0) {
718             if (get_bits1(&s->gb) == 0)
719                 return -1;
720             mb_type = MB_QUANT | MB_INTRA;
721         } else {
722             mb_type = MB_INTRA;
723         }
724         break;
725     case P_TYPE:
726         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
727         if (mb_type < 0){
728             fprintf(stderr, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
729             return -1;
730         }
731         break;
732     case B_TYPE:
733         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
734         if (mb_type < 0){
735             fprintf(stderr, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
736             return -1;
737         }
738         break;
739     }
740     dprintf("mb_type=%x\n", mb_type);
741     motion_type = 0; /* avoid warning */
742     if (mb_type & (MB_FOR|MB_BACK)) {
743         /* get additionnal motion vector type */
744         if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
745             motion_type = MT_FRAME;
746         else
747             motion_type = get_bits(&s->gb, 2);
748     }
749     /* compute dct type */
750     if (s->picture_structure == PICT_FRAME && 
751         !s->frame_pred_frame_dct &&
752         (mb_type & (MB_PAT | MB_INTRA))) {
753         s->interlaced_dct = get_bits1(&s->gb);
754 #ifdef DEBUG
755         if (s->interlaced_dct)
756             printf("interlaced_dct\n");
757 #endif
758     } else {
759         s->interlaced_dct = 0; /* frame based */
760     }
761
762     if (mb_type & MB_QUANT) {
763         s->qscale = get_qscale(s);
764     }
765     if (mb_type & MB_INTRA) {
766         if (s->concealment_motion_vectors) {
767             /* just parse them */
768             if (s->picture_structure != PICT_FRAME) 
769                 skip_bits1(&s->gb); /* field select */
770             mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
771             mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
772         }
773         s->mb_intra = 1;
774         cbp = 0x3f;
775         memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
776     } else {
777         s->mb_intra = 0;
778         cbp = 0;
779     }
780     /* special case of implicit zero motion vector */
781     if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
782         s->mv_dir = MV_DIR_FORWARD;
783         s->mv_type = MV_TYPE_16X16;
784         s->last_mv[0][0][0] = 0;
785         s->last_mv[0][0][1] = 0;
786         s->last_mv[0][1][0] = 0;
787         s->last_mv[0][1][1] = 0;
788         s->mv[0][0][0] = 0;
789         s->mv[0][0][1] = 0;
790     } else if (mb_type & (MB_FOR | MB_BACK)) {
791         /* motion vectors */
792         s->mv_dir = 0;
793         for(i=0;i<2;i++) {
794             if (mb_type & (MB_FOR >> i)) {
795                 s->mv_dir |= (MV_DIR_FORWARD >> i);
796                 dprintf("motion_type=%d\n", motion_type);
797                 switch(motion_type) {
798                 case MT_FRAME: /* or MT_16X8 */
799                     if (s->picture_structure == PICT_FRAME) {
800                         /* MT_FRAME */
801                         s->mv_type = MV_TYPE_16X16;
802                         for(k=0;k<2;k++) {
803                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
804                                                      s->last_mv[i][0][k]);
805                             s->last_mv[i][0][k] = val;
806                             s->last_mv[i][1][k] = val;
807                             /* full_pel: only for mpeg1 */
808                             if (s->full_pel[i])
809                                 val = val << 1;
810                             s->mv[i][0][k] = val;
811                             dprintf("mv%d: %d\n", k, val);
812                         }
813                     } else {
814                         /* MT_16X8 */
815                         s->mv_type = MV_TYPE_16X8;
816                         for(j=0;j<2;j++) {
817                             s->field_select[i][j] = get_bits1(&s->gb);
818                             for(k=0;k<2;k++) {
819                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
820                                                          s->last_mv[i][j][k]);
821                                 s->last_mv[i][j][k] = val;
822                                 s->mv[i][j][k] = val;
823                             }
824                         }
825                     }
826                     break;
827                 case MT_FIELD:
828                     if (s->picture_structure == PICT_FRAME) {
829                         s->mv_type = MV_TYPE_FIELD;
830                         for(j=0;j<2;j++) {
831                             s->field_select[i][j] = get_bits1(&s->gb);
832                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
833                                                      s->last_mv[i][j][0]);
834                             s->last_mv[i][j][0] = val;
835                             s->mv[i][j][0] = val;
836                             dprintf("fmx=%d\n", val);
837                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
838                                                      s->last_mv[i][j][1] >> 1);
839                             s->last_mv[i][j][1] = val << 1;
840                             s->mv[i][j][1] = val;
841                             dprintf("fmy=%d\n", val);
842                         }
843                     } else {
844                         s->mv_type = MV_TYPE_16X16;
845                         s->field_select[i][0] = get_bits1(&s->gb);
846                         for(k=0;k<2;k++) {
847                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
848                                                      s->last_mv[i][0][k]);
849                             s->last_mv[i][0][k] = val;
850                             s->last_mv[i][1][k] = val;
851                             s->mv[i][0][k] = val;
852                         }
853                     }
854                     break;
855                 case MT_DMV:
856                     {
857                         int dmx, dmy, mx, my, m;
858
859                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
860                                                 s->last_mv[i][0][0]);
861                         s->last_mv[i][0][0] = mx;
862                         s->last_mv[i][1][0] = mx;
863                         dmx = get_dmv(s);
864                         my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
865                                                 s->last_mv[i][0][1] >> 1);
866                         dmy = get_dmv(s);
867                         s->mv_type = MV_TYPE_DMV;
868                         /* XXX: totally broken */
869                         if (s->picture_structure == PICT_FRAME) {
870                             s->last_mv[i][0][1] = my << 1;
871                             s->last_mv[i][1][1] = my << 1;
872
873                             m = s->top_field_first ? 1 : 3;
874                             /* top -> top pred */
875                             s->mv[i][0][0] = mx; 
876                             s->mv[i][0][1] = my << 1;
877                             s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
878                             s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
879                             m = 4 - m;
880                             s->mv[i][2][0] = mx;
881                             s->mv[i][2][1] = my << 1;
882                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
883                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
884                         } else {
885                             s->last_mv[i][0][1] = my;
886                             s->last_mv[i][1][1] = my;
887                             s->mv[i][0][0] = mx;
888                             s->mv[i][0][1] = my;
889                             s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
890                             s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
891                                 /* + 2 * cur_field */;
892                         }
893                     }
894                     break;
895                 }
896             }
897         }
898     }
899
900     if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
901         skip_bits1(&s->gb); /* marker */
902     }
903     
904     if (mb_type & MB_PAT) {
905         cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
906         if (cbp < 0){
907             fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
908             return -1;
909         }
910         cbp++;
911     }
912     dprintf("cbp=%x\n", cbp);
913
914     if (s->mpeg2) {
915         if (s->mb_intra) {
916             for(i=0;i<6;i++) {
917                 if (cbp & (1 << (5 - i))) {
918                     if (mpeg2_decode_block_intra(s, block[i], i) < 0)
919                         return -1;
920                 } else {
921                     s->block_last_index[i] = -1;
922                 }
923             }
924         } else {
925             for(i=0;i<6;i++) {
926                 if (cbp & (1 << (5 - i))) {
927                     if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
928                         return -1;
929                 } else {
930                     s->block_last_index[i] = -1;
931                 }
932             }
933         }
934     } else {
935         for(i=0;i<6;i++) {
936             if (cbp & (1 << (5 - i))) {
937                 if (mpeg1_decode_block(s, block[i], i) < 0)
938                     return -1;
939             } else {
940                 s->block_last_index[i] = -1;
941             }
942         }
943     }
944     return 0;
945 }
946
947 /* as h263, but only 17 codes */
948 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
949 {
950     int code, sign, val, m, l, shift;
951
952     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
953     if (code < 0) {
954         return 0xffff;
955     }
956     if (code == 0) {
957         return pred;
958     }
959     sign = get_bits1(&s->gb);
960     shift = fcode - 1;
961     val = (code - 1) << shift;
962     if (shift > 0)
963         val |= get_bits(&s->gb, shift);
964     val++;
965     if (sign)
966         val = -val;
967     val += pred;
968     
969     /* modulo decoding */
970     l = (1 << shift) * 16;
971     m = 2 * l;
972     if (val < -l) {
973         val += m;
974     } else if (val >= l) {
975         val -= m;
976     }
977     return val;
978 }
979
980 static inline int decode_dc(MpegEncContext *s, int component)
981 {
982     int code, diff;
983
984     if (component == 0) {
985         code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
986     } else {
987         code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
988     }
989     if (code < 0){
990         fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
991         return 0xffff;
992     }
993     if (code == 0) {
994         diff = 0;
995     } else {
996         diff = get_bits(&s->gb, code);
997         if ((diff & (1 << (code - 1))) == 0) 
998             diff = (-1 << code) | (diff + 1);
999     }
1000     return diff;
1001 }
1002
1003 static int mpeg1_decode_block(MpegEncContext *s, 
1004                                DCTELEM *block, 
1005                                int n)
1006 {
1007     int level, dc, diff, i, j, run;
1008     int code, component;
1009     RLTable *rl = &rl_mpeg1;
1010
1011     if (s->mb_intra) {
1012         /* DC coef */
1013         component = (n <= 3 ? 0 : n - 4 + 1);
1014         diff = decode_dc(s, component);
1015         if (diff >= 0xffff)
1016             return -1;
1017         dc = s->last_dc[component];
1018         dc += diff;
1019         s->last_dc[component] = dc;
1020         block[0] = dc;
1021         dprintf("dc=%d diff=%d\n", dc, diff);
1022         i = 1;
1023     } else {
1024         int v;
1025         OPEN_READER(re, &s->gb);
1026         i = 0;
1027         /* special case for the first coef. no need to add a second vlc table */
1028         UPDATE_CACHE(re, &s->gb);
1029         v= SHOW_UBITS(re, &s->gb, 2);
1030         if (v & 2) {
1031             run = 0;
1032             level = 1 - ((v & 1) << 1);
1033             SKIP_BITS(re, &s->gb, 2);
1034             CLOSE_READER(re, &s->gb);
1035             goto add_coef;
1036         }
1037         CLOSE_READER(re, &s->gb);
1038     }
1039
1040     /* now quantify & encode AC coefs */
1041     for(;;) {
1042         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1043         if (code < 0) {
1044             return -1;
1045         }
1046         if (code == 112) {
1047             break;
1048         } else if (code == 111) {
1049             /* escape */
1050             run = get_bits(&s->gb, 6);
1051             level = get_bits(&s->gb, 8);
1052             level= (level + ((-1)<<7)) ^ ((-1)<<7); //sign extension
1053             if (level == -128) {
1054                 level = get_bits(&s->gb, 8) - 256;
1055             } else if (level == 0) {
1056                 level = get_bits(&s->gb, 8);
1057             }
1058         } else {
1059             run = rl->table_run[code];
1060             level = rl->table_level[code];
1061             if (get_bits1(&s->gb))
1062                 level = -level;
1063         }
1064         i += run;
1065         if (i >= 64)
1066             return -1;
1067     add_coef:
1068         dprintf("%d: run=%d level=%d\n", n, run, level);
1069         j = zigzag_direct[i];
1070         block[j] = level;
1071         i++;
1072     }
1073     s->block_last_index[n] = i-1;
1074     return 0;
1075 }
1076
1077 /* Also does unquantization here, since I will never support mpeg2
1078    encoding */
1079 static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1080                                         DCTELEM *block, 
1081                                         int n)
1082 {
1083     int level, i, j, run;
1084     int code;
1085     RLTable *rl = &rl_mpeg1;
1086     const UINT8 *scan_table;
1087     const UINT16 *matrix;
1088     int mismatch;
1089
1090     if (s->alternate_scan)
1091         scan_table = ff_alternate_vertical_scan;
1092     else
1093         scan_table = zigzag_direct;
1094     mismatch = 1;
1095
1096     {
1097         int v;
1098         OPEN_READER(re, &s->gb);
1099         i = 0;
1100         if (n < 4)
1101             matrix = s->inter_matrix;
1102         else
1103             matrix = s->chroma_inter_matrix;
1104
1105         /* special case for the first coef. no need to add a second vlc table */
1106         UPDATE_CACHE(re, &s->gb);
1107         v= SHOW_UBITS(re, &s->gb, 2);
1108         if (v & 2) {
1109             run = 0;
1110             level = 1 - ((v & 1) << 1);
1111             SKIP_BITS(re, &s->gb, 2);
1112             CLOSE_READER(re, &s->gb);
1113             goto add_coef;
1114         }
1115         CLOSE_READER(re, &s->gb);
1116     }
1117
1118     /* now quantify & encode AC coefs */
1119     for(;;) {
1120         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1121         if (code < 0){
1122             fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1123             return -1;
1124         }
1125         if (code == 112) {
1126             break;
1127         } else if (code == 111) {
1128             /* escape */
1129             run = get_bits(&s->gb, 6);
1130             level = get_bits(&s->gb, 12);
1131             level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
1132         } else {
1133             run = rl->table_run[code];
1134             level = rl->table_level[code];
1135             if (get_bits1(&s->gb))
1136                 level = -level;
1137         }
1138         i += run;
1139         if (i >= 64){
1140             fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1141             return -1;
1142         }
1143     add_coef:
1144         j = scan_table[i];
1145         dprintf("%d: run=%d level=%d\n", n, run, level);
1146         /* XXX: optimize */
1147         if (level > 0) {
1148             level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1149         } else {
1150             level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1151             level = -level;
1152         }
1153         /* XXX: is it really necessary to saturate since the encoder
1154            knows whats going on ? */
1155         mismatch ^= level;
1156         block[j] = level;
1157         i++;
1158     }
1159     block[63] ^= (mismatch & 1);
1160     s->block_last_index[n] = i;
1161     return 0;
1162 }
1163
1164 static int mpeg2_decode_block_intra(MpegEncContext *s, 
1165                                     DCTELEM *block, 
1166                                     int n)
1167 {
1168     int level, dc, diff, i, j, run;
1169     int code, component;
1170     RLTable *rl;
1171     const UINT8 *scan_table;
1172     const UINT16 *matrix;
1173     int mismatch;
1174
1175     if (s->alternate_scan)
1176         scan_table = ff_alternate_vertical_scan;
1177     else
1178         scan_table = zigzag_direct;
1179
1180     /* DC coef */
1181     component = (n <= 3 ? 0 : n - 4 + 1);
1182     diff = decode_dc(s, component);
1183     if (diff >= 0xffff)
1184         return -1;
1185     dc = s->last_dc[component];
1186     dc += diff;
1187     s->last_dc[component] = dc;
1188     block[0] = dc << (3 - s->intra_dc_precision);
1189     dprintf("dc=%d\n", block[0]);
1190     mismatch = block[0] ^ 1;
1191     i = 1;
1192     if (s->intra_vlc_format)
1193         rl = &rl_mpeg2;
1194     else
1195         rl = &rl_mpeg1;
1196     if (n < 4) 
1197         matrix = s->intra_matrix;
1198     else
1199         matrix = s->chroma_intra_matrix;
1200
1201     /* now quantify & encode AC coefs */
1202     for(;;) {
1203         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
1204         if (code < 0){
1205             fprintf(stderr, "invalid ac code at %d %d\n", s->mb_x, s->mb_y);
1206             return -1;
1207         }
1208         if (code == 112) {
1209             break;
1210         } else if (code == 111) {
1211             /* escape */
1212             run = get_bits(&s->gb, 6);
1213             level = get_bits(&s->gb, 12);
1214             level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
1215         } else {
1216             run = rl->table_run[code];
1217             level = rl->table_level[code];
1218             if (get_bits1(&s->gb))
1219                 level = -level;
1220         }
1221         i += run;
1222         if (i >= 64){
1223             fprintf(stderr, "run too long at %d %d\n", s->mb_x, s->mb_y);
1224             return -1;
1225         }
1226         j = scan_table[i];
1227         dprintf("%d: run=%d level=%d\n", n, run, level);
1228         level = (level * s->qscale * matrix[j]) / 16;
1229         /* XXX: is it really necessary to saturate since the encoder
1230            knows whats going on ? */
1231         mismatch ^= level;
1232         block[j] = level;
1233         i++;
1234     }
1235     block[63] ^= (mismatch & 1);
1236     s->block_last_index[n] = i;
1237     return 0;
1238 }
1239
1240 /* compressed picture size */
1241 #define PICTURE_BUFFER_SIZE 100000
1242
1243 typedef struct Mpeg1Context {
1244     MpegEncContext mpeg_enc_ctx;
1245     UINT32 header_state;
1246     int start_code; /* current start code */
1247     UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1248     UINT8 *buf_ptr;
1249     int buffer_size;
1250     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1251     int repeat_field; /* true if we must repeat the field */
1252 } Mpeg1Context;
1253
1254 static int mpeg_decode_init(AVCodecContext *avctx)
1255 {
1256     Mpeg1Context *s = avctx->priv_data;
1257     
1258     s->mpeg_enc_ctx.flags= avctx->flags;
1259     common_init(&s->mpeg_enc_ctx);
1260
1261     s->header_state = 0xff;
1262     s->mpeg_enc_ctx_allocated = 0;
1263     s->buffer_size = PICTURE_BUFFER_SIZE;
1264     s->start_code = -1;
1265     s->buf_ptr = s->buffer;
1266     s->mpeg_enc_ctx.picture_number = 0;
1267     s->repeat_field = 0;
1268     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1269     avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1270     return 0;
1271 }
1272
1273 /* return the 8 bit start code value and update the search
1274    state. Return -1 if no start code found */
1275 static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1276                            UINT32 *header_state)
1277 {
1278     UINT8 *buf_ptr;
1279     unsigned int state, v;
1280     int val;
1281
1282     state = *header_state;
1283     buf_ptr = *pbuf_ptr;
1284     while (buf_ptr < buf_end) {
1285         v = *buf_ptr++;
1286         if (state == 0x000001) {
1287             state = ((state << 8) | v) & 0xffffff;
1288             val = state;
1289             goto found;
1290         }
1291         state = ((state << 8) | v) & 0xffffff;
1292     }
1293     val = -1;
1294  found:
1295     *pbuf_ptr = buf_ptr;
1296     *header_state = state;
1297     return val;
1298 }
1299
1300 static int mpeg1_decode_picture(AVCodecContext *avctx, 
1301                                 UINT8 *buf, int buf_size)
1302 {
1303     Mpeg1Context *s1 = avctx->priv_data;
1304     MpegEncContext *s = &s1->mpeg_enc_ctx;
1305     int ref, f_code;
1306
1307     init_get_bits(&s->gb, buf, buf_size);
1308
1309     ref = get_bits(&s->gb, 10); /* temporal ref */
1310     s->pict_type = get_bits(&s->gb, 3);
1311     dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1312     skip_bits(&s->gb, 16);
1313     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1314         s->full_pel[0] = get_bits1(&s->gb);
1315         f_code = get_bits(&s->gb, 3);
1316         if (f_code == 0)
1317             return -1;
1318         s->mpeg_f_code[0][0] = f_code;
1319         s->mpeg_f_code[0][1] = f_code;
1320     }
1321     if (s->pict_type == B_TYPE) {
1322         s->full_pel[1] = get_bits1(&s->gb);
1323         f_code = get_bits(&s->gb, 3);
1324         if (f_code == 0)
1325             return -1;
1326         s->mpeg_f_code[1][0] = f_code;
1327         s->mpeg_f_code[1][1] = f_code;
1328     }
1329     s->y_dc_scale = 8;
1330     s->c_dc_scale = 8;
1331     s->first_slice = 1;
1332     return 0;
1333 }
1334
1335 static void mpeg_decode_sequence_extension(MpegEncContext *s)
1336 {
1337     int horiz_size_ext, vert_size_ext;
1338     int bit_rate_ext, vbv_buf_ext, low_delay;
1339     int frame_rate_ext_n, frame_rate_ext_d;
1340
1341     skip_bits(&s->gb, 8); /* profil and level */
1342     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1343     skip_bits(&s->gb, 2); /* chroma_format */
1344     horiz_size_ext = get_bits(&s->gb, 2);
1345     vert_size_ext = get_bits(&s->gb, 2);
1346     s->width |= (horiz_size_ext << 12);
1347     s->height |= (vert_size_ext << 12);
1348     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1349     s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1350     skip_bits1(&s->gb); /* marker */
1351     vbv_buf_ext = get_bits(&s->gb, 8);
1352     low_delay = get_bits1(&s->gb);
1353     frame_rate_ext_n = get_bits(&s->gb, 2);
1354     frame_rate_ext_d = get_bits(&s->gb, 5);
1355     if (frame_rate_ext_d >= 1)
1356         s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1357     dprintf("sequence extension\n");
1358     s->mpeg2 = 1;
1359     s->avctx->sub_id = 2; /* indicates mpeg2 found */
1360 }
1361
1362 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1363 {
1364     int i, v, j;
1365
1366     dprintf("matrix extension\n");
1367
1368     if (get_bits1(&s->gb)) {
1369         for(i=0;i<64;i++) {
1370             v = get_bits(&s->gb, 8);
1371             j = zigzag_direct[i];
1372             s->intra_matrix[j] = v;
1373             s->chroma_intra_matrix[j] = v;
1374         }
1375     }
1376     if (get_bits1(&s->gb)) {
1377         for(i=0;i<64;i++) {
1378             v = get_bits(&s->gb, 8);
1379             j = zigzag_direct[i];
1380             s->inter_matrix[j] = v;
1381             s->chroma_inter_matrix[j] = v;
1382         }
1383     }
1384     if (get_bits1(&s->gb)) {
1385         for(i=0;i<64;i++) {
1386             v = get_bits(&s->gb, 8);
1387             j = zigzag_direct[i];
1388             s->chroma_intra_matrix[j] = v;
1389         }
1390     }
1391     if (get_bits1(&s->gb)) {
1392         for(i=0;i<64;i++) {
1393             v = get_bits(&s->gb, 8);
1394             j = zigzag_direct[i];
1395             s->chroma_inter_matrix[j] = v;
1396         }
1397     }
1398 }
1399
1400 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1401 {
1402     s->full_pel[0] = s->full_pel[1] = 0;
1403     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1404     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1405     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1406     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1407     s->intra_dc_precision = get_bits(&s->gb, 2);
1408     s->picture_structure = get_bits(&s->gb, 2);
1409     s->top_field_first = get_bits1(&s->gb);
1410     s->frame_pred_frame_dct = get_bits1(&s->gb);
1411     s->concealment_motion_vectors = get_bits1(&s->gb);
1412     s->q_scale_type = get_bits1(&s->gb);
1413     s->intra_vlc_format = get_bits1(&s->gb);
1414     s->alternate_scan = get_bits1(&s->gb);
1415     s->repeat_first_field = get_bits1(&s->gb);
1416     s->chroma_420_type = get_bits1(&s->gb);
1417     s->progressive_frame = get_bits1(&s->gb);
1418     /* composite display not parsed */
1419     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1420     dprintf("picture_structure=%d\n", s->picture_structure);
1421     dprintf("top field first=%d\n", s->top_field_first);
1422     dprintf("repeat first field=%d\n", s->repeat_first_field);
1423     dprintf("conceal=%d\n", s->concealment_motion_vectors);
1424     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1425     dprintf("alternate_scan=%d\n", s->alternate_scan);
1426     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1427     dprintf("progressive_frame=%d\n", s->progressive_frame);
1428 }
1429
1430 static void mpeg_decode_extension(AVCodecContext *avctx, 
1431                                   UINT8 *buf, int buf_size)
1432 {
1433     Mpeg1Context *s1 = avctx->priv_data;
1434     MpegEncContext *s = &s1->mpeg_enc_ctx;
1435     int ext_type;
1436
1437     init_get_bits(&s->gb, buf, buf_size);
1438     
1439     ext_type = get_bits(&s->gb, 4);
1440     switch(ext_type) {
1441     case 0x1:
1442         /* sequence ext */
1443         mpeg_decode_sequence_extension(s);
1444         break;
1445     case 0x3:
1446         /* quant matrix extension */
1447         mpeg_decode_quant_matrix_extension(s);
1448         break;
1449     case 0x8:
1450         /* picture extension */
1451         mpeg_decode_picture_coding_extension(s);
1452         break;
1453     }
1454 }
1455
1456 /* return 1 if end of frame */
1457 static int mpeg_decode_slice(AVCodecContext *avctx, 
1458                               AVPicture *pict,
1459                               int start_code,
1460                               UINT8 *buf, int buf_size)
1461 {
1462     Mpeg1Context *s1 = avctx->priv_data;
1463     MpegEncContext *s = &s1->mpeg_enc_ctx;
1464     int ret;
1465
1466     start_code = (start_code - 1) & 0xff;
1467     if (start_code >= s->mb_height){
1468         fprintf(stderr, "slice below image\n");
1469         return -1;
1470     }
1471     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1472     s->last_dc[1] = s->last_dc[0];
1473     s->last_dc[2] = s->last_dc[0];
1474     memset(s->last_mv, 0, sizeof(s->last_mv));
1475     s->mb_x = -1;
1476     s->mb_y = start_code;
1477     s->mb_incr = 0;
1478     /* start frame decoding */
1479     if (s->first_slice) {
1480         s->first_slice = 0;
1481         MPV_frame_start(s, avctx);
1482     }
1483
1484     init_get_bits(&s->gb, buf, buf_size);
1485
1486     s->qscale = get_qscale(s);
1487     /* extra slice info */
1488     while (get_bits1(&s->gb) != 0) {
1489         skip_bits(&s->gb, 8);
1490     }
1491
1492     for(;;) {
1493         clear_blocks(s->block[0]);
1494         emms_c();
1495         ret = mpeg_decode_mb(s, s->block);
1496         dprintf("ret=%d\n", ret);
1497         if (ret < 0)
1498             return -1;
1499         if (ret == 1)
1500             break;
1501         MPV_decode_mb(s, s->block);
1502     }
1503     emms_c();
1504
1505     /* end of slice reached */
1506     if (s->mb_x == (s->mb_width - 1) &&
1507         s->mb_y == (s->mb_height - 1)) {
1508         /* end of image */
1509         UINT8 **picture;
1510
1511         MPV_frame_end(s);
1512
1513         /* XXX: incorrect reported qscale for mpeg2 */
1514         if (s->pict_type == B_TYPE) {
1515             picture = s->current_picture;
1516             avctx->quality = s->qscale;
1517         } else {
1518             /* latency of 1 frame for I and P frames */
1519             /* XXX: use another variable than picture_number */
1520             if (s->picture_number == 0) {
1521                 picture = NULL;
1522             } else {
1523                 picture = s->last_picture;
1524                 avctx->quality = s->last_qscale;
1525             }
1526             s->last_qscale = s->qscale;
1527             s->picture_number++;
1528         }
1529         if (picture) {
1530             pict->data[0] = picture[0];
1531             pict->data[1] = picture[1];
1532             pict->data[2] = picture[2];
1533             pict->linesize[0] = s->linesize;
1534             pict->linesize[1] = s->uvlinesize;
1535             pict->linesize[2] = s->uvlinesize;
1536             return 1;
1537         } else {
1538             return 0;
1539         }
1540     } else {
1541         return 0;
1542     }
1543 }
1544
1545 static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1546                                  UINT8 *buf, int buf_size)
1547 {
1548     Mpeg1Context *s1 = avctx->priv_data;
1549     MpegEncContext *s = &s1->mpeg_enc_ctx;
1550     int width, height, i, v, j;
1551
1552     init_get_bits(&s->gb, buf, buf_size);
1553
1554     width = get_bits(&s->gb, 12);
1555     height = get_bits(&s->gb, 12);
1556     skip_bits(&s->gb, 4);
1557     s->frame_rate_index = get_bits(&s->gb, 4);
1558     if (s->frame_rate_index == 0)
1559         return -1;
1560     s->bit_rate = get_bits(&s->gb, 18) * 400;
1561     if (get_bits1(&s->gb) == 0) /* marker */
1562         return -1;
1563     if (width <= 0 || height <= 0 ||
1564         (width % 2) != 0 || (height % 2) != 0)
1565         return -1;
1566     if (width != s->width ||
1567         height != s->height) {
1568         /* start new mpeg1 context decoding */
1569         s->out_format = FMT_MPEG1;
1570         if (s1->mpeg_enc_ctx_allocated) {
1571             MPV_common_end(s);
1572         }
1573         s->width = width;
1574         s->height = height;
1575         avctx->has_b_frames= s->has_b_frames = 1;
1576         s->avctx = avctx;
1577         avctx->width = width;
1578         avctx->height = height;
1579         if (s->frame_rate_index >= 9) {
1580             /* at least give a valid frame rate (some old mpeg1 have this) */
1581             avctx->frame_rate = 25 * FRAME_RATE_BASE;
1582         } else {
1583             avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1584         }
1585         s->frame_rate = avctx->frame_rate;
1586         avctx->bit_rate = s->bit_rate;
1587         
1588         if (MPV_common_init(s) < 0)
1589             return -1;
1590         mpeg1_init_vlc(s);
1591         s1->mpeg_enc_ctx_allocated = 1;
1592     }
1593
1594     skip_bits(&s->gb, 10); /* vbv_buffer_size */
1595     skip_bits(&s->gb, 1);
1596
1597     /* get matrix */
1598     if (get_bits1(&s->gb)) {
1599         for(i=0;i<64;i++) {
1600             v = get_bits(&s->gb, 8);
1601             j = zigzag_direct[i];
1602             s->intra_matrix[j] = v;
1603             s->chroma_intra_matrix[j] = v;
1604         }
1605 #ifdef DEBUG
1606         dprintf("intra matrix present\n");
1607         for(i=0;i<64;i++)
1608             dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1609         printf("\n");
1610 #endif
1611     } else {
1612         for(i=0;i<64;i++) {
1613             v = ff_mpeg1_default_intra_matrix[i];
1614             s->intra_matrix[i] = v;
1615             s->chroma_intra_matrix[i] = v;
1616         }
1617     }
1618     if (get_bits1(&s->gb)) {
1619         for(i=0;i<64;i++) {
1620             v = get_bits(&s->gb, 8);
1621             j = zigzag_direct[i];
1622             s->inter_matrix[j] = v;
1623             s->chroma_inter_matrix[j] = v;
1624         }
1625 #ifdef DEBUG
1626         dprintf("non intra matrix present\n");
1627         for(i=0;i<64;i++)
1628             dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1629         printf("\n");
1630 #endif
1631     } else {
1632         for(i=0;i<64;i++) {
1633             v = ff_mpeg1_default_non_intra_matrix[i];
1634             s->inter_matrix[i] = v;
1635             s->chroma_inter_matrix[i] = v;
1636         }
1637     }
1638
1639     /* we set mpeg2 parameters so that it emulates mpeg1 */
1640     s->progressive_sequence = 1;
1641     s->progressive_frame = 1;
1642     s->picture_structure = PICT_FRAME;
1643     s->frame_pred_frame_dct = 1;
1644     s->mpeg2 = 0;
1645     avctx->sub_id = 1; /* indicates mpeg1 */
1646     return 0;
1647 }
1648
1649 /* handle buffering and image synchronisation */
1650 static int mpeg_decode_frame(AVCodecContext *avctx, 
1651                              void *data, int *data_size,
1652                              UINT8 *buf, int buf_size)
1653 {
1654     Mpeg1Context *s = avctx->priv_data;
1655     UINT8 *buf_end, *buf_ptr, *buf_start;
1656     int len, start_code_found, ret, code, start_code, input_size;
1657     AVPicture *picture = data;
1658     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1659             
1660     dprintf("fill_buffer\n");
1661
1662     *data_size = 0;
1663
1664     /* special case for last picture */
1665     if (buf_size == 0) {
1666         if (s2->picture_number > 0) {
1667             picture->data[0] = s2->next_picture[0];
1668             picture->data[1] = s2->next_picture[1];
1669             picture->data[2] = s2->next_picture[2];
1670             picture->linesize[0] = s2->linesize;
1671             picture->linesize[1] = s2->uvlinesize;
1672             picture->linesize[2] = s2->uvlinesize;
1673             *data_size = sizeof(AVPicture);
1674         }
1675         return 0;
1676     }
1677
1678     buf_ptr = buf;
1679     buf_end = buf + buf_size;
1680
1681 #if 0    
1682     if (s->repeat_field % 2 == 1) { 
1683         s->repeat_field++;
1684         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1685         //        s2->picture_number, s->repeat_field);
1686         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1687             *data_size = sizeof(AVPicture);
1688             goto the_end;
1689         }
1690     }
1691 #endif
1692     while (buf_ptr < buf_end) {
1693         buf_start = buf_ptr;
1694         /* find start next code */
1695         code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1696         if (code >= 0) {
1697             start_code_found = 1;
1698         } else {
1699             start_code_found = 0;
1700         }
1701         /* copy to buffer */
1702         len = buf_ptr - buf_start;
1703         if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1704             /* data too big : flush */
1705             s->buf_ptr = s->buffer;
1706             if (start_code_found)
1707                 s->start_code = code;
1708         } else {
1709             memcpy(s->buf_ptr, buf_start, len);
1710             s->buf_ptr += len;
1711             
1712             if (start_code_found) {
1713                 /* prepare data for next start code */
1714                 input_size = s->buf_ptr - s->buffer;
1715                 start_code = s->start_code;
1716                 s->buf_ptr = s->buffer;
1717                 s->start_code = code;
1718                 switch(start_code) {
1719                 case SEQ_START_CODE:
1720                     mpeg1_decode_sequence(avctx, s->buffer, 
1721                                           input_size);
1722                     break;
1723                             
1724                 case PICTURE_START_CODE:
1725                     /* we have a complete image : we try to decompress it */
1726                     mpeg1_decode_picture(avctx, 
1727                                          s->buffer, input_size);
1728                     break;
1729                 case EXT_START_CODE:
1730                     mpeg_decode_extension(avctx,
1731                                           s->buffer, input_size);
1732                     break;
1733                 default:
1734                     if (start_code >= SLICE_MIN_START_CODE &&
1735                         start_code <= SLICE_MAX_START_CODE) {
1736                         ret = mpeg_decode_slice(avctx, picture,
1737                                                 start_code, s->buffer, input_size);
1738                         if (ret == 1) {
1739                             /* got a picture: exit */
1740                             /* first check if we must repeat the frame */
1741                             avctx->repeat_pict = 0;
1742 #if 0
1743                             if (s2->progressive_frame && s2->repeat_first_field) {
1744                                 //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1745                                 //s2->repeat_first_field = 0;
1746                                 //s2->progressive_frame = 0;
1747                                 if (++s->repeat_field > 2)
1748                                     s->repeat_field = 0;
1749                                 avctx->repeat_pict = 1;
1750                             }
1751 #endif                      
1752                             if (s2->repeat_first_field) {
1753                                 if (s2->progressive_sequence) {
1754                                     if (s2->top_field_first)
1755                                         avctx->repeat_pict = 4;
1756                                     else
1757                                         avctx->repeat_pict = 2;
1758                                 } else if (s2->progressive_frame) {
1759                                     avctx->repeat_pict = 1;
1760                                 }
1761                             }         
1762                             *data_size = sizeof(AVPicture);
1763                             goto the_end;
1764                         }else if(ret==-1){
1765                             printf("Error while decoding slice\n");
1766                         }
1767                     }
1768                     break;
1769                 }
1770             }
1771         }
1772     }
1773  the_end:
1774     return buf_ptr - buf;
1775 }
1776
1777 static int mpeg_decode_end(AVCodecContext *avctx)
1778 {
1779     Mpeg1Context *s = avctx->priv_data;
1780
1781     if (s->mpeg_enc_ctx_allocated)
1782         MPV_common_end(&s->mpeg_enc_ctx);
1783     return 0;
1784 }
1785
1786 AVCodec mpeg_decoder = {
1787     "mpegvideo",
1788     CODEC_TYPE_VIDEO,
1789     CODEC_ID_MPEG1VIDEO,
1790     sizeof(Mpeg1Context),
1791     mpeg_decode_init,
1792     NULL,
1793     mpeg_decode_end,
1794     mpeg_decode_frame,
1795     CODEC_CAP_DR1,
1796 };