mpeg2_fast_decode_block_intra()
[ffmpeg.git] / libavcodec / mpeg12.c
1 /*
2  * MPEG1 codec / MPEG2 decoder
3  * Copyright (c) 2000,2001 Fabrice Bellard.
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> 
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20  
21 /**
22  * @file mpeg12.c
23  * MPEG1/2 codec
24  */
25  
26 //#define DEBUG
27 #include "avcodec.h"
28 #include "dsputil.h"
29 #include "mpegvideo.h"
30
31 #include "mpeg12data.h"
32
33 //#undef NDEBUG
34 //#include <assert.h>
35
36
37 /* Start codes. */
38 #define SEQ_END_CODE            0x000001b7
39 #define SEQ_START_CODE          0x000001b3
40 #define GOP_START_CODE          0x000001b8
41 #define PICTURE_START_CODE      0x00000100
42 #define SLICE_MIN_START_CODE    0x00000101
43 #define SLICE_MAX_START_CODE    0x000001af
44 #define EXT_START_CODE          0x000001b5
45 #define USER_START_CODE         0x000001b2
46
47 #define DC_VLC_BITS 9
48 #define MV_VLC_BITS 9
49 #define MBINCR_VLC_BITS 9
50 #define MB_PAT_VLC_BITS 9
51 #define MB_PTYPE_VLC_BITS 6
52 #define MB_BTYPE_VLC_BITS 6
53 #define TEX_VLC_BITS 9
54
55 #ifdef CONFIG_ENCODERS
56 static void mpeg1_encode_block(MpegEncContext *s, 
57                          DCTELEM *block, 
58                          int component);
59 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code);    // RAL: f_code parameter added
60 #endif //CONFIG_ENCODERS
61 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
62                               DCTELEM *block, 
63                               int n);
64 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
65                               DCTELEM *block, 
66                               int n);
67 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n);
68 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
69                                         DCTELEM *block, 
70                                         int n);
71 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
72                                     DCTELEM *block, 
73                                     int n);
74 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, DCTELEM *block, int n);
75 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, DCTELEM *block, int n);
76 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
77 static void exchange_uv(MpegEncContext *s);
78
79 #ifdef HAVE_XVMC
80 extern int XVMC_field_start(MpegEncContext *s, AVCodecContext *avctx);
81 extern int XVMC_field_end(MpegEncContext *s);
82 extern void XVMC_pack_pblocks(MpegEncContext *s,int cbp);
83 extern void XVMC_init_block(MpegEncContext *s);//set s->block
84 #endif
85
86 const enum PixelFormat pixfmt_yuv_420[]= {PIX_FMT_YUV420P,-1};
87 const enum PixelFormat pixfmt_yuv_422[]= {PIX_FMT_YUV422P,-1};
88 const enum PixelFormat pixfmt_yuv_444[]= {PIX_FMT_YUV444P,-1};
89 const enum PixelFormat pixfmt_xvmc_mpg2_420[] = {
90                                            PIX_FMT_XVMC_MPEG2_IDCT,
91                                            PIX_FMT_XVMC_MPEG2_MC,
92                                            -1};
93 #ifdef CONFIG_ENCODERS
94 static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
95 static uint8_t fcode_tab[MAX_MV*2+1];
96
97 static uint32_t uni_mpeg1_ac_vlc_bits[64*64*2];
98 static uint8_t  uni_mpeg1_ac_vlc_len [64*64*2];
99
100 /* simple include everything table for dc, first byte is bits number next 3 are code*/
101 static uint32_t mpeg1_lum_dc_uni[512];
102 static uint32_t mpeg1_chr_dc_uni[512];
103
104 static uint8_t mpeg1_index_run[2][64];
105 static int8_t mpeg1_max_level[2][64];
106 #endif //CONFIG_ENCODERS
107
108 static void init_2d_vlc_rl(RLTable *rl, int use_static)
109 {
110     int i;
111     
112     init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
113              &rl->table_vlc[0][1], 4, 2,
114              &rl->table_vlc[0][0], 4, 2, use_static);
115
116     if(use_static)    
117         rl->rl_vlc[0]= av_mallocz_static(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
118     else
119         rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
120
121     for(i=0; i<rl->vlc.table_size; i++){
122         int code= rl->vlc.table[i][0];
123         int len = rl->vlc.table[i][1];
124         int level, run;
125     
126         if(len==0){ // illegal code
127             run= 65;
128             level= MAX_LEVEL;
129         }else if(len<0){ //more bits needed
130             run= 0;
131             level= code;
132         }else{
133             if(code==rl->n){ //esc
134                 run= 65;
135                 level= 0;
136             }else if(code==rl->n+1){ //eob
137                 run= 0;
138                 level= 127;
139             }else{
140                 run=   rl->table_run  [code] + 1;
141                 level= rl->table_level[code];
142             }
143         }
144         rl->rl_vlc[0][i].len= len;
145         rl->rl_vlc[0][i].level= level;
146         rl->rl_vlc[0][i].run= run;
147     }
148 }
149
150 #ifdef CONFIG_ENCODERS
151 static void init_uni_ac_vlc(RLTable *rl, uint32_t *uni_ac_vlc_bits, uint8_t *uni_ac_vlc_len){
152     int i;
153
154     for(i=0; i<128; i++){
155         int level= i-64;
156         int run;
157         for(run=0; run<64; run++){
158             int len, bits, code;
159             
160             int alevel= ABS(level);
161             int sign= (level>>31)&1;
162
163             if (alevel > rl->max_level[0][run])
164                 code= 111; /*rl->n*/
165             else
166                 code= rl->index_run[0][run] + alevel - 1;
167
168             if (code < 111 /* rl->n */) {
169                 /* store the vlc & sign at once */
170                 len=   mpeg1_vlc[code][1]+1;
171                 bits= (mpeg1_vlc[code][0]<<1) + sign;
172             } else {
173                 len=  mpeg1_vlc[111/*rl->n*/][1]+6;
174                 bits= mpeg1_vlc[111/*rl->n*/][0]<<6;
175
176                 bits|= run;
177                 if (alevel < 128) {
178                     bits<<=8; len+=8;
179                     bits|= level & 0xff;
180                 } else {
181                     bits<<=16; len+=16;
182                     bits|= level & 0xff;
183                     if (level < 0) {
184                         bits|= 0x8001 + level + 255;
185                     } else {
186                         bits|= level & 0xffff;
187                     }
188                 }
189             }
190
191             uni_ac_vlc_bits[UNI_AC_ENC_INDEX(run, i)]= bits;
192             uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
193         }
194     }
195 }
196
197
198 static int find_frame_rate_index(MpegEncContext *s){
199     int i;
200     int64_t dmin= INT64_MAX;
201     int64_t d;
202
203     for(i=1;i<14;i++) {
204         int64_t n0= 1001LL/frame_rate_tab[i].den*frame_rate_tab[i].num*s->avctx->frame_rate_base;
205         int64_t n1= 1001LL*s->avctx->frame_rate;
206         if(s->avctx->strict_std_compliance >= 0 && i>=9) break;
207
208         d = ABS(n0 - n1);
209         if(d < dmin){
210             dmin=d;
211             s->frame_rate_index= i;
212         }
213     }
214     if(dmin)
215         return -1;
216     else
217         return 0;
218 }
219
220 static int encode_init(AVCodecContext *avctx)
221 {
222     MpegEncContext *s = avctx->priv_data;
223
224     if(MPV_encode_init(avctx) < 0)
225         return -1;
226
227     if(find_frame_rate_index(s) < 0){
228         if(s->strict_std_compliance >=0){
229             av_log(avctx, AV_LOG_ERROR, "MPEG1/2 doesnt support %d/%d fps\n", avctx->frame_rate, avctx->frame_rate_base);
230             return -1;
231         }else{
232             av_log(avctx, AV_LOG_INFO, "MPEG1/2 doesnt support %d/%d fps, there may be AV sync issues\n", avctx->frame_rate, avctx->frame_rate_base);
233         }
234     }
235     
236     return 0;
237 }
238
239 static void put_header(MpegEncContext *s, int header)
240 {
241     align_put_bits(&s->pb);
242     put_bits(&s->pb, 16, header>>16);
243     put_bits(&s->pb, 16, header&0xFFFF);
244 }
245
246 /* put sequence header if needed */
247 static void mpeg1_encode_sequence_header(MpegEncContext *s)
248 {
249         unsigned int vbv_buffer_size;
250         unsigned int fps, v;
251         int i;
252         uint64_t time_code;
253         float best_aspect_error= 1E10;
254         float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);
255         int constraint_parameter_flag;
256         
257         if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
258         
259         if (s->current_picture.key_frame) {
260             AVRational framerate= frame_rate_tab[s->frame_rate_index];
261
262             /* mpeg1 header repeated every gop */
263             put_header(s, SEQ_START_CODE);
264  
265             put_bits(&s->pb, 12, s->width);
266             put_bits(&s->pb, 12, s->height);
267             
268             for(i=1; i<15; i++){
269                 float error= aspect_ratio;
270                 if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1)
271                     error-= 1.0/mpeg1_aspect[i];
272                 else
273                     error-= av_q2d(mpeg2_aspect[i])*s->height/s->width;
274              
275                 error= ABS(error);
276                 
277                 if(error < best_aspect_error){
278                     best_aspect_error= error;
279                     s->aspect_ratio_info= i;
280                 }
281             }
282             
283             put_bits(&s->pb, 4, s->aspect_ratio_info);
284             put_bits(&s->pb, 4, s->frame_rate_index);
285             
286             if(s->avctx->rc_max_rate){
287                 v = (s->avctx->rc_max_rate + 399) / 400;
288                 if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO)
289                     v = 0x3ffff;
290             }else{
291                 v= 0x3FFFF;
292             }
293
294             if(s->avctx->rc_buffer_size)
295                 vbv_buffer_size = s->avctx->rc_buffer_size;
296             else
297                 /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
298                 vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
299             vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;
300
301             put_bits(&s->pb, 18, v & 0x3FFFF);
302             put_bits(&s->pb, 1, 1); /* marker */
303             put_bits(&s->pb, 10, vbv_buffer_size & 0x3FF);
304
305             constraint_parameter_flag= 
306                 s->width <= 768 && s->height <= 576 && 
307                 s->mb_width * s->mb_height <= 396 &&
308                 s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&
309                 framerate.num <= framerate.den*30 &&
310                 s->avctx->me_range && s->avctx->me_range < 128 &&
311                 vbv_buffer_size <= 20 &&
312                 v <= 1856000/400 &&
313                 s->codec_id == CODEC_ID_MPEG1VIDEO;
314                 
315             put_bits(&s->pb, 1, constraint_parameter_flag);
316             
317             ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
318             ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
319
320             if(s->codec_id == CODEC_ID_MPEG2VIDEO){
321                 put_header(s, EXT_START_CODE);
322                 put_bits(&s->pb, 4, 1); //seq ext
323                 put_bits(&s->pb, 1, 0); //esc
324                 
325                 if(s->avctx->profile == FF_PROFILE_UNKNOWN){
326                     put_bits(&s->pb, 3, 4); //profile
327                 }else{
328                     put_bits(&s->pb, 3, s->avctx->profile); //profile
329                 }
330
331                 if(s->avctx->level == FF_LEVEL_UNKNOWN){
332                     put_bits(&s->pb, 4, 8); //level
333                 }else{
334                     put_bits(&s->pb, 4, s->avctx->level); //level
335                 }
336
337                 put_bits(&s->pb, 1, s->progressive_sequence);
338                 put_bits(&s->pb, 2, 1); //chroma format 4:2:0
339                 put_bits(&s->pb, 2, 0); //horizontal size ext
340                 put_bits(&s->pb, 2, 0); //vertical size ext
341                 put_bits(&s->pb, 12, v>>18); //bitrate ext
342                 put_bits(&s->pb, 1, 1); //marker
343                 put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
344                 put_bits(&s->pb, 1, s->low_delay);
345                 put_bits(&s->pb, 2, 0); // frame_rate_ext_n
346                 put_bits(&s->pb, 5, 0); // frame_rate_ext_d
347             }
348             
349             put_header(s, GOP_START_CODE);
350             put_bits(&s->pb, 1, 0); /* do drop frame */
351             /* time code : we must convert from the real frame rate to a
352                fake mpeg frame rate in case of low frame rate */
353             fps = (framerate.num + framerate.den/2)/ framerate.den;
354             time_code = s->current_picture_ptr->coded_picture_number;
355
356             s->gop_picture_number = time_code;
357             put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
358             put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
359             put_bits(&s->pb, 1, 1);
360             put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
361             put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
362             put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
363             put_bits(&s->pb, 1, 0); /* broken link */
364         }
365 }
366
367 static inline void encode_mb_skip_run(MpegEncContext *s, int run){
368     while (run >= 33) {
369         put_bits(&s->pb, 11, 0x008);
370         run -= 33;
371     }
372     put_bits(&s->pb, mbAddrIncrTable[run][1], 
373              mbAddrIncrTable[run][0]);
374 }
375 #endif //CONFIG_ENCODERS
376
377 static void common_init(MpegEncContext *s)
378 {
379
380     s->y_dc_scale_table=
381     s->c_dc_scale_table= mpeg2_dc_scale_table[s->intra_dc_precision];
382
383 }
384
385 void ff_mpeg1_clean_buffers(MpegEncContext *s){
386     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
387     s->last_dc[1] = s->last_dc[0];
388     s->last_dc[2] = s->last_dc[0];
389     memset(s->last_mv, 0, sizeof(s->last_mv));
390 }
391
392 #ifdef CONFIG_ENCODERS
393
394 void ff_mpeg1_encode_slice_header(MpegEncContext *s){
395     put_header(s, SLICE_MIN_START_CODE + s->mb_y);
396     put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
397     put_bits(&s->pb, 1, 0); /* slice extra information */
398 }
399
400 void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
401 {
402     mpeg1_encode_sequence_header(s);
403
404     /* mpeg1 picture header */
405     put_header(s, PICTURE_START_CODE);
406     /* temporal reference */
407
408     // RAL: s->picture_number instead of s->fake_picture_number
409     put_bits(&s->pb, 10, (s->picture_number - 
410                           s->gop_picture_number) & 0x3ff); 
411     put_bits(&s->pb, 3, s->pict_type);
412
413     s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
414     put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
415     
416     // RAL: Forward f_code also needed for B frames
417     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
418         put_bits(&s->pb, 1, 0); /* half pel coordinates */
419         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
420             put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
421         else
422             put_bits(&s->pb, 3, 7); /* forward_f_code */
423     }
424     
425     // RAL: Backward f_code necessary for B frames
426     if (s->pict_type == B_TYPE) {
427         put_bits(&s->pb, 1, 0); /* half pel coordinates */
428         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
429             put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
430         else
431             put_bits(&s->pb, 3, 7); /* backward_f_code */
432     }
433
434     put_bits(&s->pb, 1, 0); /* extra bit picture */
435
436     s->frame_pred_frame_dct = 1;
437     if(s->codec_id == CODEC_ID_MPEG2VIDEO){
438         put_header(s, EXT_START_CODE);
439         put_bits(&s->pb, 4, 8); //pic ext
440         if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
441             put_bits(&s->pb, 4, s->f_code);
442             put_bits(&s->pb, 4, s->f_code);
443         }else{
444             put_bits(&s->pb, 8, 255);
445         }
446         if (s->pict_type == B_TYPE) {
447             put_bits(&s->pb, 4, s->b_code);
448             put_bits(&s->pb, 4, s->b_code);
449         }else{
450             put_bits(&s->pb, 8, 255);
451         }
452         put_bits(&s->pb, 2, s->intra_dc_precision);
453         
454         assert(s->picture_structure == PICT_FRAME);
455         put_bits(&s->pb, 2, s->picture_structure);
456         if (s->progressive_sequence) {
457             put_bits(&s->pb, 1, 0); /* no repeat */
458         } else {
459             put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
460         }
461         /* XXX: optimize the generation of this flag with entropy
462            measures */
463         s->frame_pred_frame_dct = s->progressive_sequence;
464         
465         put_bits(&s->pb, 1, s->frame_pred_frame_dct);
466         put_bits(&s->pb, 1, s->concealment_motion_vectors);
467         put_bits(&s->pb, 1, s->q_scale_type);
468         put_bits(&s->pb, 1, s->intra_vlc_format);
469         put_bits(&s->pb, 1, s->alternate_scan);
470         put_bits(&s->pb, 1, s->repeat_first_field);
471         put_bits(&s->pb, 1, s->chroma_420_type=1);
472         s->progressive_frame = s->progressive_sequence;
473         put_bits(&s->pb, 1, s->progressive_frame);
474         put_bits(&s->pb, 1, 0); //composite_display_flag
475     }
476     if(s->flags & CODEC_FLAG_SVCD_SCAN_OFFSET){
477         int i;
478
479         put_header(s, USER_START_CODE);
480         for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
481             put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
482         }
483     }
484     
485     s->mb_y=0;
486     ff_mpeg1_encode_slice_header(s);
487 }
488
489 static inline void put_mb_modes(MpegEncContext *s, int n, int bits, 
490                                 int has_mv, int field_motion)
491 {
492     put_bits(&s->pb, n, bits);
493     if (!s->frame_pred_frame_dct) {
494         if (has_mv) 
495             put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
496         put_bits(&s->pb, 1, s->interlaced_dct);
497     }
498 }
499
500 void mpeg1_encode_mb(MpegEncContext *s,
501                      DCTELEM block[6][64],
502                      int motion_x, int motion_y)
503 {
504     int i, cbp;
505     const int mb_x = s->mb_x;
506     const int mb_y = s->mb_y;
507     const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
508
509     /* compute cbp */
510     cbp = 0;
511     for(i=0;i<6;i++) {
512         if (s->block_last_index[i] >= 0)
513             cbp |= 1 << (5 - i);
514     }
515     
516     if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
517         (mb_x != s->mb_width - 1 || (mb_y != s->mb_height - 1 && s->codec_id == CODEC_ID_MPEG1VIDEO)) && 
518         ((s->pict_type == P_TYPE && (motion_x | motion_y) == 0) ||
519         (s->pict_type == B_TYPE && s->mv_dir == s->last_mv_dir && (((s->mv_dir & MV_DIR_FORWARD) ? ((s->mv[0][0][0] - s->last_mv[0][0][0])|(s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
520         ((s->mv_dir & MV_DIR_BACKWARD) ? ((s->mv[1][0][0] - s->last_mv[1][0][0])|(s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
521         s->mb_skip_run++;
522         s->qscale -= s->dquant;
523         s->skip_count++;
524         s->misc_bits++;
525         s->last_bits++;
526         if(s->pict_type == P_TYPE){
527             s->last_mv[0][1][0]= s->last_mv[0][0][0]= 
528             s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
529         }
530     } else {
531         if(first_mb){
532             assert(s->mb_skip_run == 0);
533             encode_mb_skip_run(s, s->mb_x);
534         }else{
535             encode_mb_skip_run(s, s->mb_skip_run);
536         }
537         
538         if (s->pict_type == I_TYPE) {
539             if(s->dquant && cbp){
540                 put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
541                 put_bits(&s->pb, 5, s->qscale);
542             }else{
543                 put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
544                 s->qscale -= s->dquant;
545             }
546             s->misc_bits+= get_bits_diff(s);
547             s->i_count++;
548         } else if (s->mb_intra) {
549             if(s->dquant && cbp){
550                 put_mb_modes(s, 6, 0x01, 0, 0);
551                 put_bits(&s->pb, 5, s->qscale);
552             }else{
553                 put_mb_modes(s, 5, 0x03, 0, 0);
554                 s->qscale -= s->dquant;
555             }
556             s->misc_bits+= get_bits_diff(s);
557             s->i_count++;
558             memset(s->last_mv, 0, sizeof(s->last_mv));
559         } else if (s->pict_type == P_TYPE) { 
560             if(s->mv_type == MV_TYPE_16X16){
561                 if (cbp != 0) {
562                     if ((motion_x|motion_y) == 0) {
563                         if(s->dquant){
564                             put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
565                             put_bits(&s->pb, 5, s->qscale);
566                         }else{
567                             put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
568                         }
569                         s->misc_bits+= get_bits_diff(s);
570                     } else {
571                         if(s->dquant){
572                             put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
573                             put_bits(&s->pb, 5, s->qscale);
574                         }else{
575                             put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
576                         }
577                         s->misc_bits+= get_bits_diff(s);
578                         mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
579                         mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
580                         s->mv_bits+= get_bits_diff(s);
581                     }
582                 } else {
583                     put_bits(&s->pb, 3, 1); /* motion only */
584                     if (!s->frame_pred_frame_dct)
585                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
586                     s->misc_bits+= get_bits_diff(s);
587                     mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
588                     mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
589                     s->qscale -= s->dquant;
590                     s->mv_bits+= get_bits_diff(s);
591                 }
592                 s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
593                 s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
594             }else{
595                 assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
596
597                 if (cbp) {
598                     if(s->dquant){
599                         put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
600                         put_bits(&s->pb, 5, s->qscale);
601                     }else{
602                         put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
603                     }
604                 } else {
605                     put_bits(&s->pb, 3, 1); /* motion only */
606                     put_bits(&s->pb, 2, 1); /* motion_type: field */
607                     s->qscale -= s->dquant;
608                 }
609                 s->misc_bits+= get_bits_diff(s);
610                 for(i=0; i<2; i++){
611                     put_bits(&s->pb, 1, s->field_select[0][i]);
612                     mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
613                     mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
614                     s->last_mv[0][i][0]=   s->mv[0][i][0];
615                     s->last_mv[0][i][1]= 2*s->mv[0][i][1];
616                 }
617                 s->mv_bits+= get_bits_diff(s);
618             }
619             if(cbp)
620                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
621             s->f_count++;
622         } else{  
623             static const int mb_type_len[4]={0,3,4,2}; //bak,for,bi
624
625             if(s->mv_type == MV_TYPE_16X16){
626                 if (cbp){    // With coded bloc pattern
627                     if (s->dquant) {
628                         if(s->mv_dir == MV_DIR_FORWARD)
629                             put_mb_modes(s, 6, 3, 1, 0);
630                         else
631                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 0);
632                         put_bits(&s->pb, 5, s->qscale);
633                     } else {
634                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 0);
635                     }
636                 }else{    // No coded bloc pattern
637                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
638                     if (!s->frame_pred_frame_dct)
639                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
640                     s->qscale -= s->dquant;
641                 }
642                 s->misc_bits += get_bits_diff(s);
643                 if (s->mv_dir&MV_DIR_FORWARD){
644                     mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code); 
645                     mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code); 
646                     s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
647                     s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
648                     s->f_count++;
649                 }
650                 if (s->mv_dir&MV_DIR_BACKWARD){
651                     mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code); 
652                     mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code); 
653                     s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
654                     s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
655                     s->b_count++;
656                 }
657             }else{
658                 assert(s->mv_type == MV_TYPE_FIELD);
659                 assert(!s->frame_pred_frame_dct);
660                 if (cbp){    // With coded bloc pattern
661                     if (s->dquant) {
662                         if(s->mv_dir == MV_DIR_FORWARD)
663                             put_mb_modes(s, 6, 3, 1, 1);
664                         else
665                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 1);
666                         put_bits(&s->pb, 5, s->qscale);
667                     } else {
668                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 1);
669                     }
670                 }else{    // No coded bloc pattern
671                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
672                     put_bits(&s->pb, 2, 1); /* motion_type: field */
673                     s->qscale -= s->dquant;
674                 }
675                 s->misc_bits += get_bits_diff(s);
676                 if (s->mv_dir&MV_DIR_FORWARD){
677                     for(i=0; i<2; i++){
678                         put_bits(&s->pb, 1, s->field_select[0][i]);
679                         mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
680                         mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
681                         s->last_mv[0][i][0]=   s->mv[0][i][0];
682                         s->last_mv[0][i][1]= 2*s->mv[0][i][1];
683                     }
684                     s->f_count++;
685                 }
686                 if (s->mv_dir&MV_DIR_BACKWARD){
687                     for(i=0; i<2; i++){
688                         put_bits(&s->pb, 1, s->field_select[1][i]);
689                         mpeg1_encode_motion(s, s->mv[1][i][0] -  s->last_mv[1][i][0]    , s->b_code);
690                         mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
691                         s->last_mv[1][i][0]=   s->mv[1][i][0];
692                         s->last_mv[1][i][1]= 2*s->mv[1][i][1];
693                     }
694                     s->b_count++;
695                 }
696             }
697             s->mv_bits += get_bits_diff(s);
698             if(cbp)
699                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
700         }
701         for(i=0;i<6;i++) {
702             if (cbp & (1 << (5 - i))) {
703                 mpeg1_encode_block(s, block[i], i);
704             }
705         }
706         s->mb_skip_run = 0;
707         if(s->mb_intra)
708             s->i_tex_bits+= get_bits_diff(s);
709         else
710             s->p_tex_bits+= get_bits_diff(s);
711     }
712 }
713
714 // RAL: Parameter added: f_or_b_code
715 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
716 {
717     int code, bit_size, l, bits, range, sign;
718
719     if (val == 0) {
720         /* zero vector */
721         code = 0;
722         put_bits(&s->pb,
723                  mbMotionVectorTable[0][1], 
724                  mbMotionVectorTable[0][0]); 
725     } else {
726         bit_size = f_or_b_code - 1;
727         range = 1 << bit_size;
728         /* modulo encoding */
729         l= INT_BIT - 5 - bit_size;
730         val= (val<<l)>>l;
731
732         if (val >= 0) {
733             val--;
734             code = (val >> bit_size) + 1;
735             bits = val & (range - 1);
736             sign = 0;
737         } else {
738             val = -val;
739             val--;
740             code = (val >> bit_size) + 1;
741             bits = val & (range - 1);
742             sign = 1;
743         }
744
745         assert(code > 0 && code <= 16);
746
747         put_bits(&s->pb,
748                  mbMotionVectorTable[code][1], 
749                  mbMotionVectorTable[code][0]); 
750
751         put_bits(&s->pb, 1, sign);
752         if (bit_size > 0) {
753             put_bits(&s->pb, bit_size, bits);
754         }
755     }
756 }
757
758 void ff_mpeg1_encode_init(MpegEncContext *s)
759 {
760     static int done=0;
761
762     common_init(s);
763
764     if(!done){
765         int f_code;
766         int mv;
767         int i;
768
769         done=1;
770         init_rl(&rl_mpeg1, 1);
771
772         for(i=0; i<64; i++)
773         {
774                 mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
775                 mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
776         }
777         
778         init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_bits, uni_mpeg1_ac_vlc_len);
779
780         /* build unified dc encoding tables */
781         for(i=-255; i<256; i++)
782         {
783                 int adiff, index;
784                 int bits, code;
785                 int diff=i;
786
787                 adiff = ABS(diff);
788                 if(diff<0) diff--;
789                 index = av_log2(2*adiff);
790
791                 bits= vlc_dc_lum_bits[index] + index;
792                 code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
793                 mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
794                 
795                 bits= vlc_dc_chroma_bits[index] + index;
796                 code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
797                 mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
798         }
799
800         mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
801
802         for(f_code=1; f_code<=MAX_FCODE; f_code++){
803             for(mv=-MAX_MV; mv<=MAX_MV; mv++){
804                 int len;
805
806                 if(mv==0) len= mbMotionVectorTable[0][1];
807                 else{
808                     int val, bit_size, range, code;
809
810                     bit_size = f_code - 1;
811                     range = 1 << bit_size;
812
813                     val=mv;
814                     if (val < 0) 
815                         val = -val;
816                     val--;
817                     code = (val >> bit_size) + 1;
818                     if(code<17){
819                         len= mbMotionVectorTable[code][1] + 1 + bit_size;
820                     }else{
821                         len= mbMotionVectorTable[16][1] + 2 + bit_size;
822                     }
823                 }
824
825                 mv_penalty[f_code][mv+MAX_MV]= len;
826             }
827         }
828         
829
830         for(f_code=MAX_FCODE; f_code>0; f_code--){
831             for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
832                 fcode_tab[mv+MAX_MV]= f_code;
833             }
834         }
835     }
836     s->me.mv_penalty= mv_penalty;
837     s->fcode_tab= fcode_tab;
838     if(s->codec_id == CODEC_ID_MPEG1VIDEO){
839         s->min_qcoeff=-255;
840         s->max_qcoeff= 255;
841     }else{
842         s->min_qcoeff=-2047;
843         s->max_qcoeff= 2047;
844     }
845     s->intra_ac_vlc_length=
846     s->inter_ac_vlc_length=
847     s->intra_ac_vlc_last_length=
848     s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
849 }
850
851 static inline void encode_dc(MpegEncContext *s, int diff, int component)
852 {
853   if(((unsigned) (diff+255)) >= 511){
854         int index;
855
856         if(diff<0){
857             index= av_log2_16bit(-2*diff);
858             diff--;
859         }else{
860             index= av_log2_16bit(2*diff);
861         }
862         if (component == 0) {
863             put_bits(
864                 &s->pb, 
865                 vlc_dc_lum_bits[index] + index,
866                 (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1)));
867         }else{
868             put_bits(
869                 &s->pb, 
870                 vlc_dc_chroma_bits[index] + index,
871                 (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1)));
872         }
873   }else{
874     if (component == 0) {
875         put_bits(
876             &s->pb, 
877             mpeg1_lum_dc_uni[diff+255]&0xFF,
878             mpeg1_lum_dc_uni[diff+255]>>8);
879     } else {
880         put_bits(
881             &s->pb, 
882             mpeg1_chr_dc_uni[diff+255]&0xFF,
883             mpeg1_chr_dc_uni[diff+255]>>8);
884     }
885   }
886 }
887
888 static void mpeg1_encode_block(MpegEncContext *s, 
889                                DCTELEM *block, 
890                                int n)
891 {
892     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
893     int code, component;
894 //    RLTable *rl = &rl_mpeg1;
895
896     last_index = s->block_last_index[n];
897
898     /* DC coef */
899     if (s->mb_intra) {
900         component = (n <= 3 ? 0 : n - 4 + 1);
901         dc = block[0]; /* overflow is impossible */
902         diff = dc - s->last_dc[component];
903         encode_dc(s, diff, component);
904         s->last_dc[component] = dc;
905         i = 1;
906 /*
907         if (s->intra_vlc_format)
908             rl = &rl_mpeg2;
909         else
910             rl = &rl_mpeg1;
911 */
912     } else {
913         /* encode the first coefficient : needs to be done here because
914            it is handled slightly differently */
915         level = block[0];
916         if (abs(level) == 1) {
917                 code = ((uint32_t)level >> 31); /* the sign bit */
918                 put_bits(&s->pb, 2, code | 0x02);
919                 i = 1;
920         } else {
921             i = 0;
922             last_non_zero = -1;
923             goto next_coef;
924         }
925     }
926
927     /* now quantify & encode AC coefs */
928     last_non_zero = i - 1;
929
930     for(;i<=last_index;i++) {
931         j = s->intra_scantable.permutated[i];
932         level = block[j];
933     next_coef:
934 #if 0
935         if (level != 0)
936             dprintf("level[%d]=%d\n", i, level);
937 #endif            
938         /* encode using VLC */
939         if (level != 0) {
940             run = i - last_non_zero - 1;
941             
942             alevel= level;
943             MASK_ABS(sign, alevel)
944             sign&=1;
945
946 //            code = get_rl_index(rl, 0, run, alevel);
947             if (alevel <= mpeg1_max_level[0][run]){
948                 code= mpeg1_index_run[0][run] + alevel - 1;
949                 /* store the vlc & sign at once */
950                 put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
951             } else {
952                 /* escape seems to be pretty rare <5% so i dont optimize it */
953                 put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
954                 /* escape: only clip in this case */
955                 put_bits(&s->pb, 6, run);
956                 if(s->codec_id == CODEC_ID_MPEG1VIDEO){
957                     if (alevel < 128) {
958                         put_bits(&s->pb, 8, level & 0xff);
959                     } else {
960                         if (level < 0) {
961                             put_bits(&s->pb, 16, 0x8001 + level + 255);
962                         } else {
963                             put_bits(&s->pb, 16, level & 0xffff);
964                         }
965                     }
966                 }else{
967                     put_bits(&s->pb, 12, level & 0xfff);
968                 }
969             }
970             last_non_zero = i;
971         }
972     }
973     /* end of block */
974     put_bits(&s->pb, 2, 0x2);
975 }
976 #endif //CONFIG_ENCODERS
977
978 /******************************************/
979 /* decoding */
980
981 static VLC dc_lum_vlc;
982 static VLC dc_chroma_vlc;
983 static VLC mv_vlc;
984 static VLC mbincr_vlc;
985 static VLC mb_ptype_vlc;
986 static VLC mb_btype_vlc;
987 static VLC mb_pat_vlc;
988
989 static void init_vlcs(void)
990 {
991     static int done = 0;
992
993     if (!done) {
994         done = 1;
995
996         init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
997                  vlc_dc_lum_bits, 1, 1,
998                  vlc_dc_lum_code, 2, 2, 1);
999         init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
1000                  vlc_dc_chroma_bits, 1, 1,
1001                  vlc_dc_chroma_code, 2, 2, 1);
1002         init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
1003                  &mbMotionVectorTable[0][1], 2, 1,
1004                  &mbMotionVectorTable[0][0], 2, 1, 1);
1005         init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 36, 
1006                  &mbAddrIncrTable[0][1], 2, 1,
1007                  &mbAddrIncrTable[0][0], 2, 1, 1);
1008         init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,
1009                  &mbPatTable[0][1], 2, 1,
1010                  &mbPatTable[0][0], 2, 1, 1);
1011         
1012         init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7, 
1013                  &table_mb_ptype[0][1], 2, 1,
1014                  &table_mb_ptype[0][0], 2, 1, 1);
1015         init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11, 
1016                  &table_mb_btype[0][1], 2, 1,
1017                  &table_mb_btype[0][0], 2, 1, 1);
1018         init_rl(&rl_mpeg1, 1);
1019         init_rl(&rl_mpeg2, 1);
1020
1021         init_2d_vlc_rl(&rl_mpeg1, 1);
1022         init_2d_vlc_rl(&rl_mpeg2, 1);
1023     }
1024 }
1025
1026 static inline int get_dmv(MpegEncContext *s)
1027 {
1028     if(get_bits1(&s->gb)) 
1029         return 1 - (get_bits1(&s->gb) << 1);
1030     else
1031         return 0;
1032 }
1033
1034 static inline int get_qscale(MpegEncContext *s)
1035 {
1036     int qscale = get_bits(&s->gb, 5);
1037     if (s->q_scale_type) {
1038         return non_linear_qscale[qscale];
1039     } else {
1040         return qscale << 1;
1041     }
1042 }
1043
1044 /* motion type (for mpeg2) */
1045 #define MT_FIELD 1
1046 #define MT_FRAME 2
1047 #define MT_16X8  2
1048 #define MT_DMV   3
1049
1050 static int mpeg_decode_mb(MpegEncContext *s,
1051                           DCTELEM block[12][64])
1052 {
1053     int i, j, k, cbp, val, mb_type, motion_type;
1054     const int mb_block_count = 4 + (1<< s->chroma_format);
1055
1056     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
1057
1058     assert(s->mb_skiped==0);
1059
1060     if (s->mb_skip_run-- != 0) {
1061         if(s->pict_type == I_TYPE){
1062             av_log(s->avctx, AV_LOG_ERROR, "skiped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1063             return -1;
1064         }
1065     
1066         /* skip mb */
1067         s->mb_intra = 0;
1068         for(i=0;i<12;i++)
1069             s->block_last_index[i] = -1;
1070         if(s->picture_structure == PICT_FRAME)
1071             s->mv_type = MV_TYPE_16X16;
1072         else
1073             s->mv_type = MV_TYPE_FIELD;
1074         if (s->pict_type == P_TYPE) {
1075             /* if P type, zero motion vector is implied */
1076             s->mv_dir = MV_DIR_FORWARD;
1077             s->mv[0][0][0] = s->mv[0][0][1] = 0;
1078             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
1079             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
1080             s->field_select[0][0]= s->picture_structure - 1;
1081             s->mb_skiped = 1;
1082             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
1083         } else {
1084             int mb_type;
1085             
1086             if(s->mb_x)
1087                 mb_type= s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1];
1088             else
1089                 mb_type= s->current_picture.mb_type[ s->mb_width + (s->mb_y-1)*s->mb_stride - 1]; // FIXME not sure if this is allowed in mpeg at all, 
1090             if(IS_INTRA(mb_type))
1091                 return -1;
1092             
1093             /* if B type, reuse previous vectors and directions */
1094             s->mv[0][0][0] = s->last_mv[0][0][0];
1095             s->mv[0][0][1] = s->last_mv[0][0][1];
1096             s->mv[1][0][0] = s->last_mv[1][0][0];
1097             s->mv[1][0][1] = s->last_mv[1][0][1];
1098
1099             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= 
1100                 mb_type | MB_TYPE_SKIP;
1101 //            assert(s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1]&(MB_TYPE_16x16|MB_TYPE_16x8));
1102
1103             if((s->mv[0][0][0]|s->mv[0][0][1]|s->mv[1][0][0]|s->mv[1][0][1])==0) 
1104                 s->mb_skiped = 1;
1105         }
1106
1107         return 0;
1108     }
1109
1110     switch(s->pict_type) {
1111     default:
1112     case I_TYPE:
1113         if (get_bits1(&s->gb) == 0) {
1114             if (get_bits1(&s->gb) == 0){
1115                 av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in I Frame at %d %d\n", s->mb_x, s->mb_y);
1116                 return -1;
1117             }
1118             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
1119         } else {
1120             mb_type = MB_TYPE_INTRA;
1121         }
1122         break;
1123     case P_TYPE:
1124         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
1125         if (mb_type < 0){
1126             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
1127             return -1;
1128         }
1129         mb_type = ptype2mb_type[ mb_type ];
1130         break;
1131     case B_TYPE:
1132         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
1133         if (mb_type < 0){
1134             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
1135             return -1;
1136         }
1137         mb_type = btype2mb_type[ mb_type ];
1138         break;
1139     }
1140     dprintf("mb_type=%x\n", mb_type);
1141 //    motion_type = 0; /* avoid warning */
1142     if (IS_INTRA(mb_type)) {
1143         /* compute dct type */
1144         if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1145             !s->frame_pred_frame_dct) {
1146             s->interlaced_dct = get_bits1(&s->gb);
1147         }
1148
1149         if (IS_QUANT(mb_type))
1150             s->qscale = get_qscale(s);
1151         
1152         if (s->concealment_motion_vectors) {
1153             /* just parse them */
1154             if (s->picture_structure != PICT_FRAME) 
1155                 skip_bits1(&s->gb); /* field select */
1156             
1157             s->mv[0][0][0]= s->last_mv[0][0][0]= s->last_mv[0][1][0] = 
1158                 mpeg_decode_motion(s, s->mpeg_f_code[0][0], s->last_mv[0][0][0]);
1159             s->mv[0][0][1]= s->last_mv[0][0][1]= s->last_mv[0][1][1] = 
1160                 mpeg_decode_motion(s, s->mpeg_f_code[0][1], s->last_mv[0][0][1]);
1161
1162             skip_bits1(&s->gb); /* marker */
1163         }else
1164             memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
1165         s->mb_intra = 1;
1166 #ifdef HAVE_XVMC
1167         //one 1 we memcpy blocks in xvmcvideo
1168         if(s->avctx->xvmc_acceleration > 1){
1169             XVMC_pack_pblocks(s,-1);//inter are always full blocks
1170             if(s->swap_uv){
1171                 exchange_uv(s);
1172             }
1173         }
1174 #endif
1175
1176         if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
1177             if(s->flags2 & CODEC_FLAG2_FAST){
1178                 for(i=0;i<6;i++) {
1179                     mpeg2_fast_decode_block_intra(s, s->pblocks[i], i);
1180                 }
1181             }else{
1182                 for(i=0;i<mb_block_count;i++) {
1183                     if (mpeg2_decode_block_intra(s, s->pblocks[i], i) < 0)
1184                         return -1;
1185                 }
1186             }
1187         } else {
1188             for(i=0;i<6;i++) {
1189                 if (mpeg1_decode_block_intra(s, s->pblocks[i], i) < 0)
1190                     return -1;
1191             }
1192         }
1193     } else {
1194         if (mb_type & MB_TYPE_ZERO_MV){
1195             assert(mb_type & MB_TYPE_CBP);
1196
1197             /* compute dct type */
1198             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1199                 !s->frame_pred_frame_dct) {
1200                 s->interlaced_dct = get_bits1(&s->gb);
1201             }
1202
1203             if (IS_QUANT(mb_type))
1204                 s->qscale = get_qscale(s);
1205
1206             s->mv_dir = MV_DIR_FORWARD;
1207             if(s->picture_structure == PICT_FRAME)
1208                 s->mv_type = MV_TYPE_16X16;
1209             else{
1210                 s->mv_type = MV_TYPE_FIELD;
1211                 mb_type |= MB_TYPE_INTERLACED;
1212                 s->field_select[0][0]= s->picture_structure - 1;
1213             }
1214             s->last_mv[0][0][0] = 0;
1215             s->last_mv[0][0][1] = 0;
1216             s->last_mv[0][1][0] = 0;
1217             s->last_mv[0][1][1] = 0;
1218             s->mv[0][0][0] = 0;
1219             s->mv[0][0][1] = 0;
1220         }else{
1221             assert(mb_type & MB_TYPE_L0L1);
1222 //FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
1223             /* get additionnal motion vector type */
1224             if (s->frame_pred_frame_dct) 
1225                 motion_type = MT_FRAME;
1226             else{
1227                 motion_type = get_bits(&s->gb, 2);
1228             }
1229
1230             /* compute dct type */
1231             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
1232                 !s->frame_pred_frame_dct && HAS_CBP(mb_type)) {
1233                 s->interlaced_dct = get_bits1(&s->gb);
1234             }
1235
1236             if (IS_QUANT(mb_type))
1237                 s->qscale = get_qscale(s);
1238
1239             /* motion vectors */
1240             s->mv_dir = 0;
1241             for(i=0;i<2;i++) {
1242                 if (USES_LIST(mb_type, i)) {
1243                     s->mv_dir |= (MV_DIR_FORWARD >> i);
1244                     dprintf("motion_type=%d\n", motion_type);
1245                     switch(motion_type) {
1246                     case MT_FRAME: /* or MT_16X8 */
1247                         if (s->picture_structure == PICT_FRAME) {
1248                             /* MT_FRAME */
1249                             mb_type |= MB_TYPE_16x16; 
1250                             s->mv_type = MV_TYPE_16X16;
1251                             s->mv[i][0][0]= s->last_mv[i][0][0]= s->last_mv[i][1][0] = 
1252                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0], s->last_mv[i][0][0]);
1253                             s->mv[i][0][1]= s->last_mv[i][0][1]= s->last_mv[i][1][1] = 
1254                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1], s->last_mv[i][0][1]);
1255                             /* full_pel: only for mpeg1 */
1256                             if (s->full_pel[i]){
1257                                 s->mv[i][0][0] <<= 1;
1258                                 s->mv[i][0][1] <<= 1;
1259                             }
1260                         } else {
1261                             /* MT_16X8 */
1262                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; 
1263                             s->mv_type = MV_TYPE_16X8;
1264                             for(j=0;j<2;j++) {
1265                                 s->field_select[i][j] = get_bits1(&s->gb);
1266                                 for(k=0;k<2;k++) {
1267                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1268                                                              s->last_mv[i][j][k]);
1269                                     s->last_mv[i][j][k] = val;
1270                                     s->mv[i][j][k] = val;
1271                                 }
1272                             }
1273                         }
1274                         break;
1275                     case MT_FIELD:
1276                         s->mv_type = MV_TYPE_FIELD;
1277                         if (s->picture_structure == PICT_FRAME) {
1278                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; 
1279                             for(j=0;j<2;j++) {
1280                                 s->field_select[i][j] = get_bits1(&s->gb);
1281                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
1282                                                          s->last_mv[i][j][0]);
1283                                 s->last_mv[i][j][0] = val;
1284                                 s->mv[i][j][0] = val;
1285                                 dprintf("fmx=%d\n", val);
1286                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
1287                                                          s->last_mv[i][j][1] >> 1);
1288                                 s->last_mv[i][j][1] = val << 1;
1289                                 s->mv[i][j][1] = val;
1290                                 dprintf("fmy=%d\n", val);
1291                             }
1292                         } else {
1293                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED; 
1294                             s->field_select[i][0] = get_bits1(&s->gb);
1295                             for(k=0;k<2;k++) {
1296                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
1297                                                          s->last_mv[i][0][k]);
1298                                 s->last_mv[i][0][k] = val;
1299                                 s->last_mv[i][1][k] = val;
1300                                 s->mv[i][0][k] = val;
1301                             }
1302                         }
1303                         break;
1304                     case MT_DMV:
1305                         {
1306                             int dmx, dmy, mx, my, m;
1307
1308                             mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
1309                                                     s->last_mv[i][0][0]);
1310                             s->last_mv[i][0][0] = mx;
1311                             s->last_mv[i][1][0] = mx;
1312                             dmx = get_dmv(s);
1313                             my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
1314                                                     s->last_mv[i][0][1] >> 1);
1315                             dmy = get_dmv(s);
1316                             s->mv_type = MV_TYPE_DMV;
1317
1318
1319                             s->last_mv[i][0][1] = my<<1;
1320                             s->last_mv[i][1][1] = my<<1;
1321
1322                             s->mv[i][0][0] = mx;
1323                             s->mv[i][0][1] = my;
1324                             s->mv[i][1][0] = mx;//not used
1325                             s->mv[i][1][1] = my;//not used
1326
1327                             if (s->picture_structure == PICT_FRAME) {
1328                                 mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED; 
1329
1330                                 //m = 1 + 2 * s->top_field_first;
1331                                 m = s->top_field_first ? 1 : 3;
1332
1333                                 /* top -> top pred */
1334                                 s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1335                                 s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
1336                                 m = 4 - m;
1337                                 s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1338                                 s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
1339                             } else {
1340                                 mb_type |= MB_TYPE_16x16;
1341
1342                                 s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
1343                                 s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
1344                                 if(s->picture_structure == PICT_TOP_FIELD)
1345                                     s->mv[i][2][1]--;
1346                                 else 
1347                                     s->mv[i][2][1]++;
1348                             }
1349                         }
1350                         break;
1351                     default:
1352                         av_log(s->avctx, AV_LOG_ERROR, "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
1353                         return -1;
1354                     }
1355                 }
1356             }
1357         }
1358         
1359         s->mb_intra = 0;
1360
1361         if (HAS_CBP(mb_type)) {
1362             cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1363             if (cbp < 0 || ((cbp == 0) && (s->chroma_format < 2)) ){
1364                 av_log(s->avctx, AV_LOG_ERROR, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
1365                 return -1;
1366             }
1367             if(mb_block_count > 6){
1368                  cbp<<= mb_block_count-6;
1369                  cbp |= get_bits(&s->gb, mb_block_count-6);
1370             }
1371
1372 #ifdef HAVE_XVMC
1373             //on 1 we memcpy blocks in xvmcvideo
1374             if(s->avctx->xvmc_acceleration > 1){
1375                 XVMC_pack_pblocks(s,cbp);
1376                 if(s->swap_uv){
1377                     exchange_uv(s);
1378                 }
1379             }    
1380 #endif
1381
1382             if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
1383                 if(s->flags2 & CODEC_FLAG2_FAST){
1384                     for(i=0;i<6;i++) {
1385                         if(cbp & 32) {
1386                             mpeg2_fast_decode_block_non_intra(s, s->pblocks[i], i);
1387                         } else {
1388                             s->block_last_index[i] = -1;
1389                         }
1390                         cbp+=cbp;
1391                     }
1392                 }else{
1393                     cbp<<= 12-mb_block_count;
1394     
1395                     for(i=0;i<mb_block_count;i++) {
1396                         if ( cbp & (1<<11) ) {
1397                             if (mpeg2_decode_block_non_intra(s, s->pblocks[i], i) < 0)
1398                                 return -1;
1399                         } else {
1400                             s->block_last_index[i] = -1;
1401                         }
1402                         cbp+=cbp;
1403                     }
1404                 }
1405             } else {
1406                 if(s->flags2 & CODEC_FLAG2_FAST){
1407                     for(i=0;i<6;i++) {
1408                         if (cbp & 32) {
1409                             mpeg1_fast_decode_block_inter(s, s->pblocks[i], i);
1410                         } else {
1411                             s->block_last_index[i] = -1;
1412                         }
1413                         cbp+=cbp;
1414                     }
1415                 }else{
1416                     for(i=0;i<6;i++) {
1417                         if (cbp & 32) {
1418                             if (mpeg1_decode_block_inter(s, s->pblocks[i], i) < 0)
1419                                 return -1;
1420                         } else {
1421                             s->block_last_index[i] = -1;
1422                         }
1423                         cbp+=cbp;
1424                     }
1425                 }
1426             }
1427         }else{
1428             for(i=0;i<6;i++)
1429                 s->block_last_index[i] = -1;
1430         }
1431     }
1432
1433     s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= mb_type;
1434
1435     return 0;
1436 }
1437
1438 /* as h263, but only 17 codes */
1439 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
1440 {
1441     int code, sign, val, l, shift;
1442
1443     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
1444     if (code == 0) {
1445         return pred;
1446     }
1447     if (code < 0) {
1448         return 0xffff;
1449     }
1450
1451     sign = get_bits1(&s->gb);
1452     shift = fcode - 1;
1453     val = code;
1454     if (shift) {
1455         val = (val - 1) << shift;
1456         val |= get_bits(&s->gb, shift);
1457         val++;
1458     }
1459     if (sign)
1460         val = -val;
1461     val += pred;
1462     
1463     /* modulo decoding */
1464     l= INT_BIT - 5 - shift;
1465     val = (val<<l)>>l;
1466     return val;
1467 }
1468
1469 static inline int decode_dc(GetBitContext *gb, int component)
1470 {
1471     int code, diff;
1472
1473     if (component == 0) {
1474         code = get_vlc2(gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
1475     } else {
1476         code = get_vlc2(gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
1477     }
1478     if (code < 0){
1479         av_log(NULL, AV_LOG_ERROR, "invalid dc code at\n");
1480         return 0xffff;
1481     }
1482     if (code == 0) {
1483         diff = 0;
1484     } else {
1485         diff = get_xbits(gb, code);
1486     }
1487     return diff;
1488 }
1489
1490 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
1491                                DCTELEM *block, 
1492                                int n)
1493 {
1494     int level, dc, diff, i, j, run;
1495     int component;
1496     RLTable *rl = &rl_mpeg1;
1497     uint8_t * const scantable= s->intra_scantable.permutated;
1498     const uint16_t *quant_matrix= s->intra_matrix;
1499     const int qscale= s->qscale;
1500
1501     /* DC coef */
1502     component = (n <= 3 ? 0 : n - 4 + 1);
1503     diff = decode_dc(&s->gb, component);
1504     if (diff >= 0xffff)
1505         return -1;
1506     dc = s->last_dc[component];
1507     dc += diff;
1508     s->last_dc[component] = dc;
1509     block[0] = dc<<3;
1510     dprintf("dc=%d diff=%d\n", dc, diff);
1511     i = 0;
1512     {
1513         OPEN_READER(re, &s->gb);    
1514         /* now quantify & encode AC coefs */
1515         for(;;) {
1516             UPDATE_CACHE(re, &s->gb);
1517             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1518             
1519             if(level == 127){
1520                 break;
1521             } else if(level != 0) {
1522                 i += run;
1523                 j = scantable[i];
1524                 level= (level*qscale*quant_matrix[j])>>4;
1525                 level= (level-1)|1;
1526                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1527                 LAST_SKIP_BITS(re, &s->gb, 1);
1528             } else {
1529                 /* escape */
1530                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1531                 UPDATE_CACHE(re, &s->gb);
1532                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1533                 if (level == -128) {
1534                     level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
1535                 } else if (level == 0) {
1536                     level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
1537                 }
1538                 i += run;
1539                 j = scantable[i];
1540                 if(level<0){
1541                     level= -level;
1542                     level= (level*qscale*quant_matrix[j])>>4;
1543                     level= (level-1)|1;
1544                     level= -level;
1545                 }else{
1546                     level= (level*qscale*quant_matrix[j])>>4;
1547                     level= (level-1)|1;
1548                 }
1549             }
1550             if (i > 63){
1551                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1552                 return -1;
1553             }
1554
1555             block[j] = level;
1556         }
1557         CLOSE_READER(re, &s->gb);
1558     }
1559     s->block_last_index[n] = i;
1560    return 0;
1561 }
1562
1563 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
1564                                DCTELEM *block, 
1565                                int n)
1566 {
1567     int level, i, j, run;
1568     RLTable *rl = &rl_mpeg1;
1569     uint8_t * const scantable= s->intra_scantable.permutated;
1570     const uint16_t *quant_matrix= s->inter_matrix;
1571     const int qscale= s->qscale;
1572
1573     {
1574         OPEN_READER(re, &s->gb);
1575         i = -1;
1576         /* special case for the first coef. no need to add a second vlc table */
1577         UPDATE_CACHE(re, &s->gb);
1578         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1579             level= (3*qscale*quant_matrix[0])>>5;
1580             level= (level-1)|1;
1581             if(GET_CACHE(re, &s->gb)&0x40000000)
1582                 level= -level;
1583             block[0] = level;
1584             i++;
1585             SKIP_BITS(re, &s->gb, 2);
1586             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1587                 goto end;
1588         }
1589
1590         /* now quantify & encode AC coefs */
1591         for(;;) {
1592             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1593             
1594             if(level != 0) {
1595                 i += run;
1596                 j = scantable[i];
1597                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1598                 level= (level-1)|1;
1599                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1600                 SKIP_BITS(re, &s->gb, 1);
1601             } else {
1602                 /* escape */
1603                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1604                 UPDATE_CACHE(re, &s->gb);
1605                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1606                 if (level == -128) {
1607                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
1608                 } else if (level == 0) {
1609                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
1610                 }
1611                 i += run;
1612                 j = scantable[i];
1613                 if(level<0){
1614                     level= -level;
1615                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1616                     level= (level-1)|1;
1617                     level= -level;
1618                 }else{
1619                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1620                     level= (level-1)|1;
1621                 }
1622             }
1623             if (i > 63){
1624                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1625                 return -1;
1626             }
1627
1628             block[j] = level;
1629             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1630                 break;
1631             UPDATE_CACHE(re, &s->gb);
1632         }
1633 end:
1634         LAST_SKIP_BITS(re, &s->gb, 2);
1635         CLOSE_READER(re, &s->gb);
1636     }
1637     s->block_last_index[n] = i;
1638     return 0;
1639 }
1640
1641 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n)
1642 {
1643     int level, i, j, run;
1644     RLTable *rl = &rl_mpeg1;
1645     uint8_t * const scantable= s->intra_scantable.permutated;
1646     const int qscale= s->qscale;
1647
1648     {
1649         OPEN_READER(re, &s->gb);
1650         i = -1;
1651         /* special case for the first coef. no need to add a second vlc table */
1652         UPDATE_CACHE(re, &s->gb);
1653         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1654             level= (3*qscale)>>1;
1655             level= (level-1)|1;
1656             if(GET_CACHE(re, &s->gb)&0x40000000)
1657                 level= -level;
1658             block[0] = level;
1659             i++;
1660             SKIP_BITS(re, &s->gb, 2);
1661             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1662                 goto end;
1663         }
1664
1665         /* now quantify & encode AC coefs */
1666         for(;;) {
1667             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1668             
1669             if(level != 0) {
1670                 i += run;
1671                 j = scantable[i];
1672                 level= ((level*2+1)*qscale)>>1;
1673                 level= (level-1)|1;
1674                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1675                 SKIP_BITS(re, &s->gb, 1);
1676             } else {
1677                 /* escape */
1678                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1679                 UPDATE_CACHE(re, &s->gb);
1680                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
1681                 if (level == -128) {
1682                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
1683                 } else if (level == 0) {
1684                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
1685                 }
1686                 i += run;
1687                 j = scantable[i];
1688                 if(level<0){
1689                     level= -level;
1690                     level= ((level*2+1)*qscale)>>1;
1691                     level= (level-1)|1;
1692                     level= -level;
1693                 }else{
1694                     level= ((level*2+1)*qscale)>>1;
1695                     level= (level-1)|1;
1696                 }
1697             }
1698
1699             block[j] = level;
1700             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1701                 break;
1702             UPDATE_CACHE(re, &s->gb);
1703         }
1704 end:
1705         LAST_SKIP_BITS(re, &s->gb, 2);
1706         CLOSE_READER(re, &s->gb);
1707     }
1708     s->block_last_index[n] = i;
1709     return 0;
1710 }
1711
1712
1713 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
1714                                DCTELEM *block, 
1715                                int n)
1716 {
1717     int level, i, j, run;
1718     RLTable *rl = &rl_mpeg1;
1719     uint8_t * const scantable= s->intra_scantable.permutated;
1720     const uint16_t *quant_matrix;
1721     const int qscale= s->qscale;
1722     int mismatch;
1723
1724     mismatch = 1;
1725
1726     {
1727         OPEN_READER(re, &s->gb);
1728         i = -1;
1729         if (n < 4)
1730             quant_matrix = s->inter_matrix;
1731         else
1732             quant_matrix = s->chroma_inter_matrix;
1733
1734         /* special case for the first coef. no need to add a second vlc table */
1735         UPDATE_CACHE(re, &s->gb);
1736         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1737             level= (3*qscale*quant_matrix[0])>>5;
1738             if(GET_CACHE(re, &s->gb)&0x40000000)
1739                 level= -level;
1740             block[0] = level;
1741             mismatch ^= level;
1742             i++;
1743             SKIP_BITS(re, &s->gb, 2);
1744             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1745                 goto end;
1746         }
1747
1748         /* now quantify & encode AC coefs */
1749         for(;;) {
1750             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1751             
1752             if(level != 0) {
1753                 i += run;
1754                 j = scantable[i];
1755                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1756                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1757                 SKIP_BITS(re, &s->gb, 1);
1758             } else {
1759                 /* escape */
1760                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1761                 UPDATE_CACHE(re, &s->gb);
1762                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1763
1764                 i += run;
1765                 j = scantable[i];
1766                 if(level<0){
1767                     level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
1768                     level= -level;
1769                 }else{
1770                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
1771                 }
1772             }
1773             if (i > 63){
1774                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1775                 return -1;
1776             }
1777             
1778             mismatch ^= level;
1779             block[j] = level;
1780             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1781                 break;
1782             UPDATE_CACHE(re, &s->gb);
1783         }
1784 end:
1785         LAST_SKIP_BITS(re, &s->gb, 2);
1786         CLOSE_READER(re, &s->gb);
1787     }
1788     block[63] ^= (mismatch & 1);
1789     
1790     s->block_last_index[n] = i;
1791     return 0;
1792 }
1793
1794 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, 
1795                                DCTELEM *block, 
1796                                int n)
1797 {
1798     int level, i, j, run;
1799     RLTable *rl = &rl_mpeg1;
1800     uint8_t * const scantable= s->intra_scantable.permutated;
1801     const int qscale= s->qscale;
1802     int v;
1803     OPEN_READER(re, &s->gb);
1804     i = -1;
1805
1806     /* special case for the first coef. no need to add a second vlc table */
1807     UPDATE_CACHE(re, &s->gb);
1808     if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
1809         level= (3*qscale)>>1;
1810         if(GET_CACHE(re, &s->gb)&0x40000000)
1811             level= -level;
1812         block[0] = level;
1813         i++;
1814         SKIP_BITS(re, &s->gb, 2);
1815         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1816             goto end;
1817     }
1818
1819     /* now quantify & encode AC coefs */
1820     for(;;) {
1821         GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1822         
1823         if(level != 0) {
1824             i += run;
1825             j = scantable[i];
1826             level= ((level*2+1)*qscale)>>1;
1827             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1828             SKIP_BITS(re, &s->gb, 1);
1829         } else {
1830             /* escape */
1831             run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1832             UPDATE_CACHE(re, &s->gb);
1833             level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1834
1835             i += run;
1836             j = scantable[i];
1837             if(level<0){
1838                 level= ((-level*2+1)*qscale)>>1;
1839                 level= -level;
1840             }else{
1841                 level= ((level*2+1)*qscale)>>1;
1842             }
1843         }
1844         
1845         block[j] = level;
1846         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
1847             break;
1848         UPDATE_CACHE(re, &s->gb);
1849     }
1850 end:
1851     LAST_SKIP_BITS(re, &s->gb, 2);    
1852     CLOSE_READER(re, &s->gb);
1853     s->block_last_index[n] = i;
1854     return 0;
1855 }
1856
1857
1858 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
1859                                DCTELEM *block, 
1860                                int n)
1861 {
1862     int level, dc, diff, i, j, run;
1863     int component;
1864     RLTable *rl;
1865     uint8_t * const scantable= s->intra_scantable.permutated;
1866     const uint16_t *quant_matrix;
1867     const int qscale= s->qscale;
1868     int mismatch;
1869
1870     /* DC coef */
1871     if (n < 4){
1872         quant_matrix = s->intra_matrix;
1873         component = 0; 
1874     }else{
1875         quant_matrix = s->chroma_intra_matrix;
1876         component = (n&1) + 1;
1877     }
1878     diff = decode_dc(&s->gb, component);
1879     if (diff >= 0xffff)
1880         return -1;
1881     dc = s->last_dc[component];
1882     dc += diff;
1883     s->last_dc[component] = dc;
1884     block[0] = dc << (3 - s->intra_dc_precision);
1885     dprintf("dc=%d\n", block[0]);
1886     mismatch = block[0] ^ 1;
1887     i = 0;
1888     if (s->intra_vlc_format)
1889         rl = &rl_mpeg2;
1890     else
1891         rl = &rl_mpeg1;
1892
1893     {
1894         OPEN_READER(re, &s->gb);    
1895         /* now quantify & encode AC coefs */
1896         for(;;) {
1897             UPDATE_CACHE(re, &s->gb);
1898             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1899             
1900             if(level == 127){
1901                 break;
1902             } else if(level != 0) {
1903                 i += run;
1904                 j = scantable[i];
1905                 level= (level*qscale*quant_matrix[j])>>4;
1906                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1907                 LAST_SKIP_BITS(re, &s->gb, 1);
1908             } else {
1909                 /* escape */
1910                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1911                 UPDATE_CACHE(re, &s->gb);
1912                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1913                 i += run;
1914                 j = scantable[i];
1915                 if(level<0){
1916                     level= (-level*qscale*quant_matrix[j])>>4;
1917                     level= -level;
1918                 }else{
1919                     level= (level*qscale*quant_matrix[j])>>4;
1920                 }
1921             }
1922             if (i > 63){
1923                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1924                 return -1;
1925             }
1926             
1927             mismatch^= level;
1928             block[j] = level;
1929         }
1930         CLOSE_READER(re, &s->gb);
1931     }
1932     block[63]^= mismatch&1;
1933     
1934     s->block_last_index[n] = i;
1935     return 0;
1936 }
1937
1938 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, 
1939                                DCTELEM *block, 
1940                                int n)
1941 {
1942     int level, dc, diff, j, run;
1943     int component;
1944     RLTable *rl;
1945     uint8_t * scantable= s->intra_scantable.permutated;
1946     const uint16_t *quant_matrix;
1947     const int qscale= s->qscale;
1948
1949     /* DC coef */
1950     if (n < 4){
1951         quant_matrix = s->intra_matrix;
1952         component = 0; 
1953     }else{
1954         quant_matrix = s->chroma_intra_matrix;
1955         component = (n&1) + 1;
1956     }
1957     diff = decode_dc(&s->gb, component);
1958     if (diff >= 0xffff)
1959         return -1;
1960     dc = s->last_dc[component];
1961     dc += diff;
1962     s->last_dc[component] = dc;
1963     block[0] = dc << (3 - s->intra_dc_precision);
1964     if (s->intra_vlc_format)
1965         rl = &rl_mpeg2;
1966     else
1967         rl = &rl_mpeg1;
1968
1969     {
1970         OPEN_READER(re, &s->gb);    
1971         /* now quantify & encode AC coefs */
1972         for(;;) {
1973             UPDATE_CACHE(re, &s->gb);
1974             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
1975             
1976             if(level == 127){
1977                 break;
1978             } else if(level != 0) {
1979                 scantable += run;
1980                 j = *scantable;
1981                 level= (level*qscale*quant_matrix[j])>>4;
1982                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1983                 LAST_SKIP_BITS(re, &s->gb, 1);
1984             } else {
1985                 /* escape */
1986                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
1987                 UPDATE_CACHE(re, &s->gb);
1988                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
1989                 scantable += run;
1990                 j = *scantable;
1991                 if(level<0){
1992                     level= (-level*qscale*quant_matrix[j])>>4;
1993                     level= -level;
1994                 }else{
1995                     level= (level*qscale*quant_matrix[j])>>4;
1996                 }
1997             }
1998             
1999             block[j] = level;
2000         }
2001         CLOSE_READER(re, &s->gb);
2002     }
2003     
2004     s->block_last_index[n] = scantable - s->intra_scantable.permutated;
2005     return 0;
2006 }
2007
2008 typedef struct Mpeg1Context {
2009     MpegEncContext mpeg_enc_ctx;
2010     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
2011     int repeat_field; /* true if we must repeat the field */
2012     AVPanScan pan_scan; /** some temporary storage for the panscan */
2013     int slice_count;
2014     int swap_uv;//indicate VCR2
2015     int save_aspect_info;
2016     AVRational frame_rate_ext;       ///< MPEG-2 specific framerate modificator
2017
2018 } Mpeg1Context;
2019
2020 static int mpeg_decode_init(AVCodecContext *avctx)
2021 {
2022     Mpeg1Context *s = avctx->priv_data;
2023     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2024     int i;
2025     
2026     //we need some parmutation to store
2027     //matrixes, until MPV_common_init()
2028     //set the real permutatuon 
2029     for(i=0;i<64;i++)
2030        s2->dsp.idct_permutation[i]=i;
2031
2032     MPV_decode_defaults(s2);
2033     
2034     s->mpeg_enc_ctx.avctx= avctx;
2035     s->mpeg_enc_ctx.flags= avctx->flags;
2036     s->mpeg_enc_ctx.flags2= avctx->flags2;
2037     common_init(&s->mpeg_enc_ctx);
2038     init_vlcs();
2039
2040     s->mpeg_enc_ctx_allocated = 0;
2041     s->mpeg_enc_ctx.picture_number = 0;
2042     s->repeat_field = 0;
2043     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
2044     return 0;
2045 }
2046
2047 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm, 
2048                                      const uint8_t *new_perm){
2049     uint16_t temp_matrix[64];
2050     int i;
2051
2052     memcpy(temp_matrix,matrix,64*sizeof(uint16_t));
2053     
2054     for(i=0;i<64;i++){
2055         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
2056     }      
2057 }
2058
2059 //Call this function when we know all parameters
2060 //it may be called in different places for mpeg1 and mpeg2
2061 static int mpeg_decode_postinit(AVCodecContext *avctx){
2062     Mpeg1Context *s1 = avctx->priv_data;
2063     MpegEncContext *s = &s1->mpeg_enc_ctx;
2064     uint8_t old_permutation[64];
2065
2066     if (
2067         (s1->mpeg_enc_ctx_allocated == 0)|| 
2068         avctx->coded_width  != s->width ||
2069         avctx->coded_height != s->height||
2070         s1->save_aspect_info != s->aspect_ratio_info||
2071         0)
2072     {
2073     
2074         if (s1->mpeg_enc_ctx_allocated) {
2075             MPV_common_end(s);
2076         }
2077
2078         if( (s->width == 0 )||(s->height == 0))
2079             return -2;
2080
2081         avcodec_set_dimensions(avctx, s->width, s->height);
2082         avctx->bit_rate = s->bit_rate;
2083         s1->save_aspect_info = s->aspect_ratio_info;
2084
2085      //low_delay may be forced, in this case we will have B frames
2086      //that behave like P frames
2087         avctx->has_b_frames = !(s->low_delay);
2088
2089         if(avctx->sub_id==1){//s->codec_id==avctx->codec_id==CODEC_ID
2090             //mpeg1 fps
2091             avctx->frame_rate     = frame_rate_tab[s->frame_rate_index].num;
2092             avctx->frame_rate_base= frame_rate_tab[s->frame_rate_index].den;
2093             //mpeg1 aspect
2094             avctx->sample_aspect_ratio= av_d2q(
2095                     1.0/mpeg1_aspect[s->aspect_ratio_info], 255);
2096
2097         }else{//mpeg2
2098         //mpeg2 fps
2099             av_reduce(
2100                 &s->avctx->frame_rate, 
2101                 &s->avctx->frame_rate_base, 
2102                 frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num,
2103                 frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
2104                 1<<30);
2105         //mpeg2 aspect
2106             if(s->aspect_ratio_info > 1){
2107                 if( (s1->pan_scan.width == 0 )||(s1->pan_scan.height == 0) ){
2108                     s->avctx->sample_aspect_ratio= 
2109                         av_div_q(
2110                          mpeg2_aspect[s->aspect_ratio_info], 
2111                          (AVRational){s->width, s->height}
2112                          );
2113                 }else{
2114                     s->avctx->sample_aspect_ratio= 
2115                         av_div_q(
2116                          mpeg2_aspect[s->aspect_ratio_info], 
2117                          (AVRational){s1->pan_scan.width, s1->pan_scan.height}
2118                         );
2119                 }
2120             }else{
2121                 s->avctx->sample_aspect_ratio= 
2122                     mpeg2_aspect[s->aspect_ratio_info];
2123             }
2124         }//mpeg2
2125
2126         if(avctx->xvmc_acceleration){
2127             avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
2128         }else{
2129             if(s->chroma_format <  2){
2130                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
2131             }else
2132             if(s->chroma_format == 2){
2133                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_422);
2134             }else
2135             if(s->chroma_format >  2){
2136                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_444);
2137             }
2138         }
2139         //until then pix_fmt may be changed right after codec init
2140         if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
2141             if( avctx->idct_algo == FF_IDCT_AUTO )
2142                 avctx->idct_algo = FF_IDCT_SIMPLE;
2143
2144         //quantization matrixes may need reordering 
2145         //if dct permutation is changed
2146         memcpy(old_permutation,s->dsp.idct_permutation,64*sizeof(uint8_t));
2147
2148         if (MPV_common_init(s) < 0)
2149             return -2;
2150
2151         quant_matrix_rebuild(s->intra_matrix,       old_permutation,s->dsp.idct_permutation);
2152         quant_matrix_rebuild(s->inter_matrix,       old_permutation,s->dsp.idct_permutation);
2153         quant_matrix_rebuild(s->chroma_intra_matrix,old_permutation,s->dsp.idct_permutation);
2154         quant_matrix_rebuild(s->chroma_inter_matrix,old_permutation,s->dsp.idct_permutation);
2155
2156         s1->mpeg_enc_ctx_allocated = 1;
2157     }
2158     return 0;
2159 }
2160
2161 /* return the 8 bit start code value and update the search
2162    state. Return -1 if no start code found */
2163 static int find_start_code(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
2164 {
2165     const uint8_t *buf_ptr= *pbuf_ptr;
2166
2167     buf_ptr++; //gurantees that -1 is within the array
2168     buf_end -= 2; // gurantees that +2 is within the array
2169
2170     while (buf_ptr < buf_end) {
2171         if(*buf_ptr==0){
2172             while(buf_ptr < buf_end && buf_ptr[1]==0)
2173                 buf_ptr++;
2174
2175             if(buf_ptr[-1] == 0 && buf_ptr[1] == 1){
2176                 *pbuf_ptr = buf_ptr+3;
2177                 return buf_ptr[2] + 0x100;
2178             }
2179         }
2180         buf_ptr += 2;
2181     }
2182     buf_end += 2; //undo the hack above
2183     
2184     *pbuf_ptr = buf_end;
2185     return -1;
2186 }
2187
2188 static int mpeg1_decode_picture(AVCodecContext *avctx, 
2189                                 const uint8_t *buf, int buf_size)
2190 {
2191     Mpeg1Context *s1 = avctx->priv_data;
2192     MpegEncContext *s = &s1->mpeg_enc_ctx;
2193     int ref, f_code, vbv_delay;
2194
2195     if(mpeg_decode_postinit(s->avctx) < 0) 
2196        return -2;
2197
2198     init_get_bits(&s->gb, buf, buf_size*8);
2199
2200     ref = get_bits(&s->gb, 10); /* temporal ref */
2201     s->pict_type = get_bits(&s->gb, 3);
2202     if(s->pict_type == 0 || s->pict_type > 3)
2203         return -1;
2204
2205     vbv_delay= get_bits(&s->gb, 16);
2206     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
2207         s->full_pel[0] = get_bits1(&s->gb);
2208         f_code = get_bits(&s->gb, 3);
2209         if (f_code == 0)
2210             return -1;
2211         s->mpeg_f_code[0][0] = f_code;
2212         s->mpeg_f_code[0][1] = f_code;
2213     }
2214     if (s->pict_type == B_TYPE) {
2215         s->full_pel[1] = get_bits1(&s->gb);
2216         f_code = get_bits(&s->gb, 3);
2217         if (f_code == 0)
2218             return -1;
2219         s->mpeg_f_code[1][0] = f_code;
2220         s->mpeg_f_code[1][1] = f_code;
2221     }
2222     s->current_picture.pict_type= s->pict_type;
2223     s->current_picture.key_frame= s->pict_type == I_TYPE;
2224     
2225     if(avctx->debug & FF_DEBUG_PICT_INFO)
2226         av_log(avctx, AV_LOG_DEBUG, "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
2227     
2228     s->y_dc_scale = 8;
2229     s->c_dc_scale = 8;
2230     s->first_slice = 1;
2231     return 0;
2232 }
2233
2234 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
2235 {
2236     MpegEncContext *s= &s1->mpeg_enc_ctx;
2237     int horiz_size_ext, vert_size_ext;
2238     int bit_rate_ext;
2239
2240     skip_bits(&s->gb, 1); /* profil and level esc*/
2241     s->avctx->profile= get_bits(&s->gb, 3);
2242     s->avctx->level= get_bits(&s->gb, 4);
2243     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
2244     s->chroma_format = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
2245     horiz_size_ext = get_bits(&s->gb, 2);
2246     vert_size_ext = get_bits(&s->gb, 2);
2247     s->width |= (horiz_size_ext << 12);
2248     s->height |= (vert_size_ext << 12);
2249     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
2250     s->bit_rate += (bit_rate_ext << 18) * 400;
2251     skip_bits1(&s->gb); /* marker */
2252     s->avctx->rc_buffer_size += get_bits(&s->gb, 8)*1024*16<<10;
2253
2254     s->low_delay = get_bits1(&s->gb);
2255     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
2256
2257     s1->frame_rate_ext.num = get_bits(&s->gb, 2)+1;
2258     s1->frame_rate_ext.den = get_bits(&s->gb, 5)+1;
2259
2260     dprintf("sequence extension\n");
2261     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
2262     s->avctx->sub_id = 2; /* indicates mpeg2 found */
2263
2264     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2265         av_log(s->avctx, AV_LOG_DEBUG, "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n", 
2266                s->avctx->profile, s->avctx->level, s->avctx->rc_buffer_size, s->bit_rate);
2267
2268 }
2269
2270 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
2271 {
2272     MpegEncContext *s= &s1->mpeg_enc_ctx;
2273     int color_description, w, h;
2274
2275     skip_bits(&s->gb, 3); /* video format */
2276     color_description= get_bits1(&s->gb);
2277     if(color_description){
2278         skip_bits(&s->gb, 8); /* color primaries */
2279         skip_bits(&s->gb, 8); /* transfer_characteristics */
2280         skip_bits(&s->gb, 8); /* matrix_coefficients */
2281     }
2282     w= get_bits(&s->gb, 14);
2283     skip_bits(&s->gb, 1); //marker
2284     h= get_bits(&s->gb, 14);
2285     skip_bits(&s->gb, 1); //marker
2286     
2287     s1->pan_scan.width= 16*w;
2288     s1->pan_scan.height=16*h;
2289         
2290     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2291         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
2292 }
2293
2294 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
2295 {
2296     MpegEncContext *s= &s1->mpeg_enc_ctx;
2297     int i,nofco;
2298
2299     nofco = 1;
2300     if(s->progressive_sequence){
2301         if(s->repeat_first_field){
2302             nofco++;
2303             if(s->top_field_first)
2304                 nofco++;        
2305         }
2306     }else{
2307         if(s->picture_structure == PICT_FRAME){
2308             nofco++;
2309             if(s->repeat_first_field)
2310                 nofco++;
2311         }
2312     }
2313     for(i=0; i<nofco; i++){
2314         s1->pan_scan.position[i][0]= get_sbits(&s->gb, 16);
2315         skip_bits(&s->gb, 1); //marker
2316         s1->pan_scan.position[i][1]= get_sbits(&s->gb, 16);
2317         skip_bits(&s->gb, 1); //marker
2318     }
2319    
2320     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2321         av_log(s->avctx, AV_LOG_DEBUG, "pde (%d,%d) (%d,%d) (%d,%d)\n", 
2322             s1->pan_scan.position[0][0], s1->pan_scan.position[0][1], 
2323             s1->pan_scan.position[1][0], s1->pan_scan.position[1][1], 
2324             s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]
2325         );
2326 }
2327
2328 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
2329 {
2330     int i, v, j;
2331
2332     dprintf("matrix extension\n");
2333
2334     if (get_bits1(&s->gb)) {
2335         for(i=0;i<64;i++) {
2336             v = get_bits(&s->gb, 8);
2337             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2338             s->intra_matrix[j] = v;
2339             s->chroma_intra_matrix[j] = v;
2340         }
2341     }
2342     if (get_bits1(&s->gb)) {
2343         for(i=0;i<64;i++) {
2344             v = get_bits(&s->gb, 8);
2345             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2346             s->inter_matrix[j] = v;
2347             s->chroma_inter_matrix[j] = v;
2348         }
2349     }
2350     if (get_bits1(&s->gb)) {
2351         for(i=0;i<64;i++) {
2352             v = get_bits(&s->gb, 8);
2353             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2354             s->chroma_intra_matrix[j] = v;
2355         }
2356     }
2357     if (get_bits1(&s->gb)) {
2358         for(i=0;i<64;i++) {
2359             v = get_bits(&s->gb, 8);
2360             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2361             s->chroma_inter_matrix[j] = v;
2362         }
2363     }
2364 }
2365
2366 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
2367 {
2368     s->full_pel[0] = s->full_pel[1] = 0;
2369     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
2370     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
2371     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
2372     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
2373     s->intra_dc_precision = get_bits(&s->gb, 2);
2374     s->picture_structure = get_bits(&s->gb, 2);
2375     s->top_field_first = get_bits1(&s->gb);
2376     s->frame_pred_frame_dct = get_bits1(&s->gb);
2377     s->concealment_motion_vectors = get_bits1(&s->gb);
2378     s->q_scale_type = get_bits1(&s->gb);
2379     s->intra_vlc_format = get_bits1(&s->gb);
2380     s->alternate_scan = get_bits1(&s->gb);
2381     s->repeat_first_field = get_bits1(&s->gb);
2382     s->chroma_420_type = get_bits1(&s->gb);
2383     s->progressive_frame = get_bits1(&s->gb);
2384
2385     if(s->picture_structure == PICT_FRAME)
2386         s->first_field=0;
2387     else{
2388         s->first_field ^= 1;
2389         memset(s->mbskip_table, 0, s->mb_stride*s->mb_height);
2390     }
2391     
2392     if(s->alternate_scan){
2393         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
2394         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
2395     }else{
2396         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
2397         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
2398     }
2399     
2400     /* composite display not parsed */
2401     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
2402     dprintf("picture_structure=%d\n", s->picture_structure);
2403     dprintf("top field first=%d\n", s->top_field_first);
2404     dprintf("repeat first field=%d\n", s->repeat_first_field);
2405     dprintf("conceal=%d\n", s->concealment_motion_vectors);
2406     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
2407     dprintf("alternate_scan=%d\n", s->alternate_scan);
2408     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
2409     dprintf("progressive_frame=%d\n", s->progressive_frame);
2410 }
2411
2412 static void mpeg_decode_extension(AVCodecContext *avctx, 
2413                                   const uint8_t *buf, int buf_size)
2414 {
2415     Mpeg1Context *s1 = avctx->priv_data;
2416     MpegEncContext *s = &s1->mpeg_enc_ctx;
2417     int ext_type;
2418
2419     init_get_bits(&s->gb, buf, buf_size*8);
2420     
2421     ext_type = get_bits(&s->gb, 4);
2422     switch(ext_type) {
2423     case 0x1:
2424         mpeg_decode_sequence_extension(s1);
2425         break;
2426     case 0x2:
2427         mpeg_decode_sequence_display_extension(s1);
2428         break;
2429     case 0x3:
2430         mpeg_decode_quant_matrix_extension(s);
2431         break;
2432     case 0x7:
2433         mpeg_decode_picture_display_extension(s1);
2434         break;
2435     case 0x8:
2436         mpeg_decode_picture_coding_extension(s);
2437         break;
2438     }
2439 }
2440
2441 static void exchange_uv(MpegEncContext *s){
2442     short * tmp = s->pblocks[4];
2443     s->pblocks[4] = s->pblocks[5];
2444     s->pblocks[5] = tmp;
2445 }
2446
2447 static int mpeg_field_start(MpegEncContext *s){
2448     AVCodecContext *avctx= s->avctx;
2449     Mpeg1Context *s1 = (Mpeg1Context*)s;
2450
2451     /* start frame decoding */
2452     if(s->first_field || s->picture_structure==PICT_FRAME){
2453         if(MPV_frame_start(s, avctx) < 0)
2454             return -1;
2455
2456         ff_er_frame_start(s);
2457
2458         /* first check if we must repeat the frame */
2459         s->current_picture_ptr->repeat_pict = 0;
2460         if (s->repeat_first_field) {
2461             if (s->progressive_sequence) {
2462                 if (s->top_field_first)
2463                     s->current_picture_ptr->repeat_pict = 4;
2464                 else
2465                     s->current_picture_ptr->repeat_pict = 2;
2466             } else if (s->progressive_frame) {
2467                 s->current_picture_ptr->repeat_pict = 1;
2468             }
2469         }         
2470
2471         *s->current_picture_ptr->pan_scan= s1->pan_scan;
2472     }else{ //second field
2473             int i;
2474             
2475             if(!s->current_picture_ptr){
2476                 av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
2477                 return -1;
2478             }
2479             
2480             for(i=0; i<4; i++){
2481                 s->current_picture.data[i] = s->current_picture_ptr->data[i];
2482                 if(s->picture_structure == PICT_BOTTOM_FIELD){
2483                     s->current_picture.data[i] += s->current_picture_ptr->linesize[i];
2484                 } 
2485             }
2486     }
2487 #ifdef HAVE_XVMC
2488 // MPV_frame_start will call this function too,
2489 // but we need to call it on every field
2490     if(s->avctx->xvmc_acceleration)
2491          XVMC_field_start(s,avctx);
2492 #endif
2493
2494     return 0;
2495 }
2496
2497 #define DECODE_SLICE_ERROR -1
2498 #define DECODE_SLICE_OK 0
2499
2500 /**
2501  * decodes a slice. MpegEncContext.mb_y must be set to the MB row from the startcode
2502  * @return DECODE_SLICE_ERROR if the slice is damaged<br>
2503  *         DECODE_SLICE_OK if this slice is ok<br>
2504  */
2505 static int mpeg_decode_slice(Mpeg1Context *s1, int mb_y,
2506                              const uint8_t **buf, int buf_size)
2507 {
2508     MpegEncContext *s = &s1->mpeg_enc_ctx;
2509     AVCodecContext *avctx= s->avctx;
2510     int ret;
2511     const int field_pic= s->picture_structure != PICT_FRAME;
2512     const int lowres= s->avctx->lowres;
2513
2514     s->resync_mb_x=
2515     s->resync_mb_y= -1;
2516
2517     if (mb_y<<field_pic >= s->mb_height){
2518         av_log(s->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s->mb_height);
2519         return -1;
2520     }
2521     
2522     init_get_bits(&s->gb, *buf, buf_size*8);
2523
2524     ff_mpeg1_clean_buffers(s);
2525     s->interlaced_dct = 0;
2526
2527     s->qscale = get_qscale(s);
2528
2529     if(s->qscale == 0){
2530         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
2531         return -1;
2532     }
2533     
2534     /* extra slice info */
2535     while (get_bits1(&s->gb) != 0) {
2536         skip_bits(&s->gb, 8);
2537     }
2538     
2539     s->mb_x=0;
2540
2541     for(;;) {
2542         int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
2543         if (code < 0){
2544             av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
2545             return -1;
2546         }
2547         if (code >= 33) {
2548             if (code == 33) {
2549                 s->mb_x += 33;
2550             }
2551             /* otherwise, stuffing, nothing to do */
2552         } else {
2553             s->mb_x += code;
2554             break;
2555         }
2556     }
2557
2558     s->resync_mb_x= s->mb_x;
2559     s->resync_mb_y= s->mb_y= mb_y;
2560     s->mb_skip_run= 0;
2561     ff_init_block_index(s);
2562
2563     if (s->mb_y==0 && s->mb_x==0 && (s->first_field || s->picture_structure==PICT_FRAME)) {
2564         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2565              av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%2d%2d%2d%2d %s %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n", 
2566                  s->qscale, s->mpeg_f_code[0][0],s->mpeg_f_code[0][1],s->mpeg_f_code[1][0],s->mpeg_f_code[1][1],
2567                  s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
2568                  s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", 
2569                  s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
2570                  s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
2571         }
2572     }    
2573     
2574     for(;;) {
2575 #ifdef HAVE_XVMC
2576         //one 1 we memcpy blocks in xvmcvideo
2577         if(s->avctx->xvmc_acceleration > 1)
2578             XVMC_init_block(s);//set s->block
2579 #endif
2580
2581         s->dsp.clear_blocks(s->block[0]);
2582         if(!s->chroma_y_shift){
2583             s->dsp.clear_blocks(s->block[6]);
2584         }
2585         ret = mpeg_decode_mb(s, s->block);
2586         s->chroma_qscale= s->qscale;
2587
2588         dprintf("ret=%d\n", ret);
2589         if (ret < 0)
2590             return -1;
2591
2592         if(s->current_picture.motion_val[0] && !s->encoding){ //note motion_val is normally NULL unless we want to extract the MVs
2593             const int wrap = field_pic ? 2*s->b8_stride : s->b8_stride;
2594             int xy = s->mb_x*2 + s->mb_y*2*wrap;
2595             int motion_x, motion_y, dir, i;
2596             if(field_pic && !s->first_field)
2597                 xy += wrap/2;
2598
2599             for(i=0; i<2; i++){
2600                 for(dir=0; dir<2; dir++){
2601                     if (s->mb_intra || (dir==1 && s->pict_type != B_TYPE)) {
2602                         motion_x = motion_y = 0;
2603                     }else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)){
2604                         motion_x = s->mv[dir][0][0];
2605                         motion_y = s->mv[dir][0][1];
2606                     } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ {
2607                         motion_x = s->mv[dir][i][0];
2608                         motion_y = s->mv[dir][i][1];
2609                     }
2610
2611                     s->current_picture.motion_val[dir][xy    ][0] = motion_x;
2612                     s->current_picture.motion_val[dir][xy    ][1] = motion_y;
2613                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
2614                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
2615                     s->current_picture.ref_index [dir][xy    ]=
2616                     s->current_picture.ref_index [dir][xy + 1]= s->field_select[dir][i];
2617                 }
2618                 xy += wrap;
2619             }
2620         }
2621
2622         s->dest[0] += 16 >> lowres;
2623         s->dest[1] += 16 >> (s->chroma_x_shift + lowres);
2624         s->dest[2] += 16 >> (s->chroma_x_shift + lowres);
2625
2626         MPV_decode_mb(s, s->block);
2627         
2628         if (++s->mb_x >= s->mb_width) {
2629             const int mb_size= 16>>s->avctx->lowres;
2630
2631             ff_draw_horiz_band(s, mb_size*s->mb_y, mb_size);
2632
2633             s->mb_x = 0;
2634             s->mb_y++;
2635
2636             if(s->mb_y<<field_pic >= s->mb_height){
2637                 int left= s->gb.size_in_bits - get_bits_count(&s->gb);
2638
2639                 if(left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23)))
2640                    || (avctx->error_resilience >= FF_ER_AGGRESSIVE && left>8)){
2641                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d\n", left);
2642                     return -1;
2643                 }else
2644                     goto eos;
2645             }
2646             
2647             ff_init_block_index(s);
2648         }
2649
2650         /* skip mb handling */
2651         if (s->mb_skip_run == -1) {
2652             /* read again increment */
2653             s->mb_skip_run = 0;
2654             for(;;) {
2655                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
2656                 if (code < 0){
2657                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
2658                     return -1;
2659                 }
2660                 if (code >= 33) {
2661                     if (code == 33) {
2662                         s->mb_skip_run += 33;
2663                     }else if(code == 35){
2664                         if(s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0){
2665                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
2666                             return -1;
2667                         }
2668                         goto eos; /* end of slice */
2669                     }
2670                     /* otherwise, stuffing, nothing to do */
2671                 } else {
2672                     s->mb_skip_run += code;
2673                     break;
2674                 }
2675             }
2676         }
2677     }
2678 eos: // end of slice
2679     *buf += get_bits_count(&s->gb)/8 - 1;
2680 //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
2681     return 0;
2682 }
2683
2684 static int slice_decode_thread(AVCodecContext *c, void *arg){
2685     MpegEncContext *s= arg;
2686     const uint8_t *buf= s->gb.buffer;
2687     int mb_y= s->start_mb_y;
2688
2689     s->error_count= 3*(s->end_mb_y - s->start_mb_y)*s->mb_width;
2690
2691     for(;;){
2692         int start_code, ret;
2693
2694         ret= mpeg_decode_slice((Mpeg1Context*)s, mb_y, &buf, s->gb.buffer_end - buf);
2695         emms_c();
2696 //av_log(c, AV_LOG_DEBUG, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n", 
2697 //ret, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, s->start_mb_y, s->end_mb_y, s->error_count);
2698         if(ret < 0){
2699             if(s->resync_mb_x>=0 && s->resync_mb_y>=0)
2700                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, AC_ERROR|DC_ERROR|MV_ERROR);
2701         }else{
2702             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, AC_END|DC_END|MV_END);
2703         }
2704         
2705         if(s->mb_y == s->end_mb_y)
2706             return 0;
2707         
2708         start_code = find_start_code(&buf, s->gb.buffer_end);
2709         mb_y= start_code - SLICE_MIN_START_CODE;
2710         if(mb_y < 0 || mb_y >= s->end_mb_y)
2711             return -1;
2712     }
2713     
2714     return 0; //not reached
2715 }
2716
2717 /**
2718  * handles slice ends.
2719  * @return 1 if it seems to be the last slice of 
2720  */
2721 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
2722 {
2723     Mpeg1Context *s1 = avctx->priv_data;
2724     MpegEncContext *s = &s1->mpeg_enc_ctx;
2725        
2726     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
2727         return 0;
2728
2729 #ifdef HAVE_XVMC
2730     if(s->avctx->xvmc_acceleration)
2731         XVMC_field_end(s);
2732 #endif
2733     /* end of slice reached */
2734     if (/*s->mb_y<<field_pic == s->mb_height &&*/ !s->first_field) {
2735         /* end of image */
2736
2737         s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_MPEG2;
2738
2739         ff_er_frame_end(s);
2740
2741         MPV_frame_end(s);
2742
2743         if (s->pict_type == B_TYPE || s->low_delay) {
2744             *pict= *(AVFrame*)s->current_picture_ptr;
2745             ff_print_debug_info(s, pict);
2746         } else {
2747             s->picture_number++;
2748             /* latency of 1 frame for I and P frames */
2749             /* XXX: use another variable than picture_number */
2750             if (s->last_picture_ptr != NULL) {
2751                 *pict= *(AVFrame*)s->last_picture_ptr;
2752                  ff_print_debug_info(s, pict);
2753             }
2754         }
2755
2756         return 1;
2757     } else {
2758         return 0;
2759     }
2760 }
2761
2762 static int mpeg1_decode_sequence(AVCodecContext *avctx, 
2763                                  const uint8_t *buf, int buf_size)
2764 {
2765     Mpeg1Context *s1 = avctx->priv_data;
2766     MpegEncContext *s = &s1->mpeg_enc_ctx;
2767     int width,height;
2768     int i, v, j;
2769
2770     init_get_bits(&s->gb, buf, buf_size*8);
2771
2772     width = get_bits(&s->gb, 12);
2773     height = get_bits(&s->gb, 12);
2774     if (width <= 0 || height <= 0 ||
2775         (width % 2) != 0 || (height % 2) != 0)
2776         return -1;
2777     s->aspect_ratio_info= get_bits(&s->gb, 4);
2778     if (s->aspect_ratio_info == 0)
2779         return -1;
2780     s->frame_rate_index = get_bits(&s->gb, 4);
2781     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2782         return -1;
2783     s->bit_rate = get_bits(&s->gb, 18) * 400;
2784     if (get_bits1(&s->gb) == 0) /* marker */
2785         return -1;
2786     s->width = width;
2787     s->height = height;
2788
2789     s->avctx->rc_buffer_size= get_bits(&s->gb, 10) * 1024*16;
2790     skip_bits(&s->gb, 1);
2791
2792     /* get matrix */
2793     if (get_bits1(&s->gb)) {
2794         for(i=0;i<64;i++) {
2795             v = get_bits(&s->gb, 8);
2796             if(v==0){
2797                 av_log(s->avctx, AV_LOG_ERROR, "intra matrix damaged\n");
2798                 return -1;
2799             }
2800             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2801             s->intra_matrix[j] = v;
2802             s->chroma_intra_matrix[j] = v;
2803         }
2804 #ifdef DEBUG
2805         dprintf("intra matrix present\n");
2806         for(i=0;i<64;i++)
2807             dprintf(" %d", s->intra_matrix[s->dsp.idct_permutation[i]]);
2808         printf("\n");
2809 #endif
2810     } else {
2811         for(i=0;i<64;i++) {
2812             j = s->dsp.idct_permutation[i];
2813             v = ff_mpeg1_default_intra_matrix[i];
2814             s->intra_matrix[j] = v;
2815             s->chroma_intra_matrix[j] = v;
2816         }
2817     }
2818     if (get_bits1(&s->gb)) {
2819         for(i=0;i<64;i++) {
2820             v = get_bits(&s->gb, 8);
2821             if(v==0){
2822                 av_log(s->avctx, AV_LOG_ERROR, "inter matrix damaged\n");
2823                 return -1;
2824             }
2825             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
2826             s->inter_matrix[j] = v;
2827             s->chroma_inter_matrix[j] = v;
2828         }
2829 #ifdef DEBUG
2830         dprintf("non intra matrix present\n");
2831         for(i=0;i<64;i++)
2832             dprintf(" %d", s->inter_matrix[s->dsp.idct_permutation[i]]);
2833         printf("\n");
2834 #endif
2835     } else {
2836         for(i=0;i<64;i++) {
2837             int j= s->dsp.idct_permutation[i];
2838             v = ff_mpeg1_default_non_intra_matrix[i];
2839             s->inter_matrix[j] = v;
2840             s->chroma_inter_matrix[j] = v;
2841         }
2842     }
2843     
2844     if(show_bits(&s->gb, 23) != 0){
2845         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2846         return -1;
2847     }
2848
2849     /* we set mpeg2 parameters so that it emulates mpeg1 */
2850     s->progressive_sequence = 1;
2851     s->progressive_frame = 1;
2852     s->picture_structure = PICT_FRAME;
2853     s->frame_pred_frame_dct = 1;
2854     s->chroma_format = 1;
2855     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG1VIDEO;
2856     avctx->sub_id = 1; /* indicates mpeg1 */
2857     s->out_format = FMT_MPEG1;
2858     s->swap_uv = 0;//AFAIK VCR2 don't have SEQ_HEADER
2859     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
2860     
2861     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2862         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n", 
2863                s->avctx->rc_buffer_size, s->bit_rate);
2864     
2865     return 0;
2866 }
2867
2868 static int vcr2_init_sequence(AVCodecContext *avctx)
2869 {
2870     Mpeg1Context *s1 = avctx->priv_data;
2871     MpegEncContext *s = &s1->mpeg_enc_ctx;
2872     int i, v;
2873
2874     /* start new mpeg1 context decoding */
2875     s->out_format = FMT_MPEG1;
2876     if (s1->mpeg_enc_ctx_allocated) {
2877         MPV_common_end(s);
2878     }
2879     s->width  = avctx->coded_width;
2880     s->height = avctx->coded_height;
2881     avctx->has_b_frames= 0; //true?
2882     s->low_delay= 1;
2883
2884     if(avctx->xvmc_acceleration){
2885         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
2886     }else{
2887         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
2888     }
2889
2890     if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
2891         if( avctx->idct_algo == FF_IDCT_AUTO )
2892             avctx->idct_algo = FF_IDCT_SIMPLE;
2893     
2894     if (MPV_common_init(s) < 0)
2895         return -1;
2896     exchange_uv(s);//common init reset pblocks, so we swap them here
2897     s->swap_uv = 1;// in case of xvmc we need to swap uv for each MB 
2898     s1->mpeg_enc_ctx_allocated = 1;
2899
2900     for(i=0;i<64;i++) {
2901         int j= s->dsp.idct_permutation[i];
2902         v = ff_mpeg1_default_intra_matrix[i];
2903         s->intra_matrix[j] = v;
2904         s->chroma_intra_matrix[j] = v;
2905
2906         v = ff_mpeg1_default_non_intra_matrix[i];
2907         s->inter_matrix[j] = v;
2908         s->chroma_inter_matrix[j] = v;
2909     }
2910
2911     s->progressive_sequence = 1;
2912     s->progressive_frame = 1;
2913     s->picture_structure = PICT_FRAME;
2914     s->frame_pred_frame_dct = 1;
2915     s->chroma_format = 1;
2916     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
2917     avctx->sub_id = 2; /* indicates mpeg2 */
2918     return 0;
2919 }
2920
2921
2922 static void mpeg_decode_user_data(AVCodecContext *avctx, 
2923                                   const uint8_t *buf, int buf_size)
2924 {
2925     const uint8_t *p;
2926     int len, flags;
2927     p = buf;
2928     len = buf_size;
2929
2930     /* we parse the DTG active format information */
2931     if (len >= 5 &&
2932         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2933         flags = p[4];
2934         p += 5;
2935         len -= 5;
2936         if (flags & 0x80) {
2937             /* skip event id */
2938             if (len < 2)
2939                 return;
2940             p += 2;
2941             len -= 2;
2942         }
2943         if (flags & 0x40) {
2944             if (len < 1)
2945                 return;
2946             avctx->dtg_active_format = p[0] & 0x0f;
2947         }
2948     }
2949 }
2950
2951 static void mpeg_decode_gop(AVCodecContext *avctx, 
2952                             const uint8_t *buf, int buf_size){
2953     Mpeg1Context *s1 = avctx->priv_data;
2954     MpegEncContext *s = &s1->mpeg_enc_ctx;
2955
2956     int drop_frame_flag;
2957     int time_code_hours, time_code_minutes;
2958     int time_code_seconds, time_code_pictures;
2959     int broken_link;
2960
2961     init_get_bits(&s->gb, buf, buf_size*8);
2962
2963     drop_frame_flag = get_bits1(&s->gb);
2964     
2965     time_code_hours=get_bits(&s->gb,5);
2966     time_code_minutes = get_bits(&s->gb,6);
2967     skip_bits1(&s->gb);//marker bit
2968     time_code_seconds = get_bits(&s->gb,6);
2969     time_code_pictures = get_bits(&s->gb,6);
2970
2971     /*broken_link indicate that after editing the
2972       reference frames of the first B-Frames after GOP I-Frame
2973       are missing (open gop)*/
2974     broken_link = get_bits1(&s->gb);
2975
2976     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
2977         av_log(s->avctx, AV_LOG_DEBUG, "GOP (%2d:%02d:%02d.[%02d]) broken_link=%d\n",
2978             time_code_hours, time_code_minutes, time_code_seconds,
2979             time_code_pictures, broken_link);
2980 }
2981 /**
2982  * finds the end of the current frame in the bitstream.
2983  * @return the position of the first byte of the next frame, or -1
2984  */
2985 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size)
2986 {
2987     int i;
2988     uint32_t state;
2989     
2990     state= pc->state;
2991     
2992     i=0;
2993     if(!pc->frame_start_found){
2994         for(i=0; i<buf_size; i++){
2995             state= (state<<8) | buf[i];
2996             if(state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){
2997                 i++;
2998                 pc->frame_start_found=1;
2999                 break;
3000             }
3001         }
3002     }
3003     
3004     if(pc->frame_start_found){
3005         /* EOF considered as end of frame */
3006         if (buf_size == 0)
3007             return 0;
3008         for(; i<buf_size; i++){
3009             state= (state<<8) | buf[i];
3010             if((state&0xFFFFFF00) == 0x100){
3011                 if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){
3012                     pc->frame_start_found=0;
3013                     pc->state=-1; 
3014                     return i-3;
3015                 }
3016             }
3017         }
3018     }        
3019     pc->state= state;
3020     return END_NOT_FOUND;
3021 }
3022
3023 /* handle buffering and image synchronisation */
3024 static int mpeg_decode_frame(AVCodecContext *avctx, 
3025                              void *data, int *data_size,
3026                              uint8_t *buf, int buf_size)
3027 {
3028     Mpeg1Context *s = avctx->priv_data;
3029     const uint8_t *buf_end;
3030     const uint8_t *buf_ptr;
3031     int ret, start_code, input_size;
3032     AVFrame *picture = data;
3033     MpegEncContext *s2 = &s->mpeg_enc_ctx;
3034     dprintf("fill_buffer\n");
3035
3036     if (buf_size == 0) {
3037         /* special case for last picture */
3038         if (s2->low_delay==0 && s2->next_picture_ptr) {
3039             *picture= *(AVFrame*)s2->next_picture_ptr;
3040             s2->next_picture_ptr= NULL;
3041
3042             *data_size = sizeof(AVFrame);
3043         }
3044         return 0;
3045     }
3046
3047     if(s2->flags&CODEC_FLAG_TRUNCATED){
3048         int next= ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size);
3049         
3050         if( ff_combine_frame(&s2->parse_context, next, &buf, &buf_size) < 0 )
3051             return buf_size;
3052     }    
3053     
3054     buf_ptr = buf;
3055     buf_end = buf + buf_size;
3056
3057 #if 0    
3058     if (s->repeat_field % 2 == 1) { 
3059         s->repeat_field++;
3060         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
3061         //        s2->picture_number, s->repeat_field);
3062         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
3063             *data_size = sizeof(AVPicture);
3064             goto the_end;
3065         }
3066     }
3067 #endif
3068
3069     if(s->mpeg_enc_ctx_allocated==0 && avctx->codec_tag == ff_get_fourcc("VCR2"))
3070         vcr2_init_sequence(avctx);
3071     
3072     s->slice_count= 0;
3073         
3074     for(;;) {
3075         /* find start next code */
3076         start_code = find_start_code(&buf_ptr, buf_end);
3077         if (start_code < 0){
3078             if(s2->pict_type != B_TYPE || avctx->hurry_up==0){
3079                 if(avctx->thread_count > 1){
3080                     int i;
3081
3082                     avctx->execute(avctx, slice_decode_thread,  (void**)&(s2->thread_context[0]), NULL, s->slice_count);
3083                     for(i=0; i<s->slice_count; i++)
3084                         s2->error_count += s2->thread_context[i]->error_count;
3085                 }
3086                 if (slice_end(avctx, picture)) {
3087                     if(s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
3088                         *data_size = sizeof(AVPicture);
3089                 }
3090             }
3091             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
3092         }
3093         
3094         input_size = buf_end - buf_ptr;
3095
3096         if(avctx->debug & FF_DEBUG_STARTCODE){
3097             av_log(avctx, AV_LOG_DEBUG, "%3X at %zd left %d\n", start_code, buf_ptr-buf, input_size);
3098         }
3099
3100                 /* prepare data for next start code */
3101                 switch(start_code) {
3102                 case SEQ_START_CODE:
3103                     mpeg1_decode_sequence(avctx, buf_ptr, 
3104                                           input_size);
3105                     break;
3106                             
3107                 case PICTURE_START_CODE:
3108                     /* we have a complete image : we try to decompress it */
3109                     mpeg1_decode_picture(avctx, 
3110                                          buf_ptr, input_size);
3111                     break;
3112                 case EXT_START_CODE:
3113                     mpeg_decode_extension(avctx,
3114                                           buf_ptr, input_size);
3115                     break;
3116                 case USER_START_CODE:
3117                     mpeg_decode_user_data(avctx, 
3118                                           buf_ptr, input_size);
3119                     break;
3120                 case GOP_START_CODE:
3121                     s2->first_field=0;
3122                     mpeg_decode_gop(avctx, 
3123                                           buf_ptr, input_size);
3124                     break;
3125                 default:
3126                     if (start_code >= SLICE_MIN_START_CODE &&
3127                         start_code <= SLICE_MAX_START_CODE) {
3128                         int mb_y= start_code - SLICE_MIN_START_CODE;
3129                         
3130                         /* skip b frames if we dont have reference frames */
3131                         if(s2->last_picture_ptr==NULL && s2->pict_type==B_TYPE) break;
3132                         /* skip b frames if we are in a hurry */
3133                         if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
3134                         /* skip everything if we are in a hurry>=5 */
3135                         if(avctx->hurry_up>=5) break;
3136                         
3137                         if (!s->mpeg_enc_ctx_allocated) break;
3138
3139                         if(s2->codec_id == CODEC_ID_MPEG2VIDEO){
3140                             if(mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
3141                                 break;
3142                         }
3143                         
3144                         if(s2->first_slice){
3145                             s2->first_slice=0;
3146                             if(mpeg_field_start(s2) < 0)
3147                                 return -1;
3148                         }
3149                         
3150                         if(avctx->thread_count > 1){
3151                             int threshold= (s2->mb_height*s->slice_count + avctx->thread_count/2) / avctx->thread_count;
3152                             if(threshold <= mb_y){
3153                                 MpegEncContext *thread_context= s2->thread_context[s->slice_count];
3154                                 
3155                                 thread_context->start_mb_y= mb_y;
3156                                 thread_context->end_mb_y  = s2->mb_height;
3157                                 if(s->slice_count){
3158                                     s2->thread_context[s->slice_count-1]->end_mb_y= mb_y;
3159                                     ff_update_duplicate_context(thread_context, s2);
3160                                 }
3161                                 init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
3162                                 s->slice_count++;
3163                             }
3164                             buf_ptr += 2; //FIXME add minimum num of bytes per slice
3165                         }else{
3166                             ret = mpeg_decode_slice(s, mb_y, &buf_ptr, input_size);
3167                             emms_c();
3168
3169                             if(ret < 0){
3170                                 if(s2->resync_mb_x>=0 && s2->resync_mb_y>=0)
3171                                     ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x, s2->mb_y, AC_ERROR|DC_ERROR|MV_ERROR);
3172                             }else{
3173                                 ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x-1, s2->mb_y, AC_END|DC_END|MV_END);
3174                             }
3175                         }
3176                     }
3177                     break;
3178                 }
3179     }
3180 }
3181
3182 static int mpeg_decode_end(AVCodecContext *avctx)
3183 {
3184     Mpeg1Context *s = avctx->priv_data;
3185
3186     if (s->mpeg_enc_ctx_allocated)
3187         MPV_common_end(&s->mpeg_enc_ctx);
3188     return 0;
3189 }
3190
3191 AVCodec mpeg1video_decoder = {
3192     "mpeg1video",
3193     CODEC_TYPE_VIDEO,
3194     CODEC_ID_MPEG1VIDEO,
3195     sizeof(Mpeg1Context),
3196     mpeg_decode_init,
3197     NULL,
3198     mpeg_decode_end,
3199     mpeg_decode_frame,
3200     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3201     .flush= ff_mpeg_flush,
3202 };
3203
3204 AVCodec mpeg2video_decoder = {
3205     "mpeg2video",
3206     CODEC_TYPE_VIDEO,
3207     CODEC_ID_MPEG2VIDEO,
3208     sizeof(Mpeg1Context),
3209     mpeg_decode_init,
3210     NULL,
3211     mpeg_decode_end,
3212     mpeg_decode_frame,
3213     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3214     .flush= ff_mpeg_flush,
3215 };
3216
3217 //legacy decoder
3218 AVCodec mpegvideo_decoder = {
3219     "mpegvideo",
3220     CODEC_TYPE_VIDEO,
3221     CODEC_ID_MPEG2VIDEO,
3222     sizeof(Mpeg1Context),
3223     mpeg_decode_init,
3224     NULL,
3225     mpeg_decode_end,
3226     mpeg_decode_frame,
3227     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
3228     .flush= ff_mpeg_flush,
3229 };
3230
3231 #ifdef CONFIG_ENCODERS
3232
3233 AVCodec mpeg1video_encoder = {
3234     "mpeg1video",
3235     CODEC_TYPE_VIDEO,
3236     CODEC_ID_MPEG1VIDEO,
3237     sizeof(MpegEncContext),
3238     encode_init,
3239     MPV_encode_picture,
3240     MPV_encode_end,
3241     .supported_framerates= frame_rate_tab+1,
3242     .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
3243     .capabilities= CODEC_CAP_DELAY,
3244 };
3245
3246 AVCodec mpeg2video_encoder = {
3247     "mpeg2video",
3248     CODEC_TYPE_VIDEO,
3249     CODEC_ID_MPEG2VIDEO,
3250     sizeof(MpegEncContext),
3251     encode_init,
3252     MPV_encode_picture,
3253     MPV_encode_end,
3254     .supported_framerates= frame_rate_tab+1,
3255     .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
3256     .capabilities= CODEC_CAP_DELAY,
3257 };
3258 #endif
3259
3260 #ifdef HAVE_XVMC
3261 static int mpeg_mc_decode_init(AVCodecContext *avctx){
3262     Mpeg1Context *s;
3263
3264     if( avctx->thread_count > 1) 
3265         return -1;
3266     if( !(avctx->slice_flags & SLICE_FLAG_CODED_ORDER) )
3267         return -1;
3268     if( !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD) ){
3269         dprintf("mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
3270     }
3271     mpeg_decode_init(avctx);
3272     s = avctx->priv_data;
3273
3274     avctx->pix_fmt = PIX_FMT_XVMC_MPEG2_IDCT;
3275     avctx->xvmc_acceleration = 2;//2 - the blocks are packed!
3276
3277     return 0;
3278 }
3279
3280 AVCodec mpeg_xvmc_decoder = {
3281     "mpegvideo_xvmc",
3282     CODEC_TYPE_VIDEO,
3283     CODEC_ID_MPEG2VIDEO_XVMC,
3284     sizeof(Mpeg1Context),
3285     mpeg_mc_decode_init,
3286     NULL,
3287     mpeg_decode_end,
3288     mpeg_decode_frame,
3289     CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED| CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
3290     .flush= ff_mpeg_flush,
3291 };
3292
3293 #endif
3294
3295 /* this is ugly i know, but the alternative is too make 
3296    hundreds of vars global and prefix them with ff_mpeg1_
3297    which is far uglier. */
3298 #include "mdec.c"