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