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