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