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