]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg12.c
* fix for empty image queue
[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 #if 1
27 #define PRINT_QP(a, b) {}
28 #else
29 #define PRINT_QP(a, b) printf(a, b)
30 #endif
31
32 /* Start codes. */
33 #define SEQ_END_CODE            0x000001b7
34 #define SEQ_START_CODE          0x000001b3
35 #define GOP_START_CODE          0x000001b8
36 #define PICTURE_START_CODE      0x00000100
37 #define SLICE_MIN_START_CODE    0x00000101
38 #define SLICE_MAX_START_CODE    0x000001af
39 #define EXT_START_CODE          0x000001b5
40 #define USER_START_CODE         0x000001b2
41
42 #define DC_VLC_BITS 9
43 #define MV_VLC_BITS 9
44 #define MBINCR_VLC_BITS 9
45 #define MB_PAT_VLC_BITS 9
46 #define MB_PTYPE_VLC_BITS 6
47 #define MB_BTYPE_VLC_BITS 6
48 #define TEX_VLC_BITS 9
49
50 static void mpeg1_encode_block(MpegEncContext *s, 
51                          DCTELEM *block, 
52                          int component);
53 static void mpeg1_encode_motion(MpegEncContext *s, int val);
54 static void mpeg1_skip_picture(MpegEncContext *s, int pict_num);
55 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
56                               DCTELEM *block, 
57                               int n);
58 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
59                               DCTELEM *block, 
60                               int n);
61 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
62                                         DCTELEM *block, 
63                                         int n);
64 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
65                                     DCTELEM *block, 
66                                     int n);
67 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
68
69 static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
70 static UINT8 fcode_tab[MAX_MV*2+1];
71
72 static inline int get_bits_diff(MpegEncContext *s){
73     int bits,ret;
74     
75     bits= get_bit_count(&s->pb);
76     ret= bits - s->last_bits;
77     s->last_bits=bits;
78     
79     return ret;
80 }
81
82 static void init_2d_vlc_rl(RLTable *rl)
83 {
84     int i;
85     
86     init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
87              &rl->table_vlc[0][1], 4, 2,
88              &rl->table_vlc[0][0], 4, 2);
89
90     
91     rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
92     for(i=0; i<rl->vlc.table_size; i++){
93         int code= rl->vlc.table[i][0];
94         int len = rl->vlc.table[i][1];
95         int level, run;
96     
97         if(len==0){ // illegal code
98             run= 65;
99             level= MAX_LEVEL;
100         }else if(len<0){ //more bits needed
101             run= 0;
102             level= code;
103         }else{
104             if(code==rl->n){ //esc
105                 run= 65;
106                 level= 0;
107             }else if(code==rl->n+1){ //eob
108                 run= 0;
109                 level= 127;
110             }else{
111                 run=   rl->table_run  [code] + 1;
112                 level= rl->table_level[code];
113             }
114         }
115         rl->rl_vlc[0][i].len= len;
116         rl->rl_vlc[0][i].level= level;
117         rl->rl_vlc[0][i].run= run;
118     }
119 }
120
121
122 static void put_header(MpegEncContext *s, int header)
123 {
124     align_put_bits(&s->pb);
125     put_bits(&s->pb, 16, header>>16);
126     put_bits(&s->pb, 16, header&0xFFFF);
127 }
128
129 /* put sequence header if needed */
130 static void mpeg1_encode_sequence_header(MpegEncContext *s)
131 {
132         unsigned int vbv_buffer_size;
133         unsigned int fps, v;
134         int n, i;
135         UINT64 time_code;
136         float best_aspect_error= 1E10;
137         float aspect_ratio= s->avctx->aspect_ratio;
138         
139         if(aspect_ratio==0.0) aspect_ratio= s->width / (float)s->height; //pixel aspect 1:1 (VGA)
140         
141         if (s->current_picture.key_frame) {
142             /* mpeg1 header repeated every gop */
143             put_header(s, SEQ_START_CODE);
144             
145             /* search closest frame rate */
146             {
147                 int i, dmin, d;
148                 s->frame_rate_index = 0;
149                 dmin = 0x7fffffff;
150                 for(i=1;i<9;i++) {
151                     d = abs(s->frame_rate - frame_rate_tab[i]);
152                     if (d < dmin) {
153                         dmin = d;
154                         s->frame_rate_index = i;
155                     }
156                 }
157             }
158  
159             put_bits(&s->pb, 12, s->width);
160             put_bits(&s->pb, 12, s->height);
161             
162             for(i=1; i<15; i++){
163                 float error= mpeg1_aspect[i] - s->width/(s->height*aspect_ratio);
164                 error= ABS(error);
165                 
166                 if(error < best_aspect_error){
167                     best_aspect_error= error;
168                     s->aspect_ratio_info= i;
169                 }
170             }
171             
172             put_bits(&s->pb, 4, s->aspect_ratio_info);
173             put_bits(&s->pb, 4, s->frame_rate_index);
174             v = s->bit_rate / 400;
175             if (v > 0x3ffff)
176                 v = 0x3ffff;
177             put_bits(&s->pb, 18, v);
178             put_bits(&s->pb, 1, 1); /* marker */
179
180             if(s->avctx->rc_buffer_size)
181                 vbv_buffer_size = s->avctx->rc_buffer_size;
182             else
183                 /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
184                 vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;      
185             put_bits(&s->pb, 10, (vbv_buffer_size + 16383) / 16384); 
186             put_bits(&s->pb, 1, 1); /* constrained parameter flag */
187             put_bits(&s->pb, 1, 0); /* no custom intra matrix */
188             put_bits(&s->pb, 1, 0); /* no custom non intra matrix */
189
190             put_header(s, GOP_START_CODE);
191             put_bits(&s->pb, 1, 0); /* do drop frame */
192             /* time code : we must convert from the real frame rate to a
193                fake mpeg frame rate in case of low frame rate */
194             fps = frame_rate_tab[s->frame_rate_index];
195             time_code = (INT64)s->fake_picture_number * FRAME_RATE_BASE;
196             s->gop_picture_number = s->fake_picture_number;
197             put_bits(&s->pb, 5, (UINT32)((time_code / (fps * 3600)) % 24));
198             put_bits(&s->pb, 6, (UINT32)((time_code / (fps * 60)) % 60));
199             put_bits(&s->pb, 1, 1);
200             put_bits(&s->pb, 6, (UINT32)((time_code / fps) % 60));
201             put_bits(&s->pb, 6, (UINT32)((time_code % fps) / FRAME_RATE_BASE));
202             put_bits(&s->pb, 1, 1); /* closed gop */
203             put_bits(&s->pb, 1, 0); /* broken link */
204         }
205
206         if (s->frame_rate < (24 * FRAME_RATE_BASE) && s->picture_number > 0) {
207             /* insert empty P pictures to slow down to the desired
208                frame rate. Each fake pictures takes about 20 bytes */
209             fps = frame_rate_tab[s->frame_rate_index];
210             n = (((INT64)s->picture_number * fps) / s->frame_rate) - 1;
211             while (s->fake_picture_number < n) {
212                 mpeg1_skip_picture(s, s->fake_picture_number - 
213                                    s->gop_picture_number); 
214                 s->fake_picture_number++;
215             }
216
217         }
218 }
219
220
221 /* insert a fake P picture */
222 static void mpeg1_skip_picture(MpegEncContext *s, int pict_num)
223 {
224     unsigned int mb_incr;
225
226     /* mpeg1 picture header */
227     put_header(s, PICTURE_START_CODE);
228     /* temporal reference */
229     put_bits(&s->pb, 10, pict_num & 0x3ff); 
230     
231     put_bits(&s->pb, 3, P_TYPE);
232     put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
233     
234     put_bits(&s->pb, 1, 1); /* integer coordinates */
235     put_bits(&s->pb, 3, 1); /* forward_f_code */
236     
237     put_bits(&s->pb, 1, 0); /* extra bit picture */
238     
239     /* only one slice */
240     put_header(s, SLICE_MIN_START_CODE);
241     put_bits(&s->pb, 5, 1); /* quantizer scale */
242     put_bits(&s->pb, 1, 0); /* slice extra information */
243     
244     mb_incr = 1;
245     put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
246              mbAddrIncrTable[mb_incr - 1][0]);
247     
248     /* empty macroblock */
249     put_bits(&s->pb, 3, 1); /* motion only */
250     
251     /* zero motion x & y */
252     put_bits(&s->pb, 1, 1); 
253     put_bits(&s->pb, 1, 1); 
254
255     /* output a number of empty slice */
256     mb_incr = s->mb_width * s->mb_height - 1;
257     while (mb_incr > 33) {
258         put_bits(&s->pb, 11, 0x008);
259         mb_incr -= 33;
260     }
261     put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
262              mbAddrIncrTable[mb_incr - 1][0]);
263     
264     /* empty macroblock */
265     put_bits(&s->pb, 3, 1); /* motion only */
266     
267     /* zero motion x & y */
268     put_bits(&s->pb, 1, 1); 
269     put_bits(&s->pb, 1, 1); 
270 }
271
272 static void common_init(MpegEncContext *s)
273 {
274     s->y_dc_scale_table=
275     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
276 }
277
278 void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
279 {
280     mpeg1_encode_sequence_header(s);
281
282     /* mpeg1 picture header */
283     put_header(s, PICTURE_START_CODE);
284     /* temporal reference */
285     put_bits(&s->pb, 10, (s->fake_picture_number - 
286                           s->gop_picture_number) & 0x3ff); 
287     s->fake_picture_number++;
288     
289     put_bits(&s->pb, 3, s->pict_type);
290     put_bits(&s->pb, 16, 0xffff); /* non constant bit rate */
291     
292     if (s->pict_type == P_TYPE) {
293         put_bits(&s->pb, 1, 0); /* half pel coordinates */
294         put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
295     }
296     
297     put_bits(&s->pb, 1, 0); /* extra bit picture */
298     
299     /* only one slice */
300     put_header(s, SLICE_MIN_START_CODE);
301     put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
302     put_bits(&s->pb, 1, 0); /* slice extra information */
303 }
304
305 void mpeg1_encode_mb(MpegEncContext *s,
306                      DCTELEM block[6][64],
307                      int motion_x, int motion_y)
308 {
309     int mb_incr, i, cbp, mb_x, mb_y;
310
311     mb_x = s->mb_x;
312     mb_y = s->mb_y;
313
314     /* compute cbp */
315     cbp = 0;
316     for(i=0;i<6;i++) {
317         if (s->block_last_index[i] >= 0)
318             cbp |= 1 << (5 - i);
319     }
320
321     /* skip macroblock, except if first or last macroblock of a slice */
322     if ((cbp | motion_x | motion_y) == 0 &&
323         (!((mb_x | mb_y) == 0 ||
324            (mb_x == s->mb_width - 1 && mb_y == s->mb_height - 1)))) {
325         s->mb_incr++;
326         s->qscale -= s->dquant;
327         s->skip_count++;
328         s->misc_bits++;
329         s->last_bits++;
330     } else {
331         /* output mb incr */
332         mb_incr = s->mb_incr;
333
334         while (mb_incr > 33) {
335             put_bits(&s->pb, 11, 0x008);
336             mb_incr -= 33;
337         }
338         put_bits(&s->pb, mbAddrIncrTable[mb_incr - 1][1], 
339                  mbAddrIncrTable[mb_incr - 1][0]);
340         
341         if (s->pict_type == I_TYPE) {
342             if(s->dquant && cbp){
343                 put_bits(&s->pb, 2, 1); /* macroblock_type : macroblock_quant = 1 */
344                 put_bits(&s->pb, 5, s->qscale);
345             }else{
346                 put_bits(&s->pb, 1, 1); /* macroblock_type : macroblock_quant = 0 */
347                 s->qscale -= s->dquant;
348             }
349             s->misc_bits+= get_bits_diff(s);
350             s->i_count++;
351         } else {
352             if (s->mb_intra) {
353                 if(s->dquant && cbp){
354                     put_bits(&s->pb, 6, 0x01);
355                     put_bits(&s->pb, 5, s->qscale);
356                 }else{
357                     put_bits(&s->pb, 5, 0x03);
358                     s->qscale -= s->dquant;
359                 }
360                 s->misc_bits+= get_bits_diff(s);
361                 s->i_count++;
362             } else {
363                 if (cbp != 0) {
364                     if (motion_x == 0 && motion_y == 0) {
365                         if(s->dquant){
366                             put_bits(&s->pb, 5, 1); /* macroblock_pattern & quant */
367                             put_bits(&s->pb, 5, s->qscale);
368                         }else{
369                             put_bits(&s->pb, 2, 1); /* macroblock_pattern only */
370                         }
371                         s->misc_bits+= get_bits_diff(s);
372                         put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
373                     } else {
374                         if(s->dquant){
375                             put_bits(&s->pb, 5, 2); /* motion + cbp */
376                             put_bits(&s->pb, 5, s->qscale);
377                         }else{
378                             put_bits(&s->pb, 1, 1); /* motion + cbp */
379                         }
380                         s->misc_bits+= get_bits_diff(s);
381                         mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
382                         mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
383                         s->mv_bits+= get_bits_diff(s);
384                         put_bits(&s->pb, mbPatTable[cbp - 1][1], mbPatTable[cbp - 1][0]);
385                     }
386                 } else {
387                     put_bits(&s->pb, 3, 1); /* motion only */
388                     mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0]); 
389                     mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1]); 
390                     s->qscale -= s->dquant;
391                     s->mv_bits+= get_bits_diff(s);
392                 }
393                 s->f_count++;
394             }
395         }
396         for(i=0;i<6;i++) {
397             if (cbp & (1 << (5 - i))) {
398                 mpeg1_encode_block(s, block[i], i);
399             }
400         }
401         s->mb_incr = 1;
402         if(s->mb_intra)
403             s->i_tex_bits+= get_bits_diff(s);
404         else
405             s->p_tex_bits+= get_bits_diff(s);
406     }
407     s->last_mv[0][0][0] = motion_x;
408     s->last_mv[0][0][1] = motion_y;
409 }
410
411 static void mpeg1_encode_motion(MpegEncContext *s, int val)
412 {
413     int code, bit_size, l, m, bits, range, sign;
414
415     if (val == 0) {
416         /* zero vector */
417         code = 0;
418         put_bits(&s->pb,
419                  mbMotionVectorTable[0][1], 
420                  mbMotionVectorTable[0][0]); 
421     } else {
422         bit_size = s->f_code - 1;
423         range = 1 << bit_size;
424         /* modulo encoding */
425         l = 16 * range;
426         m = 2 * l;
427         if (val < -l) {
428             val += m;
429         } else if (val >= l) {
430             val -= m;
431         }
432
433         if (val >= 0) {
434             val--;
435             code = (val >> bit_size) + 1;
436             bits = val & (range - 1);
437             sign = 0;
438         } else {
439             val = -val;
440             val--;
441             code = (val >> bit_size) + 1;
442             bits = val & (range - 1);
443             sign = 1;
444         }
445         put_bits(&s->pb,
446                  mbMotionVectorTable[code][1], 
447                  mbMotionVectorTable[code][0]); 
448         put_bits(&s->pb, 1, sign);
449         if (bit_size > 0) {
450             put_bits(&s->pb, bit_size, bits);
451         }
452     }
453 }
454
455 void ff_mpeg1_encode_init(MpegEncContext *s)
456 {
457     static int done=0;
458
459     common_init(s);
460
461     if(!done){
462         int f_code;
463         int mv;
464         int i;
465
466         done=1;
467         init_rl(&rl_mpeg1);
468         
469         for(i=0; i<64; i++)
470         {
471                 mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
472                 mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
473         }
474
475         /* build unified dc encoding tables */
476         for(i=-255; i<256; i++)
477         {
478                 int adiff, index;
479                 int bits, code;
480                 int diff=i;
481
482                 adiff = ABS(diff);
483                 if(diff<0) diff--;
484                 index = vlc_dc_table[adiff];
485
486                 bits= vlc_dc_lum_bits[index] + index;
487                 code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
488                 mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
489                 
490                 bits= vlc_dc_chroma_bits[index] + index;
491                 code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
492                 mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
493         }
494
495         for(f_code=1; f_code<=MAX_FCODE; f_code++){
496             for(mv=-MAX_MV; mv<=MAX_MV; mv++){
497                 int len;
498
499                 if(mv==0) len= mbMotionVectorTable[0][1];
500                 else{
501                     int val, bit_size, range, code;
502
503                     bit_size = s->f_code - 1;
504                     range = 1 << bit_size;
505
506                     val=mv;
507                     if (val < 0) 
508                         val = -val;
509                     val--;
510                     code = (val >> bit_size) + 1;
511                     if(code<17){
512                         len= mbMotionVectorTable[code][1] + 1 + bit_size;
513                     }else{
514                         len= mbMotionVectorTable[16][1] + 2 + bit_size;
515                     }
516                 }
517
518                 mv_penalty[f_code][mv+MAX_MV]= len;
519             }
520         }
521         
522
523         for(f_code=MAX_FCODE; f_code>0; f_code--){
524             for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
525                 fcode_tab[mv+MAX_MV]= f_code;
526             }
527         }
528     }
529     s->mv_penalty= mv_penalty;
530     s->fcode_tab= fcode_tab;
531     s->min_qcoeff=-255;
532     s->max_qcoeff= 255;
533     s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
534     s->inter_quant_bias= 0;
535 }
536
537 static inline void encode_dc(MpegEncContext *s, int diff, int component)
538 {
539     if (component == 0) {
540         put_bits(
541             &s->pb, 
542             mpeg1_lum_dc_uni[diff+255]&0xFF,
543             mpeg1_lum_dc_uni[diff+255]>>8);
544     } else {
545         put_bits(
546             &s->pb, 
547             mpeg1_chr_dc_uni[diff+255]&0xFF,
548             mpeg1_chr_dc_uni[diff+255]>>8);
549     }
550 }
551
552 static void mpeg1_encode_block(MpegEncContext *s, 
553                                DCTELEM *block, 
554                                int n)
555 {
556     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
557     int code, component;
558 //    RLTable *rl = &rl_mpeg1;
559
560     last_index = s->block_last_index[n];
561
562     /* DC coef */
563     if (s->mb_intra) {
564         component = (n <= 3 ? 0 : n - 4 + 1);
565         dc = block[0]; /* overflow is impossible */
566         diff = dc - s->last_dc[component];
567         encode_dc(s, diff, component);
568         s->last_dc[component] = dc;
569         i = 1;
570     } else {
571         /* encode the first coefficient : needs to be done here because
572            it is handled slightly differently */
573         level = block[0];
574         if (abs(level) == 1) {
575                 code = ((UINT32)level >> 31); /* the sign bit */
576                 put_bits(&s->pb, 2, code | 0x02);
577                 i = 1;
578         } else {
579             i = 0;
580             last_non_zero = -1;
581             goto next_coef;
582         }
583     }
584
585     /* now quantify & encode AC coefs */
586     last_non_zero = i - 1;
587
588     for(;i<=last_index;i++) {
589         j = s->intra_scantable.permutated[i];
590         level = block[j];
591     next_coef:
592 #if 0
593         if (level != 0)
594             dprintf("level[%d]=%d\n", i, level);
595 #endif            
596         /* encode using VLC */
597         if (level != 0) {
598             run = i - last_non_zero - 1;
599             
600             alevel= level;
601             MASK_ABS(sign, alevel)
602             sign&=1;
603
604 //            code = get_rl_index(rl, 0, run, alevel);
605             if (alevel > mpeg1_max_level[0][run])
606                 code= 111; /*rl->n*/
607             else
608                 code= mpeg1_index_run[0][run] + alevel - 1;
609
610             if (code < 111 /* rl->n */) {
611                 /* store the vlc & sign at once */
612                 put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
613             } else {
614                 /* escape seems to be pretty rare <5% so i dont optimize it */
615                 put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
616                 /* escape: only clip in this case */
617                 put_bits(&s->pb, 6, run);
618                 if (alevel < 128) {
619                     put_bits(&s->pb, 8, level & 0xff);
620                 } else {
621                     if (level < 0) {
622                         put_bits(&s->pb, 16, 0x8001 + level + 255);
623                     } else {
624                         put_bits(&s->pb, 16, level & 0xffff);
625                     }
626                 }
627             }
628             last_non_zero = i;
629         }
630     }
631     /* end of block */
632     put_bits(&s->pb, 2, 0x2);
633 }
634
635 /******************************************/
636 /* decoding */
637
638 static VLC dc_lum_vlc;
639 static VLC dc_chroma_vlc;
640 static VLC mv_vlc;
641 static VLC mbincr_vlc;
642 static VLC mb_ptype_vlc;
643 static VLC mb_btype_vlc;
644 static VLC mb_pat_vlc;
645
646 static void init_vlcs(MpegEncContext *s)
647 {
648     static int done = 0;
649
650     if (!done) {
651         done = 1;
652
653         init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
654                  vlc_dc_lum_bits, 1, 1,
655                  vlc_dc_lum_code, 2, 2);
656         init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
657                  vlc_dc_chroma_bits, 1, 1,
658                  vlc_dc_chroma_code, 2, 2);
659         init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
660                  &mbMotionVectorTable[0][1], 2, 1,
661                  &mbMotionVectorTable[0][0], 2, 1);
662         init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 35, 
663                  &mbAddrIncrTable[0][1], 2, 1,
664                  &mbAddrIncrTable[0][0], 2, 1);
665         init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 63, 
666                  &mbPatTable[0][1], 2, 1,
667                  &mbPatTable[0][0], 2, 1);
668         
669         init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 32, 
670                  &table_mb_ptype[0][1], 2, 1,
671                  &table_mb_ptype[0][0], 2, 1);
672         init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 32, 
673                  &table_mb_btype[0][1], 2, 1,
674                  &table_mb_btype[0][0], 2, 1);
675         init_rl(&rl_mpeg1);
676         init_rl(&rl_mpeg2);
677
678         init_2d_vlc_rl(&rl_mpeg1);
679         init_2d_vlc_rl(&rl_mpeg2);
680     }
681 }
682
683 static inline int get_dmv(MpegEncContext *s)
684 {
685     if(get_bits1(&s->gb)) 
686         return 1 - (get_bits1(&s->gb) << 1);
687     else
688         return 0;
689 }
690
691 static inline int get_qscale(MpegEncContext *s)
692 {
693     int qscale;
694     if (s->mpeg2) {
695         if (s->q_scale_type) {
696             qscale = non_linear_qscale[get_bits(&s->gb, 5)];
697         } else {
698             qscale = get_bits(&s->gb, 5) << 1;
699         }
700     } else {
701         /* for mpeg1, we use the generic unquant code */
702         qscale = get_bits(&s->gb, 5);
703     }
704     return qscale;
705 }
706
707 /* motion type (for mpeg2) */
708 #define MT_FIELD 1
709 #define MT_FRAME 2
710 #define MT_16X8  2
711 #define MT_DMV   3
712
713 static int mpeg_decode_mb(MpegEncContext *s,
714                           DCTELEM block[6][64])
715 {
716     int i, j, k, cbp, val, mb_type, motion_type;
717     
718     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
719
720     if (--s->mb_incr != 0) {
721         /* skip mb */
722         s->mb_intra = 0;
723         for(i=0;i<6;i++)
724             s->block_last_index[i] = -1;
725         s->mv_type = MV_TYPE_16X16;
726         if (s->pict_type == P_TYPE) {
727             /* if P type, zero motion vector is implied */
728             s->mv_dir = MV_DIR_FORWARD;
729             s->mv[0][0][0] = s->mv[0][0][1] = 0;
730             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
731             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
732         } else {
733             /* if B type, reuse previous vectors and directions */
734             s->mv[0][0][0] = s->last_mv[0][0][0];
735             s->mv[0][0][1] = s->last_mv[0][0][1];
736             s->mv[1][0][0] = s->last_mv[1][0][0];
737             s->mv[1][0][1] = s->last_mv[1][0][1];
738         }
739
740         s->mb_skiped = 1;
741         return 0;
742     }
743
744     switch(s->pict_type) {
745     default:
746     case I_TYPE:
747         if (get_bits1(&s->gb) == 0) {
748             if (get_bits1(&s->gb) == 0)
749                 return -1;
750             mb_type = MB_QUANT | MB_INTRA;
751         } else {
752             mb_type = MB_INTRA;
753         }
754         break;
755     case P_TYPE:
756         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
757         if (mb_type < 0){
758             fprintf(stderr, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
759             return -1;
760         }
761         break;
762     case B_TYPE:
763         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
764         if (mb_type < 0){
765             fprintf(stderr, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
766             return -1;
767         }
768         break;
769     }
770     dprintf("mb_type=%x\n", mb_type);
771     motion_type = 0; /* avoid warning */
772     if (mb_type & (MB_FOR|MB_BACK)) {
773         /* get additionnal motion vector type */
774         if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
775             motion_type = MT_FRAME;
776         else
777             motion_type = get_bits(&s->gb, 2);
778     }
779     /* compute dct type */
780     if (s->picture_structure == PICT_FRAME && 
781         !s->frame_pred_frame_dct &&
782         (mb_type & (MB_PAT | MB_INTRA))) {
783         s->interlaced_dct = get_bits1(&s->gb);
784 #ifdef DEBUG
785         if (s->interlaced_dct)
786             printf("interlaced_dct\n");
787 #endif
788     } else {
789         s->interlaced_dct = 0; /* frame based */
790     }
791
792     if (mb_type & MB_QUANT) {
793         s->qscale = get_qscale(s);
794     }
795     if (mb_type & MB_INTRA) {
796         if (s->concealment_motion_vectors) {
797             /* just parse them */
798             if (s->picture_structure != PICT_FRAME) 
799                 skip_bits1(&s->gb); /* field select */
800             mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
801             mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
802         }
803         s->mb_intra = 1;
804         cbp = 0x3f;
805         memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
806     } else {
807         s->mb_intra = 0;
808         cbp = 0;
809     }
810     /* special case of implicit zero motion vector */
811     if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
812         s->mv_dir = MV_DIR_FORWARD;
813         s->mv_type = MV_TYPE_16X16;
814         s->last_mv[0][0][0] = 0;
815         s->last_mv[0][0][1] = 0;
816         s->last_mv[0][1][0] = 0;
817         s->last_mv[0][1][1] = 0;
818         s->mv[0][0][0] = 0;
819         s->mv[0][0][1] = 0;
820     } else if (mb_type & (MB_FOR | MB_BACK)) {
821         /* motion vectors */
822         s->mv_dir = 0;
823         for(i=0;i<2;i++) {
824             if (mb_type & (MB_FOR >> i)) {
825                 s->mv_dir |= (MV_DIR_FORWARD >> i);
826                 dprintf("motion_type=%d\n", motion_type);
827                 switch(motion_type) {
828                 case MT_FRAME: /* or MT_16X8 */
829                     if (s->picture_structure == PICT_FRAME) {
830                         /* MT_FRAME */
831                         s->mv_type = MV_TYPE_16X16;
832                         for(k=0;k<2;k++) {
833                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
834                                                      s->last_mv[i][0][k]);
835                             s->last_mv[i][0][k] = val;
836                             s->last_mv[i][1][k] = val;
837                             /* full_pel: only for mpeg1 */
838                             if (s->full_pel[i])
839                                 val = val << 1;
840                             s->mv[i][0][k] = val;
841                             dprintf("mv%d: %d\n", k, val);
842                         }
843                     } else {
844                         /* MT_16X8 */
845                         s->mv_type = MV_TYPE_16X8;
846                         for(j=0;j<2;j++) {
847                             s->field_select[i][j] = get_bits1(&s->gb);
848                             for(k=0;k<2;k++) {
849                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
850                                                          s->last_mv[i][j][k]);
851                                 s->last_mv[i][j][k] = val;
852                                 s->mv[i][j][k] = val;
853                             }
854                         }
855                     }
856                     break;
857                 case MT_FIELD:
858                     if (s->picture_structure == PICT_FRAME) {
859                         s->mv_type = MV_TYPE_FIELD;
860                         for(j=0;j<2;j++) {
861                             s->field_select[i][j] = get_bits1(&s->gb);
862                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
863                                                      s->last_mv[i][j][0]);
864                             s->last_mv[i][j][0] = val;
865                             s->mv[i][j][0] = val;
866                             dprintf("fmx=%d\n", val);
867                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
868                                                      s->last_mv[i][j][1] >> 1);
869                             s->last_mv[i][j][1] = val << 1;
870                             s->mv[i][j][1] = val;
871                             dprintf("fmy=%d\n", val);
872                         }
873                     } else {
874                         s->mv_type = MV_TYPE_16X16;
875                         s->field_select[i][0] = get_bits1(&s->gb);
876                         for(k=0;k<2;k++) {
877                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
878                                                      s->last_mv[i][0][k]);
879                             s->last_mv[i][0][k] = val;
880                             s->last_mv[i][1][k] = val;
881                             s->mv[i][0][k] = val;
882                         }
883                     }
884                     break;
885                 case MT_DMV:
886                     {
887                         int dmx, dmy, mx, my, m;
888
889                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
890                                                 s->last_mv[i][0][0]);
891                         s->last_mv[i][0][0] = mx;
892                         s->last_mv[i][1][0] = mx;
893                         dmx = get_dmv(s);
894                         my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
895                                                 s->last_mv[i][0][1] >> 1);
896                         dmy = get_dmv(s);
897                         s->mv_type = MV_TYPE_DMV;
898                         /* XXX: totally broken */
899                         if (s->picture_structure == PICT_FRAME) {
900                             s->last_mv[i][0][1] = my << 1;
901                             s->last_mv[i][1][1] = my << 1;
902
903                             m = s->top_field_first ? 1 : 3;
904                             /* top -> top pred */
905                             s->mv[i][0][0] = mx; 
906                             s->mv[i][0][1] = my << 1;
907                             s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
908                             s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
909                             m = 4 - m;
910                             s->mv[i][2][0] = mx;
911                             s->mv[i][2][1] = my << 1;
912                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
913                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
914                         } else {
915                             s->last_mv[i][0][1] = my;
916                             s->last_mv[i][1][1] = my;
917                             s->mv[i][0][0] = mx;
918                             s->mv[i][0][1] = my;
919                             s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
920                             s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
921                                 /* + 2 * cur_field */;
922                         }
923                     }
924                     break;
925                 }
926             }
927         }
928     }
929
930     if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
931         skip_bits1(&s->gb); /* marker */
932     }
933     
934     if (mb_type & MB_PAT) {
935         cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
936         if (cbp < 0){
937             fprintf(stderr, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
938             return -1;
939         }
940         cbp++;
941     }
942     dprintf("cbp=%x\n", cbp);
943
944     if (s->mpeg2) {
945         if (s->mb_intra) {
946             for(i=0;i<6;i++) {
947                 if (mpeg2_decode_block_intra(s, block[i], i) < 0)
948                     return -1;
949             }
950         } else {
951             for(i=0;i<6;i++) {
952                 if (cbp & 32) {
953                     if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
954                         return -1;
955                 } else {
956                     s->block_last_index[i] = -1;
957                 }
958                 cbp+=cbp;
959             }
960         }
961     } else {
962         if (s->mb_intra) {
963             for(i=0;i<6;i++) {
964                 if (mpeg1_decode_block_intra(s, block[i], i) < 0)
965                     return -1;
966             }
967         }else{
968             for(i=0;i<6;i++) {
969                 if (cbp & 32) {
970                     if (mpeg1_decode_block_inter(s, block[i], i) < 0)
971                         return -1;
972                 } else {
973                     s->block_last_index[i] = -1;
974                 }
975                 cbp+=cbp;
976             }
977         }
978     }
979     return 0;
980 }
981
982 /* as h263, but only 17 codes */
983 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
984 {
985     int code, sign, val, m, l, shift;
986
987     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
988     if (code < 0) {
989         return 0xffff;
990     }
991     if (code == 0) {
992         return pred;
993     }
994     sign = get_bits1(&s->gb);
995     shift = fcode - 1;
996     val = (code - 1) << shift;
997     if (shift > 0)
998         val |= get_bits(&s->gb, shift);
999     val++;
1000     if (sign)
1001         val = -val;
1002     val += pred;
1003     
1004     /* modulo decoding */
1005     l = (1 << shift) * 16;
1006     m = 2 * l;
1007     if (val < -l) {
1008         val += m;
1009     } else if (val >= l) {
1010         val -= m;
1011     }
1012     return val;
1013 }
1014
1015 static inline int decode_dc(MpegEncContext *s, int component)
1016 {
1017     int code, diff;
1018
1019     if (component == 0) {
1020         code = get_vlc2(&s->gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
1021     } else {
1022         code = get_vlc2(&s->gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
1023     }
1024     if (code < 0){
1025         fprintf(stderr, "invalid dc code at %d %d\n", s->mb_x, s->mb_y);
1026         return 0xffff;
1027     }
1028     if (code == 0) {
1029         diff = 0;
1030     } else {
1031         diff = get_bits(&s->gb, code);
1032         if ((diff & (1 << (code - 1))) == 0) 
1033             diff = (-1 << code) | (diff + 1);
1034     }
1035     return diff;
1036 }
1037
1038 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
1039                                DCTELEM *block, 
1040                                int n)
1041 {
1042     int level, dc, diff, i, j, run;
1043     int component;
1044     RLTable *rl = &rl_mpeg1;
1045     UINT8 * const scantable= s->intra_scantable.permutated;
1046     const UINT16 *quant_matrix= s->intra_matrix;
1047     const int qscale= s->qscale;
1048
1049     /* DC coef */
1050     component = (n <= 3 ? 0 : n - 4 + 1);
1051     diff = decode_dc(s, component);
1052     if (diff >= 0xffff)
1053         return -1;
1054     dc = s->last_dc[component];
1055     dc += diff;
1056     s->last_dc[component] = dc;
1057     block[0] = dc<<3;
1058     dprintf("dc=%d diff=%d\n", dc, diff);
1059     i = 0;
1060     {
1061         OPEN_READER(re, &s->gb);    
1062         /* now quantify & encode AC coefs */
1063         for(;;) {
1064             UPDATE_CACHE(re, &s->gb);
1065             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1066             
1067             if(level == 127){
1068                 break;
1069             } else if(level != 0) {
1070                 i += run;
1071                 j = scantable[i];
1072                 level= (level*qscale*quant_matrix[j])>>3;
1073                 level= (level-1)|1;
1074                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1075                 LAST_SKIP_BITS(re, &s->gb, 1);
1076             } else {
1077                 /* escape */
1078                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1079                 UPDATE_CACHE(re, &s->gb);
1080                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1081                 if (level == -128) {
1082                     level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1083                 } else if (level == 0) {
1084                     level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1085                 }
1086                 i += run;
1087                 j = scantable[i];
1088                 if(level<0){
1089                     level= -level;
1090                     level= (level*qscale*quant_matrix[j])>>3;
1091                     level= (level-1)|1;
1092                     level= -level;
1093                 }else{
1094                     level= (level*qscale*quant_matrix[j])>>3;
1095                     level= (level-1)|1;
1096                 }
1097             }
1098             if (i > 63){
1099                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1100                 return -1;
1101             }
1102
1103             block[j] = level;
1104         }
1105         CLOSE_READER(re, &s->gb);
1106     }
1107     s->block_last_index[n] = i;
1108    return 0;
1109 }
1110
1111 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
1112                                DCTELEM *block, 
1113                                int n)
1114 {
1115     int level, i, j, run;
1116     RLTable *rl = &rl_mpeg1;
1117     UINT8 * const scantable= s->intra_scantable.permutated;
1118     const UINT16 *quant_matrix= s->inter_matrix;
1119     const int qscale= s->qscale;
1120
1121     {
1122         int v;
1123         OPEN_READER(re, &s->gb);
1124         i = -1;
1125         /* special case for the first coef. no need to add a second vlc table */
1126         UPDATE_CACHE(re, &s->gb);
1127         v= SHOW_UBITS(re, &s->gb, 2);
1128         if (v & 2) {
1129             LAST_SKIP_BITS(re, &s->gb, 2);
1130             level= (3*qscale*quant_matrix[0])>>4;
1131             level= (level-1)|1;
1132             if(v&1)
1133                 level= -level;
1134             block[0] = level;
1135             i++;
1136         }
1137
1138         /* now quantify & encode AC coefs */
1139         for(;;) {
1140             UPDATE_CACHE(re, &s->gb);
1141             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1142             
1143             if(level == 127){
1144                 break;
1145             } else if(level != 0) {
1146                 i += run;
1147                 j = scantable[i];
1148                 level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1149                 level= (level-1)|1;
1150                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1151                 LAST_SKIP_BITS(re, &s->gb, 1);
1152             } else {
1153                 /* escape */
1154                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1155                 UPDATE_CACHE(re, &s->gb);
1156                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1157                 if (level == -128) {
1158                     level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1159                 } else if (level == 0) {
1160                     level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1161                 }
1162                 i += run;
1163                 j = scantable[i];
1164                 if(level<0){
1165                     level= -level;
1166                     level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1167                     level= (level-1)|1;
1168                     level= -level;
1169                 }else{
1170                     level= ((level*2+1)*qscale*quant_matrix[j])>>4;
1171                     level= (level-1)|1;
1172                 }
1173             }
1174             if (i > 63){
1175                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1176                 return -1;
1177             }
1178
1179             block[j] = level;
1180         }
1181         CLOSE_READER(re, &s->gb);
1182     }
1183     s->block_last_index[n] = i;
1184     return 0;
1185 }
1186
1187 /* Also does unquantization here, since I will never support mpeg2
1188    encoding */
1189 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1190                                DCTELEM *block, 
1191                                int n)
1192 {
1193     int level, i, j, run;
1194     RLTable *rl = &rl_mpeg1;
1195     UINT8 * const scantable= s->intra_scantable.permutated;
1196     const UINT16 *quant_matrix;
1197     const int qscale= s->qscale;
1198     int mismatch;
1199
1200     mismatch = 1;
1201
1202     {
1203         int v;
1204         OPEN_READER(re, &s->gb);
1205         i = -1;
1206         if (n < 4)
1207             quant_matrix = s->inter_matrix;
1208         else
1209             quant_matrix = s->chroma_inter_matrix;
1210
1211         /* special case for the first coef. no need to add a second vlc table */
1212         UPDATE_CACHE(re, &s->gb);
1213         v= SHOW_UBITS(re, &s->gb, 2);
1214         if (v & 2) {
1215             LAST_SKIP_BITS(re, &s->gb, 2);
1216             level= (3*qscale*quant_matrix[0])>>5;
1217             if(v&1)
1218                 level= -level;
1219             block[0] = level;
1220             mismatch ^= level;
1221             i++;
1222         }
1223
1224         /* now quantify & encode AC coefs */
1225         for(;;) {
1226             UPDATE_CACHE(re, &s->gb);
1227             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1228             
1229             if(level == 127){
1230                 break;
1231             } else if(level != 0) {
1232                 i += run;
1233                 j = scantable[i];
1234                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1235                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1236                 LAST_SKIP_BITS(re, &s->gb, 1);
1237             } else {
1238                 /* escape */
1239                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1240                 UPDATE_CACHE(re, &s->gb);
1241                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1242
1243                 i += run;
1244                 j = scantable[i];
1245                 if(level<0){
1246                     level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
1247                     level= -level;
1248                 }else{
1249                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1250                 }
1251             }
1252             if (i > 63){
1253                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1254                 return -1;
1255             }
1256             
1257             mismatch ^= level;
1258             block[j] = level;
1259         }
1260         CLOSE_READER(re, &s->gb);
1261     }
1262     block[63] ^= (mismatch & 1);
1263     
1264     s->block_last_index[n] = i;
1265     return 0;
1266 }
1267
1268 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
1269                                DCTELEM *block, 
1270                                int n)
1271 {
1272     int level, dc, diff, i, j, run;
1273     int component;
1274     RLTable *rl;
1275     UINT8 * const scantable= s->intra_scantable.permutated;
1276     const UINT16 *quant_matrix;
1277     const int qscale= s->qscale;
1278     int mismatch;
1279
1280     /* DC coef */
1281     if (n < 4){
1282         quant_matrix = s->intra_matrix;
1283         component = 0; 
1284     }else{
1285         quant_matrix = s->chroma_intra_matrix;
1286         component = n - 3;
1287     }
1288     diff = decode_dc(s, component);
1289     if (diff >= 0xffff)
1290         return -1;
1291     dc = s->last_dc[component];
1292     dc += diff;
1293     s->last_dc[component] = dc;
1294     block[0] = dc << (3 - s->intra_dc_precision);
1295     dprintf("dc=%d\n", block[0]);
1296     mismatch = block[0] ^ 1;
1297     i = 0;
1298     if (s->intra_vlc_format)
1299         rl = &rl_mpeg2;
1300     else
1301         rl = &rl_mpeg1;
1302
1303     {
1304         OPEN_READER(re, &s->gb);    
1305         /* now quantify & encode AC coefs */
1306         for(;;) {
1307             UPDATE_CACHE(re, &s->gb);
1308             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2);
1309             
1310             if(level == 127){
1311                 break;
1312             } else if(level != 0) {
1313                 i += run;
1314                 j = scantable[i];
1315                 level= (level*qscale*quant_matrix[j])>>4;
1316                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1317                 LAST_SKIP_BITS(re, &s->gb, 1);
1318             } else {
1319                 /* escape */
1320                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1321                 UPDATE_CACHE(re, &s->gb);
1322                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1323                 i += run;
1324                 j = scantable[i];
1325                 if(level<0){
1326                     level= (-level*qscale*quant_matrix[j])>>4;
1327                     level= -level;
1328                 }else{
1329                     level= (level*qscale*quant_matrix[j])>>4;
1330                 }
1331             }
1332             if (i > 63){
1333                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1334                 return -1;
1335             }
1336             
1337             mismatch^= level;
1338             block[j] = level;
1339         }
1340         CLOSE_READER(re, &s->gb);
1341     }
1342     block[63]^= mismatch&1;
1343     
1344     s->block_last_index[n] = i;
1345     return 0;
1346 }
1347
1348 /* compressed picture size */
1349 #define PICTURE_BUFFER_SIZE 100000
1350
1351 typedef struct Mpeg1Context {
1352     MpegEncContext mpeg_enc_ctx;
1353     UINT32 header_state;
1354     int start_code; /* current start code */
1355     UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1356     UINT8 *buf_ptr;
1357     int buffer_size;
1358     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1359     int repeat_field; /* true if we must repeat the field */
1360 } Mpeg1Context;
1361
1362 static int mpeg_decode_init(AVCodecContext *avctx)
1363 {
1364     Mpeg1Context *s = avctx->priv_data;
1365     
1366     s->mpeg_enc_ctx.flags= avctx->flags;
1367     common_init(&s->mpeg_enc_ctx);
1368     init_vlcs(&s->mpeg_enc_ctx);
1369
1370     s->header_state = 0xff;
1371     s->mpeg_enc_ctx_allocated = 0;
1372     s->buffer_size = PICTURE_BUFFER_SIZE;
1373     s->start_code = -1;
1374     s->buf_ptr = s->buffer;
1375     s->mpeg_enc_ctx.picture_number = 0;
1376     s->repeat_field = 0;
1377     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1378     return 0;
1379 }
1380
1381 /* return the 8 bit start code value and update the search
1382    state. Return -1 if no start code found */
1383 static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1384                            UINT32 *header_state)
1385 {
1386     UINT8 *buf_ptr;
1387     unsigned int state, v;
1388     int val;
1389
1390     state = *header_state;
1391     buf_ptr = *pbuf_ptr;
1392     while (buf_ptr < buf_end) {
1393         v = *buf_ptr++;
1394         if (state == 0x000001) {
1395             state = ((state << 8) | v) & 0xffffff;
1396             val = state;
1397             goto found;
1398         }
1399         state = ((state << 8) | v) & 0xffffff;
1400     }
1401     val = -1;
1402  found:
1403     *pbuf_ptr = buf_ptr;
1404     *header_state = state;
1405     return val;
1406 }
1407
1408 static int mpeg1_decode_picture(AVCodecContext *avctx, 
1409                                 UINT8 *buf, int buf_size)
1410 {
1411     Mpeg1Context *s1 = avctx->priv_data;
1412     MpegEncContext *s = &s1->mpeg_enc_ctx;
1413     int ref, f_code;
1414
1415     init_get_bits(&s->gb, buf, buf_size);
1416
1417     ref = get_bits(&s->gb, 10); /* temporal ref */
1418     s->pict_type = get_bits(&s->gb, 3);
1419     dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1420
1421     skip_bits(&s->gb, 16);
1422     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1423         s->full_pel[0] = get_bits1(&s->gb);
1424         f_code = get_bits(&s->gb, 3);
1425         if (f_code == 0)
1426             return -1;
1427         s->mpeg_f_code[0][0] = f_code;
1428         s->mpeg_f_code[0][1] = f_code;
1429     }
1430     if (s->pict_type == B_TYPE) {
1431         s->full_pel[1] = get_bits1(&s->gb);
1432         f_code = get_bits(&s->gb, 3);
1433         if (f_code == 0)
1434             return -1;
1435         s->mpeg_f_code[1][0] = f_code;
1436         s->mpeg_f_code[1][1] = f_code;
1437     }
1438     s->current_picture.pict_type= s->pict_type;
1439     s->current_picture.key_frame= s->pict_type == I_TYPE;
1440     
1441     s->y_dc_scale = 8;
1442     s->c_dc_scale = 8;
1443     s->first_slice = 1;
1444     return 0;
1445 }
1446
1447 static void mpeg_decode_sequence_extension(MpegEncContext *s)
1448 {
1449     int horiz_size_ext, vert_size_ext;
1450     int bit_rate_ext, vbv_buf_ext;
1451     int frame_rate_ext_n, frame_rate_ext_d;
1452     float aspect;
1453
1454     skip_bits(&s->gb, 8); /* profil and level */
1455     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1456     skip_bits(&s->gb, 2); /* chroma_format */
1457     horiz_size_ext = get_bits(&s->gb, 2);
1458     vert_size_ext = get_bits(&s->gb, 2);
1459     s->width |= (horiz_size_ext << 12);
1460     s->height |= (vert_size_ext << 12);
1461     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1462     s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1463     skip_bits1(&s->gb); /* marker */
1464     vbv_buf_ext = get_bits(&s->gb, 8);
1465     s->low_delay = get_bits1(&s->gb);
1466     frame_rate_ext_n = get_bits(&s->gb, 2);
1467     frame_rate_ext_d = get_bits(&s->gb, 5);
1468     if (frame_rate_ext_d >= 1)
1469         s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1470     dprintf("sequence extension\n");
1471     s->mpeg2 = 1;
1472     s->avctx->sub_id = 2; /* indicates mpeg2 found */
1473
1474     aspect= mpeg2_aspect[s->aspect_ratio_info];
1475     if(aspect>0.0)      s->avctx->aspect_ratio= s->width/(aspect*s->height);
1476     else if(aspect<0.0) s->avctx->aspect_ratio= -1.0/aspect;
1477 }
1478
1479 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1480 {
1481     int i, v, j;
1482
1483     dprintf("matrix extension\n");
1484
1485     if (get_bits1(&s->gb)) {
1486         for(i=0;i<64;i++) {
1487             v = get_bits(&s->gb, 8);
1488             j= s->idct_permutation[ ff_zigzag_direct[i] ];
1489             s->intra_matrix[j] = v;
1490             s->chroma_intra_matrix[j] = v;
1491         }
1492     }
1493     if (get_bits1(&s->gb)) {
1494         for(i=0;i<64;i++) {
1495             v = get_bits(&s->gb, 8);
1496             j= s->idct_permutation[ ff_zigzag_direct[i] ];
1497             s->inter_matrix[j] = v;
1498             s->chroma_inter_matrix[j] = v;
1499         }
1500     }
1501     if (get_bits1(&s->gb)) {
1502         for(i=0;i<64;i++) {
1503             v = get_bits(&s->gb, 8);
1504             j= s->idct_permutation[ ff_zigzag_direct[i] ];
1505             s->chroma_intra_matrix[j] = v;
1506         }
1507     }
1508     if (get_bits1(&s->gb)) {
1509         for(i=0;i<64;i++) {
1510             v = get_bits(&s->gb, 8);
1511             j= s->idct_permutation[ ff_zigzag_direct[i] ];
1512             s->chroma_inter_matrix[j] = v;
1513         }
1514     }
1515 }
1516
1517 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1518 {
1519     s->full_pel[0] = s->full_pel[1] = 0;
1520     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1521     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1522     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1523     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1524     s->intra_dc_precision = get_bits(&s->gb, 2);
1525     s->picture_structure = get_bits(&s->gb, 2);
1526     s->top_field_first = get_bits1(&s->gb);
1527     s->frame_pred_frame_dct = get_bits1(&s->gb);
1528     s->concealment_motion_vectors = get_bits1(&s->gb);
1529     s->q_scale_type = get_bits1(&s->gb);
1530     s->intra_vlc_format = get_bits1(&s->gb);
1531     s->alternate_scan = get_bits1(&s->gb);
1532     s->repeat_first_field = get_bits1(&s->gb);
1533     s->chroma_420_type = get_bits1(&s->gb);
1534     s->progressive_frame = get_bits1(&s->gb);
1535     
1536     if(s->alternate_scan){
1537         ff_init_scantable(s, &s->inter_scantable  , ff_alternate_vertical_scan);
1538         ff_init_scantable(s, &s->intra_scantable  , ff_alternate_vertical_scan);
1539         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_vertical_scan);
1540         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1541     }else{
1542         ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
1543         ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
1544         ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
1545         ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
1546     }
1547     
1548     /* composite display not parsed */
1549     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1550     dprintf("picture_structure=%d\n", s->picture_structure);
1551     dprintf("top field first=%d\n", s->top_field_first);
1552     dprintf("repeat first field=%d\n", s->repeat_first_field);
1553     dprintf("conceal=%d\n", s->concealment_motion_vectors);
1554     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1555     dprintf("alternate_scan=%d\n", s->alternate_scan);
1556     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1557     dprintf("progressive_frame=%d\n", s->progressive_frame);
1558 }
1559
1560 static void mpeg_decode_extension(AVCodecContext *avctx, 
1561                                   UINT8 *buf, int buf_size)
1562 {
1563     Mpeg1Context *s1 = avctx->priv_data;
1564     MpegEncContext *s = &s1->mpeg_enc_ctx;
1565     int ext_type;
1566
1567     init_get_bits(&s->gb, buf, buf_size);
1568     
1569     ext_type = get_bits(&s->gb, 4);
1570     switch(ext_type) {
1571     case 0x1:
1572         /* sequence ext */
1573         mpeg_decode_sequence_extension(s);
1574         break;
1575     case 0x3:
1576         /* quant matrix extension */
1577         mpeg_decode_quant_matrix_extension(s);
1578         break;
1579     case 0x8:
1580         /* picture extension */
1581         mpeg_decode_picture_coding_extension(s);
1582         break;
1583     }
1584 }
1585
1586 #define DECODE_SLICE_FATAL_ERROR -2
1587 #define DECODE_SLICE_ERROR -1
1588 #define DECODE_SLICE_OK 0
1589 #define DECODE_SLICE_EOP 1
1590
1591 /**
1592  * decodes a slice.
1593  * @return DECODE_SLICE_FATAL_ERROR if a non recoverable error occured<br>
1594  *         DECODE_SLICE_ERROR if the slice is damaged<br>
1595  *         DECODE_SLICE_OK if this slice is ok<br>
1596  *         DECODE_SLICE_EOP if the end of the picture is reached
1597  */
1598 static int mpeg_decode_slice(AVCodecContext *avctx, 
1599                               AVFrame *pict,
1600                               int start_code,
1601                               UINT8 *buf, int buf_size)
1602 {
1603     Mpeg1Context *s1 = avctx->priv_data;
1604     MpegEncContext *s = &s1->mpeg_enc_ctx;
1605     int ret;
1606
1607     start_code = (start_code - 1) & 0xff;
1608     if (start_code >= s->mb_height){
1609         fprintf(stderr, "slice below image (%d >= %d)\n", start_code, s->mb_height);
1610         return DECODE_SLICE_ERROR;
1611     }
1612     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1613     s->last_dc[1] = s->last_dc[0];
1614     s->last_dc[2] = s->last_dc[0];
1615     memset(s->last_mv, 0, sizeof(s->last_mv));
1616     /* start frame decoding */
1617     if (s->first_slice) {
1618         s->first_slice = 0;
1619         if(MPV_frame_start(s, avctx) < 0)
1620             return DECODE_SLICE_FATAL_ERROR;
1621             
1622         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
1623              printf("qp:%d fc:%d%d%d%d %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n", 
1624                  s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1],
1625                  s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
1626                  s->progressive_sequence ? "pro" :"", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", 
1627                  s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
1628                  s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
1629         }
1630     }
1631
1632     init_get_bits(&s->gb, buf, buf_size);
1633
1634     s->qscale = get_qscale(s);
1635     /* extra slice info */
1636     while (get_bits1(&s->gb) != 0) {
1637         skip_bits(&s->gb, 8);
1638     }
1639
1640     s->mb_x=0;
1641     for(;;) {
1642         int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1643         if (code < 0)
1644             return -1; /* error = end of slice, but empty slice is bad or?*/
1645         if (code >= 33) {
1646             if (code == 33) {
1647                 s->mb_x += 33;
1648             }
1649             /* otherwise, stuffing, nothing to do */
1650         } else {
1651             s->mb_x += code;
1652             break;
1653         }
1654     }
1655     s->mb_y = start_code;
1656     s->mb_incr= 1;
1657
1658     for(;;) {
1659         s->dsp.clear_blocks(s->block[0]);
1660         
1661         ret = mpeg_decode_mb(s, s->block);
1662         dprintf("ret=%d\n", ret);
1663         if (ret < 0)
1664             return -1;
1665     
1666         MPV_decode_mb(s, s->block);
1667
1668         if (++s->mb_x >= s->mb_width) {
1669             ff_draw_horiz_band(s);
1670
1671             s->mb_x = 0;
1672             s->mb_y++;
1673             PRINT_QP("%s", "\n");
1674         }
1675         PRINT_QP("%2d", s->qscale);
1676
1677         /* skip mb handling */
1678         if (s->mb_incr == 0) {
1679             /* read again increment */
1680             s->mb_incr = 1;
1681             for(;;) {
1682                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1683                 if (code < 0)
1684                     goto eos; /* error = end of slice */
1685                 if (code >= 33) {
1686                     if (code == 33) {
1687                         s->mb_incr += 33;
1688                     }
1689                     /* otherwise, stuffing, nothing to do */
1690                 } else {
1691                     s->mb_incr += code;
1692                     break;
1693                 }
1694             }
1695         }
1696         if(s->mb_y >= s->mb_height){
1697             fprintf(stderr, "slice too long\n");
1698             return DECODE_SLICE_ERROR;
1699         }
1700     }
1701 eos: //end of slice
1702     
1703     emms_c();
1704
1705     /* end of slice reached */
1706     if (/*s->mb_x == 0 &&*/
1707         s->mb_y == s->mb_height) {
1708         /* end of image */
1709
1710         if(s->mpeg2)
1711             s->qscale >>=1;
1712
1713         MPV_frame_end(s);
1714
1715         if (s->pict_type == B_TYPE || s->low_delay) {
1716             *pict= *(AVFrame*)&s->current_picture;
1717         } else {
1718             s->picture_number++;
1719             /* latency of 1 frame for I and P frames */
1720             /* XXX: use another variable than picture_number */
1721             if (s->last_picture.data[0] == NULL) {
1722                 return DECODE_SLICE_OK;
1723             } else {
1724                 *pict= *(AVFrame*)&s->last_picture;
1725             }
1726         }
1727         return DECODE_SLICE_EOP;
1728     } else {
1729         return DECODE_SLICE_OK;
1730     }
1731 }
1732
1733 static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1734                                  UINT8 *buf, int buf_size)
1735 {
1736     Mpeg1Context *s1 = avctx->priv_data;
1737     MpegEncContext *s = &s1->mpeg_enc_ctx;
1738     int width, height, i, v, j;
1739     float aspect;
1740
1741     init_get_bits(&s->gb, buf, buf_size);
1742
1743     width = get_bits(&s->gb, 12);
1744     height = get_bits(&s->gb, 12);
1745     s->aspect_ratio_info= get_bits(&s->gb, 4);
1746     if(!s->mpeg2){
1747         aspect= mpeg1_aspect[s->aspect_ratio_info];
1748         if(aspect!=0.0) avctx->aspect_ratio= width/(aspect*height);
1749     }
1750
1751     s->frame_rate_index = get_bits(&s->gb, 4);
1752     if (s->frame_rate_index == 0)
1753         return -1;
1754     s->bit_rate = get_bits(&s->gb, 18) * 400;
1755     if (get_bits1(&s->gb) == 0) /* marker */
1756         return -1;
1757     if (width <= 0 || height <= 0 ||
1758         (width % 2) != 0 || (height % 2) != 0)
1759         return -1;
1760     if (width != s->width ||
1761         height != s->height) {
1762         /* start new mpeg1 context decoding */
1763         s->out_format = FMT_MPEG1;
1764         if (s1->mpeg_enc_ctx_allocated) {
1765             MPV_common_end(s);
1766         }
1767         s->width = width;
1768         s->height = height;
1769         avctx->has_b_frames= 1;
1770         s->avctx = avctx;
1771         avctx->width = width;
1772         avctx->height = height;
1773         if (s->frame_rate_index >= 9) {
1774             /* at least give a valid frame rate (some old mpeg1 have this) */
1775             avctx->frame_rate = 25 * FRAME_RATE_BASE;
1776         } else {
1777             avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1778         }
1779         s->frame_rate = avctx->frame_rate;
1780         avctx->bit_rate = s->bit_rate;
1781         
1782         if (MPV_common_init(s) < 0)
1783             return -1;
1784         s1->mpeg_enc_ctx_allocated = 1;
1785     }
1786
1787     skip_bits(&s->gb, 10); /* vbv_buffer_size */
1788     skip_bits(&s->gb, 1);
1789
1790     /* get matrix */
1791     if (get_bits1(&s->gb)) {
1792         for(i=0;i<64;i++) {
1793             v = get_bits(&s->gb, 8);
1794             j = s->intra_scantable.permutated[i];
1795             s->intra_matrix[j] = v;
1796             s->chroma_intra_matrix[j] = v;
1797         }
1798 #ifdef DEBUG
1799         dprintf("intra matrix present\n");
1800         for(i=0;i<64;i++)
1801             dprintf(" %d", s->intra_matrix[s->intra_scantable.permutated[i]]);
1802         printf("\n");
1803 #endif
1804     } else {
1805         for(i=0;i<64;i++) {
1806             int j= s->idct_permutation[i];
1807             v = ff_mpeg1_default_intra_matrix[i];
1808             s->intra_matrix[j] = v;
1809             s->chroma_intra_matrix[j] = v;
1810         }
1811     }
1812     if (get_bits1(&s->gb)) {
1813         for(i=0;i<64;i++) {
1814             v = get_bits(&s->gb, 8);
1815             j = s->intra_scantable.permutated[i];
1816             s->inter_matrix[j] = v;
1817             s->chroma_inter_matrix[j] = v;
1818         }
1819 #ifdef DEBUG
1820         dprintf("non intra matrix present\n");
1821         for(i=0;i<64;i++)
1822             dprintf(" %d", s->inter_matrix[s->intra_scantable.permutated[i]]);
1823         printf("\n");
1824 #endif
1825     } else {
1826         for(i=0;i<64;i++) {
1827             int j= s->idct_permutation[i];
1828             v = ff_mpeg1_default_non_intra_matrix[i];
1829             s->inter_matrix[j] = v;
1830             s->chroma_inter_matrix[j] = v;
1831         }
1832     }
1833
1834     /* we set mpeg2 parameters so that it emulates mpeg1 */
1835     s->progressive_sequence = 1;
1836     s->progressive_frame = 1;
1837     s->picture_structure = PICT_FRAME;
1838     s->frame_pred_frame_dct = 1;
1839     s->mpeg2 = 0;
1840     avctx->sub_id = 1; /* indicates mpeg1 */
1841     return 0;
1842 }
1843
1844 /* handle buffering and image synchronisation */
1845 static int mpeg_decode_frame(AVCodecContext *avctx, 
1846                              void *data, int *data_size,
1847                              UINT8 *buf, int buf_size)
1848 {
1849     Mpeg1Context *s = avctx->priv_data;
1850     UINT8 *buf_end, *buf_ptr, *buf_start;
1851     int len, start_code_found, ret, code, start_code, input_size;
1852     AVFrame *picture = data;
1853     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1854             
1855     dprintf("fill_buffer\n");
1856
1857     *data_size = 0;
1858
1859     /* special case for last picture */
1860     if (buf_size == 0) {
1861         if (s2->picture_number > 0) {
1862             *picture= *(AVFrame*)&s2->next_picture;
1863
1864             *data_size = sizeof(AVFrame);
1865         }
1866         return 0;
1867     }
1868
1869     buf_ptr = buf;
1870     buf_end = buf + buf_size;
1871
1872 #if 0    
1873     if (s->repeat_field % 2 == 1) { 
1874         s->repeat_field++;
1875         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1876         //        s2->picture_number, s->repeat_field);
1877         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1878             *data_size = sizeof(AVPicture);
1879             goto the_end;
1880         }
1881     }
1882 #endif
1883     while (buf_ptr < buf_end) {
1884         buf_start = buf_ptr;
1885         /* find start next code */
1886         code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1887         if (code >= 0) {
1888             start_code_found = 1;
1889         } else {
1890             start_code_found = 0;
1891         }
1892         /* copy to buffer */
1893         len = buf_ptr - buf_start;
1894         if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1895             /* data too big : flush */
1896             s->buf_ptr = s->buffer;
1897             if (start_code_found)
1898                 s->start_code = code;
1899         } else {
1900             memcpy(s->buf_ptr, buf_start, len);
1901             s->buf_ptr += len;
1902             if(   (!(s2->flags&CODEC_FLAG_TRUNCATED)) && (!start_code_found) 
1903                && s->buf_ptr+4<s->buffer+s->buffer_size){
1904                 start_code_found= 1;
1905                 code= 0x1FF;
1906                 s->header_state=0xFF;
1907                 s->buf_ptr[0]=0;
1908                 s->buf_ptr[1]=0;
1909                 s->buf_ptr[2]=1;
1910                 s->buf_ptr[3]=0xFF;
1911                 s->buf_ptr+=4;
1912             }
1913             if (start_code_found) {
1914                 /* prepare data for next start code */
1915                 input_size = s->buf_ptr - s->buffer;
1916                 start_code = s->start_code;
1917                 s->buf_ptr = s->buffer;
1918                 s->start_code = code;
1919                 switch(start_code) {
1920                 case SEQ_START_CODE:
1921                     mpeg1_decode_sequence(avctx, s->buffer, 
1922                                           input_size);
1923                     break;
1924                             
1925                 case PICTURE_START_CODE:
1926                     /* we have a complete image : we try to decompress it */
1927                     mpeg1_decode_picture(avctx, 
1928                                          s->buffer, input_size);
1929                     break;
1930                 case EXT_START_CODE:
1931                     mpeg_decode_extension(avctx,
1932                                           s->buffer, input_size);
1933                     break;
1934                 default:
1935                     if (start_code >= SLICE_MIN_START_CODE &&
1936                         start_code <= SLICE_MAX_START_CODE) {
1937                         
1938                         /* skip b frames if we dont have reference frames */
1939                         if(s2->last_picture.data[0]==NULL && s2->pict_type==B_TYPE) break;
1940                         /* skip b frames if we are in a hurry */
1941                         if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
1942                         /* skip everything if we are in a hurry>=5 */
1943                         if(avctx->hurry_up>=5) break;
1944
1945                         ret = mpeg_decode_slice(avctx, picture,
1946                                                 start_code, s->buffer, input_size);
1947                         if (ret == DECODE_SLICE_EOP) {
1948                             /* got a picture: exit */
1949                             /* first check if we must repeat the frame */
1950                             avctx->repeat_pict = 0;
1951 #if 0
1952                             if (s2->progressive_frame && s2->repeat_first_field) {
1953                                 //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1954                                 //s2->repeat_first_field = 0;
1955                                 //s2->progressive_frame = 0;
1956                                 if (++s->repeat_field > 2)
1957                                     s->repeat_field = 0;
1958                                 avctx->repeat_pict = 1;
1959                             }
1960 #endif                      
1961                             if (s2->repeat_first_field) {
1962                                 if (s2->progressive_sequence) {
1963                                     if (s2->top_field_first)
1964                                         avctx->repeat_pict = 4;
1965                                     else
1966                                         avctx->repeat_pict = 2;
1967                                 } else if (s2->progressive_frame) {
1968                                     avctx->repeat_pict = 1;
1969                                 }
1970                             }         
1971                             *data_size = sizeof(AVPicture);
1972                             goto the_end;
1973                         }else if(ret<0){
1974                             fprintf(stderr,"Error while decoding slice\n");
1975                             if(ret==DECODE_SLICE_FATAL_ERROR) return -1;
1976                         }
1977                     }
1978                     break;
1979                 }
1980             }
1981         }
1982     }
1983  the_end:
1984     return buf_ptr - buf;
1985 }
1986
1987 static int mpeg_decode_end(AVCodecContext *avctx)
1988 {
1989     Mpeg1Context *s = avctx->priv_data;
1990
1991     if (s->mpeg_enc_ctx_allocated)
1992         MPV_common_end(&s->mpeg_enc_ctx);
1993     return 0;
1994 }
1995
1996 AVCodec mpeg_decoder = {
1997     "mpegvideo",
1998     CODEC_TYPE_VIDEO,
1999     CODEC_ID_MPEG1VIDEO,
2000     sizeof(Mpeg1Context),
2001     mpeg_decode_init,
2002     NULL,
2003     mpeg_decode_end,
2004     mpeg_decode_frame,
2005     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED,
2006 };