• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files

hvirtual/quicktime/ffmpeg/libavcodec/mpeg12.c

Go to the documentation of this file.
00001 /*
00002  * MPEG1 codec / MPEG2 decoder
00003  * Copyright (c) 2000,2001 Fabrice Bellard.
00004  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> 
00005  *
00006  * This library is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2 of the License, or (at your option) any later version.
00010  *
00011  * This library is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with this library; if not, write to the Free Software
00018  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00019  */
00020  
00026 //#define DEBUG
00027 #include "avcodec.h"
00028 #include "dsputil.h"
00029 #include "mpegvideo.h"
00030 
00031 #include "mpeg12data.h"
00032 
00033 //#undef NDEBUG
00034 //#include <assert.h>
00035 
00036 
00037 /* Start codes. */
00038 #define SEQ_END_CODE            0x000001b7
00039 #define SEQ_START_CODE          0x000001b3
00040 #define GOP_START_CODE          0x000001b8
00041 #define PICTURE_START_CODE      0x00000100
00042 #define SLICE_MIN_START_CODE    0x00000101
00043 #define SLICE_MAX_START_CODE    0x000001af
00044 #define EXT_START_CODE          0x000001b5
00045 #define USER_START_CODE         0x000001b2
00046 
00047 #define DC_VLC_BITS 9
00048 #define MV_VLC_BITS 9
00049 #define MBINCR_VLC_BITS 9
00050 #define MB_PAT_VLC_BITS 9
00051 #define MB_PTYPE_VLC_BITS 6
00052 #define MB_BTYPE_VLC_BITS 6
00053 #define TEX_VLC_BITS 9
00054 
00055 #ifdef CONFIG_ENCODERS
00056 static void mpeg1_encode_block(MpegEncContext *s, 
00057                          DCTELEM *block, 
00058                          int component);
00059 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code);    // RAL: f_code parameter added
00060 #endif //CONFIG_ENCODERS
00061 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
00062                               DCTELEM *block, 
00063                               int n);
00064 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
00065                               DCTELEM *block, 
00066                               int n);
00067 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n);
00068 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
00069                                         DCTELEM *block, 
00070                                         int n);
00071 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
00072                                     DCTELEM *block, 
00073                                     int n);
00074 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, DCTELEM *block, int n);
00075 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, DCTELEM *block, int n);
00076 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
00077 static void exchange_uv(MpegEncContext *s);
00078 
00079 #ifdef HAVE_XVMC
00080 extern int XVMC_field_start(MpegEncContext *s, AVCodecContext *avctx);
00081 extern int XVMC_field_end(MpegEncContext *s);
00082 extern void XVMC_pack_pblocks(MpegEncContext *s,int cbp);
00083 extern void XVMC_init_block(MpegEncContext *s);//set s->block
00084 #endif
00085 
00086 const enum PixelFormat pixfmt_yuv_420[]= {PIX_FMT_YUV420P,-1};
00087 const enum PixelFormat pixfmt_yuv_422[]= {PIX_FMT_YUV422P,-1};
00088 const enum PixelFormat pixfmt_yuv_444[]= {PIX_FMT_YUV444P,-1};
00089 const enum PixelFormat pixfmt_xvmc_mpg2_420[] = {
00090                                            PIX_FMT_XVMC_MPEG2_IDCT,
00091                                            PIX_FMT_XVMC_MPEG2_MC,
00092                                            -1};
00093 #ifdef CONFIG_ENCODERS
00094 static uint8_t (*mv_penalty)[MAX_MV*2+1]= NULL;
00095 static uint8_t fcode_tab[MAX_MV*2+1];
00096 
00097 static uint32_t uni_mpeg1_ac_vlc_bits[64*64*2];
00098 static uint8_t  uni_mpeg1_ac_vlc_len [64*64*2];
00099 
00100 /* simple include everything table for dc, first byte is bits number next 3 are code*/
00101 static uint32_t mpeg1_lum_dc_uni[512];
00102 static uint32_t mpeg1_chr_dc_uni[512];
00103 
00104 static uint8_t mpeg1_index_run[2][64];
00105 static int8_t mpeg1_max_level[2][64];
00106 #endif //CONFIG_ENCODERS
00107 
00108 static void init_2d_vlc_rl(RLTable *rl, int use_static)
00109 {
00110     int i;
00111     
00112     init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2, 
00113              &rl->table_vlc[0][1], 4, 2,
00114              &rl->table_vlc[0][0], 4, 2, use_static);
00115 
00116     if(use_static)    
00117         rl->rl_vlc[0]= av_mallocz_static(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
00118     else
00119         rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
00120 
00121     for(i=0; i<rl->vlc.table_size; i++){
00122         int code= rl->vlc.table[i][0];
00123         int len = rl->vlc.table[i][1];
00124         int level, run;
00125     
00126         if(len==0){ // illegal code
00127             run= 65;
00128             level= MAX_LEVEL;
00129         }else if(len<0){ //more bits needed
00130             run= 0;
00131             level= code;
00132         }else{
00133             if(code==rl->n){ //esc
00134                 run= 65;
00135                 level= 0;
00136             }else if(code==rl->n+1){ //eob
00137                 run= 0;
00138                 level= 127;
00139             }else{
00140                 run=   rl->table_run  [code] + 1;
00141                 level= rl->table_level[code];
00142             }
00143         }
00144         rl->rl_vlc[0][i].len= len;
00145         rl->rl_vlc[0][i].level= level;
00146         rl->rl_vlc[0][i].run= run;
00147     }
00148 }
00149 
00150 #ifdef CONFIG_ENCODERS
00151 static void init_uni_ac_vlc(RLTable *rl, uint32_t *uni_ac_vlc_bits, uint8_t *uni_ac_vlc_len){
00152     int i;
00153 
00154     for(i=0; i<128; i++){
00155         int level= i-64;
00156         int run;
00157         for(run=0; run<64; run++){
00158             int len, bits, code;
00159             
00160             int alevel= ABS(level);
00161             int sign= (level>>31)&1;
00162 
00163             if (alevel > rl->max_level[0][run])
00164                 code= 111; /*rl->n*/
00165             else
00166                 code= rl->index_run[0][run] + alevel - 1;
00167 
00168             if (code < 111 /* rl->n */) {
00169                 /* store the vlc & sign at once */
00170                 len=   mpeg1_vlc[code][1]+1;
00171                 bits= (mpeg1_vlc[code][0]<<1) + sign;
00172             } else {
00173                 len=  mpeg1_vlc[111/*rl->n*/][1]+6;
00174                 bits= mpeg1_vlc[111/*rl->n*/][0]<<6;
00175 
00176                 bits|= run;
00177                 if (alevel < 128) {
00178                     bits<<=8; len+=8;
00179                     bits|= level & 0xff;
00180                 } else {
00181                     bits<<=16; len+=16;
00182                     bits|= level & 0xff;
00183                     if (level < 0) {
00184                         bits|= 0x8001 + level + 255;
00185                     } else {
00186                         bits|= level & 0xffff;
00187                     }
00188                 }
00189             }
00190 
00191             uni_ac_vlc_bits[UNI_AC_ENC_INDEX(run, i)]= bits;
00192             uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
00193         }
00194     }
00195 }
00196 
00197 
00198 static int find_frame_rate_index(MpegEncContext *s){
00199     int i;
00200     int64_t dmin= INT64_MAX;
00201     int64_t d;
00202 
00203     for(i=1;i<14;i++) {
00204         int64_t n0= 1001LL/frame_rate_tab[i].den*frame_rate_tab[i].num*s->avctx->time_base.num;
00205         int64_t n1= 1001LL*s->avctx->time_base.den;
00206         if(s->avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL && i>=9) break;
00207 
00208         d = ABS(n0 - n1);
00209         if(d < dmin){
00210             dmin=d;
00211             s->frame_rate_index= i;
00212         }
00213     }
00214     if(dmin)
00215         return -1;
00216     else
00217         return 0;
00218 }
00219 
00220 static int encode_init(AVCodecContext *avctx)
00221 {
00222     MpegEncContext *s = avctx->priv_data;
00223 
00224     if(MPV_encode_init(avctx) < 0)
00225         return -1;
00226 
00227     if(find_frame_rate_index(s) < 0){
00228         if(s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
00229             av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n", avctx->time_base.den, avctx->time_base.num);
00230             return -1;
00231         }else{
00232             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);
00233         }
00234     }
00235     
00236     return 0;
00237 }
00238 
00239 static void put_header(MpegEncContext *s, int header)
00240 {
00241     align_put_bits(&s->pb);
00242     put_bits(&s->pb, 16, header>>16);
00243     put_bits(&s->pb, 16, header&0xFFFF);
00244 }
00245 
00246 /* put sequence header if needed */
00247 static void mpeg1_encode_sequence_header(MpegEncContext *s)
00248 {
00249         unsigned int vbv_buffer_size;
00250         unsigned int fps, v;
00251         int i;
00252         uint64_t time_code;
00253         float best_aspect_error= 1E10;
00254         float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);
00255         int constraint_parameter_flag;
00256         
00257         if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
00258         
00259         if (s->current_picture.key_frame) {
00260             AVRational framerate= frame_rate_tab[s->frame_rate_index];
00261 
00262             /* mpeg1 header repeated every gop */
00263             put_header(s, SEQ_START_CODE);
00264  
00265             put_bits(&s->pb, 12, s->width);
00266             put_bits(&s->pb, 12, s->height);
00267             
00268             for(i=1; i<15; i++){
00269                 float error= aspect_ratio;
00270                 if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1)
00271                     error-= 1.0/mpeg1_aspect[i];
00272                 else
00273                     error-= av_q2d(mpeg2_aspect[i])*s->height/s->width;
00274              
00275                 error= ABS(error);
00276                 
00277                 if(error < best_aspect_error){
00278                     best_aspect_error= error;
00279                     s->aspect_ratio_info= i;
00280                 }
00281             }
00282             
00283             put_bits(&s->pb, 4, s->aspect_ratio_info);
00284             put_bits(&s->pb, 4, s->frame_rate_index);
00285             
00286             if(s->avctx->rc_max_rate){
00287                 v = (s->avctx->rc_max_rate + 399) / 400;
00288                 if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO)
00289                     v = 0x3ffff;
00290             }else{
00291                 v= 0x3FFFF;
00292             }
00293 
00294             if(s->avctx->rc_buffer_size)
00295                 vbv_buffer_size = s->avctx->rc_buffer_size;
00296             else
00297                 /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
00298                 vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
00299             vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;
00300 
00301             put_bits(&s->pb, 18, v & 0x3FFFF);
00302             put_bits(&s->pb, 1, 1); /* marker */
00303             put_bits(&s->pb, 10, vbv_buffer_size & 0x3FF);
00304 
00305             constraint_parameter_flag= 
00306                 s->width <= 768 && s->height <= 576 && 
00307                 s->mb_width * s->mb_height <= 396 &&
00308                 s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&
00309                 framerate.num <= framerate.den*30 &&
00310                 s->avctx->me_range && s->avctx->me_range < 128 &&
00311                 vbv_buffer_size <= 20 &&
00312                 v <= 1856000/400 &&
00313                 s->codec_id == CODEC_ID_MPEG1VIDEO;
00314                 
00315             put_bits(&s->pb, 1, constraint_parameter_flag);
00316             
00317             ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
00318             ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
00319 
00320             if(s->codec_id == CODEC_ID_MPEG2VIDEO){
00321                 put_header(s, EXT_START_CODE);
00322                 put_bits(&s->pb, 4, 1); //seq ext
00323                 put_bits(&s->pb, 1, 0); //esc
00324                 
00325                 if(s->avctx->profile == FF_PROFILE_UNKNOWN){
00326                     put_bits(&s->pb, 3, 4); //profile
00327                 }else{
00328                     put_bits(&s->pb, 3, s->avctx->profile); //profile
00329                 }
00330 
00331                 if(s->avctx->level == FF_LEVEL_UNKNOWN){
00332                     put_bits(&s->pb, 4, 8); //level
00333                 }else{
00334                     put_bits(&s->pb, 4, s->avctx->level); //level
00335                 }
00336 
00337                 put_bits(&s->pb, 1, s->progressive_sequence);
00338                 put_bits(&s->pb, 2, 1); //chroma format 4:2:0
00339                 put_bits(&s->pb, 2, 0); //horizontal size ext
00340                 put_bits(&s->pb, 2, 0); //vertical size ext
00341                 put_bits(&s->pb, 12, v>>18); //bitrate ext
00342                 put_bits(&s->pb, 1, 1); //marker
00343                 put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
00344                 put_bits(&s->pb, 1, s->low_delay);
00345                 put_bits(&s->pb, 2, 0); // frame_rate_ext_n
00346                 put_bits(&s->pb, 5, 0); // frame_rate_ext_d
00347             }
00348             
00349             put_header(s, GOP_START_CODE);
00350             put_bits(&s->pb, 1, 0); /* do drop frame */
00351             /* time code : we must convert from the real frame rate to a
00352                fake mpeg frame rate in case of low frame rate */
00353             fps = (framerate.num + framerate.den/2)/ framerate.den;
00354             time_code = s->current_picture_ptr->coded_picture_number;
00355 
00356             s->gop_picture_number = time_code;
00357             put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
00358             put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
00359             put_bits(&s->pb, 1, 1);
00360             put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
00361             put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
00362             put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
00363             put_bits(&s->pb, 1, 0); /* broken link */
00364         }
00365 }
00366 
00367 static inline void encode_mb_skip_run(MpegEncContext *s, int run){
00368     while (run >= 33) {
00369         put_bits(&s->pb, 11, 0x008);
00370         run -= 33;
00371     }
00372     put_bits(&s->pb, mbAddrIncrTable[run][1], 
00373              mbAddrIncrTable[run][0]);
00374 }
00375 #endif //CONFIG_ENCODERS
00376 
00377 static void common_init(MpegEncContext *s)
00378 {
00379 
00380     s->y_dc_scale_table=
00381     s->c_dc_scale_table= mpeg2_dc_scale_table[s->intra_dc_precision];
00382 
00383 }
00384 
00385 void ff_mpeg1_clean_buffers(MpegEncContext *s){
00386     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
00387     s->last_dc[1] = s->last_dc[0];
00388     s->last_dc[2] = s->last_dc[0];
00389     memset(s->last_mv, 0, sizeof(s->last_mv));
00390 }
00391 
00392 #ifdef CONFIG_ENCODERS
00393 
00394 void ff_mpeg1_encode_slice_header(MpegEncContext *s){
00395     put_header(s, SLICE_MIN_START_CODE + s->mb_y);
00396     put_bits(&s->pb, 5, s->qscale); /* quantizer scale */
00397     put_bits(&s->pb, 1, 0); /* slice extra information */
00398 }
00399 
00400 void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
00401 {
00402     mpeg1_encode_sequence_header(s);
00403 
00404     /* mpeg1 picture header */
00405     put_header(s, PICTURE_START_CODE);
00406     /* temporal reference */
00407 
00408     // RAL: s->picture_number instead of s->fake_picture_number
00409     put_bits(&s->pb, 10, (s->picture_number - 
00410                           s->gop_picture_number) & 0x3ff); 
00411     put_bits(&s->pb, 3, s->pict_type);
00412 
00413     s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
00414     put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
00415     
00416     // RAL: Forward f_code also needed for B frames
00417     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
00418         put_bits(&s->pb, 1, 0); /* half pel coordinates */
00419         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
00420             put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
00421         else
00422             put_bits(&s->pb, 3, 7); /* forward_f_code */
00423     }
00424     
00425     // RAL: Backward f_code necessary for B frames
00426     if (s->pict_type == B_TYPE) {
00427         put_bits(&s->pb, 1, 0); /* half pel coordinates */
00428         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
00429             put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
00430         else
00431             put_bits(&s->pb, 3, 7); /* backward_f_code */
00432     }
00433 
00434     put_bits(&s->pb, 1, 0); /* extra bit picture */
00435 
00436     s->frame_pred_frame_dct = 1;
00437     if(s->codec_id == CODEC_ID_MPEG2VIDEO){
00438         put_header(s, EXT_START_CODE);
00439         put_bits(&s->pb, 4, 8); //pic ext
00440         if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
00441             put_bits(&s->pb, 4, s->f_code);
00442             put_bits(&s->pb, 4, s->f_code);
00443         }else{
00444             put_bits(&s->pb, 8, 255);
00445         }
00446         if (s->pict_type == B_TYPE) {
00447             put_bits(&s->pb, 4, s->b_code);
00448             put_bits(&s->pb, 4, s->b_code);
00449         }else{
00450             put_bits(&s->pb, 8, 255);
00451         }
00452         put_bits(&s->pb, 2, s->intra_dc_precision);
00453         
00454         assert(s->picture_structure == PICT_FRAME);
00455         put_bits(&s->pb, 2, s->picture_structure);
00456         if (s->progressive_sequence) {
00457             put_bits(&s->pb, 1, 0); /* no repeat */
00458         } else {
00459             put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
00460         }
00461         /* XXX: optimize the generation of this flag with entropy
00462            measures */
00463         s->frame_pred_frame_dct = s->progressive_sequence;
00464         
00465         put_bits(&s->pb, 1, s->frame_pred_frame_dct);
00466         put_bits(&s->pb, 1, s->concealment_motion_vectors);
00467         put_bits(&s->pb, 1, s->q_scale_type);
00468         put_bits(&s->pb, 1, s->intra_vlc_format);
00469         put_bits(&s->pb, 1, s->alternate_scan);
00470         put_bits(&s->pb, 1, s->repeat_first_field);
00471         s->progressive_frame = s->progressive_sequence;
00472         put_bits(&s->pb, 1, s->chroma_420_type=s->progressive_frame);
00473         put_bits(&s->pb, 1, s->progressive_frame);
00474         put_bits(&s->pb, 1, 0); //composite_display_flag
00475     }
00476     if(s->flags & CODEC_FLAG_SVCD_SCAN_OFFSET){
00477         int i;
00478 
00479         put_header(s, USER_START_CODE);
00480         for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
00481             put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
00482         }
00483     }
00484     
00485     s->mb_y=0;
00486     ff_mpeg1_encode_slice_header(s);
00487 }
00488 
00489 static inline void put_mb_modes(MpegEncContext *s, int n, int bits, 
00490                                 int has_mv, int field_motion)
00491 {
00492     put_bits(&s->pb, n, bits);
00493     if (!s->frame_pred_frame_dct) {
00494         if (has_mv) 
00495             put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
00496         put_bits(&s->pb, 1, s->interlaced_dct);
00497     }
00498 }
00499 
00500 void mpeg1_encode_mb(MpegEncContext *s,
00501                      DCTELEM block[6][64],
00502                      int motion_x, int motion_y)
00503 {
00504     int i, cbp;
00505     const int mb_x = s->mb_x;
00506     const int mb_y = s->mb_y;
00507     const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
00508 
00509     /* compute cbp */
00510     cbp = 0;
00511     for(i=0;i<6;i++) {
00512         if (s->block_last_index[i] >= 0)
00513             cbp |= 1 << (5 - i);
00514     }
00515     
00516     if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
00517         (mb_x != s->mb_width - 1 || (mb_y != s->mb_height - 1 && s->codec_id == CODEC_ID_MPEG1VIDEO)) && 
00518         ((s->pict_type == P_TYPE && (motion_x | motion_y) == 0) ||
00519         (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) |
00520         ((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))) {
00521         s->mb_skip_run++;
00522         s->qscale -= s->dquant;
00523         s->skip_count++;
00524         s->misc_bits++;
00525         s->last_bits++;
00526         if(s->pict_type == P_TYPE){
00527             s->last_mv[0][1][0]= s->last_mv[0][0][0]= 
00528             s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
00529         }
00530     } else {
00531         if(first_mb){
00532             assert(s->mb_skip_run == 0);
00533             encode_mb_skip_run(s, s->mb_x);
00534         }else{
00535             encode_mb_skip_run(s, s->mb_skip_run);
00536         }
00537         
00538         if (s->pict_type == I_TYPE) {
00539             if(s->dquant && cbp){
00540                 put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
00541                 put_bits(&s->pb, 5, s->qscale);
00542             }else{
00543                 put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
00544                 s->qscale -= s->dquant;
00545             }
00546             s->misc_bits+= get_bits_diff(s);
00547             s->i_count++;
00548         } else if (s->mb_intra) {
00549             if(s->dquant && cbp){
00550                 put_mb_modes(s, 6, 0x01, 0, 0);
00551                 put_bits(&s->pb, 5, s->qscale);
00552             }else{
00553                 put_mb_modes(s, 5, 0x03, 0, 0);
00554                 s->qscale -= s->dquant;
00555             }
00556             s->misc_bits+= get_bits_diff(s);
00557             s->i_count++;
00558             memset(s->last_mv, 0, sizeof(s->last_mv));
00559         } else if (s->pict_type == P_TYPE) { 
00560             if(s->mv_type == MV_TYPE_16X16){
00561                 if (cbp != 0) {
00562                     if ((motion_x|motion_y) == 0) {
00563                         if(s->dquant){
00564                             put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
00565                             put_bits(&s->pb, 5, s->qscale);
00566                         }else{
00567                             put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
00568                         }
00569                         s->misc_bits+= get_bits_diff(s);
00570                     } else {
00571                         if(s->dquant){
00572                             put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
00573                             put_bits(&s->pb, 5, s->qscale);
00574                         }else{
00575                             put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
00576                         }
00577                         s->misc_bits+= get_bits_diff(s);
00578                         mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
00579                         mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
00580                         s->mv_bits+= get_bits_diff(s);
00581                     }
00582                 } else {
00583                     put_bits(&s->pb, 3, 1); /* motion only */
00584                     if (!s->frame_pred_frame_dct)
00585                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
00586                     s->misc_bits+= get_bits_diff(s);
00587                     mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
00588                     mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
00589                     s->qscale -= s->dquant;
00590                     s->mv_bits+= get_bits_diff(s);
00591                 }
00592                 s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
00593                 s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
00594             }else{
00595                 assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
00596 
00597                 if (cbp) {
00598                     if(s->dquant){
00599                         put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
00600                         put_bits(&s->pb, 5, s->qscale);
00601                     }else{
00602                         put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
00603                     }
00604                 } else {
00605                     put_bits(&s->pb, 3, 1); /* motion only */
00606                     put_bits(&s->pb, 2, 1); /* motion_type: field */
00607                     s->qscale -= s->dquant;
00608                 }
00609                 s->misc_bits+= get_bits_diff(s);
00610                 for(i=0; i<2; i++){
00611                     put_bits(&s->pb, 1, s->field_select[0][i]);
00612                     mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
00613                     mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
00614                     s->last_mv[0][i][0]=   s->mv[0][i][0];
00615                     s->last_mv[0][i][1]= 2*s->mv[0][i][1];
00616                 }
00617                 s->mv_bits+= get_bits_diff(s);
00618             }
00619             if(cbp)
00620                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
00621             s->f_count++;
00622         } else{  
00623             static const int mb_type_len[4]={0,3,4,2}; //bak,for,bi
00624 
00625             if(s->mv_type == MV_TYPE_16X16){
00626                 if (cbp){    // With coded bloc pattern
00627                     if (s->dquant) {
00628                         if(s->mv_dir == MV_DIR_FORWARD)
00629                             put_mb_modes(s, 6, 3, 1, 0);
00630                         else
00631                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 0);
00632                         put_bits(&s->pb, 5, s->qscale);
00633                     } else {
00634                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 0);
00635                     }
00636                 }else{    // No coded bloc pattern
00637                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
00638                     if (!s->frame_pred_frame_dct)
00639                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
00640                     s->qscale -= s->dquant;
00641                 }
00642                 s->misc_bits += get_bits_diff(s);
00643                 if (s->mv_dir&MV_DIR_FORWARD){
00644                     mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code); 
00645                     mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code); 
00646                     s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
00647                     s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
00648                     s->f_count++;
00649                 }
00650                 if (s->mv_dir&MV_DIR_BACKWARD){
00651                     mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code); 
00652                     mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code); 
00653                     s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
00654                     s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
00655                     s->b_count++;
00656                 }
00657             }else{
00658                 assert(s->mv_type == MV_TYPE_FIELD);
00659                 assert(!s->frame_pred_frame_dct);
00660                 if (cbp){    // With coded bloc pattern
00661                     if (s->dquant) {
00662                         if(s->mv_dir == MV_DIR_FORWARD)
00663                             put_mb_modes(s, 6, 3, 1, 1);
00664                         else
00665                             put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 1);
00666                         put_bits(&s->pb, 5, s->qscale);
00667                     } else {
00668                         put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 1);
00669                     }
00670                 }else{    // No coded bloc pattern
00671                     put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
00672                     put_bits(&s->pb, 2, 1); /* motion_type: field */
00673                     s->qscale -= s->dquant;
00674                 }
00675                 s->misc_bits += get_bits_diff(s);
00676                 if (s->mv_dir&MV_DIR_FORWARD){
00677                     for(i=0; i<2; i++){
00678                         put_bits(&s->pb, 1, s->field_select[0][i]);
00679                         mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
00680                         mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
00681                         s->last_mv[0][i][0]=   s->mv[0][i][0];
00682                         s->last_mv[0][i][1]= 2*s->mv[0][i][1];
00683                     }
00684                     s->f_count++;
00685                 }
00686                 if (s->mv_dir&MV_DIR_BACKWARD){
00687                     for(i=0; i<2; i++){
00688                         put_bits(&s->pb, 1, s->field_select[1][i]);
00689                         mpeg1_encode_motion(s, s->mv[1][i][0] -  s->last_mv[1][i][0]    , s->b_code);
00690                         mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
00691                         s->last_mv[1][i][0]=   s->mv[1][i][0];
00692                         s->last_mv[1][i][1]= 2*s->mv[1][i][1];
00693                     }
00694                     s->b_count++;
00695                 }
00696             }
00697             s->mv_bits += get_bits_diff(s);
00698             if(cbp)
00699                 put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
00700         }
00701         for(i=0;i<6;i++) {
00702             if (cbp & (1 << (5 - i))) {
00703                 mpeg1_encode_block(s, block[i], i);
00704             }
00705         }
00706         s->mb_skip_run = 0;
00707         if(s->mb_intra)
00708             s->i_tex_bits+= get_bits_diff(s);
00709         else
00710             s->p_tex_bits+= get_bits_diff(s);
00711     }
00712 }
00713 
00714 // RAL: Parameter added: f_or_b_code
00715 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
00716 {
00717     int code, bit_size, l, bits, range, sign;
00718 
00719     if (val == 0) {
00720         /* zero vector */
00721         code = 0;
00722         put_bits(&s->pb,
00723                  mbMotionVectorTable[0][1], 
00724                  mbMotionVectorTable[0][0]); 
00725     } else {
00726         bit_size = f_or_b_code - 1;
00727         range = 1 << bit_size;
00728         /* modulo encoding */
00729         l= INT_BIT - 5 - bit_size;
00730         val= (val<<l)>>l;
00731 
00732         if (val >= 0) {
00733             val--;
00734             code = (val >> bit_size) + 1;
00735             bits = val & (range - 1);
00736             sign = 0;
00737         } else {
00738             val = -val;
00739             val--;
00740             code = (val >> bit_size) + 1;
00741             bits = val & (range - 1);
00742             sign = 1;
00743         }
00744 
00745         assert(code > 0 && code <= 16);
00746 
00747         put_bits(&s->pb,
00748                  mbMotionVectorTable[code][1], 
00749                  mbMotionVectorTable[code][0]); 
00750 
00751         put_bits(&s->pb, 1, sign);
00752         if (bit_size > 0) {
00753             put_bits(&s->pb, bit_size, bits);
00754         }
00755     }
00756 }
00757 
00758 void ff_mpeg1_encode_init(MpegEncContext *s)
00759 {
00760     static int done=0;
00761 
00762     common_init(s);
00763 
00764     if(!done){
00765         int f_code;
00766         int mv;
00767         int i;
00768 
00769         done=1;
00770         init_rl(&rl_mpeg1, 1);
00771 
00772         for(i=0; i<64; i++)
00773         {
00774                 mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];
00775                 mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];
00776         }
00777         
00778         init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_bits, uni_mpeg1_ac_vlc_len);
00779 
00780         /* build unified dc encoding tables */
00781         for(i=-255; i<256; i++)
00782         {
00783                 int adiff, index;
00784                 int bits, code;
00785                 int diff=i;
00786 
00787                 adiff = ABS(diff);
00788                 if(diff<0) diff--;
00789                 index = av_log2(2*adiff);
00790 
00791                 bits= vlc_dc_lum_bits[index] + index;
00792                 code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
00793                 mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
00794                 
00795                 bits= vlc_dc_chroma_bits[index] + index;
00796                 code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
00797                 mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
00798         }
00799 
00800         mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
00801 
00802         for(f_code=1; f_code<=MAX_FCODE; f_code++){
00803             for(mv=-MAX_MV; mv<=MAX_MV; mv++){
00804                 int len;
00805 
00806                 if(mv==0) len= mbMotionVectorTable[0][1];
00807                 else{
00808                     int val, bit_size, range, code;
00809 
00810                     bit_size = f_code - 1;
00811                     range = 1 << bit_size;
00812 
00813                     val=mv;
00814                     if (val < 0) 
00815                         val = -val;
00816                     val--;
00817                     code = (val >> bit_size) + 1;
00818                     if(code<17){
00819                         len= mbMotionVectorTable[code][1] + 1 + bit_size;
00820                     }else{
00821                         len= mbMotionVectorTable[16][1] + 2 + bit_size;
00822                     }
00823                 }
00824 
00825                 mv_penalty[f_code][mv+MAX_MV]= len;
00826             }
00827         }
00828         
00829 
00830         for(f_code=MAX_FCODE; f_code>0; f_code--){
00831             for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
00832                 fcode_tab[mv+MAX_MV]= f_code;
00833             }
00834         }
00835     }
00836     s->me.mv_penalty= mv_penalty;
00837     s->fcode_tab= fcode_tab;
00838     if(s->codec_id == CODEC_ID_MPEG1VIDEO){
00839         s->min_qcoeff=-255;
00840         s->max_qcoeff= 255;
00841     }else{
00842         s->min_qcoeff=-2047;
00843         s->max_qcoeff= 2047;
00844     }
00845     s->intra_ac_vlc_length=
00846     s->inter_ac_vlc_length=
00847     s->intra_ac_vlc_last_length=
00848     s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
00849 }
00850 
00851 static inline void encode_dc(MpegEncContext *s, int diff, int component)
00852 {
00853   if(((unsigned) (diff+255)) >= 511){
00854         int index;
00855 
00856         if(diff<0){
00857             index= av_log2_16bit(-2*diff);
00858             diff--;
00859         }else{
00860             index= av_log2_16bit(2*diff);
00861         }
00862         if (component == 0) {
00863             put_bits(
00864                 &s->pb, 
00865                 vlc_dc_lum_bits[index] + index,
00866                 (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1)));
00867         }else{
00868             put_bits(
00869                 &s->pb, 
00870                 vlc_dc_chroma_bits[index] + index,
00871                 (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1)));
00872         }
00873   }else{
00874     if (component == 0) {
00875         put_bits(
00876             &s->pb, 
00877             mpeg1_lum_dc_uni[diff+255]&0xFF,
00878             mpeg1_lum_dc_uni[diff+255]>>8);
00879     } else {
00880         put_bits(
00881             &s->pb, 
00882             mpeg1_chr_dc_uni[diff+255]&0xFF,
00883             mpeg1_chr_dc_uni[diff+255]>>8);
00884     }
00885   }
00886 }
00887 
00888 static void mpeg1_encode_block(MpegEncContext *s, 
00889                                DCTELEM *block, 
00890                                int n)
00891 {
00892     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
00893     int code, component;
00894 //    RLTable *rl = &rl_mpeg1;
00895 
00896     last_index = s->block_last_index[n];
00897 
00898     /* DC coef */
00899     if (s->mb_intra) {
00900         component = (n <= 3 ? 0 : n - 4 + 1);
00901         dc = block[0]; /* overflow is impossible */
00902         diff = dc - s->last_dc[component];
00903         encode_dc(s, diff, component);
00904         s->last_dc[component] = dc;
00905         i = 1;
00906 /*
00907         if (s->intra_vlc_format)
00908             rl = &rl_mpeg2;
00909         else
00910             rl = &rl_mpeg1;
00911 */
00912     } else {
00913         /* encode the first coefficient : needs to be done here because
00914            it is handled slightly differently */
00915         level = block[0];
00916         if (abs(level) == 1) {
00917                 code = ((uint32_t)level >> 31); /* the sign bit */
00918                 put_bits(&s->pb, 2, code | 0x02);
00919                 i = 1;
00920         } else {
00921             i = 0;
00922             last_non_zero = -1;
00923             goto next_coef;
00924         }
00925     }
00926 
00927     /* now quantify & encode AC coefs */
00928     last_non_zero = i - 1;
00929 
00930     for(;i<=last_index;i++) {
00931         j = s->intra_scantable.permutated[i];
00932         level = block[j];
00933     next_coef:
00934 #if 0
00935         if (level != 0)
00936             dprintf("level[%d]=%d\n", i, level);
00937 #endif            
00938         /* encode using VLC */
00939         if (level != 0) {
00940             run = i - last_non_zero - 1;
00941             
00942             alevel= level;
00943             MASK_ABS(sign, alevel)
00944             sign&=1;
00945 
00946 //            code = get_rl_index(rl, 0, run, alevel);
00947             if (alevel <= mpeg1_max_level[0][run]){
00948                 code= mpeg1_index_run[0][run] + alevel - 1;
00949                 /* store the vlc & sign at once */
00950                 put_bits(&s->pb, mpeg1_vlc[code][1]+1, (mpeg1_vlc[code][0]<<1) + sign);
00951             } else {
00952                 /* escape seems to be pretty rare <5% so i dont optimize it */
00953                 put_bits(&s->pb, mpeg1_vlc[111/*rl->n*/][1], mpeg1_vlc[111/*rl->n*/][0]);
00954                 /* escape: only clip in this case */
00955                 put_bits(&s->pb, 6, run);
00956                 if(s->codec_id == CODEC_ID_MPEG1VIDEO){
00957                     if (alevel < 128) {
00958                         put_bits(&s->pb, 8, level & 0xff);
00959                     } else {
00960                         if (level < 0) {
00961                             put_bits(&s->pb, 16, 0x8001 + level + 255);
00962                         } else {
00963                             put_bits(&s->pb, 16, level & 0xffff);
00964                         }
00965                     }
00966                 }else{
00967                     put_bits(&s->pb, 12, level & 0xfff);
00968                 }
00969             }
00970             last_non_zero = i;
00971         }
00972     }
00973     /* end of block */
00974     put_bits(&s->pb, 2, 0x2);
00975 }
00976 #endif //CONFIG_ENCODERS
00977 
00978 /******************************************/
00979 /* decoding */
00980 
00981 static VLC dc_lum_vlc;
00982 static VLC dc_chroma_vlc;
00983 static VLC mv_vlc;
00984 static VLC mbincr_vlc;
00985 static VLC mb_ptype_vlc;
00986 static VLC mb_btype_vlc;
00987 static VLC mb_pat_vlc;
00988 
00989 static void init_vlcs(void)
00990 {
00991     static int done = 0;
00992 
00993     if (!done) {
00994         done = 1;
00995 
00996         init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12, 
00997                  vlc_dc_lum_bits, 1, 1,
00998                  vlc_dc_lum_code, 2, 2, 1);
00999         init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12, 
01000                  vlc_dc_chroma_bits, 1, 1,
01001                  vlc_dc_chroma_code, 2, 2, 1);
01002         init_vlc(&mv_vlc, MV_VLC_BITS, 17, 
01003                  &mbMotionVectorTable[0][1], 2, 1,
01004                  &mbMotionVectorTable[0][0], 2, 1, 1);
01005         init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 36, 
01006                  &mbAddrIncrTable[0][1], 2, 1,
01007                  &mbAddrIncrTable[0][0], 2, 1, 1);
01008         init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,
01009                  &mbPatTable[0][1], 2, 1,
01010                  &mbPatTable[0][0], 2, 1, 1);
01011         
01012         init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7, 
01013                  &table_mb_ptype[0][1], 2, 1,
01014                  &table_mb_ptype[0][0], 2, 1, 1);
01015         init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11, 
01016                  &table_mb_btype[0][1], 2, 1,
01017                  &table_mb_btype[0][0], 2, 1, 1);
01018         init_rl(&rl_mpeg1, 1);
01019         init_rl(&rl_mpeg2, 1);
01020 
01021         init_2d_vlc_rl(&rl_mpeg1, 1);
01022         init_2d_vlc_rl(&rl_mpeg2, 1);
01023     }
01024 }
01025 
01026 static inline int get_dmv(MpegEncContext *s)
01027 {
01028     if(get_bits1(&s->gb)) 
01029         return 1 - (get_bits1(&s->gb) << 1);
01030     else
01031         return 0;
01032 }
01033 
01034 static inline int get_qscale(MpegEncContext *s)
01035 {
01036     int qscale = get_bits(&s->gb, 5);
01037     if (s->q_scale_type) {
01038         return non_linear_qscale[qscale];
01039     } else {
01040         return qscale << 1;
01041     }
01042 }
01043 
01044 /* motion type (for mpeg2) */
01045 #define MT_FIELD 1
01046 #define MT_FRAME 2
01047 #define MT_16X8  2
01048 #define MT_DMV   3
01049 
01050 static int mpeg_decode_mb(MpegEncContext *s,
01051                           DCTELEM block[12][64])
01052 {
01053     int i, j, k, cbp, val, mb_type, motion_type;
01054     const int mb_block_count = 4 + (1<< s->chroma_format);
01055 
01056     dprintf("decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
01057 
01058     assert(s->mb_skipped==0);
01059 
01060     if (s->mb_skip_run-- != 0) {
01061         if(s->pict_type == I_TYPE){
01062             av_log(s->avctx, AV_LOG_ERROR, "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
01063             return -1;
01064         }
01065     
01066         /* skip mb */
01067         s->mb_intra = 0;
01068         for(i=0;i<12;i++)
01069             s->block_last_index[i] = -1;
01070         if(s->picture_structure == PICT_FRAME)
01071             s->mv_type = MV_TYPE_16X16;
01072         else
01073             s->mv_type = MV_TYPE_FIELD;
01074         if (s->pict_type == P_TYPE) {
01075             /* if P type, zero motion vector is implied */
01076             s->mv_dir = MV_DIR_FORWARD;
01077             s->mv[0][0][0] = s->mv[0][0][1] = 0;
01078             s->last_mv[0][0][0] = s->last_mv[0][0][1] = 0;
01079             s->last_mv[0][1][0] = s->last_mv[0][1][1] = 0;
01080             s->field_select[0][0]= s->picture_structure - 1;
01081             s->mb_skipped = 1;
01082             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
01083         } else {
01084             int mb_type;
01085             
01086             if(s->mb_x)
01087                 mb_type= s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1];
01088             else
01089                 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, 
01090             if(IS_INTRA(mb_type))
01091                 return -1;
01092             
01093             /* if B type, reuse previous vectors and directions */
01094             s->mv[0][0][0] = s->last_mv[0][0][0];
01095             s->mv[0][0][1] = s->last_mv[0][0][1];
01096             s->mv[1][0][0] = s->last_mv[1][0][0];
01097             s->mv[1][0][1] = s->last_mv[1][0][1];
01098 
01099             s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= 
01100                 mb_type | MB_TYPE_SKIP;
01101 //            assert(s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride - 1]&(MB_TYPE_16x16|MB_TYPE_16x8));
01102 
01103             if((s->mv[0][0][0]|s->mv[0][0][1]|s->mv[1][0][0]|s->mv[1][0][1])==0) 
01104                 s->mb_skipped = 1;
01105         }
01106 
01107         return 0;
01108     }
01109 
01110     switch(s->pict_type) {
01111     default:
01112     case I_TYPE:
01113         if (get_bits1(&s->gb) == 0) {
01114             if (get_bits1(&s->gb) == 0){
01115                 av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in I Frame at %d %d\n", s->mb_x, s->mb_y);
01116                 return -1;
01117             }
01118             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
01119         } else {
01120             mb_type = MB_TYPE_INTRA;
01121         }
01122         break;
01123     case P_TYPE:
01124         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
01125         if (mb_type < 0){
01126             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
01127             return -1;
01128         }
01129         mb_type = ptype2mb_type[ mb_type ];
01130         break;
01131     case B_TYPE:
01132         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
01133         if (mb_type < 0){
01134             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
01135             return -1;
01136         }
01137         mb_type = btype2mb_type[ mb_type ];
01138         break;
01139     }
01140     dprintf("mb_type=%x\n", mb_type);
01141 //    motion_type = 0; /* avoid warning */
01142     if (IS_INTRA(mb_type)) {
01143         s->dsp.clear_blocks(s->block[0]);
01144     
01145         if(!s->chroma_y_shift){
01146             s->dsp.clear_blocks(s->block[6]);
01147         }
01148     
01149         /* compute dct type */
01150         if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
01151             !s->frame_pred_frame_dct) {
01152             s->interlaced_dct = get_bits1(&s->gb);
01153         }
01154 
01155         if (IS_QUANT(mb_type))
01156             s->qscale = get_qscale(s);
01157         
01158         if (s->concealment_motion_vectors) {
01159             /* just parse them */
01160             if (s->picture_structure != PICT_FRAME) 
01161                 skip_bits1(&s->gb); /* field select */
01162             
01163             s->mv[0][0][0]= s->last_mv[0][0][0]= s->last_mv[0][1][0] = 
01164                 mpeg_decode_motion(s, s->mpeg_f_code[0][0], s->last_mv[0][0][0]);
01165             s->mv[0][0][1]= s->last_mv[0][0][1]= s->last_mv[0][1][1] = 
01166                 mpeg_decode_motion(s, s->mpeg_f_code[0][1], s->last_mv[0][0][1]);
01167 
01168             skip_bits1(&s->gb); /* marker */
01169         }else
01170             memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
01171         s->mb_intra = 1;
01172 #ifdef HAVE_XVMC
01173         //one 1 we memcpy blocks in xvmcvideo
01174         if(s->avctx->xvmc_acceleration > 1){
01175             XVMC_pack_pblocks(s,-1);//inter are always full blocks
01176             if(s->swap_uv){
01177                 exchange_uv(s);
01178             }
01179         }
01180 #endif
01181 
01182         if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
01183             if(s->flags2 & CODEC_FLAG2_FAST){
01184                 for(i=0;i<6;i++) {
01185                     mpeg2_fast_decode_block_intra(s, s->pblocks[i], i);
01186                 }
01187             }else{
01188                 for(i=0;i<mb_block_count;i++) {
01189                     if (mpeg2_decode_block_intra(s, s->pblocks[i], i) < 0)
01190                         return -1;
01191                 }
01192             }
01193         } else {
01194             for(i=0;i<6;i++) {
01195                 if (mpeg1_decode_block_intra(s, s->pblocks[i], i) < 0)
01196                     return -1;
01197             }
01198         }
01199     } else {
01200         if (mb_type & MB_TYPE_ZERO_MV){
01201             assert(mb_type & MB_TYPE_CBP);
01202 
01203             /* compute dct type */
01204             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
01205                 !s->frame_pred_frame_dct) {
01206                 s->interlaced_dct = get_bits1(&s->gb);
01207             }
01208 
01209             if (IS_QUANT(mb_type))
01210                 s->qscale = get_qscale(s);
01211 
01212             s->mv_dir = MV_DIR_FORWARD;
01213             if(s->picture_structure == PICT_FRAME)
01214                 s->mv_type = MV_TYPE_16X16;
01215             else{
01216                 s->mv_type = MV_TYPE_FIELD;
01217                 mb_type |= MB_TYPE_INTERLACED;
01218                 s->field_select[0][0]= s->picture_structure - 1;
01219             }
01220             s->last_mv[0][0][0] = 0;
01221             s->last_mv[0][0][1] = 0;
01222             s->last_mv[0][1][0] = 0;
01223             s->last_mv[0][1][1] = 0;
01224             s->mv[0][0][0] = 0;
01225             s->mv[0][0][1] = 0;
01226         }else{
01227             assert(mb_type & MB_TYPE_L0L1);
01228 //FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
01229             /* get additionnal motion vector type */
01230             if (s->frame_pred_frame_dct) 
01231                 motion_type = MT_FRAME;
01232             else{
01233                 motion_type = get_bits(&s->gb, 2);
01234             }
01235 
01236             /* compute dct type */
01237             if (s->picture_structure == PICT_FRAME && //FIXME add a interlaced_dct coded var?
01238                 !s->frame_pred_frame_dct && HAS_CBP(mb_type)) {
01239                 s->interlaced_dct = get_bits1(&s->gb);
01240             }
01241 
01242             if (IS_QUANT(mb_type))
01243                 s->qscale = get_qscale(s);
01244 
01245             /* motion vectors */
01246             s->mv_dir = 0;
01247             for(i=0;i<2;i++) {
01248                 if (USES_LIST(mb_type, i)) {
01249                     s->mv_dir |= (MV_DIR_FORWARD >> i);
01250                     dprintf("motion_type=%d\n", motion_type);
01251                     switch(motion_type) {
01252                     case MT_FRAME: /* or MT_16X8 */
01253                         if (s->picture_structure == PICT_FRAME) {
01254                             /* MT_FRAME */
01255                             mb_type |= MB_TYPE_16x16; 
01256                             s->mv_type = MV_TYPE_16X16;
01257                             s->mv[i][0][0]= s->last_mv[i][0][0]= s->last_mv[i][1][0] = 
01258                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0], s->last_mv[i][0][0]);
01259                             s->mv[i][0][1]= s->last_mv[i][0][1]= s->last_mv[i][1][1] = 
01260                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1], s->last_mv[i][0][1]);
01261                             /* full_pel: only for mpeg1 */
01262                             if (s->full_pel[i]){
01263                                 s->mv[i][0][0] <<= 1;
01264                                 s->mv[i][0][1] <<= 1;
01265                             }
01266                         } else {
01267                             /* MT_16X8 */
01268                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; 
01269                             s->mv_type = MV_TYPE_16X8;
01270                             for(j=0;j<2;j++) {
01271                                 s->field_select[i][j] = get_bits1(&s->gb);
01272                                 for(k=0;k<2;k++) {
01273                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
01274                                                              s->last_mv[i][j][k]);
01275                                     s->last_mv[i][j][k] = val;
01276                                     s->mv[i][j][k] = val;
01277                                 }
01278                             }
01279                         }
01280                         break;
01281                     case MT_FIELD:
01282                         s->mv_type = MV_TYPE_FIELD;
01283                         if (s->picture_structure == PICT_FRAME) {
01284                             mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; 
01285                             for(j=0;j<2;j++) {
01286                                 s->field_select[i][j] = get_bits1(&s->gb);
01287                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
01288                                                          s->last_mv[i][j][0]);
01289                                 s->last_mv[i][j][0] = val;
01290                                 s->mv[i][j][0] = val;
01291                                 dprintf("fmx=%d\n", val);
01292                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
01293                                                          s->last_mv[i][j][1] >> 1);
01294                                 s->last_mv[i][j][1] = val << 1;
01295                                 s->mv[i][j][1] = val;
01296                                 dprintf("fmy=%d\n", val);
01297                             }
01298                         } else {
01299                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED; 
01300                             s->field_select[i][0] = get_bits1(&s->gb);
01301                             for(k=0;k<2;k++) {
01302                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
01303                                                          s->last_mv[i][0][k]);
01304                                 s->last_mv[i][0][k] = val;
01305                                 s->last_mv[i][1][k] = val;
01306                                 s->mv[i][0][k] = val;
01307                             }
01308                         }
01309                         break;
01310                     case MT_DMV:
01311                         {
01312                             int dmx, dmy, mx, my, m;
01313 
01314                             mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0], 
01315                                                     s->last_mv[i][0][0]);
01316                             s->last_mv[i][0][0] = mx;
01317                             s->last_mv[i][1][0] = mx;
01318                             dmx = get_dmv(s);
01319                             my = mpeg_decode_motion(s, s->mpeg_f_code[i][1], 
01320                                                     s->last_mv[i][0][1] >> 1);
01321                             dmy = get_dmv(s);
01322                             s->mv_type = MV_TYPE_DMV;
01323 
01324 
01325                             s->last_mv[i][0][1] = my<<1;
01326                             s->last_mv[i][1][1] = my<<1;
01327 
01328                             s->mv[i][0][0] = mx;
01329                             s->mv[i][0][1] = my;
01330                             s->mv[i][1][0] = mx;//not used
01331                             s->mv[i][1][1] = my;//not used
01332 
01333                             if (s->picture_structure == PICT_FRAME) {
01334                                 mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED; 
01335 
01336                                 //m = 1 + 2 * s->top_field_first;
01337                                 m = s->top_field_first ? 1 : 3;
01338 
01339                                 /* top -> top pred */
01340                                 s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
01341                                 s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
01342                                 m = 4 - m;
01343                                 s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
01344                                 s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
01345                             } else {
01346                                 mb_type |= MB_TYPE_16x16;
01347 
01348                                 s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
01349                                 s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
01350                                 if(s->picture_structure == PICT_TOP_FIELD)
01351                                     s->mv[i][2][1]--;
01352                                 else 
01353                                     s->mv[i][2][1]++;
01354                             }
01355                         }
01356                         break;
01357                     default:
01358                         av_log(s->avctx, AV_LOG_ERROR, "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
01359                         return -1;
01360                     }
01361                 }
01362             }
01363         }
01364         
01365         s->mb_intra = 0;
01366         if (HAS_CBP(mb_type)) {
01367             s->dsp.clear_blocks(s->block[0]);
01368         
01369             if(!s->chroma_y_shift){
01370                 s->dsp.clear_blocks(s->block[6]);
01371             }
01372 
01373             cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
01374             if (cbp < 0 || ((cbp == 0) && (s->chroma_format < 2)) ){
01375                 av_log(s->avctx, AV_LOG_ERROR, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
01376                 return -1;
01377             }
01378             if(mb_block_count > 6){
01379                  cbp<<= mb_block_count-6;
01380                  cbp |= get_bits(&s->gb, mb_block_count-6);
01381             }
01382 
01383 #ifdef HAVE_XVMC
01384             //on 1 we memcpy blocks in xvmcvideo
01385             if(s->avctx->xvmc_acceleration > 1){
01386                 XVMC_pack_pblocks(s,cbp);
01387                 if(s->swap_uv){
01388                     exchange_uv(s);
01389                 }
01390             }    
01391 #endif
01392 
01393             if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
01394                 if(s->flags2 & CODEC_FLAG2_FAST){
01395                     for(i=0;i<6;i++) {
01396                         if(cbp & 32) {
01397                             mpeg2_fast_decode_block_non_intra(s, s->pblocks[i], i);
01398                         } else {
01399                             s->block_last_index[i] = -1;
01400                         }
01401                         cbp+=cbp;
01402                     }
01403                 }else{
01404                     cbp<<= 12-mb_block_count;
01405     
01406                     for(i=0;i<mb_block_count;i++) {
01407                         if ( cbp & (1<<11) ) {
01408                             if (mpeg2_decode_block_non_intra(s, s->pblocks[i], i) < 0)
01409                                 return -1;
01410                         } else {
01411                             s->block_last_index[i] = -1;
01412                         }
01413                         cbp+=cbp;
01414                     }
01415                 }
01416             } else {
01417                 if(s->flags2 & CODEC_FLAG2_FAST){
01418                     for(i=0;i<6;i++) {
01419                         if (cbp & 32) {
01420                             mpeg1_fast_decode_block_inter(s, s->pblocks[i], i);
01421                         } else {
01422                             s->block_last_index[i] = -1;
01423                         }
01424                         cbp+=cbp;
01425                     }
01426                 }else{
01427                     for(i=0;i<6;i++) {
01428                         if (cbp & 32) {
01429                             if (mpeg1_decode_block_inter(s, s->pblocks[i], i) < 0)
01430                                 return -1;
01431                         } else {
01432                             s->block_last_index[i] = -1;
01433                         }
01434                         cbp+=cbp;
01435                     }
01436                 }
01437             }
01438         }else{
01439             for(i=0;i<6;i++)
01440                 s->block_last_index[i] = -1;
01441         }
01442     }
01443 
01444     s->current_picture.mb_type[ s->mb_x + s->mb_y*s->mb_stride ]= mb_type;
01445 
01446     return 0;
01447 }
01448 
01449 /* as h263, but only 17 codes */
01450 static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
01451 {
01452     int code, sign, val, l, shift;
01453 
01454     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
01455     if (code == 0) {
01456         return pred;
01457     }
01458     if (code < 0) {
01459         return 0xffff;
01460     }
01461 
01462     sign = get_bits1(&s->gb);
01463     shift = fcode - 1;
01464     val = code;
01465     if (shift) {
01466         val = (val - 1) << shift;
01467         val |= get_bits(&s->gb, shift);
01468         val++;
01469     }
01470     if (sign)
01471         val = -val;
01472     val += pred;
01473     
01474     /* modulo decoding */
01475     l= INT_BIT - 5 - shift;
01476     val = (val<<l)>>l;
01477     return val;
01478 }
01479 
01480 static inline int decode_dc(GetBitContext *gb, int component)
01481 {
01482     int code, diff;
01483 
01484     if (component == 0) {
01485         code = get_vlc2(gb, dc_lum_vlc.table, DC_VLC_BITS, 2);
01486     } else {
01487         code = get_vlc2(gb, dc_chroma_vlc.table, DC_VLC_BITS, 2);
01488     }
01489     if (code < 0){
01490         av_log(NULL, AV_LOG_ERROR, "invalid dc code at\n");
01491         return 0xffff;
01492     }
01493     if (code == 0) {
01494         diff = 0;
01495     } else {
01496         diff = get_xbits(gb, code);
01497     }
01498     return diff;
01499 }
01500 
01501 static inline int mpeg1_decode_block_intra(MpegEncContext *s, 
01502                                DCTELEM *block, 
01503                                int n)
01504 {
01505     int level, dc, diff, i, j, run;
01506     int component;
01507     RLTable *rl = &rl_mpeg1;
01508     uint8_t * const scantable= s->intra_scantable.permutated;
01509     const uint16_t *quant_matrix= s->intra_matrix;
01510     const int qscale= s->qscale;
01511 
01512     /* DC coef */
01513     component = (n <= 3 ? 0 : n - 4 + 1);
01514     diff = decode_dc(&s->gb, component);
01515     if (diff >= 0xffff)
01516         return -1;
01517     dc = s->last_dc[component];
01518     dc += diff;
01519     s->last_dc[component] = dc;
01520     block[0] = dc<<3;
01521     dprintf("dc=%d diff=%d\n", dc, diff);
01522     i = 0;
01523     {
01524         OPEN_READER(re, &s->gb);    
01525         /* now quantify & encode AC coefs */
01526         for(;;) {
01527             UPDATE_CACHE(re, &s->gb);
01528             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01529             
01530             if(level == 127){
01531                 break;
01532             } else if(level != 0) {
01533                 i += run;
01534                 j = scantable[i];
01535                 level= (level*qscale*quant_matrix[j])>>4;
01536                 level= (level-1)|1;
01537                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01538                 LAST_SKIP_BITS(re, &s->gb, 1);
01539             } else {
01540                 /* escape */
01541                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01542                 UPDATE_CACHE(re, &s->gb);
01543                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
01544                 if (level == -128) {
01545                     level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);
01546                 } else if (level == 0) {
01547                     level = SHOW_UBITS(re, &s->gb, 8)      ; LAST_SKIP_BITS(re, &s->gb, 8);
01548                 }
01549                 i += run;
01550                 j = scantable[i];
01551                 if(level<0){
01552                     level= -level;
01553                     level= (level*qscale*quant_matrix[j])>>4;
01554                     level= (level-1)|1;
01555                     level= -level;
01556                 }else{
01557                     level= (level*qscale*quant_matrix[j])>>4;
01558                     level= (level-1)|1;
01559                 }
01560             }
01561             if (i > 63){
01562                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
01563                 return -1;
01564             }
01565 
01566             block[j] = level;
01567         }
01568         CLOSE_READER(re, &s->gb);
01569     }
01570     s->block_last_index[n] = i;
01571    return 0;
01572 }
01573 
01574 static inline int mpeg1_decode_block_inter(MpegEncContext *s, 
01575                                DCTELEM *block, 
01576                                int n)
01577 {
01578     int level, i, j, run;
01579     RLTable *rl = &rl_mpeg1;
01580     uint8_t * const scantable= s->intra_scantable.permutated;
01581     const uint16_t *quant_matrix= s->inter_matrix;
01582     const int qscale= s->qscale;
01583 
01584     {
01585         OPEN_READER(re, &s->gb);
01586         i = -1;
01587         /* special case for the first coef. no need to add a second vlc table */
01588         UPDATE_CACHE(re, &s->gb);
01589         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
01590             level= (3*qscale*quant_matrix[0])>>5;
01591             level= (level-1)|1;
01592             if(GET_CACHE(re, &s->gb)&0x40000000)
01593                 level= -level;
01594             block[0] = level;
01595             i++;
01596             SKIP_BITS(re, &s->gb, 2);
01597             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01598                 goto end;
01599         }
01600 
01601         /* now quantify & encode AC coefs */
01602         for(;;) {
01603             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01604             
01605             if(level != 0) {
01606                 i += run;
01607                 j = scantable[i];
01608                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
01609                 level= (level-1)|1;
01610                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01611                 SKIP_BITS(re, &s->gb, 1);
01612             } else {
01613                 /* escape */
01614                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01615                 UPDATE_CACHE(re, &s->gb);
01616                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
01617                 if (level == -128) {
01618                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
01619                 } else if (level == 0) {
01620                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
01621                 }
01622                 i += run;
01623                 j = scantable[i];
01624                 if(level<0){
01625                     level= -level;
01626                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
01627                     level= (level-1)|1;
01628                     level= -level;
01629                 }else{
01630                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
01631                     level= (level-1)|1;
01632                 }
01633             }
01634             if (i > 63){
01635                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
01636                 return -1;
01637             }
01638 
01639             block[j] = level;
01640             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01641                 break;
01642             UPDATE_CACHE(re, &s->gb);
01643         }
01644 end:
01645         LAST_SKIP_BITS(re, &s->gb, 2);
01646         CLOSE_READER(re, &s->gb);
01647     }
01648     s->block_last_index[n] = i;
01649     return 0;
01650 }
01651 
01652 static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n)
01653 {
01654     int level, i, j, run;
01655     RLTable *rl = &rl_mpeg1;
01656     uint8_t * const scantable= s->intra_scantable.permutated;
01657     const int qscale= s->qscale;
01658 
01659     {
01660         OPEN_READER(re, &s->gb);
01661         i = -1;
01662         /* special case for the first coef. no need to add a second vlc table */
01663         UPDATE_CACHE(re, &s->gb);
01664         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
01665             level= (3*qscale)>>1;
01666             level= (level-1)|1;
01667             if(GET_CACHE(re, &s->gb)&0x40000000)
01668                 level= -level;
01669             block[0] = level;
01670             i++;
01671             SKIP_BITS(re, &s->gb, 2);
01672             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01673                 goto end;
01674         }
01675 
01676         /* now quantify & encode AC coefs */
01677         for(;;) {
01678             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01679             
01680             if(level != 0) {
01681                 i += run;
01682                 j = scantable[i];
01683                 level= ((level*2+1)*qscale)>>1;
01684                 level= (level-1)|1;
01685                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01686                 SKIP_BITS(re, &s->gb, 1);
01687             } else {
01688                 /* escape */
01689                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01690                 UPDATE_CACHE(re, &s->gb);
01691                 level = SHOW_SBITS(re, &s->gb, 8); SKIP_BITS(re, &s->gb, 8);
01692                 if (level == -128) {
01693                     level = SHOW_UBITS(re, &s->gb, 8) - 256; SKIP_BITS(re, &s->gb, 8);
01694                 } else if (level == 0) {
01695                     level = SHOW_UBITS(re, &s->gb, 8)      ; SKIP_BITS(re, &s->gb, 8);
01696                 }
01697                 i += run;
01698                 j = scantable[i];
01699                 if(level<0){
01700                     level= -level;
01701                     level= ((level*2+1)*qscale)>>1;
01702                     level= (level-1)|1;
01703                     level= -level;
01704                 }else{
01705                     level= ((level*2+1)*qscale)>>1;
01706                     level= (level-1)|1;
01707                 }
01708             }
01709 
01710             block[j] = level;
01711             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01712                 break;
01713             UPDATE_CACHE(re, &s->gb);
01714         }
01715 end:
01716         LAST_SKIP_BITS(re, &s->gb, 2);
01717         CLOSE_READER(re, &s->gb);
01718     }
01719     s->block_last_index[n] = i;
01720     return 0;
01721 }
01722 
01723 
01724 static inline int mpeg2_decode_block_non_intra(MpegEncContext *s, 
01725                                DCTELEM *block, 
01726                                int n)
01727 {
01728     int level, i, j, run;
01729     RLTable *rl = &rl_mpeg1;
01730     uint8_t * const scantable= s->intra_scantable.permutated;
01731     const uint16_t *quant_matrix;
01732     const int qscale= s->qscale;
01733     int mismatch;
01734 
01735     mismatch = 1;
01736 
01737     {
01738         OPEN_READER(re, &s->gb);
01739         i = -1;
01740         if (n < 4)
01741             quant_matrix = s->inter_matrix;
01742         else
01743             quant_matrix = s->chroma_inter_matrix;
01744 
01745         /* special case for the first coef. no need to add a second vlc table */
01746         UPDATE_CACHE(re, &s->gb);
01747         if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
01748             level= (3*qscale*quant_matrix[0])>>5;
01749             if(GET_CACHE(re, &s->gb)&0x40000000)
01750                 level= -level;
01751             block[0] = level;
01752             mismatch ^= level;
01753             i++;
01754             SKIP_BITS(re, &s->gb, 2);
01755             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01756                 goto end;
01757         }
01758 
01759         /* now quantify & encode AC coefs */
01760         for(;;) {
01761             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01762             
01763             if(level != 0) {
01764                 i += run;
01765                 j = scantable[i];
01766                 level= ((level*2+1)*qscale*quant_matrix[j])>>5;
01767                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01768                 SKIP_BITS(re, &s->gb, 1);
01769             } else {
01770                 /* escape */
01771                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01772                 UPDATE_CACHE(re, &s->gb);
01773                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
01774 
01775                 i += run;
01776                 j = scantable[i];
01777                 if(level<0){
01778                     level= ((-level*2+1)*qscale*quant_matrix[j])>>5;
01779                     level= -level;
01780                 }else{
01781                     level= ((level*2+1)*qscale*quant_matrix[j])>>5;
01782                 }
01783             }
01784             if (i > 63){
01785                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
01786                 return -1;
01787             }
01788             
01789             mismatch ^= level;
01790             block[j] = level;
01791             if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01792                 break;
01793             UPDATE_CACHE(re, &s->gb);
01794         }
01795 end:
01796         LAST_SKIP_BITS(re, &s->gb, 2);
01797         CLOSE_READER(re, &s->gb);
01798     }
01799     block[63] ^= (mismatch & 1);
01800     
01801     s->block_last_index[n] = i;
01802     return 0;
01803 }
01804 
01805 static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, 
01806                                DCTELEM *block, 
01807                                int n)
01808 {
01809     int level, i, j, run;
01810     RLTable *rl = &rl_mpeg1;
01811     uint8_t * const scantable= s->intra_scantable.permutated;
01812     const int qscale= s->qscale;
01813     int v;
01814     OPEN_READER(re, &s->gb);
01815     i = -1;
01816 
01817     /* special case for the first coef. no need to add a second vlc table */
01818     UPDATE_CACHE(re, &s->gb);
01819     if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {
01820         level= (3*qscale)>>1;
01821         if(GET_CACHE(re, &s->gb)&0x40000000)
01822             level= -level;
01823         block[0] = level;
01824         i++;
01825         SKIP_BITS(re, &s->gb, 2);
01826         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01827             goto end;
01828     }
01829 
01830     /* now quantify & encode AC coefs */
01831     for(;;) {
01832         GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01833         
01834         if(level != 0) {
01835             i += run;
01836             j = scantable[i];
01837             level= ((level*2+1)*qscale)>>1;
01838             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01839             SKIP_BITS(re, &s->gb, 1);
01840         } else {
01841             /* escape */
01842             run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01843             UPDATE_CACHE(re, &s->gb);
01844             level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
01845 
01846             i += run;
01847             j = scantable[i];
01848             if(level<0){
01849                 level= ((-level*2+1)*qscale)>>1;
01850                 level= -level;
01851             }else{
01852                 level= ((level*2+1)*qscale)>>1;
01853             }
01854         }
01855         
01856         block[j] = level;
01857         if(((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
01858             break;
01859         UPDATE_CACHE(re, &s->gb);
01860     }
01861 end:
01862     LAST_SKIP_BITS(re, &s->gb, 2);    
01863     CLOSE_READER(re, &s->gb);
01864     s->block_last_index[n] = i;
01865     return 0;
01866 }
01867 
01868 
01869 static inline int mpeg2_decode_block_intra(MpegEncContext *s, 
01870                                DCTELEM *block, 
01871                                int n)
01872 {
01873     int level, dc, diff, i, j, run;
01874     int component;
01875     RLTable *rl;
01876     uint8_t * const scantable= s->intra_scantable.permutated;
01877     const uint16_t *quant_matrix;
01878     const int qscale= s->qscale;
01879     int mismatch;
01880 
01881     /* DC coef */
01882     if (n < 4){
01883         quant_matrix = s->intra_matrix;
01884         component = 0; 
01885     }else{
01886         quant_matrix = s->chroma_intra_matrix;
01887         component = (n&1) + 1;
01888     }
01889     diff = decode_dc(&s->gb, component);
01890     if (diff >= 0xffff)
01891         return -1;
01892     dc = s->last_dc[component];
01893     dc += diff;
01894     s->last_dc[component] = dc;
01895     block[0] = dc << (3 - s->intra_dc_precision);
01896     dprintf("dc=%d\n", block[0]);
01897     mismatch = block[0] ^ 1;
01898     i = 0;
01899     if (s->intra_vlc_format)
01900         rl = &rl_mpeg2;
01901     else
01902         rl = &rl_mpeg1;
01903 
01904     {
01905         OPEN_READER(re, &s->gb);    
01906         /* now quantify & encode AC coefs */
01907         for(;;) {
01908             UPDATE_CACHE(re, &s->gb);
01909             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01910             
01911             if(level == 127){
01912                 break;
01913             } else if(level != 0) {
01914                 i += run;
01915                 j = scantable[i];
01916                 level= (level*qscale*quant_matrix[j])>>4;
01917                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01918                 LAST_SKIP_BITS(re, &s->gb, 1);
01919             } else {
01920                 /* escape */
01921                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01922                 UPDATE_CACHE(re, &s->gb);
01923                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
01924                 i += run;
01925                 j = scantable[i];
01926                 if(level<0){
01927                     level= (-level*qscale*quant_matrix[j])>>4;
01928                     level= -level;
01929                 }else{
01930                     level= (level*qscale*quant_matrix[j])>>4;
01931                 }
01932             }
01933             if (i > 63){
01934                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
01935                 return -1;
01936             }
01937             
01938             mismatch^= level;
01939             block[j] = level;
01940         }
01941         CLOSE_READER(re, &s->gb);
01942     }
01943     block[63]^= mismatch&1;
01944     
01945     s->block_last_index[n] = i;
01946     return 0;
01947 }
01948 
01949 static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, 
01950                                DCTELEM *block, 
01951                                int n)
01952 {
01953     int level, dc, diff, j, run;
01954     int component;
01955     RLTable *rl;
01956     uint8_t * scantable= s->intra_scantable.permutated;
01957     const uint16_t *quant_matrix;
01958     const int qscale= s->qscale;
01959 
01960     /* DC coef */
01961     if (n < 4){
01962         quant_matrix = s->intra_matrix;
01963         component = 0; 
01964     }else{
01965         quant_matrix = s->chroma_intra_matrix;
01966         component = (n&1) + 1;
01967     }
01968     diff = decode_dc(&s->gb, component);
01969     if (diff >= 0xffff)
01970         return -1;
01971     dc = s->last_dc[component];
01972     dc += diff;
01973     s->last_dc[component] = dc;
01974     block[0] = dc << (3 - s->intra_dc_precision);
01975     if (s->intra_vlc_format)
01976         rl = &rl_mpeg2;
01977     else
01978         rl = &rl_mpeg1;
01979 
01980     {
01981         OPEN_READER(re, &s->gb);    
01982         /* now quantify & encode AC coefs */
01983         for(;;) {
01984             UPDATE_CACHE(re, &s->gb);
01985             GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
01986             
01987             if(level == 127){
01988                 break;
01989             } else if(level != 0) {
01990                 scantable += run;
01991                 j = *scantable;
01992                 level= (level*qscale*quant_matrix[j])>>4;
01993                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
01994                 LAST_SKIP_BITS(re, &s->gb, 1);
01995             } else {
01996                 /* escape */
01997                 run = SHOW_UBITS(re, &s->gb, 6)+1; LAST_SKIP_BITS(re, &s->gb, 6);
01998                 UPDATE_CACHE(re, &s->gb);
01999                 level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);
02000                 scantable += run;
02001                 j = *scantable;
02002                 if(level<0){
02003                     level= (-level*qscale*quant_matrix[j])>>4;
02004                     level= -level;
02005                 }else{
02006                     level= (level*qscale*quant_matrix[j])>>4;
02007                 }
02008             }
02009             
02010             block[j] = level;
02011         }
02012         CLOSE_READER(re, &s->gb);
02013     }
02014     
02015     s->block_last_index[n] = scantable - s->intra_scantable.permutated;
02016     return 0;
02017 }
02018 
02019 typedef struct Mpeg1Context {
02020     MpegEncContext mpeg_enc_ctx;
02021     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
02022     int repeat_field; /* true if we must repeat the field */
02023     AVPanScan pan_scan; 
02024     int slice_count;
02025     int swap_uv;//indicate VCR2
02026     int save_aspect_info;
02027     AVRational frame_rate_ext;       
02028 
02029 } Mpeg1Context;
02030 
02031 static int mpeg_decode_init(AVCodecContext *avctx)
02032 {
02033     Mpeg1Context *s = avctx->priv_data;
02034     MpegEncContext *s2 = &s->mpeg_enc_ctx;
02035     int i;
02036     
02037     //we need some parmutation to store
02038     //matrixes, until MPV_common_init()
02039     //set the real permutatuon 
02040     for(i=0;i<64;i++)
02041        s2->dsp.idct_permutation[i]=i;
02042 
02043     MPV_decode_defaults(s2);
02044     
02045     s->mpeg_enc_ctx.avctx= avctx;
02046     s->mpeg_enc_ctx.flags= avctx->flags;
02047     s->mpeg_enc_ctx.flags2= avctx->flags2;
02048     common_init(&s->mpeg_enc_ctx);
02049     init_vlcs();
02050 
02051     s->mpeg_enc_ctx_allocated = 0;
02052     s->mpeg_enc_ctx.picture_number = 0;
02053     s->repeat_field = 0;
02054     s->mpeg_enc_ctx.codec_id= avctx->codec->id;
02055     return 0;
02056 }
02057 
02058 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm, 
02059                                      const uint8_t *new_perm){
02060     uint16_t temp_matrix[64];
02061     int i;
02062 
02063     memcpy(temp_matrix,matrix,64*sizeof(uint16_t));
02064     
02065     for(i=0;i<64;i++){
02066         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
02067     }      
02068 }
02069 
02070 //Call this function when we know all parameters
02071 //it may be called in different places for mpeg1 and mpeg2
02072 static int mpeg_decode_postinit(AVCodecContext *avctx){
02073     Mpeg1Context *s1 = avctx->priv_data;
02074     MpegEncContext *s = &s1->mpeg_enc_ctx;
02075     uint8_t old_permutation[64];
02076 
02077     if (
02078         (s1->mpeg_enc_ctx_allocated == 0)|| 
02079         avctx->coded_width  != s->width ||
02080         avctx->coded_height != s->height||
02081         s1->save_aspect_info != s->aspect_ratio_info||
02082         0)
02083     {
02084     
02085         if (s1->mpeg_enc_ctx_allocated) {
02086             ParseContext pc= s->parse_context;
02087             s->parse_context.buffer=0;
02088             MPV_common_end(s);
02089             s->parse_context= pc;
02090         }
02091 
02092         if( (s->width == 0 )||(s->height == 0))
02093             return -2;
02094 
02095         avcodec_set_dimensions(avctx, s->width, s->height);
02096         avctx->bit_rate = s->bit_rate;
02097         s1->save_aspect_info = s->aspect_ratio_info;
02098 
02099      //low_delay may be forced, in this case we will have B frames
02100      //that behave like P frames
02101         avctx->has_b_frames = !(s->low_delay);
02102 
02103         if(avctx->sub_id==1){//s->codec_id==avctx->codec_id==CODEC_ID
02104             //mpeg1 fps
02105             avctx->time_base.den     = frame_rate_tab[s->frame_rate_index].num;
02106             avctx->time_base.num= frame_rate_tab[s->frame_rate_index].den;
02107             //mpeg1 aspect
02108             avctx->sample_aspect_ratio= av_d2q(
02109                     1.0/mpeg1_aspect[s->aspect_ratio_info], 255);
02110 
02111         }else{//mpeg2
02112         //mpeg2 fps
02113             av_reduce(
02114                 &s->avctx->time_base.den, 
02115                 &s->avctx->time_base.num, 
02116                 frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num,
02117                 frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
02118                 1<<30);
02119         //mpeg2 aspect
02120             if(s->aspect_ratio_info > 1){
02121                 if( (s1->pan_scan.width == 0 )||(s1->pan_scan.height == 0) ){
02122                     s->avctx->sample_aspect_ratio= 
02123                         av_div_q(
02124                          mpeg2_aspect[s->aspect_ratio_info], 
02125                          (AVRational){s->width, s->height}
02126                          );
02127                 }else{
02128                     s->avctx->sample_aspect_ratio= 
02129                         av_div_q(
02130                          mpeg2_aspect[s->aspect_ratio_info], 
02131                          (AVRational){s1->pan_scan.width, s1->pan_scan.height}
02132                         );
02133                 }
02134             }else{
02135                 s->avctx->sample_aspect_ratio= 
02136                     mpeg2_aspect[s->aspect_ratio_info];
02137             }
02138         }//mpeg2
02139 
02140         if(avctx->xvmc_acceleration){
02141             avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
02142         }else{
02143             if(s->chroma_format <  2){
02144                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
02145             }else
02146             if(s->chroma_format == 2){
02147                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_422);
02148             }else
02149             if(s->chroma_format >  2){
02150                 avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_444);
02151             }
02152         }
02153         //until then pix_fmt may be changed right after codec init
02154         if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
02155             if( avctx->idct_algo == FF_IDCT_AUTO )
02156                 avctx->idct_algo = FF_IDCT_SIMPLE;
02157 
02158         //quantization matrixes may need reordering 
02159         //if dct permutation is changed
02160         memcpy(old_permutation,s->dsp.idct_permutation,64*sizeof(uint8_t));
02161 
02162         if (MPV_common_init(s) < 0)
02163             return -2;
02164 
02165         quant_matrix_rebuild(s->intra_matrix,       old_permutation,s->dsp.idct_permutation);
02166         quant_matrix_rebuild(s->inter_matrix,       old_permutation,s->dsp.idct_permutation);
02167         quant_matrix_rebuild(s->chroma_intra_matrix,old_permutation,s->dsp.idct_permutation);
02168         quant_matrix_rebuild(s->chroma_inter_matrix,old_permutation,s->dsp.idct_permutation);
02169 
02170         s1->mpeg_enc_ctx_allocated = 1;
02171     }
02172     return 0;
02173 }
02174 
02175 /* return the 8 bit start code value and update the search
02176    state. Return -1 if no start code found */
02177 static int find_start_code(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
02178 {
02179     const uint8_t *buf_ptr= *pbuf_ptr;
02180 
02181     buf_ptr++; //gurantees that -1 is within the array
02182     buf_end -= 2; // gurantees that +2 is within the array
02183 
02184     while (buf_ptr < buf_end) {
02185         if(*buf_ptr==0){
02186             while(buf_ptr < buf_end && buf_ptr[1]==0)
02187                 buf_ptr++;
02188 
02189             if(buf_ptr[-1] == 0 && buf_ptr[1] == 1){
02190                 *pbuf_ptr = buf_ptr+3;
02191                 return buf_ptr[2] + 0x100;
02192             }
02193         }
02194         buf_ptr += 2;
02195     }
02196     buf_end += 2; //undo the hack above
02197     
02198     *pbuf_ptr = buf_end;
02199     return -1;
02200 }
02201 
02202 static int mpeg1_decode_picture(AVCodecContext *avctx, 
02203                                 const uint8_t *buf, int buf_size)
02204 {
02205     Mpeg1Context *s1 = avctx->priv_data;
02206     MpegEncContext *s = &s1->mpeg_enc_ctx;
02207     int ref, f_code, vbv_delay;
02208 
02209     if(mpeg_decode_postinit(s->avctx) < 0) 
02210        return -2;
02211 
02212     init_get_bits(&s->gb, buf, buf_size*8);
02213 
02214     ref = get_bits(&s->gb, 10); /* temporal ref */
02215     s->pict_type = get_bits(&s->gb, 3);
02216     if(s->pict_type == 0 || s->pict_type > 3)
02217         return -1;
02218 
02219     vbv_delay= get_bits(&s->gb, 16);
02220     if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
02221         s->full_pel[0] = get_bits1(&s->gb);
02222         f_code = get_bits(&s->gb, 3);
02223         if (f_code == 0 && avctx->error_resilience >= FF_ER_COMPLIANT)
02224             return -1;
02225         s->mpeg_f_code[0][0] = f_code;
02226         s->mpeg_f_code[0][1] = f_code;
02227     }
02228     if (s->pict_type == B_TYPE) {
02229         s->full_pel[1] = get_bits1(&s->gb);
02230         f_code = get_bits(&s->gb, 3);
02231         if (f_code == 0 && avctx->error_resilience >= FF_ER_COMPLIANT)
02232             return -1;
02233         s->mpeg_f_code[1][0] = f_code;
02234         s->mpeg_f_code[1][1] = f_code;
02235     }
02236     s->current_picture.pict_type= s->pict_type;
02237     s->current_picture.key_frame= s->pict_type == I_TYPE;
02238     
02239     if(avctx->debug & FF_DEBUG_PICT_INFO)
02240         av_log(avctx, AV_LOG_DEBUG, "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
02241     
02242     s->y_dc_scale = 8;
02243     s->c_dc_scale = 8;
02244     s->first_slice = 1;
02245     return 0;
02246 }
02247 
02248 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
02249 {
02250     MpegEncContext *s= &s1->mpeg_enc_ctx;
02251     int horiz_size_ext, vert_size_ext;
02252     int bit_rate_ext;
02253 
02254     skip_bits(&s->gb, 1); /* profil and level esc*/
02255     s->avctx->profile= get_bits(&s->gb, 3);
02256     s->avctx->level= get_bits(&s->gb, 4);
02257     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
02258     s->chroma_format = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
02259     horiz_size_ext = get_bits(&s->gb, 2);
02260     vert_size_ext = get_bits(&s->gb, 2);
02261     s->width |= (horiz_size_ext << 12);
02262     s->height |= (vert_size_ext << 12);
02263     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
02264     s->bit_rate += (bit_rate_ext << 18) * 400;
02265     skip_bits1(&s->gb); /* marker */
02266     s->avctx->rc_buffer_size += get_bits(&s->gb, 8)*1024*16<<10;
02267 
02268     s->low_delay = get_bits1(&s->gb);
02269     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
02270 
02271     s1->frame_rate_ext.num = get_bits(&s->gb, 2)+1;
02272     s1->frame_rate_ext.den = get_bits(&s->gb, 5)+1;
02273 
02274     dprintf("sequence extension\n");
02275     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
02276     s->avctx->sub_id = 2; /* indicates mpeg2 found */
02277 
02278     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
02279         av_log(s->avctx, AV_LOG_DEBUG, "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n", 
02280                s->avctx->profile, s->avctx->level, s->avctx->rc_buffer_size, s->bit_rate);
02281 
02282 }
02283 
02284 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
02285 {
02286     MpegEncContext *s= &s1->mpeg_enc_ctx;
02287     int color_description, w, h;
02288 
02289     skip_bits(&s->gb, 3); /* video format */
02290     color_description= get_bits1(&s->gb);
02291     if(color_description){
02292         skip_bits(&s->gb, 8); /* color primaries */
02293         skip_bits(&s->gb, 8); /* transfer_characteristics */
02294         skip_bits(&s->gb, 8); /* matrix_coefficients */
02295     }
02296     w= get_bits(&s->gb, 14);
02297     skip_bits(&s->gb, 1); //marker
02298     h= get_bits(&s->gb, 14);
02299     skip_bits(&s->gb, 1); //marker
02300     
02301     s1->pan_scan.width= 16*w;
02302     s1->pan_scan.height=16*h;
02303         
02304     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
02305         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
02306 }
02307 
02308 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
02309 {
02310     MpegEncContext *s= &s1->mpeg_enc_ctx;
02311     int i,nofco;
02312 
02313     nofco = 1;
02314     if(s->progressive_sequence){
02315         if(s->repeat_first_field){
02316             nofco++;
02317             if(s->top_field_first)
02318                 nofco++;        
02319         }
02320     }else{
02321         if(s->picture_structure == PICT_FRAME){
02322             nofco++;
02323             if(s->repeat_first_field)
02324                 nofco++;
02325         }
02326     }
02327     for(i=0; i<nofco; i++){
02328         s1->pan_scan.position[i][0]= get_sbits(&s->gb, 16);
02329         skip_bits(&s->gb, 1); //marker
02330         s1->pan_scan.position[i][1]= get_sbits(&s->gb, 16);
02331         skip_bits(&s->gb, 1); //marker
02332     }
02333    
02334     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
02335         av_log(s->avctx, AV_LOG_DEBUG, "pde (%d,%d) (%d,%d) (%d,%d)\n", 
02336             s1->pan_scan.position[0][0], s1->pan_scan.position[0][1], 
02337             s1->pan_scan.position[1][0], s1->pan_scan.position[1][1], 
02338             s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]
02339         );
02340 }
02341 
02342 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
02343 {
02344     int i, v, j;
02345 
02346     dprintf("matrix extension\n");
02347 
02348     if (get_bits1(&s->gb)) {
02349         for(i=0;i<64;i++) {
02350             v = get_bits(&s->gb, 8);
02351             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02352             s->intra_matrix[j] = v;
02353             s->chroma_intra_matrix[j] = v;
02354         }
02355     }
02356     if (get_bits1(&s->gb)) {
02357         for(i=0;i<64;i++) {
02358             v = get_bits(&s->gb, 8);
02359             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02360             s->inter_matrix[j] = v;
02361             s->chroma_inter_matrix[j] = v;
02362         }
02363     }
02364     if (get_bits1(&s->gb)) {
02365         for(i=0;i<64;i++) {
02366             v = get_bits(&s->gb, 8);
02367             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02368             s->chroma_intra_matrix[j] = v;
02369         }
02370     }
02371     if (get_bits1(&s->gb)) {
02372         for(i=0;i<64;i++) {
02373             v = get_bits(&s->gb, 8);
02374             j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02375             s->chroma_inter_matrix[j] = v;
02376         }
02377     }
02378 }
02379 
02380 static void mpeg_decode_picture_coding_extension(MpegEncContext *s)
02381 {
02382     s->full_pel[0] = s->full_pel[1] = 0;
02383     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
02384     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
02385     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
02386     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
02387     s->intra_dc_precision = get_bits(&s->gb, 2);
02388     s->picture_structure = get_bits(&s->gb, 2);
02389     s->top_field_first = get_bits1(&s->gb);
02390     s->frame_pred_frame_dct = get_bits1(&s->gb);
02391     s->concealment_motion_vectors = get_bits1(&s->gb);
02392     s->q_scale_type = get_bits1(&s->gb);
02393     s->intra_vlc_format = get_bits1(&s->gb);
02394     s->alternate_scan = get_bits1(&s->gb);
02395     s->repeat_first_field = get_bits1(&s->gb);
02396     s->chroma_420_type = get_bits1(&s->gb);
02397     s->progressive_frame = get_bits1(&s->gb);
02398 
02399     if(s->picture_structure == PICT_FRAME)
02400         s->first_field=0;
02401     else{
02402         s->first_field ^= 1;
02403         memset(s->mbskip_table, 0, s->mb_stride*s->mb_height);
02404     }
02405     
02406     if(s->alternate_scan){
02407         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
02408         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
02409     }else{
02410         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
02411         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
02412     }
02413     
02414     /* composite display not parsed */
02415     dprintf("intra_dc_precision=%d\n", s->intra_dc_precision);
02416     dprintf("picture_structure=%d\n", s->picture_structure);
02417     dprintf("top field first=%d\n", s->top_field_first);
02418     dprintf("repeat first field=%d\n", s->repeat_first_field);
02419     dprintf("conceal=%d\n", s->concealment_motion_vectors);
02420     dprintf("intra_vlc_format=%d\n", s->intra_vlc_format);
02421     dprintf("alternate_scan=%d\n", s->alternate_scan);
02422     dprintf("frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
02423     dprintf("progressive_frame=%d\n", s->progressive_frame);
02424 }
02425 
02426 static void mpeg_decode_extension(AVCodecContext *avctx, 
02427                                   const uint8_t *buf, int buf_size)
02428 {
02429     Mpeg1Context *s1 = avctx->priv_data;
02430     MpegEncContext *s = &s1->mpeg_enc_ctx;
02431     int ext_type;
02432 
02433     init_get_bits(&s->gb, buf, buf_size*8);
02434     
02435     ext_type = get_bits(&s->gb, 4);
02436     switch(ext_type) {
02437     case 0x1:
02438         mpeg_decode_sequence_extension(s1);
02439         break;
02440     case 0x2:
02441         mpeg_decode_sequence_display_extension(s1);
02442         break;
02443     case 0x3:
02444         mpeg_decode_quant_matrix_extension(s);
02445         break;
02446     case 0x7:
02447         mpeg_decode_picture_display_extension(s1);
02448         break;
02449     case 0x8:
02450         mpeg_decode_picture_coding_extension(s);
02451         break;
02452     }
02453 }
02454 
02455 static void exchange_uv(MpegEncContext *s){
02456     short * tmp = s->pblocks[4];
02457     s->pblocks[4] = s->pblocks[5];
02458     s->pblocks[5] = tmp;
02459 }
02460 
02461 static int mpeg_field_start(MpegEncContext *s){
02462     AVCodecContext *avctx= s->avctx;
02463     Mpeg1Context *s1 = (Mpeg1Context*)s;
02464 
02465     /* start frame decoding */
02466     if(s->first_field || s->picture_structure==PICT_FRAME){
02467         if(MPV_frame_start(s, avctx) < 0)
02468             return -1;
02469 
02470         ff_er_frame_start(s);
02471 
02472         /* first check if we must repeat the frame */
02473         s->current_picture_ptr->repeat_pict = 0;
02474         if (s->repeat_first_field) {
02475             if (s->progressive_sequence) {
02476                 if (s->top_field_first)
02477                     s->current_picture_ptr->repeat_pict = 4;
02478                 else
02479                     s->current_picture_ptr->repeat_pict = 2;
02480             } else if (s->progressive_frame) {
02481                 s->current_picture_ptr->repeat_pict = 1;
02482             }
02483         }         
02484 
02485         *s->current_picture_ptr->pan_scan= s1->pan_scan;
02486     }else{ //second field
02487             int i;
02488             
02489             if(!s->current_picture_ptr){
02490                 av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
02491                 return -1;
02492             }
02493             
02494             for(i=0; i<4; i++){
02495                 s->current_picture.data[i] = s->current_picture_ptr->data[i];
02496                 if(s->picture_structure == PICT_BOTTOM_FIELD){
02497                     s->current_picture.data[i] += s->current_picture_ptr->linesize[i];
02498                 } 
02499             }
02500     }
02501 #ifdef HAVE_XVMC
02502 // MPV_frame_start will call this function too,
02503 // but we need to call it on every field
02504     if(s->avctx->xvmc_acceleration)
02505          XVMC_field_start(s,avctx);
02506 #endif
02507 
02508     return 0;
02509 }
02510 
02511 #define DECODE_SLICE_ERROR -1
02512 #define DECODE_SLICE_OK 0
02513 
02519 static int mpeg_decode_slice(Mpeg1Context *s1, int mb_y,
02520                              const uint8_t **buf, int buf_size)
02521 {
02522     MpegEncContext *s = &s1->mpeg_enc_ctx;
02523     AVCodecContext *avctx= s->avctx;
02524     int ret;
02525     const int field_pic= s->picture_structure != PICT_FRAME;
02526     const int lowres= s->avctx->lowres;
02527 
02528     s->resync_mb_x=
02529     s->resync_mb_y= -1;
02530 
02531     if (mb_y<<field_pic >= s->mb_height){
02532         av_log(s->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s->mb_height);
02533         return -1;
02534     }
02535     
02536     init_get_bits(&s->gb, *buf, buf_size*8);
02537 
02538     ff_mpeg1_clean_buffers(s);
02539     s->interlaced_dct = 0;
02540 
02541     s->qscale = get_qscale(s);
02542 
02543     if(s->qscale == 0){
02544         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
02545         return -1;
02546     }
02547     
02548     /* extra slice info */
02549     while (get_bits1(&s->gb) != 0) {
02550         skip_bits(&s->gb, 8);
02551     }
02552     
02553     s->mb_x=0;
02554 
02555     for(;;) {
02556         int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
02557         if (code < 0){
02558             av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
02559             return -1;
02560         }
02561         if (code >= 33) {
02562             if (code == 33) {
02563                 s->mb_x += 33;
02564             }
02565             /* otherwise, stuffing, nothing to do */
02566         } else {
02567             s->mb_x += code;
02568             break;
02569         }
02570     }
02571 
02572     s->resync_mb_x= s->mb_x;
02573     s->resync_mb_y= s->mb_y= mb_y;
02574     s->mb_skip_run= 0;
02575     ff_init_block_index(s);
02576 
02577     if (s->mb_y==0 && s->mb_x==0 && (s->first_field || s->picture_structure==PICT_FRAME)) {
02578         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
02579              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", 
02580                  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],
02581                  s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")), 
02582                  s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"", 
02583                  s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
02584                  s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
02585         }
02586     }    
02587     
02588     for(;;) {
02589 #ifdef HAVE_XVMC
02590         //one 1 we memcpy blocks in xvmcvideo
02591         if(s->avctx->xvmc_acceleration > 1)
02592             XVMC_init_block(s);//set s->block
02593 #endif
02594 
02595         ret = mpeg_decode_mb(s, s->block);
02596         s->chroma_qscale= s->qscale;
02597 
02598         dprintf("ret=%d\n", ret);
02599         if (ret < 0)
02600             return -1;
02601 
02602         if(s->current_picture.motion_val[0] && !s->encoding){ //note motion_val is normally NULL unless we want to extract the MVs
02603             const int wrap = field_pic ? 2*s->b8_stride : s->b8_stride;
02604             int xy = s->mb_x*2 + s->mb_y*2*wrap;
02605             int motion_x, motion_y, dir, i;
02606             if(field_pic && !s->first_field)
02607                 xy += wrap/2;
02608 
02609             for(i=0; i<2; i++){
02610                 for(dir=0; dir<2; dir++){
02611                     if (s->mb_intra || (dir==1 && s->pict_type != B_TYPE)) {
02612                         motion_x = motion_y = 0;
02613                     }else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)){
02614                         motion_x = s->mv[dir][0][0];
02615                         motion_y = s->mv[dir][0][1];
02616                     } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ {
02617                         motion_x = s->mv[dir][i][0];
02618                         motion_y = s->mv[dir][i][1];
02619                     }
02620 
02621                     s->current_picture.motion_val[dir][xy    ][0] = motion_x;
02622                     s->current_picture.motion_val[dir][xy    ][1] = motion_y;
02623                     s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
02624                     s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
02625                     s->current_picture.ref_index [dir][xy    ]=
02626                     s->current_picture.ref_index [dir][xy + 1]= s->field_select[dir][i];
02627                     assert(s->field_select[dir][i]==0 || s->field_select[dir][i]==1);
02628                 }
02629                 xy += wrap;
02630             }
02631         }
02632 
02633         s->dest[0] += 16 >> lowres;
02634         s->dest[1] += 16 >> (s->chroma_x_shift + lowres);
02635         s->dest[2] += 16 >> (s->chroma_x_shift + lowres);
02636 
02637         MPV_decode_mb(s, s->block);
02638         
02639         if (++s->mb_x >= s->mb_width) {
02640             const int mb_size= 16>>s->avctx->lowres;
02641 
02642             ff_draw_horiz_band(s, mb_size*s->mb_y, mb_size);
02643 
02644             s->mb_x = 0;
02645             s->mb_y++;
02646 
02647             if(s->mb_y<<field_pic >= s->mb_height){
02648                 int left= s->gb.size_in_bits - get_bits_count(&s->gb);
02649 
02650                 if(left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23)))
02651                    || (avctx->error_resilience >= FF_ER_AGGRESSIVE && left>8)){
02652                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d\n", left);
02653                     return -1;
02654                 }else
02655                     goto eos;
02656             }
02657             
02658             ff_init_block_index(s);
02659         }
02660 
02661         /* skip mb handling */
02662         if (s->mb_skip_run == -1) {
02663             /* read again increment */
02664             s->mb_skip_run = 0;
02665             for(;;) {
02666                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
02667                 if (code < 0){
02668                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
02669                     return -1;
02670                 }
02671                 if (code >= 33) {
02672                     if (code == 33) {
02673                         s->mb_skip_run += 33;
02674                     }else if(code == 35){
02675                         if(s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0){
02676                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
02677                             return -1;
02678                         }
02679                         goto eos; /* end of slice */
02680                     }
02681                     /* otherwise, stuffing, nothing to do */
02682                 } else {
02683                     s->mb_skip_run += code;
02684                     break;
02685                 }
02686             }
02687         }
02688     }
02689 eos: // end of slice
02690     *buf += get_bits_count(&s->gb)/8 - 1;
02691 //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
02692     return 0;
02693 }
02694 
02695 static int slice_decode_thread(AVCodecContext *c, void *arg){
02696     MpegEncContext *s= arg;
02697     const uint8_t *buf= s->gb.buffer;
02698     int mb_y= s->start_mb_y;
02699 
02700     s->error_count= 3*(s->end_mb_y - s->start_mb_y)*s->mb_width;
02701 
02702     for(;;){
02703         int start_code, ret;
02704 
02705         ret= mpeg_decode_slice((Mpeg1Context*)s, mb_y, &buf, s->gb.buffer_end - buf);
02706         emms_c();
02707 //av_log(c, AV_LOG_DEBUG, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n", 
02708 //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);
02709         if(ret < 0){
02710             if(s->resync_mb_x>=0 && s->resync_mb_y>=0)
02711                 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);
02712         }else{
02713             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);
02714         }
02715         
02716         if(s->mb_y == s->end_mb_y)
02717             return 0;
02718         
02719         start_code = find_start_code(&buf, s->gb.buffer_end);
02720         mb_y= start_code - SLICE_MIN_START_CODE;
02721         if(mb_y < 0 || mb_y >= s->end_mb_y)
02722             return -1;
02723     }
02724     
02725     return 0; //not reached
02726 }
02727 
02732 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
02733 {
02734     Mpeg1Context *s1 = avctx->priv_data;
02735     MpegEncContext *s = &s1->mpeg_enc_ctx;
02736        
02737     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
02738         return 0;
02739 
02740 #ifdef HAVE_XVMC
02741     if(s->avctx->xvmc_acceleration)
02742         XVMC_field_end(s);
02743 #endif
02744     /* end of slice reached */
02745     if (/*s->mb_y<<field_pic == s->mb_height &&*/ !s->first_field) {
02746         /* end of image */
02747 
02748         s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_MPEG2;
02749 
02750         ff_er_frame_end(s);
02751 
02752         MPV_frame_end(s);
02753 
02754         if (s->pict_type == B_TYPE || s->low_delay) {
02755             *pict= *(AVFrame*)s->current_picture_ptr;
02756             ff_print_debug_info(s, pict);
02757         } else {
02758             s->picture_number++;
02759             /* latency of 1 frame for I and P frames */
02760             /* XXX: use another variable than picture_number */
02761             if (s->last_picture_ptr != NULL) {
02762                 *pict= *(AVFrame*)s->last_picture_ptr;
02763                  ff_print_debug_info(s, pict);
02764             }
02765         }
02766 
02767         return 1;
02768     } else {
02769         return 0;
02770     }
02771 }
02772 
02773 static int mpeg1_decode_sequence(AVCodecContext *avctx, 
02774                                  const uint8_t *buf, int buf_size)
02775 {
02776     Mpeg1Context *s1 = avctx->priv_data;
02777     MpegEncContext *s = &s1->mpeg_enc_ctx;
02778     int width,height;
02779     int i, v, j;
02780 
02781     init_get_bits(&s->gb, buf, buf_size*8);
02782 
02783     width = get_bits(&s->gb, 12);
02784     height = get_bits(&s->gb, 12);
02785     if (width <= 0 || height <= 0 ||
02786         (width % 2) != 0 || (height % 2) != 0)
02787         return -1;
02788     s->aspect_ratio_info= get_bits(&s->gb, 4);
02789     if (s->aspect_ratio_info == 0)
02790         return -1;
02791     s->frame_rate_index = get_bits(&s->gb, 4);
02792     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
02793         return -1;
02794     s->bit_rate = get_bits(&s->gb, 18) * 400;
02795     if (get_bits1(&s->gb) == 0) /* marker */
02796         return -1;
02797     s->width = width;
02798     s->height = height;
02799 
02800     s->avctx->rc_buffer_size= get_bits(&s->gb, 10) * 1024*16;
02801     skip_bits(&s->gb, 1);
02802 
02803     /* get matrix */
02804     if (get_bits1(&s->gb)) {
02805         for(i=0;i<64;i++) {
02806             v = get_bits(&s->gb, 8);
02807             if(v==0){
02808                 av_log(s->avctx, AV_LOG_ERROR, "intra matrix damaged\n");
02809                 return -1;
02810             }
02811             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02812             s->intra_matrix[j] = v;
02813             s->chroma_intra_matrix[j] = v;
02814         }
02815 #ifdef DEBUG
02816         dprintf("intra matrix present\n");
02817         for(i=0;i<64;i++)
02818             dprintf(" %d", s->intra_matrix[s->dsp.idct_permutation[i]]);
02819         printf("\n");
02820 #endif
02821     } else {
02822         for(i=0;i<64;i++) {
02823             j = s->dsp.idct_permutation[i];
02824             v = ff_mpeg1_default_intra_matrix[i];
02825             s->intra_matrix[j] = v;
02826             s->chroma_intra_matrix[j] = v;
02827         }
02828     }
02829     if (get_bits1(&s->gb)) {
02830         for(i=0;i<64;i++) {
02831             v = get_bits(&s->gb, 8);
02832             if(v==0){
02833                 av_log(s->avctx, AV_LOG_ERROR, "inter matrix damaged\n");
02834                 return -1;
02835             }
02836             j = s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
02837             s->inter_matrix[j] = v;
02838             s->chroma_inter_matrix[j] = v;
02839         }
02840 #ifdef DEBUG
02841         dprintf("non intra matrix present\n");
02842         for(i=0;i<64;i++)
02843             dprintf(" %d", s->inter_matrix[s->dsp.idct_permutation[i]]);
02844         printf("\n");
02845 #endif
02846     } else {
02847         for(i=0;i<64;i++) {
02848             int j= s->dsp.idct_permutation[i];
02849             v = ff_mpeg1_default_non_intra_matrix[i];
02850             s->inter_matrix[j] = v;
02851             s->chroma_inter_matrix[j] = v;
02852         }
02853     }
02854     
02855     if(show_bits(&s->gb, 23) != 0){
02856         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
02857         return -1;
02858     }
02859 
02860     /* we set mpeg2 parameters so that it emulates mpeg1 */
02861     s->progressive_sequence = 1;
02862     s->progressive_frame = 1;
02863     s->picture_structure = PICT_FRAME;
02864     s->frame_pred_frame_dct = 1;
02865     s->chroma_format = 1;
02866     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG1VIDEO;
02867     avctx->sub_id = 1; /* indicates mpeg1 */
02868     s->out_format = FMT_MPEG1;
02869     s->swap_uv = 0;//AFAIK VCR2 don't have SEQ_HEADER
02870     if(s->flags & CODEC_FLAG_LOW_DELAY) s->low_delay=1;
02871     
02872     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
02873         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n", 
02874                s->avctx->rc_buffer_size, s->bit_rate);
02875     
02876     return 0;
02877 }
02878 
02879 static int vcr2_init_sequence(AVCodecContext *avctx)
02880 {
02881     Mpeg1Context *s1 = avctx->priv_data;
02882     MpegEncContext *s = &s1->mpeg_enc_ctx;
02883     int i, v;
02884 
02885     /* start new mpeg1 context decoding */
02886     s->out_format = FMT_MPEG1;
02887     if (s1->mpeg_enc_ctx_allocated) {
02888         MPV_common_end(s);
02889     }
02890     s->width  = avctx->coded_width;
02891     s->height = avctx->coded_height;
02892     avctx->has_b_frames= 0; //true?
02893     s->low_delay= 1;
02894 
02895     if(avctx->xvmc_acceleration){
02896         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_xvmc_mpg2_420);
02897     }else{
02898         avctx->pix_fmt = avctx->get_format(avctx,pixfmt_yuv_420);
02899     }
02900 
02901     if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT )
02902         if( avctx->idct_algo == FF_IDCT_AUTO )
02903             avctx->idct_algo = FF_IDCT_SIMPLE;
02904     
02905     if (MPV_common_init(s) < 0)
02906         return -1;
02907     exchange_uv(s);//common init reset pblocks, so we swap them here
02908     s->swap_uv = 1;// in case of xvmc we need to swap uv for each MB 
02909     s1->mpeg_enc_ctx_allocated = 1;
02910 
02911     for(i=0;i<64;i++) {
02912         int j= s->dsp.idct_permutation[i];
02913         v = ff_mpeg1_default_intra_matrix[i];
02914         s->intra_matrix[j] = v;
02915         s->chroma_intra_matrix[j] = v;
02916 
02917         v = ff_mpeg1_default_non_intra_matrix[i];
02918         s->inter_matrix[j] = v;
02919         s->chroma_inter_matrix[j] = v;
02920     }
02921 
02922     s->progressive_sequence = 1;
02923     s->progressive_frame = 1;
02924     s->picture_structure = PICT_FRAME;
02925     s->frame_pred_frame_dct = 1;
02926     s->chroma_format = 1;
02927     s->codec_id= s->avctx->codec_id= CODEC_ID_MPEG2VIDEO;
02928     avctx->sub_id = 2; /* indicates mpeg2 */
02929     return 0;
02930 }
02931 
02932 
02933 static void mpeg_decode_user_data(AVCodecContext *avctx, 
02934                                   const uint8_t *buf, int buf_size)
02935 {
02936     const uint8_t *p;
02937     int len, flags;
02938     p = buf;
02939     len = buf_size;
02940 
02941     /* we parse the DTG active format information */
02942     if (len >= 5 &&
02943         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
02944         flags = p[4];
02945         p += 5;
02946         len -= 5;
02947         if (flags & 0x80) {
02948             /* skip event id */
02949             if (len < 2)
02950                 return;
02951             p += 2;
02952             len -= 2;
02953         }
02954         if (flags & 0x40) {
02955             if (len < 1)
02956                 return;
02957             avctx->dtg_active_format = p[0] & 0x0f;
02958         }
02959     }
02960 }
02961 
02962 static void mpeg_decode_gop(AVCodecContext *avctx, 
02963                             const uint8_t *buf, int buf_size){
02964     Mpeg1Context *s1 = avctx->priv_data;
02965     MpegEncContext *s = &s1->mpeg_enc_ctx;
02966 
02967     int drop_frame_flag;
02968     int time_code_hours, time_code_minutes;
02969     int time_code_seconds, time_code_pictures;
02970     int broken_link;
02971 
02972     init_get_bits(&s->gb, buf, buf_size*8);
02973 
02974     drop_frame_flag = get_bits1(&s->gb);
02975     
02976     time_code_hours=get_bits(&s->gb,5);
02977     time_code_minutes = get_bits(&s->gb,6);
02978     skip_bits1(&s->gb);//marker bit
02979     time_code_seconds = get_bits(&s->gb,6);
02980     time_code_pictures = get_bits(&s->gb,6);
02981 
02982     /*broken_link indicate that after editing the
02983       reference frames of the first B-Frames after GOP I-Frame
02984       are missing (open gop)*/
02985     broken_link = get_bits1(&s->gb);
02986 
02987     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
02988         av_log(s->avctx, AV_LOG_DEBUG, "GOP (%2d:%02d:%02d.[%02d]) broken_link=%d\n",
02989             time_code_hours, time_code_minutes, time_code_seconds,
02990             time_code_pictures, broken_link);
02991 }
02996 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size)
02997 {
02998     int i;
02999     uint32_t state;
03000     
03001     state= pc->state;
03002     
03003     i=0;
03004     if(!pc->frame_start_found){
03005         for(i=0; i<buf_size; i++){
03006             state= (state<<8) | buf[i];
03007             if(state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){
03008                 i++;
03009                 pc->frame_start_found=1;
03010                 break;
03011             }
03012         }
03013     }
03014     
03015     if(pc->frame_start_found){
03016         /* EOF considered as end of frame */
03017         if (buf_size == 0)
03018             return 0;
03019         for(; i<buf_size; i++){
03020             state= (state<<8) | buf[i];
03021             if((state&0xFFFFFF00) == 0x100){
03022                 if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){
03023                     pc->frame_start_found=0;
03024                     pc->state=-1; 
03025                     return i-3;
03026                 }
03027             }
03028         }
03029     }        
03030     pc->state= state;
03031     return END_NOT_FOUND;
03032 }
03033 
03034 /* handle buffering and image synchronisation */
03035 static int mpeg_decode_frame(AVCodecContext *avctx, 
03036                              void *data, int *data_size,
03037                              uint8_t *buf, int buf_size)
03038 {
03039     Mpeg1Context *s = avctx->priv_data;
03040     const uint8_t *buf_end;
03041     const uint8_t *buf_ptr;
03042     int ret, start_code, input_size;
03043     AVFrame *picture = data;
03044     MpegEncContext *s2 = &s->mpeg_enc_ctx;
03045     dprintf("fill_buffer\n");
03046 
03047     if (buf_size == 0) {
03048         /* special case for last picture */
03049         if (s2->low_delay==0 && s2->next_picture_ptr) {
03050             *picture= *(AVFrame*)s2->next_picture_ptr;
03051             s2->next_picture_ptr= NULL;
03052 
03053             *data_size = sizeof(AVFrame);
03054         }
03055         return 0;
03056     }
03057 
03058     if(s2->flags&CODEC_FLAG_TRUNCATED){
03059         int next= ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size);
03060         
03061         if( ff_combine_frame(&s2->parse_context, next, &buf, &buf_size) < 0 )
03062             return buf_size;
03063     }    
03064     
03065     buf_ptr = buf;
03066     buf_end = buf + buf_size;
03067 
03068 #if 0    
03069     if (s->repeat_field % 2 == 1) { 
03070         s->repeat_field++;
03071         //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,
03072         //        s2->picture_number, s->repeat_field);
03073         if (avctx->flags & CODEC_FLAG_REPEAT_FIELD) {
03074             *data_size = sizeof(AVPicture);
03075             goto the_end;
03076         }
03077     }
03078 #endif
03079 
03080     if(s->mpeg_enc_ctx_allocated==0 && avctx->codec_tag == ff_get_fourcc("VCR2"))
03081         vcr2_init_sequence(avctx);
03082     
03083     s->slice_count= 0;
03084         
03085     for(;;) {
03086         /* find start next code */
03087         start_code = find_start_code(&buf_ptr, buf_end);
03088         if (start_code < 0){
03089             if(s2->pict_type != B_TYPE || avctx->skip_frame <= AVDISCARD_DEFAULT){
03090                 if(avctx->thread_count > 1){
03091                     int i;
03092 
03093                     avctx->execute(avctx, slice_decode_thread,  (void**)&(s2->thread_context[0]), NULL, s->slice_count);
03094                     for(i=0; i<s->slice_count; i++)
03095                         s2->error_count += s2->thread_context[i]->error_count;
03096                 }
03097                 if (slice_end(avctx, picture)) {
03098                     if(s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
03099                         *data_size = sizeof(AVPicture);
03100                 }
03101             }
03102             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
03103         }
03104         
03105         input_size = buf_end - buf_ptr;
03106 
03107         if(avctx->debug & FF_DEBUG_STARTCODE){
03108             av_log(avctx, AV_LOG_DEBUG, "%3X at %zd left %d\n", start_code, buf_ptr-buf, input_size);
03109         }
03110 
03111                 /* prepare data for next start code */
03112                 switch(start_code) {
03113                 case SEQ_START_CODE:
03114                     mpeg1_decode_sequence(avctx, buf_ptr, 
03115                                           input_size);
03116                     break;
03117                             
03118                 case PICTURE_START_CODE:
03119                     /* we have a complete image : we try to decompress it */
03120                     mpeg1_decode_picture(avctx, 
03121                                          buf_ptr, input_size);
03122                     break;
03123                 case EXT_START_CODE:
03124                     mpeg_decode_extension(avctx,
03125                                           buf_ptr, input_size);
03126                     break;
03127                 case USER_START_CODE:
03128                     mpeg_decode_user_data(avctx, 
03129                                           buf_ptr, input_size);
03130                     break;
03131                 case GOP_START_CODE:
03132                     s2->first_field=0;
03133                     mpeg_decode_gop(avctx, 
03134                                           buf_ptr, input_size);
03135                     break;
03136                 default:
03137                     if (start_code >= SLICE_MIN_START_CODE &&
03138                         start_code <= SLICE_MAX_START_CODE) {
03139                         int mb_y= start_code - SLICE_MIN_START_CODE;
03140                         
03141                         if(s2->last_picture_ptr==NULL){
03142                         /* skip b frames if we dont have reference frames */
03143                             if(s2->pict_type==B_TYPE) break;
03144                         /* skip P frames if we dont have reference frame no valid header */
03145                             if(s2->pict_type==P_TYPE && !s2->first_slice) break;
03146                         }
03147                         /* skip b frames if we are in a hurry */
03148                         if(avctx->hurry_up && s2->pict_type==B_TYPE) break;
03149                         if(  (avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type==B_TYPE)
03150                            ||(avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type!=I_TYPE)
03151                            || avctx->skip_frame >= AVDISCARD_ALL)
03152                             break;
03153                         /* skip everything if we are in a hurry>=5 */
03154                         if(avctx->hurry_up>=5) break;
03155                         
03156                         if (!s->mpeg_enc_ctx_allocated) break;
03157 
03158                         if(s2->codec_id == CODEC_ID_MPEG2VIDEO){
03159                             if(mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
03160                                 break;
03161                         }
03162                         
03163                         if(s2->first_slice){
03164                             s2->first_slice=0;
03165                             if(mpeg_field_start(s2) < 0)
03166                                 return -1;
03167                         }
03168                         
03169                         if(avctx->thread_count > 1){
03170                             int threshold= (s2->mb_height*s->slice_count + avctx->thread_count/2) / avctx->thread_count;
03171                             if(threshold <= mb_y){
03172                                 MpegEncContext *thread_context= s2->thread_context[s->slice_count];
03173                                 
03174                                 thread_context->start_mb_y= mb_y;
03175                                 thread_context->end_mb_y  = s2->mb_height;
03176                                 if(s->slice_count){
03177                                     s2->thread_context[s->slice_count-1]->end_mb_y= mb_y;
03178                                     ff_update_duplicate_context(thread_context, s2);
03179                                 }
03180                                 init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
03181                                 s->slice_count++;
03182                             }
03183                             buf_ptr += 2; //FIXME add minimum num of bytes per slice
03184                         }else{
03185                             ret = mpeg_decode_slice(s, mb_y, &buf_ptr, input_size);
03186                             emms_c();
03187 
03188                             if(ret < 0){
03189                                 if(s2->resync_mb_x>=0 && s2->resync_mb_y>=0)
03190                                     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);
03191                             }else{
03192                                 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);
03193                             }
03194                         }
03195                     }
03196