]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpeg12.c
- repeat_pict meaning changed, now it signals the extra delay for the
[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     s->fcode_tab= fcode_tab;
403     s->min_qcoeff=-255;
404     s->max_qcoeff= 255;
405     s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
406     s->inter_quant_bias= 0;
407 }
408  
409 static inline void encode_dc(MpegEncContext *s, int diff, int component)
410 {
411     if (component == 0) {
412         put_bits(
413             &s->pb, 
414             mpeg1_lum_dc_uni[diff+255]&0xFF,
415             mpeg1_lum_dc_uni[diff+255]>>8);
416     } else {
417         put_bits(
418             &s->pb, 
419             mpeg1_chr_dc_uni[diff+255]&0xFF,
420             mpeg1_chr_dc_uni[diff+255]>>8);
421     }
422 }
423
424 static void mpeg1_encode_block(MpegEncContext *s, 
425                                DCTELEM *block, 
426                                int n)
427 {
428     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
429     int code, component;
430 //    RLTable *rl = &rl_mpeg1;
431
432     last_index = s->block_last_index[n];
433
434     /* DC coef */
435     if (s->mb_intra) {
436         component = (n <= 3 ? 0 : n - 4 + 1);
437         dc = block[0]; /* overflow is impossible */
438         diff = dc - s->last_dc[component];
439         encode_dc(s, diff, component);
440         s->last_dc[component] = dc;
441         i = 1;
442     } else {
443         /* encode the first coefficient : needs to be done here because
444            it is handled slightly differently */
445         level = block[0];
446         if (abs(level) == 1) {
447                 code = ((UINT32)level >> 31); /* the sign bit */
448                 put_bits(&s->pb, 2, code | 0x02);
449                 i = 1;
450         } else {
451             i = 0;
452             last_non_zero = -1;
453             goto next_coef;
454         }
455     }
456
457     /* now quantify & encode AC coefs */
458     last_non_zero = i - 1;
459
460     for(;i<=last_index;i++) {
461         j = zigzag_direct[i];
462         level = block[j];
463     next_coef:
464 #if 0
465         if (level != 0)
466             dprintf("level[%d]=%d\n", i, level);
467 #endif            
468         /* encode using VLC */
469         if (level != 0) {
470             run = i - last_non_zero - 1;
471 #ifdef ARCH_X86
472             asm volatile(
473                 "movl %2, %1            \n\t"
474                 "movl %1, %0            \n\t"
475                 "addl %1, %1            \n\t"
476                 "sbbl %1, %1            \n\t"
477                 "xorl %1, %0            \n\t"
478                 "subl %1, %0            \n\t"
479                 "andl $1, %1            \n\t"
480                 : "=&r" (alevel), "=&r" (sign)
481                 : "g" (level)
482             );
483 #else
484             sign = 0;
485             alevel = level;
486             if (alevel < 0) {
487                 sign = 1;
488                 alevel = -alevel;
489             }
490 #endif
491 //            code = get_rl_index(rl, 0, run, alevel);
492             if (alevel > mpeg1_max_level[0][run])
493                 code= 111; /*rl->n*/
494             else
495                 code= mpeg1_index_run[0][run] + alevel - 1;
496
497             if (code < 111 /* rl->n */) {
498                 /* store the vlc & sign at once */
499                 put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
500             } else {
501                 /* escape seems to be pretty rare <5% so i dont optimize it */
502                 put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
503                 /* escape: only clip in this case */
504                 put_bits(&s->pb, 6, run);
505                 if (alevel < 128) {
506                     put_bits(&s->pb, 8, level & 0xff);
507                 } else {
508                     if (level < 0) {
509                         put_bits(&s->pb, 16, 0x8001 + level + 255);
510                     } else {
511                         put_bits(&s->pb, 16, level & 0xffff);
512                     }
513                 }
514             }
515             last_non_zero = i;
516         }
517     }
518     /* end of block */
519     put_bits(&s->pb, 2, 0x2);
520 }
521
522 /******************************************/
523 /* decoding */
524
525 static VLC dc_lum_vlc;
526 static VLC dc_chroma_vlc;
527 static VLC mv_vlc;
528 static VLC mbincr_vlc;
529 static VLC mb_ptype_vlc;
530 static VLC mb_btype_vlc;
531 static VLC mb_pat_vlc;
532
533 void mpeg1_init_vlc(MpegEncContext *s)
534 {
535     static int done = 0;
536
537     if (!done) {
538
539         init_vlc(&dc_lum_vlc, 9, 12, 
540                  vlc_dc_lum_bits, 1, 1,
541                  vlc_dc_lum_code, 2, 2);
542         init_vlc(&dc_chroma_vlc, 9, 12, 
543                  vlc_dc_chroma_bits, 1, 1,
544                  vlc_dc_chroma_code, 2, 2);
545         init_vlc(&mv_vlc, 9, 17, 
546                  &mbMotionVectorTable[0][1], 2, 1,
547                  &mbMotionVectorTable[0][0], 2, 1);
548         init_vlc(&mbincr_vlc, 9, 35, 
549                  &mbAddrIncrTable[0][1], 2, 1,
550                  &mbAddrIncrTable[0][0], 2, 1);
551         init_vlc(&mb_pat_vlc, 9, 63, 
552                  &mbPatTable[0][1], 2, 1,
553                  &mbPatTable[0][0], 2, 1);
554         
555         init_vlc(&mb_ptype_vlc, 6, 32, 
556                  &table_mb_ptype[0][1], 2, 1,
557                  &table_mb_ptype[0][0], 2, 1);
558         init_vlc(&mb_btype_vlc, 6, 32, 
559                  &table_mb_btype[0][1], 2, 1,
560                  &table_mb_btype[0][0], 2, 1);
561         init_rl(&rl_mpeg1);
562         init_rl(&rl_mpeg2);
563         /* cannot use generic init because we must add the EOB code */
564         init_vlc(&rl_mpeg1.vlc, 9, rl_mpeg1.n + 2, 
565                  &rl_mpeg1.table_vlc[0][1], 4, 2,
566                  &rl_mpeg1.table_vlc[0][0], 4, 2);
567         init_vlc(&rl_mpeg2.vlc, 9, rl_mpeg2.n + 2, 
568                  &rl_mpeg2.table_vlc[0][1], 4, 2,
569                  &rl_mpeg2.table_vlc[0][0], 4, 2);
570     }
571 }
572
573 static inline int get_dmv(MpegEncContext *s)
574 {
575     if(get_bits1(&s->gb)) 
576         return 1 - (get_bits1(&s->gb) << 1);
577     else
578         return 0;
579 }
580
581 static inline int get_qscale(MpegEncContext *s)
582 {
583     int qscale;
584     if (s->mpeg2) {
585         if (s->q_scale_type) {
586             qscale = non_linear_qscale[get_bits(&s->gb, 5)];
587         } else {
588             qscale = get_bits(&s->gb, 5) << 1;
589         }
590     } else {
591         /* for mpeg1, we use the generic unquant code */
592         qscale = get_bits(&s->gb, 5);
593     }
594     return qscale;
595 }
596
597 /* motion type (for mpeg2) */
598 #define MT_FIELD 1
599 #define MT_FRAME 2
600 #define MT_16X8  2
601 #define MT_DMV   3
602
603 static int mpeg_decode_mb(MpegEncContext *s,
604                           DCTELEM block[6][64])
605 {
606     int i, j, k, cbp, val, code, mb_type, motion_type;
607     
608     /* skip mb handling */
609     if (s->mb_incr == 0) {
610         /* read again increment */
611         s->mb_incr = 1;
612         for(;;) {
613             code = get_vlc(&s->gb, &mbincr_vlc);
614             if (code < 0)
615                 return 1; /* error = end of slice */
616             if (code >= 33) {
617                 if (code == 33) {
618                     s->mb_incr += 33;
619                 }
620                 /* otherwise, stuffing, nothing to do */
621             } else {
622                 s->mb_incr += code;
623                 break;
624             }
625         }
626     }
627     if (++s->mb_x >= s->mb_width) {
628         s->mb_x = 0;
629         if (s->mb_y >= (s->mb_height - 1))
630             return -1;
631         s->mb_y++;
632     }
633     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
634
635     if (--s->mb_incr != 0) {
636         /* skip mb */
637         s->mb_intra = 0;
638         for(i=0;i<6;i++)
639             s->block_last_index[i] = -1;
640         s->mv_type = MV_TYPE_16X16;
641         if (s->pict_type == P_TYPE) {
642             /* if P type, zero motion vector is implied */
643             s->mv_dir = MV_DIR_FORWARD;
644             s->mv[0][0][0] = s->mv[0][0][1] = 0;
645             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
646             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
647         } else {
648             /* if B type, reuse previous vectors and directions */
649             s->mv[0][0][0] = s->last_mv[0][0][0];
650             s->mv[0][0][1] = s->last_mv[0][0][1];
651             s->mv[1][0][0] = s->last_mv[1][0][0];
652             s->mv[1][0][1] = s->last_mv[1][0][1];
653         }
654         s->mb_skiped = 1;
655         return 0;
656     }
657
658     switch(s->pict_type) {
659     default:
660     case I_TYPE:
661         if (get_bits1(&s->gb) == 0) {
662             if (get_bits1(&s->gb) == 0)
663                 return -1;
664             mb_type = MB_QUANT | MB_INTRA;
665         } else {
666             mb_type = MB_INTRA;
667         }
668         break;
669     case P_TYPE:
670         mb_type = get_vlc(&s->gb, &mb_ptype_vlc);
671         if (mb_type < 0)
672             return -1;
673         break;
674     case B_TYPE:
675         mb_type = get_vlc(&s->gb, &mb_btype_vlc);
676         if (mb_type < 0)
677             return -1;
678         break;
679     }
680     dprintf("mb_type=%x\n", mb_type);
681     motion_type = 0; /* avoid warning */
682     if (mb_type & (MB_FOR|MB_BACK)) {
683         /* get additionnal motion vector type */
684         if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) 
685             motion_type = MT_FRAME;
686         else
687             motion_type = get_bits(&s->gb, 2);
688     }
689     /* compute dct type */
690     if (s->picture_structure == PICT_FRAME && 
691         !s->frame_pred_frame_dct &&
692         (mb_type & (MB_PAT | MB_INTRA))) {
693         s->interlaced_dct = get_bits1(&s->gb);
694 #ifdef DEBUG
695         if (s->interlaced_dct)
696             printf("interlaced_dct\n");
697 #endif
698     } else {
699         s->interlaced_dct = 0; /* frame based */
700     }
701
702     if (mb_type & MB_QUANT) {
703         s->qscale = get_qscale(s);
704     }
705     if (mb_type & MB_INTRA) {
706         if (s->concealment_motion_vectors) {
707             /* just parse them */
708             if (s->picture_structure != PICT_FRAME) 
709                 skip_bits1(&s->gb); /* field select */
710             mpeg_decode_motion(s, s->mpeg_f_code[0][0], 0);
711             mpeg_decode_motion(s, s->mpeg_f_code[0][1], 0);
712         }
713         s->mb_intra = 1;
714         cbp = 0x3f;
715         memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
716     } else {
717         s->mb_intra = 0;
718         cbp = 0;
719     }
720     /* special case of implicit zero motion vector */
721     if (s->pict_type == P_TYPE && !(mb_type & MB_FOR)) {
722         s->mv_dir = MV_DIR_FORWARD;
723         s->mv_type = MV_TYPE_16X16;
724         s->last_mv[0][0][0] = 0;
725         s->last_mv[0][0][1] = 0;
726         s->last_mv[0][1][0] = 0;
727         s->last_mv[0][1][1] = 0;
728         s->mv[0][0][0] = 0;
729         s->mv[0][0][1] = 0;
730     } else if (mb_type & (MB_FOR | MB_BACK)) {
731         /* motion vectors */
732         s->mv_dir = 0;
733         for(i=0;i<2;i++) {
734             if (mb_type & (MB_FOR >> i)) {
735                 s->mv_dir |= (MV_DIR_FORWARD >> i);
736                 dprintf("motion_type=%d\n", motion_type);
737                 switch(motion_type) {
738                 case MT_FRAME: /* or MT_16X8 */
739                     if (s->picture_structure == PICT_FRAME) {
740                         /* MT_FRAME */
741                         s->mv_type = MV_TYPE_16X16;
742                         for(k=0;k<2;k++) {
743                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k], 
744                                                      s->last_mv[i][0][k]);
745                             s->last_mv[i][0][k] = val;
746                             s->last_mv[i][1][k] = val;
747                             /* full_pel: only for mpeg1 */
748                             if (s->full_pel[i])
749                                 val = val << 1;
750                             s->mv[i][0][k] = val;
751                             dprintf("mv%d: %d\n", k, val);
752                         }
753                     } else {
754                         /* MT_16X8 */
755                         s->mv_type = MV_TYPE_16X8;
756                         for(j=0;j<2;j++) {
757                             s->field_select[i][j] = get_bits1(&s->gb);
758                             for(k=0;k<2;k++) {
759                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
760                                                          s->last_mv[i][j][k]);
761                                 s->last_mv[i][j][k] = val;
762                                 s->mv[i][j][k] = val;
763                             }
764                         }
765                     }
766                     break;
767                 case MT_FIELD:
768                     if (s->picture_structure == PICT_FRAME) {
769                         s->mv_type = MV_TYPE_FIELD;
770                         for(j=0;j<2;j++) {
771                             s->field_select[i][j] = get_bits1(&s->gb);
772                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
773                                                      s->last_mv[i][j][0]);
774                             s->last_mv[i][j][0] = val;
775                             s->mv[i][j][0] = val;
776                             dprintf("fmx=%d\n", val);
777                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
778                                                      s->last_mv[i][j][1] >> 1);
779                             s->last_mv[i][j][1] = val << 1;
780                             s->mv[i][j][1] = val;
781                             dprintf("fmy=%d\n", val);
782                         }
783                     } else {
784                         s->mv_type = MV_TYPE_16X16;
785                         s->field_select[i][0] = get_bits1(&s->gb);
786                         for(k=0;k<2;k++) {
787                             val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
788                                                      s->last_mv[i][0][k]);
789                             s->last_mv[i][0][k] = val;
790                             s->last_mv[i][1][k] = val;
791                             s->mv[i][0][k] = val;
792                         }
793                     }
794                     break;
795                 case MT_DMV:
796                     {
797                         int dmx, dmy, mx, my, m;
798
799                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
800                                                 s->last_mv[i][0][0]);
801                         s->last_mv[i][0][0] = mx;
802                         s->last_mv[i][1][0] = mx;
803                         dmx = get_dmv(s);
804                         my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
805                                                 s->last_mv[i][0][1] >> 1);
806                         dmy = get_dmv(s);
807                         s->mv_type = MV_TYPE_DMV;
808                         /* XXX: totally broken */
809                         if (s->picture_structure == PICT_FRAME) {
810                             s->last_mv[i][0][1] = my << 1;
811                             s->last_mv[i][1][1] = my << 1;
812
813                             m = s->top_field_first ? 1 : 3;
814                             /* top -> top pred */
815                             s->mv[i][0][0] = mx; 
816                             s->mv[i][0][1] = my << 1;
817                             s->mv[i][1][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
818                             s->mv[i][1][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
819                             m = 4 - m;
820                             s->mv[i][2][0] = mx;
821                             s->mv[i][2][1] = my << 1;
822                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
823                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
824                         } else {
825                             s->last_mv[i][0][1] = my;
826                             s->last_mv[i][1][1] = my;
827                             s->mv[i][0][0] = mx;
828                             s->mv[i][0][1] = my;
829                             s->mv[i][1][0] = ((mx + (mx > 0)) >> 1) + dmx;
830                             s->mv[i][1][1] = ((my + (my > 0)) >> 1) + dmy - 1 
831                                 /* + 2 * cur_field */;
832                         }
833                     }
834                     break;
835                 }
836             }
837         }
838     }
839
840     if ((mb_type & MB_INTRA) && s->concealment_motion_vectors) {
841         skip_bits1(&s->gb); /* marker */
842     }
843     
844     if (mb_type & MB_PAT) {
845         cbp = get_vlc(&s->gb, &mb_pat_vlc);
846         if (cbp < 0)
847             return -1;
848         cbp++;
849     }
850     dprintf("cbp=%x\n", cbp);
851
852     if (s->mpeg2) {
853         if (s->mb_intra) {
854             for(i=0;i<6;i++) {
855                 if (cbp & (1 << (5 - i))) {
856                     if (mpeg2_decode_block_intra(s, block[i], i) < 0)
857                         return -1;
858                 }
859             }
860         } else {
861             for(i=0;i<6;i++) {
862                 if (cbp & (1 << (5 - i))) {
863                     if (mpeg2_decode_block_non_intra(s, block[i], i) < 0)
864                         return -1;
865                 }
866             }
867         }
868     } else {
869         for(i=0;i<6;i++) {
870             if (cbp & (1 << (5 - i))) {
871                 if (mpeg1_decode_block(s, block[i], i) < 0)
872                     return -1;
873             }
874         }
875     }
876     return 0;
877 }
878
879 /* as h263, but only 17 codes */
880 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
881 {
882     int code, sign, val, m, l, shift;
883
884     code = get_vlc(&s->gb, &mv_vlc);
885     if (code < 0) {
886         return 0xffff;
887     }
888     if (code == 0) {
889         return pred;
890     }
891     sign = get_bits1(&s->gb);
892     shift = fcode - 1;
893     val = (code - 1) << shift;
894     if (shift > 0)
895         val |= get_bits(&s->gb, shift);
896     val++;
897     if (sign)
898         val = -val;
899     val += pred;
900     
901     /* modulo decoding */
902     l = (1 << shift) * 16;
903     m = 2 * l;
904     if (val < -l) {
905         val += m;
906     } else if (val >= l) {
907         val -= m;
908     }
909     return val;
910 }
911
912 static inline int decode_dc(MpegEncContext *s, int component)
913 {
914     int code, diff;
915
916     if (component == 0) {
917         code = get_vlc(&s->gb, &dc_lum_vlc);
918     } else {
919         code = get_vlc(&s->gb, &dc_chroma_vlc);
920     }
921     if (code < 0)
922         return 0xffff;
923     if (code == 0) {
924         diff = 0;
925     } else {
926         diff = get_bits(&s->gb, code);
927         if ((diff & (1 << (code - 1))) == 0) 
928             diff = (-1 << code) | (diff + 1);
929     }
930     return diff;
931 }
932
933 static int mpeg1_decode_block(MpegEncContext *s, 
934                                DCTELEM *block, 
935                                int n)
936 {
937     int level, dc, diff, i, j, run;
938     int code, component;
939     RLTable *rl = &rl_mpeg1;
940
941     if (s->mb_intra) {
942         /* DC coef */
943         component = (n <= 3 ? 0 : n - 4 + 1);
944         diff = decode_dc(s, component);
945         if (diff >= 0xffff)
946             return -1;
947         dc = s->last_dc[component];
948         dc += diff;
949         s->last_dc[component] = dc;
950         block[0] = dc;
951         dprintf("dc=%d diff=%d\n", dc, diff);
952         i = 1;
953     } else {
954         int bit_cnt, v;
955         UINT32 bit_buf;
956         UINT8 *buf_ptr;
957         i = 0;
958         /* special case for the first coef. no need to add a second vlc table */
959         SAVE_BITS(&s->gb);
960         SHOW_BITS(&s->gb, v, 2);
961         if (v & 2) {
962             run = 0;
963             level = 1 - ((v & 1) << 1);
964             FLUSH_BITS(2);
965             RESTORE_BITS(&s->gb);
966             goto add_coef;
967         }
968         RESTORE_BITS(&s->gb);
969     }
970
971     /* now quantify & encode AC coefs */
972     for(;;) {
973         code = get_vlc(&s->gb, &rl->vlc);
974         if (code < 0) {
975             return -1;
976         }
977         if (code == 112) {
978             break;
979         } else if (code == 111) {
980             /* escape */
981             run = get_bits(&s->gb, 6);
982             level = get_bits(&s->gb, 8);
983             level = (level << 24) >> 24;
984             if (level == -128) {
985                 level = get_bits(&s->gb, 8) - 256;
986             } else if (level == 0) {
987                 level = get_bits(&s->gb, 8);
988             }
989         } else {
990             run = rl->table_run[code];
991             level = rl->table_level[code];
992             if (get_bits1(&s->gb))
993                 level = -level;
994         }
995         i += run;
996         if (i >= 64)
997             return -1;
998     add_coef:
999         dprintf("%d: run=%d level=%d\n", n, run, level);
1000         j = zigzag_direct[i];
1001         block[j] = level;
1002         i++;
1003     }
1004     s->block_last_index[n] = i-1;
1005     return 0;
1006 }
1007
1008 /* Also does unquantization here, since I will never support mpeg2
1009    encoding */
1010 static int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1011                                         DCTELEM *block, 
1012                                         int n)
1013 {
1014     int level, i, j, run;
1015     int code;
1016     RLTable *rl = &rl_mpeg1;
1017     const UINT8 *scan_table;
1018     const UINT16 *matrix;
1019     int mismatch;
1020
1021     if (s->alternate_scan)
1022         scan_table = ff_alternate_vertical_scan;
1023     else
1024         scan_table = zigzag_direct;
1025     mismatch = 1;
1026
1027     {
1028         int bit_cnt, v;
1029         UINT32 bit_buf;
1030         UINT8 *buf_ptr;
1031         i = 0;
1032         if (n < 4) 
1033             matrix = s->inter_matrix;
1034         else
1035             matrix = s->chroma_inter_matrix;
1036             
1037         /* special case for the first coef. no need to add a second vlc table */
1038         SAVE_BITS(&s->gb);
1039         SHOW_BITS(&s->gb, v, 2);
1040         if (v & 2) {
1041             run = 0;
1042             level = 1 - ((v & 1) << 1);
1043             FLUSH_BITS(2);
1044             RESTORE_BITS(&s->gb);
1045             goto add_coef;
1046         }
1047         RESTORE_BITS(&s->gb);
1048     }
1049
1050     /* now quantify & encode AC coefs */
1051     for(;;) {
1052         code = get_vlc(&s->gb, &rl->vlc);
1053         if (code < 0)
1054             return -1;
1055         if (code == 112) {
1056             break;
1057         } else if (code == 111) {
1058             /* escape */
1059             run = get_bits(&s->gb, 6);
1060             level = get_bits(&s->gb, 12);
1061             level = (level << 20) >> 20;
1062         } else {
1063             run = rl->table_run[code];
1064             level = rl->table_level[code];
1065             if (get_bits1(&s->gb))
1066                 level = -level;
1067         }
1068         i += run;
1069         if (i >= 64)
1070             return -1;
1071     add_coef:
1072         j = scan_table[i];
1073         dprintf("%d: run=%d level=%d\n", n, run, level);
1074         /* XXX: optimize */
1075         if (level > 0) {
1076             level = ((level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1077         } else {
1078             level = ((-level * 2 + 1) * s->qscale * matrix[j]) >> 5;
1079             level = -level;
1080         }
1081         /* XXX: is it really necessary to saturate since the encoder
1082            knows whats going on ? */
1083         mismatch ^= level;
1084         block[j] = level;
1085         i++;
1086     }
1087     block[63] ^= (mismatch & 1);
1088     s->block_last_index[n] = i;
1089     return 0;
1090 }
1091
1092 static int mpeg2_decode_block_intra(MpegEncContext *s, 
1093                                     DCTELEM *block, 
1094                                     int n)
1095 {
1096     int level, dc, diff, i, j, run;
1097     int code, component;
1098     RLTable *rl;
1099     const UINT8 *scan_table;
1100     const UINT16 *matrix;
1101     int mismatch;
1102
1103     if (s->alternate_scan)
1104         scan_table = ff_alternate_vertical_scan;
1105     else
1106         scan_table = zigzag_direct;
1107
1108     /* DC coef */
1109     component = (n <= 3 ? 0 : n - 4 + 1);
1110     diff = decode_dc(s, component);
1111     if (diff >= 0xffff)
1112         return -1;
1113     dc = s->last_dc[component];
1114     dc += diff;
1115     s->last_dc[component] = dc;
1116     block[0] = dc << (3 - s->intra_dc_precision);
1117     dprintf("dc=%d\n", block[0]);
1118     mismatch = block[0] ^ 1;
1119     i = 1;
1120     if (s->intra_vlc_format)
1121         rl = &rl_mpeg2;
1122     else
1123         rl = &rl_mpeg1;
1124     if (n < 4) 
1125         matrix = s->intra_matrix;
1126     else
1127         matrix = s->chroma_intra_matrix;
1128
1129     /* now quantify & encode AC coefs */
1130     for(;;) {
1131         code = get_vlc(&s->gb, &rl->vlc);
1132         if (code < 0)
1133             return -1;
1134         if (code == 112) {
1135             break;
1136         } else if (code == 111) {
1137             /* escape */
1138             run = get_bits(&s->gb, 6);
1139             level = get_bits(&s->gb, 12);
1140             level = (level << 20) >> 20;
1141         } else {
1142             run = rl->table_run[code];
1143             level = rl->table_level[code];
1144             if (get_bits1(&s->gb))
1145                 level = -level;
1146         }
1147         i += run;
1148         if (i >= 64)
1149             return -1;
1150         j = scan_table[i];
1151         dprintf("%d: run=%d level=%d\n", n, run, level);
1152         level = (level * s->qscale * matrix[j]) / 16;
1153         /* XXX: is it really necessary to saturate since the encoder
1154            knows whats going on ? */
1155         mismatch ^= level;
1156         block[j] = level;
1157         i++;
1158     }
1159     block[63] ^= (mismatch & 1);
1160     s->block_last_index[n] = i;
1161     return 0;
1162 }
1163
1164 /* compressed picture size */
1165 #define PICTURE_BUFFER_SIZE 100000
1166
1167 typedef struct Mpeg1Context {
1168     MpegEncContext mpeg_enc_ctx;
1169     UINT32 header_state;
1170     int start_code; /* current start code */
1171     UINT8 buffer[PICTURE_BUFFER_SIZE]; 
1172     UINT8 *buf_ptr;
1173     int buffer_size;
1174     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
1175     int repeat_field; /* true if we must repeat the field */
1176 } Mpeg1Context;
1177
1178 static int mpeg_decode_init(AVCodecContext *avctx)
1179 {
1180     Mpeg1Context *s = avctx->priv_data;
1181
1182     s->header_state = 0xff;
1183     s->mpeg_enc_ctx_allocated = 0;
1184     s->buffer_size = PICTURE_BUFFER_SIZE;
1185     s->start_code = -1;
1186     s->buf_ptr = s->buffer;
1187     s->mpeg_enc_ctx.picture_number = 0;
1188     s->repeat_field = 0;
1189     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
1190     avctx->mbskip_table= s->mpeg_enc_ctx.mbskip_table;
1191     return 0;
1192 }
1193
1194 /* return the 8 bit start code value and update the search
1195    state. Return -1 if no start code found */
1196 static int find_start_code(UINT8 **pbuf_ptr, UINT8 *buf_end, 
1197                            UINT32 *header_state)
1198 {
1199     UINT8 *buf_ptr;
1200     unsigned int state, v;
1201     int val;
1202
1203     state = *header_state;
1204     buf_ptr = *pbuf_ptr;
1205     while (buf_ptr < buf_end) {
1206         v = *buf_ptr++;
1207         if (state == 0x000001) {
1208             state = ((state << 8) | v) & 0xffffff;
1209             val = state;
1210             goto found;
1211         }
1212         state = ((state << 8) | v) & 0xffffff;
1213     }
1214     val = -1;
1215  found:
1216     *pbuf_ptr = buf_ptr;
1217     *header_state = state;
1218     return val;
1219 }
1220
1221 static int mpeg1_decode_picture(AVCodecContext *avctx, 
1222                                 UINT8 *buf, int buf_size)
1223 {
1224     Mpeg1Context *s1 = avctx->priv_data;
1225     MpegEncContext *s = &s1->mpeg_enc_ctx;
1226     int ref, f_code;
1227
1228     init_get_bits(&s->gb, buf, buf_size);
1229
1230     ref = get_bits(&s->gb, 10); /* temporal ref */
1231     s->pict_type = get_bits(&s->gb, 3);
1232     dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);
1233     skip_bits(&s->gb, 16);
1234     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
1235         s->full_pel[0] = get_bits1(&s->gb);
1236         f_code = get_bits(&s->gb, 3);
1237         if (f_code == 0)
1238             return -1;
1239         s->mpeg_f_code[0][0] = f_code;
1240         s->mpeg_f_code[0][1] = f_code;
1241     }
1242     if (s->pict_type == B_TYPE) {
1243         s->full_pel[1] = get_bits1(&s->gb);
1244         f_code = get_bits(&s->gb, 3);
1245         if (f_code == 0)
1246             return -1;
1247         s->mpeg_f_code[1][0] = f_code;
1248         s->mpeg_f_code[1][1] = f_code;
1249     }
1250     s->y_dc_scale = 8;
1251     s->c_dc_scale = 8;
1252     s->first_slice = 1;
1253     return 0;
1254 }
1255
1256 static void mpeg_decode_sequence_extension(MpegEncContext *s)
1257 {
1258     int horiz_size_ext, vert_size_ext;
1259     int bit_rate_ext, vbv_buf_ext, low_delay;
1260     int frame_rate_ext_n, frame_rate_ext_d;
1261
1262     skip_bits(&s->gb, 8); /* profil and level */
1263     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1264     skip_bits(&s->gb, 2); /* chroma_format */
1265     horiz_size_ext = get_bits(&s->gb, 2);
1266     vert_size_ext = get_bits(&s->gb, 2);
1267     s->width |= (horiz_size_ext << 12);
1268     s->height |= (vert_size_ext << 12);
1269     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1270     s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;
1271     skip_bits1(&s->gb); /* marker */
1272     vbv_buf_ext = get_bits(&s->gb, 8);
1273     low_delay = get_bits1(&s->gb);
1274     frame_rate_ext_n = get_bits(&s->gb, 2);
1275     frame_rate_ext_d = get_bits(&s->gb, 5);
1276     if (frame_rate_ext_d >= 1)
1277         s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;
1278     dprintf("sequence extension\n");
1279     s->mpeg2 = 1;
1280 }
1281
1282 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1283 {
1284     int i, v, j;
1285
1286     dprintf("matrix extension\n");
1287
1288     if (get_bits1(&s->gb)) {
1289         for(i=0;i<64;i++) {
1290             v = get_bits(&s->gb, 8);
1291             j = zigzag_direct[i];
1292             s->intra_matrix[j] = v;
1293             s->chroma_intra_matrix[j] = v;
1294         }
1295     }
1296     if (get_bits1(&s->gb)) {
1297         for(i=0;i<64;i++) {
1298             v = get_bits(&s->gb, 8);
1299             j = zigzag_direct[i];
1300             s->inter_matrix[j] = v;
1301             s->chroma_inter_matrix[j] = v;
1302         }
1303     }
1304     if (get_bits1(&s->gb)) {
1305         for(i=0;i<64;i++) {
1306             v = get_bits(&s->gb, 8);
1307             j = zigzag_direct[i];
1308             s->chroma_intra_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_inter_matrix[j] = v;
1316         }
1317     }
1318 }
1319
1320 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
1321 {
1322     s->full_pel[0] = s->full_pel[1] = 0;
1323     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1324     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1325     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1326     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1327     s->intra_dc_precision = get_bits(&s->gb, 2);
1328     s->picture_structure = get_bits(&s->gb, 2);
1329     s->top_field_first = get_bits1(&s->gb);
1330     s->frame_pred_frame_dct = get_bits1(&s->gb);
1331     s->concealment_motion_vectors = get_bits1(&s->gb);
1332     s->q_scale_type = get_bits1(&s->gb);
1333     s->intra_vlc_format = get_bits1(&s->gb);
1334     s->alternate_scan = get_bits1(&s->gb);
1335     s->repeat_first_field = get_bits1(&s->gb);
1336     s->chroma_420_type = get_bits1(&s->gb);
1337     s->progressive_frame = get_bits1(&s->gb);
1338     /* composite display not parsed */
1339     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
1340     dprintf("picture_structure=%d\n", s->picture_structure);
1341     dprintf("top field first=%d\n", s->top_field_first);
1342     dprintf("repeat first field=%d\n", s->repeat_first_field);
1343     dprintf("conceal=%d\n", s->concealment_motion_vectors);
1344     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
1345     dprintf("alternate_scan=%d\n", s->alternate_scan);
1346     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1347     dprintf("progressive_frame=%d\n", s->progressive_frame);
1348 }
1349
1350 static void mpeg_decode_extension(AVCodecContext *avctx, 
1351                                   UINT8 *buf, int buf_size)
1352 {
1353     Mpeg1Context *s1 = avctx->priv_data;
1354     MpegEncContext *s = &s1->mpeg_enc_ctx;
1355     int ext_type;
1356
1357     init_get_bits(&s->gb, buf, buf_size);
1358     
1359     ext_type = get_bits(&s->gb, 4);
1360     switch(ext_type) {
1361     case 0x1:
1362         /* sequence ext */
1363         mpeg_decode_sequence_extension(s);
1364         break;
1365     case 0x3:
1366         /* quant matrix extension */
1367         mpeg_decode_quant_matrix_extension(s);
1368         break;
1369     case 0x8:
1370         /* picture extension */
1371         mpeg_decode_picture_coding_extension(s);
1372         break;
1373     }
1374 }
1375
1376 /* return 1 if end of frame */
1377 static int mpeg_decode_slice(AVCodecContext *avctx, 
1378                               AVPicture *pict,
1379                               int start_code,
1380                               UINT8 *buf, int buf_size)
1381 {
1382     Mpeg1Context *s1 = avctx->priv_data;
1383     MpegEncContext *s = &s1->mpeg_enc_ctx;
1384     int ret;
1385
1386     start_code = (start_code - 1) & 0xff;
1387     if (start_code >= s->mb_height)
1388         return -1;
1389     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
1390     s->last_dc[1] = s->last_dc[0];
1391     s->last_dc[2] = s->last_dc[0];
1392     memset(s->last_mv, 0, sizeof(s->last_mv));
1393     s->mb_x = -1;
1394     s->mb_y = start_code;
1395     s->mb_incr = 0;
1396     /* start frame decoding */
1397     if (s->first_slice) {
1398         s->first_slice = 0;
1399         MPV_frame_start(s);
1400     }
1401
1402     init_get_bits(&s->gb, buf, buf_size);
1403
1404     s->qscale = get_qscale(s);
1405     /* extra slice info */
1406     while (get_bits1(&s->gb) != 0) {
1407         skip_bits(&s->gb, 8);
1408     }
1409
1410     for(;;) {
1411         clear_blocks(s->block[0]);
1412         emms_c();
1413         ret = mpeg_decode_mb(s, s->block);
1414         dprintf("ret=%d\n", ret);
1415         if (ret < 0)
1416             return -1;
1417         if (ret == 1)
1418             break;
1419         MPV_decode_mb(s, s->block);
1420     }
1421     emms_c();
1422
1423     /* end of slice reached */
1424     if (s->mb_x == (s->mb_width - 1) &&
1425         s->mb_y == (s->mb_height - 1)) {
1426         /* end of image */
1427         UINT8 **picture;
1428
1429         MPV_frame_end(s);
1430
1431         /* XXX: incorrect reported qscale for mpeg2 */
1432         if (s->pict_type == B_TYPE) {
1433             picture = s->current_picture;
1434             avctx->quality = s->qscale;
1435         } else {
1436             /* latency of 1 frame for I and P frames */
1437             /* XXX: use another variable than picture_number */
1438             if (s->picture_number == 0) {
1439                 picture = NULL;
1440             } else {
1441                 picture = s->last_picture;
1442                 avctx->quality = s->last_qscale;
1443             }
1444             s->last_qscale = s->qscale;
1445             s->picture_number++;
1446         }
1447         if (picture) {
1448             pict->data[0] = picture[0];
1449             pict->data[1] = picture[1];
1450             pict->data[2] = picture[2];
1451             pict->linesize[0] = s->linesize;
1452             pict->linesize[1] = s->linesize / 2;
1453             pict->linesize[2] = s->linesize / 2;
1454             return 1;
1455         } else {
1456             return 0;
1457         }
1458     } else {
1459         return 0;
1460     }
1461 }
1462
1463 static int mpeg1_decode_sequence(AVCodecContext *avctx, 
1464                                  UINT8 *buf, int buf_size)
1465 {
1466     Mpeg1Context *s1 = avctx->priv_data;
1467     MpegEncContext *s = &s1->mpeg_enc_ctx;
1468     int width, height, i, v, j;
1469     
1470     init_get_bits(&s->gb, buf, buf_size);
1471
1472     width = get_bits(&s->gb, 12);
1473     height = get_bits(&s->gb, 12);
1474     skip_bits(&s->gb, 4);
1475     s->frame_rate_index = get_bits(&s->gb, 4);
1476     if (s->frame_rate_index == 0)
1477         return -1;
1478     s->bit_rate = get_bits(&s->gb, 18) * 400;
1479     if (get_bits1(&s->gb) == 0) /* marker */
1480         return -1;
1481     if (width <= 0 || height <= 0 ||
1482         (width % 2) != 0 || (height % 2) != 0)
1483         return -1;
1484     if (width != s->width ||
1485         height != s->height) {
1486         /* start new mpeg1 context decoding */
1487         s->out_format = FMT_MPEG1;
1488         if (s1->mpeg_enc_ctx_allocated) {
1489             MPV_common_end(s);
1490         }
1491         s->width = width;
1492         s->height = height;
1493         s->has_b_frames = 1;
1494         s->avctx = avctx;
1495         avctx->width = width;
1496         avctx->height = height;
1497         avctx->frame_rate = frame_rate_tab[s->frame_rate_index];
1498         s->frame_rate = avctx->frame_rate;
1499         avctx->bit_rate = s->bit_rate;
1500         
1501         if (MPV_common_init(s) < 0)
1502             return -1;
1503         mpeg1_init_vlc(s);
1504         s1->mpeg_enc_ctx_allocated = 1;
1505     }
1506
1507     skip_bits(&s->gb, 10); /* vbv_buffer_size */
1508     skip_bits(&s->gb, 1);
1509
1510     /* get matrix */
1511     if (get_bits1(&s->gb)) {
1512         for(i=0;i<64;i++) {
1513             v = get_bits(&s->gb, 8);
1514             j = zigzag_direct[i];
1515             s->intra_matrix[j] = v;
1516             s->chroma_intra_matrix[j] = v;
1517         }
1518 #ifdef DEBUG
1519         dprintf("intra matrix present\n");
1520         for(i=0;i<64;i++)
1521             dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);
1522         printf("\n");
1523 #endif
1524     } else {
1525         for(i=0;i<64;i++) {
1526             v = default_intra_matrix[i];
1527             s->intra_matrix[i] = v;
1528             s->chroma_intra_matrix[i] = v;
1529         }
1530     }
1531     if (get_bits1(&s->gb)) {
1532         for(i=0;i<64;i++) {
1533             v = get_bits(&s->gb, 8);
1534             j = zigzag_direct[i];
1535             s->inter_matrix[j] = v;
1536             s->chroma_inter_matrix[j] = v;
1537         }
1538 #ifdef DEBUG
1539         dprintf("non intra matrix present\n");
1540         for(i=0;i<64;i++)
1541             dprintf(" %d", s->inter_matrix[zigzag_direct[i]]);
1542         printf("\n");
1543 #endif
1544     } else {
1545         for(i=0;i<64;i++) {
1546             v = default_non_intra_matrix[i];
1547             s->inter_matrix[i] = v;
1548             s->chroma_inter_matrix[i] = v;
1549         }
1550     }
1551
1552     /* we set mpeg2 parameters so that it emulates mpeg1 */
1553     s->progressive_sequence = 1;
1554     s->progressive_frame = 1;
1555     s->picture_structure = PICT_FRAME;
1556     s->frame_pred_frame_dct = 1;
1557     s->mpeg2 = 0;
1558     return 0;
1559 }
1560
1561 /* handle buffering and image synchronisation */
1562 static int mpeg_decode_frame(AVCodecContext *avctx, 
1563                              void *data, int *data_size,
1564                              UINT8 *buf, int buf_size)
1565 {
1566     Mpeg1Context *s = avctx->priv_data;
1567     UINT8 *buf_end, *buf_ptr, *buf_start;
1568     int len, start_code_found, ret, code, start_code, input_size;
1569     AVPicture *picture = data;
1570     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1571             
1572     dprintf("fill_buffer\n");
1573
1574     *data_size = 0;
1575
1576     /* special case for last picture */
1577     if (buf_size == 0) {
1578         if (s2->picture_number > 0) {
1579             picture->data[0] = s2->next_picture[0];
1580             picture->data[1] = s2->next_picture[1];
1581             picture->data[2] = s2->next_picture[2];
1582             picture->linesize[0] = s2->linesize;
1583             picture->linesize[1] = s2->linesize / 2;
1584             picture->linesize[2] = s2->linesize / 2;
1585             *data_size = sizeof(AVPicture);
1586         }
1587         return 0;
1588     }
1589
1590     buf_ptr = buf;
1591     buf_end = buf + buf_size;
1592
1593 #if 0    
1594     if (s->repeat_field % 2 == 1) { 
1595         s->repeat_field++;
1596         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
1597         //        s2->picture_number, s->repeat_field);
1598         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
1599             *data_size = sizeof(AVPicture);
1600             goto the_end;
1601         }
1602     }
1603 #endif
1604     while (buf_ptr < buf_end) {
1605         buf_start = buf_ptr;
1606         /* find start next code */
1607         code = find_start_code(&buf_ptr, buf_end, &s->header_state);
1608         if (code >= 0) {
1609             start_code_found = 1;
1610         } else {
1611             start_code_found = 0;
1612         }
1613         /* copy to buffer */
1614         len = buf_ptr - buf_start;
1615         if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
1616             /* data too big : flush */
1617             s->buf_ptr = s->buffer;
1618             if (start_code_found)
1619                 s->start_code = code;
1620         } else {
1621             memcpy(s->buf_ptr, buf_start, len);
1622             s->buf_ptr += len;
1623             
1624             if (start_code_found) {
1625                 /* prepare data for next start code */
1626                 input_size = s->buf_ptr - s->buffer;
1627                 start_code = s->start_code;
1628                 s->buf_ptr = s->buffer;
1629                 s->start_code = code;
1630                 switch(start_code) {
1631                 case SEQ_START_CODE:
1632                     mpeg1_decode_sequence(avctx, s->buffer, 
1633                                           input_size);
1634                     break;
1635                             
1636                 case PICTURE_START_CODE:
1637                     /* we have a complete image : we try to decompress it */
1638                     mpeg1_decode_picture(avctx, 
1639                                          s->buffer, input_size);
1640                     break;
1641                 case EXT_START_CODE:
1642                     mpeg_decode_extension(avctx,
1643                                           s->buffer, input_size);
1644                     break;
1645                 default:
1646                     if (start_code >= SLICE_MIN_START_CODE &&
1647                         start_code <= SLICE_MAX_START_CODE) {
1648                         ret = mpeg_decode_slice(avctx, picture,
1649                                                 start_code, s->buffer, input_size);
1650                         if (ret == 1) {
1651                             /* got a picture: exit */
1652                             /* first check if we must repeat the frame */
1653                             avctx->repeat_pict = 0;
1654 #if 0
1655                             if (s2->progressive_frame && s2->repeat_first_field) {
1656                                 //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);
1657                                 //s2->repeat_first_field = 0;
1658                                 //s2->progressive_frame = 0;
1659                                 if (++s->repeat_field > 2)
1660                                     s->repeat_field = 0;
1661                                 avctx->repeat_pict = 1;
1662                             }
1663 #endif                      
1664                             if (s2->repeat_first_field) {
1665                                 if (s2->progressive_sequence) {
1666                                     if (s2->top_field_first)
1667                                         avctx->repeat_pict = 4;
1668                                     else
1669                                         avctx->repeat_pict = 2;
1670                                 } else if (s2->progressive_frame) {
1671                                     avctx->repeat_pict = 1;
1672                                 }
1673                             }         
1674                             *data_size = sizeof(AVPicture);
1675                             goto the_end;
1676                         }
1677                     }
1678                     break;
1679                 }
1680             }
1681         }
1682     }
1683  the_end:
1684     return buf_ptr - buf;
1685 }
1686
1687 static int mpeg_decode_end(AVCodecContext *avctx)
1688 {
1689     Mpeg1Context *s = avctx->priv_data;
1690
1691     if (s->mpeg_enc_ctx_allocated)
1692         MPV_common_end(&s->mpeg_enc_ctx);
1693     return 0;
1694 }
1695
1696 AVCodec mpeg_decoder = {
1697     "mpegvideo",
1698     CODEC_TYPE_VIDEO,
1699     CODEC_ID_MPEG1VIDEO,
1700     sizeof(Mpeg1Context),
1701     mpeg_decode_init,
1702     NULL,
1703     mpeg_decode_end,
1704     mpeg_decode_frame,
1705 };