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