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