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