]> git.sesse.net Git - ffmpeg/blobdiff - libavcodec/mpegvideo.c
per file doxy
[ffmpeg] / libavcodec / mpegvideo.c
index 7a15b761e4f04b03b92f0109074985cc50637e63..fbea1f94db5691e8c671cf2e1491694fa1eef936 100644 (file)
  *
  * 4MV & hq & b-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  */
+/**
+ * @file mpegvideo.c
+ * The simplest mpeg encoder (well, it was the simplest!).
+ */ 
+#include <ctype.h>
+#include <limits.h>
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "fastmemcpy.h"
 #endif
 
+//#undef NDEBUG
+//#include <assert.h>
+
+#ifdef CONFIG_ENCODERS
 static void encode_picture(MpegEncContext *s, int picture_number);
+#endif //CONFIG_ENCODERS
 static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                    DCTELEM *block, int n, int qscale);
 static void dct_unquantize_mpeg2_c(MpegEncContext *s,
                                    DCTELEM *block, int n, int qscale);
 static void dct_unquantize_h263_c(MpegEncContext *s, 
                                   DCTELEM *block, int n, int qscale);
-static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w);
+static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w);
+#ifdef CONFIG_ENCODERS
 static int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
+static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
+#endif //CONFIG_ENCODERS
 
-void (*draw_edges)(UINT8 *buf, int wrap, int width, int height, int w)= draw_edges_c;
-static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int block_w, int block_h, 
-                                    int src_x, int src_y, int w, int h);
+void (*draw_edges)(uint8_t *buf, int wrap, int width, int height, int w)= draw_edges_c;
 
-#define EDGE_WIDTH 16
 
 /* enable all paranoid tests for rounding, overflows, etc... */
 //#define PARANOID
@@ -51,7 +64,7 @@ static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int bl
 /* for jpeg fast DCT */
 #define CONST_BITS 14
 
-static const unsigned short aanscales[64] = {
+static const uint16_t aanscales[64] = {
     /* precomputed values scaled up by 14 bits */
     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
     22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
@@ -59,60 +72,61 @@ static const unsigned short aanscales[64] = {
     19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
     12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
-    8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
-    4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
+    8867 , 12299, 11585, 10426,  8867,  6967,  4799,  2446,
+    4520 ,  6270,  5906,  5315,  4520,  3552,  2446,  1247
 };
 
-static UINT8 h263_chroma_roundtab[16] = {
+static const uint8_t h263_chroma_roundtab[16] = {
+//  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
     0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
 };
 
-static UINT16 default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
-static UINT8 default_fcode_tab[MAX_MV*2+1];
-
-extern UINT8 zigzag_end[64];
+#ifdef CONFIG_ENCODERS
+static uint16_t (*default_mv_penalty)[MAX_MV*2+1]=NULL;
+static uint8_t default_fcode_tab[MAX_MV*2+1];
 
-/* default motion estimation */
-int motion_estimation_method = ME_EPZS;
+enum PixelFormat ff_yuv420p_list[2]= {PIX_FMT_YUV420P, -1};
 
 static void convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16)[64], uint16_t (*qmat16_bias)[64],
-                           const UINT16 *quant_matrix, int bias)
+                           const uint16_t *quant_matrix, int bias, int qmin, int qmax)
 {
     int qscale;
 
-    for(qscale=1; qscale<32; qscale++){
+    for(qscale=qmin; qscale<=qmax; qscale++){
         int i;
-        if (s->fdct == ff_jpeg_fdct_islow) {
+        if (s->dsp.fdct == ff_jpeg_fdct_islow) {
             for(i=0;i<64;i++) {
-                const int j= block_permute_op(i);
+                const int j= s->dsp.idct_permutation[i];
                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
                 
-                qmat[qscale][j] = (int)((UINT64_C(1) << QMAT_SHIFT) / 
+                qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) / 
                                 (qscale * quant_matrix[j]));
             }
-        } else if (s->fdct == fdct_ifast) {
+        } else if (s->dsp.fdct == fdct_ifast) {
             for(i=0;i<64;i++) {
-                const int j= block_permute_op(i);
+                const int j= s->dsp.idct_permutation[i];
                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
                 
-                qmat[qscale][j] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) / 
+                qmat[qscale][i] = (int)((uint64_t_C(1) << (QMAT_SHIFT + 14)) / 
                                 (aanscales[i] * qscale * quant_matrix[j]));
             }
         } else {
             for(i=0;i<64;i++) {
+                const int j= s->dsp.idct_permutation[i];
                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
                    So 16           <= qscale * quant_matrix[i]             <= 7905
                    so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
                    so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
                 */
-                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
-                qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[block_permute_op(i)]);
+                qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
+//                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
+                qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
 
                 if(qmat16[qscale][i]==0 || qmat16[qscale][i]==128*256) qmat16[qscale][i]=128*256-1;
                 qmat16_bias[qscale][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][i]);
@@ -120,6 +134,8 @@ static void convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16
         }
     }
 }
+#endif //CONFIG_ENCODERS
+
 // move into common.c perhaps 
 #define CHECKED_ALLOCZ(p, size)\
 {\
@@ -130,21 +146,40 @@ static void convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16
     }\
 }
 
-/* init common structure for both encoder and decoder */
-int MPV_common_init(MpegEncContext *s)
-{
-    int c_size, i;
-    UINT8 *pict;
+void ff_init_scantable(MpegEncContext *s, ScanTable *st, const uint8_t *src_scantable){
+    int i;
+    int end;
+    
+    st->scantable= src_scantable;
+
+    for(i=0; i<64; i++){
+        int j;
+        j = src_scantable[i];
+        st->permutated[i] = s->dsp.idct_permutation[j];
+#ifdef ARCH_POWERPC
+        st->inverse[j] = i;
+#endif
+    }
+    
+    end=-1;
+    for(i=0; i<64; i++){
+        int j;
+        j = st->permutated[i];
+        if(j>end) end=j;
+        st->raster_end[i]= end;
+    }
+}
 
+/* init common dct for both encoder and decoder */
+int DCT_common_init(MpegEncContext *s)
+{
     s->dct_unquantize_h263 = dct_unquantize_h263_c;
     s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
     s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
-    s->dct_quantize= dct_quantize_c;
 
-    if(s->avctx->dct_algo==FF_DCT_FASTINT)
-        s->fdct = fdct_ifast;
-    else
-        s->fdct = ff_jpeg_fdct_islow;
+#ifdef CONFIG_ENCODERS
+    s->dct_quantize= dct_quantize_c;
+#endif
         
 #ifdef HAVE_MMX
     MPV_common_init_mmx(s);
@@ -155,128 +190,216 @@ int MPV_common_init(MpegEncContext *s)
 #ifdef HAVE_MLIB
     MPV_common_init_mlib(s);
 #endif
+#ifdef HAVE_MMI
+    MPV_common_init_mmi(s);
+#endif
+#ifdef ARCH_ARMV4L
+    MPV_common_init_armv4l(s);
+#endif
+#ifdef ARCH_POWERPC
+    MPV_common_init_ppc(s);
+#endif
 
-    s->mb_width = (s->width + 15) / 16;
-    s->mb_height = (s->height + 15) / 16;
+#ifdef CONFIG_ENCODERS
+    s->fast_dct_quantize= s->dct_quantize;
+
+    if(s->flags&CODEC_FLAG_TRELLIS_QUANT){
+        s->dct_quantize= dct_quantize_trellis_c; //move before MPV_common_init_*
+    }
+
+#endif //CONFIG_ENCODERS
+
+    /* load & permutate scantables
+       note: only wmv uses differnt ones 
+    */
+    ff_init_scantable(s, &s->inter_scantable  , ff_zigzag_direct);
+    ff_init_scantable(s, &s->intra_scantable  , ff_zigzag_direct);
+    ff_init_scantable(s, &s->intra_h_scantable, ff_alternate_horizontal_scan);
+    ff_init_scantable(s, &s->intra_v_scantable, ff_alternate_vertical_scan);
+
+    s->picture_structure= PICT_FRAME;
     
-    /* set default edge pos, will be overriden in decode_header if needed */
-    s->h_edge_pos= s->mb_width*16;
-    s->v_edge_pos= s->mb_height*16;
+    return 0;
+}
 
-    s->mb_num = s->mb_width * s->mb_height;
-    if(!(s->flags&CODEC_FLAG_DR1)){
-      s->linesize   = s->mb_width * 16 + 2 * EDGE_WIDTH;
-      s->uvlinesize = s->mb_width * 8  +     EDGE_WIDTH;
-
-      for(i=0;i<3;i++) {
-        int w, h, shift, pict_start;
-
-        w = s->linesize;
-        h = s->mb_height * 16 + 2 * EDGE_WIDTH;
-        shift = (i == 0) ? 0 : 1;
-        c_size = (s->linesize>>shift) * (h >> shift);
-        pict_start = (s->linesize>>shift) * (EDGE_WIDTH >> shift) + (EDGE_WIDTH >> shift);
-
-        CHECKED_ALLOCZ(pict, c_size)
-        s->last_picture_base[i] = pict;
-        s->last_picture[i] = pict + pict_start;
-        if(i>0) memset(s->last_picture_base[i], 128, c_size);
-    
-        CHECKED_ALLOCZ(pict, c_size)
-        s->next_picture_base[i] = pict;
-        s->next_picture[i] = pict + pict_start;
-        if(i>0) memset(s->next_picture_base[i], 128, c_size);
+/**
+ * allocates a Picture
+ * The pixels are allocated/set by calling get_buffer() if shared=0
+ */
+static int alloc_picture(MpegEncContext *s, Picture *pic, int shared){
+    
+    if(shared){
+        assert(pic->data[0]);
+        assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);
+        pic->type= FF_BUFFER_TYPE_SHARED;
+    }else{
+        int r;
+        
+        assert(!pic->data[0]);
+        
+        r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);
         
-        if (s->has_b_frames || s->codec_id==CODEC_ID_MPEG4) {
-        /* Note the MPEG4 stuff is here cuz of buggy encoders which dont set the low_delay flag but 
-           do low-delay encoding, so we cant allways distinguish b-frame containing streams from low_delay streams */
-            CHECKED_ALLOCZ(pict, c_size)
-            s->aux_picture_base[i] = pict;
-            s->aux_picture[i] = pict + pict_start;
-            if(i>0) memset(s->aux_picture_base[i], 128, c_size);
+        if(r<0 || !pic->age || !pic->type || !pic->data[0]){
+            fprintf(stderr, "get_buffer() failed (%d %d %d %p)\n", r, pic->age, pic->type, pic->data[0]);
+            return -1;
         }
-      }
-      s->ip_buffer_count= 2;
+
+        if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){
+            fprintf(stderr, "get_buffer() failed (stride changed)\n");
+            return -1;
+        }
+
+        if(pic->linesize[1] != pic->linesize[2]){
+            fprintf(stderr, "get_buffer() failed (uv stride missmatch)\n");
+            return -1;
+        }
+
+        s->linesize  = pic->linesize[0];
+        s->uvlinesize= pic->linesize[1];
     }
     
-    CHECKED_ALLOCZ(s->edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
+    if(pic->qscale_table==NULL){
+        if (s->encoding) {        
+            CHECKED_ALLOCZ(pic->mb_var   , s->mb_num * sizeof(int16_t))
+            CHECKED_ALLOCZ(pic->mc_mb_var, s->mb_num * sizeof(int16_t))
+            CHECKED_ALLOCZ(pic->mb_mean  , s->mb_num * sizeof(int8_t))
+            CHECKED_ALLOCZ(pic->mb_cmp_score, s->mb_num * sizeof(int32_t))
+        }
+
+        CHECKED_ALLOCZ(pic->mbskip_table , s->mb_num * sizeof(uint8_t)+1) //the +1 is for the slice end check
+        CHECKED_ALLOCZ(pic->qscale_table , s->mb_num * sizeof(uint8_t))
+        pic->qstride= s->mb_width;
+    }
     
+    //it might be nicer if the application would keep track of these but it would require a API change
+    memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);
+    s->prev_pict_types[0]= s->pict_type;
+    if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == B_TYPE)
+        pic->age= INT_MAX; // skiped MBs in b frames are quite rare in mpeg1/2 and its a bit tricky to skip them anyway
+    
+    return 0;
+fail: //for the CHECKED_ALLOCZ macro
+    return -1;
+}
+
+/**
+ * deallocates a picture
+ */
+static void free_picture(MpegEncContext *s, Picture *pic){
+    int i;
+
+    if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){
+        s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
+    }
+
+    av_freep(&pic->mb_var);
+    av_freep(&pic->mc_mb_var);
+    av_freep(&pic->mb_mean);
+    av_freep(&pic->mb_cmp_score);
+    av_freep(&pic->mbskip_table);
+    av_freep(&pic->qscale_table);
+    
+    if(pic->type == FF_BUFFER_TYPE_INTERNAL){
+        for(i=0; i<4; i++){
+            av_freep(&pic->base[i]);
+            pic->data[i]= NULL;
+        }
+        av_freep(&pic->opaque);
+        pic->type= 0;
+    }else if(pic->type == FF_BUFFER_TYPE_SHARED){
+        for(i=0; i<4; i++){
+            pic->base[i]=
+            pic->data[i]= NULL;
+        }
+        pic->type= 0;        
+    }
+}
+
+/* init common structure for both encoder and decoder */
+int MPV_common_init(MpegEncContext *s)
+{
+    int y_size, c_size, yc_size, i;
+
+    dsputil_init(&s->dsp, s->avctx);
+    DCT_common_init(s);
+
+    s->flags= s->avctx->flags;
+
+    s->mb_width  = (s->width  + 15) / 16;
+    s->mb_height = (s->height + 15) / 16;
+
+    /* set default edge pos, will be overriden in decode_header if needed */
+    s->h_edge_pos= s->mb_width*16;
+    s->v_edge_pos= s->mb_height*16;
+
+    s->mb_num = s->mb_width * s->mb_height;
+
+    y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
+    c_size = (s->mb_width + 2) * (s->mb_height + 2);
+    yc_size = y_size + 2 * c_size;
+
+    /* convert fourcc to upper case */
+    s->avctx->fourcc=   toupper( s->avctx->fourcc     &0xFF)          
+                     + (toupper((s->avctx->fourcc>>8 )&0xFF)<<8 )
+                     + (toupper((s->avctx->fourcc>>16)&0xFF)<<16) 
+                     + (toupper((s->avctx->fourcc>>24)&0xFF)<<24);
+
+    CHECKED_ALLOCZ(s->allocated_edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
+    s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*17;
+
+    s->avctx->coded_frame= (AVFrame*)&s->current_picture;
+
     if (s->encoding) {
-        int j;
         int mv_table_size= (s->mb_width+2)*(s->mb_height+2);
-        
-        CHECKED_ALLOCZ(s->mb_var   , s->mb_num * sizeof(INT16))
-        CHECKED_ALLOCZ(s->mc_mb_var, s->mb_num * sizeof(INT16))
 
         /* Allocate MV tables */
-        CHECKED_ALLOCZ(s->p_mv_table            , mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_forw_mv_table       , mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_back_mv_table       , mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_bidir_forw_mv_table , mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_bidir_back_mv_table , mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_direct_forw_mv_table, mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_direct_back_mv_table, mv_table_size * 2 * sizeof(INT16))
-        CHECKED_ALLOCZ(s->b_direct_mv_table     , mv_table_size * 2 * sizeof(INT16))
-
-        CHECKED_ALLOCZ(s->me_scratchpad,  s->linesize*16*3*sizeof(uint8_t))
+        CHECKED_ALLOCZ(s->p_mv_table            , mv_table_size * 2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->b_forw_mv_table       , mv_table_size * 2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->b_back_mv_table       , mv_table_size * 2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->b_bidir_forw_mv_table , mv_table_size * 2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->b_bidir_back_mv_table , mv_table_size * 2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->b_direct_mv_table     , mv_table_size * 2 * sizeof(int16_t))
+
+        //FIXME should be linesize instead of s->width*2 but that isnt known before get_buffer()
+        CHECKED_ALLOCZ(s->me.scratchpad,  s->width*2*16*3*sizeof(uint8_t)) 
         
-        CHECKED_ALLOCZ(s->me_map      , ME_MAP_SIZE*sizeof(uint32_t))
-        CHECKED_ALLOCZ(s->me_score_map, ME_MAP_SIZE*sizeof(uint16_t))
-
-        if(s->max_b_frames){
-            for(j=0; j<REORDER_BUFFER_SIZE; j++){
-                int i;
-                for(i=0;i<3;i++) {
-                    int w, h, shift;
-
-                    w = s->linesize;
-                    h = s->mb_height * 16;
-                    shift = (i == 0) ? 0 : 1;
-                    c_size = (w >> shift) * (h >> shift);
-
-                    CHECKED_ALLOCZ(pict, c_size);
-                    s->picture_buffer[j][i] = pict;
-                }
-            }
-        }
+        CHECKED_ALLOCZ(s->me.map      , ME_MAP_SIZE*sizeof(uint32_t))
+        CHECKED_ALLOCZ(s->me.score_map, ME_MAP_SIZE*sizeof(uint32_t))
 
         if(s->codec_id==CODEC_ID_MPEG4){
             CHECKED_ALLOCZ(s->tex_pb_buffer, PB_BUFFER_SIZE);
             CHECKED_ALLOCZ(   s->pb2_buffer, PB_BUFFER_SIZE);
         }
         
+        if(s->msmpeg4_version){
+            CHECKED_ALLOCZ(s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int));
+        }
         CHECKED_ALLOCZ(s->avctx->stats_out, 256);
     }
+        
+    CHECKED_ALLOCZ(s->error_status_table, s->mb_num*sizeof(uint8_t))
     
     if (s->out_format == FMT_H263 || s->encoding) {
         int size;
         /* Allocate MB type table */
-        CHECKED_ALLOCZ(s->mb_type  , s->mb_num * sizeof(UINT8))
+        CHECKED_ALLOCZ(s->mb_type  , s->mb_num * sizeof(uint8_t))
 
         /* MV prediction */
         size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
-        CHECKED_ALLOCZ(s->motion_val, size * 2 * sizeof(INT16));
-        
-        /* 4mv direct mode decoding table */
-        CHECKED_ALLOCZ(s->non_b_mv4_table, size * sizeof(UINT8))
+        CHECKED_ALLOCZ(s->motion_val, size * 2 * sizeof(int16_t));
     }
 
-    if (s->h263_pred || s->h263_plus) {
-        int y_size, c_size, i, size;
-        
-        /* dc values */
-
-        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
-        c_size = (s->mb_width + 2) * (s->mb_height + 2);
-        size = y_size + 2 * c_size;
-        CHECKED_ALLOCZ(s->dc_val[0], size * sizeof(INT16));
-        s->dc_val[1] = s->dc_val[0] + y_size;
-        s->dc_val[2] = s->dc_val[1] + c_size;
-        for(i=0;i<size;i++)
-            s->dc_val[0][i] = 1024;
-
+    if(s->codec_id==CODEC_ID_MPEG4){
+        /* interlaced direct mode decoding tables */
+        CHECKED_ALLOCZ(s->field_mv_table, s->mb_num*2*2 * sizeof(int16_t))
+        CHECKED_ALLOCZ(s->field_select_table, s->mb_num*2* sizeof(int8_t))
+    }
+    /* 4mv b frame decoding table */
+    //note this is needed for h263 without b frames too (segfault on damaged streams otherwise)
+    CHECKED_ALLOCZ(s->co_located_type_table, s->mb_num * sizeof(uint8_t))
+    if (s->out_format == FMT_H263) {
         /* ac values */
-        CHECKED_ALLOCZ(s->ac_val[0], size * sizeof(INT16) * 16);
+        CHECKED_ALLOCZ(s->ac_val[0], yc_size * sizeof(int16_t) * 16);
         s->ac_val[1] = s->ac_val[0] + y_size;
         s->ac_val[2] = s->ac_val[1] + c_size;
         
@@ -285,13 +408,22 @@ int MPV_common_init(MpegEncContext *s)
         
         /* divx501 bitstream reorder buffer */
         CHECKED_ALLOCZ(s->bitstream_buffer, BITSTREAM_BUFFER_SIZE);
-        
+
         /* cbp, ac_pred, pred_dir */
-        CHECKED_ALLOCZ(s->cbp_table  , s->mb_num * sizeof(UINT8))
-        CHECKED_ALLOCZ(s->pred_dir_table, s->mb_num * sizeof(UINT8))
+        CHECKED_ALLOCZ(s->cbp_table  , s->mb_num * sizeof(uint8_t))
+        CHECKED_ALLOCZ(s->pred_dir_table, s->mb_num * sizeof(uint8_t))
     }
-    CHECKED_ALLOCZ(s->qscale_table  , s->mb_num * sizeof(UINT8))
     
+    if (s->h263_pred || s->h263_plus || !s->encoding) {
+        /* dc values */
+        //MN: we need these for error resilience of intra-frames
+        CHECKED_ALLOCZ(s->dc_val[0], yc_size * sizeof(int16_t));
+        s->dc_val[1] = s->dc_val[0] + y_size;
+        s->dc_val[2] = s->dc_val[1] + c_size;
+        for(i=0;i<yc_size;i++)
+            s->dc_val[0][i] = 1024;
+    }
+
     /* which mb is a intra block */
     CHECKED_ALLOCZ(s->mbintra_table, s->mb_num);
     memset(s->mbintra_table, 1, s->mb_num);
@@ -300,10 +432,14 @@ int MPV_common_init(MpegEncContext *s)
     s->picture_structure = PICT_FRAME;
     
     /* init macroblock skip table */
-    CHECKED_ALLOCZ(s->mbskip_table, s->mb_num);
+    CHECKED_ALLOCZ(s->mbskip_table, s->mb_num+1);
+    //Note the +1 is for a quicker mpeg4 slice_end detection
+    CHECKED_ALLOCZ(s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE);
     
     s->block= s->blocks[0];
 
+    s->parse_context.state= -1;
+
     s->context_initialized = 1;
     return 0;
  fail:
@@ -320,15 +456,11 @@ void MPV_common_end(MpegEncContext *s)
     int i;
 
     av_freep(&s->mb_type);
-    av_freep(&s->mb_var);
-    av_freep(&s->mc_mb_var);
     av_freep(&s->p_mv_table);
     av_freep(&s->b_forw_mv_table);
     av_freep(&s->b_back_mv_table);
     av_freep(&s->b_bidir_forw_mv_table);
     av_freep(&s->b_bidir_back_mv_table);
-    av_freep(&s->b_direct_forw_mv_table);
-    av_freep(&s->b_direct_back_mv_table);
     av_freep(&s->b_direct_mv_table);
     av_freep(&s->motion_val);
     av_freep(&s->dc_val[0]);
@@ -337,40 +469,31 @@ void MPV_common_end(MpegEncContext *s)
     av_freep(&s->mbintra_table);
     av_freep(&s->cbp_table);
     av_freep(&s->pred_dir_table);
-    av_freep(&s->qscale_table);
-    av_freep(&s->me_scratchpad);
-    av_freep(&s->me_map);
-    av_freep(&s->me_score_map);
+    av_freep(&s->me.scratchpad);
+    av_freep(&s->me.map);
+    av_freep(&s->me.score_map);
     
     av_freep(&s->mbskip_table);
+    av_freep(&s->prev_pict_types);
     av_freep(&s->bitstream_buffer);
     av_freep(&s->tex_pb_buffer);
     av_freep(&s->pb2_buffer);
-    av_freep(&s->edge_emu_buffer);
-    av_freep(&s->non_b_mv4_table);
+    av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL;
+    av_freep(&s->co_located_type_table);
+    av_freep(&s->field_mv_table);
+    av_freep(&s->field_select_table);
     av_freep(&s->avctx->stats_out);
-    
-    for(i=0;i<3;i++) {
-        int j;
-        if(!(s->flags&CODEC_FLAG_DR1)){
-            av_freep(&s->last_picture_base[i]);
-            av_freep(&s->next_picture_base[i]);
-            av_freep(&s->aux_picture_base[i]);
-        }
-        s->last_picture_base[i]=
-        s->next_picture_base[i]=
-        s->aux_picture_base [i] = NULL;
-        s->last_picture[i]=
-        s->next_picture[i]=
-        s->aux_picture [i] = NULL;
+    av_freep(&s->ac_stats);
+    av_freep(&s->error_status_table);
 
-        for(j=0; j<REORDER_BUFFER_SIZE; j++){
-            av_freep(&s->picture_buffer[j][i]);
-        }
+    for(i=0; i<MAX_PICTURE_COUNT; i++){
+        free_picture(s, &s->picture[i]);
     }
     s->context_initialized = 0;
 }
 
+#ifdef CONFIG_ENCODERS
+
 /* init video encoder */
 int MPV_encode_init(AVCodecContext *avctx)
 {
@@ -399,12 +522,6 @@ int MPV_encode_init(AVCodecContext *avctx)
     s->qcompress= avctx->qcompress;
     s->qblur= avctx->qblur;
     s->avctx = avctx;
-    s->aspect_ratio_info= avctx->aspect_ratio_info;
-    if (avctx->aspect_ratio_info == FF_ASPECT_EXTENDED)
-    {
-       s->aspected_width = avctx->aspected_width;
-       s->aspected_height = avctx->aspected_height;
-    }
     s->flags= avctx->flags;
     s->max_b_frames= avctx->max_b_frames;
     s->b_frame_strategy= avctx->b_frame_strategy;
@@ -413,6 +530,7 @@ int MPV_encode_init(AVCodecContext *avctx)
     s->chroma_elim_threshold= avctx->chroma_elim_threshold;
     s->strict_std_compliance= avctx->strict_std_compliance;
     s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
+    s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
     s->mpeg_quant= avctx->mpeg_quant;
 
     if (s->gop_size <= 1) {
@@ -421,17 +539,21 @@ int MPV_encode_init(AVCodecContext *avctx)
     } else {
         s->intra_only = 0;
     }
-    
-    /* ME algorithm */
-    if (avctx->me_method == 0)
-        /* For compatibility */
-        s->me_method = motion_estimation_method;
-    else
-        s->me_method = avctx->me_method;
-        
+
+    s->me_method = avctx->me_method;
+
     /* Fixed QSCALE */
     s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
     
+    s->adaptive_quant= (   s->avctx->lumi_masking
+                        || s->avctx->dark_masking
+                        || s->avctx->temporal_cplx_masking 
+                        || s->avctx->spatial_cplx_masking
+                        || s->avctx->p_masking)
+                       && !s->fixed_qscale;
+    
+    s->progressive_sequence= !(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
+
     switch(avctx->codec->id) {
     case CODEC_ID_MPEG1VIDEO:
         s->out_format = FMT_MPEG1;
@@ -451,7 +573,9 @@ int MPV_encode_init(AVCodecContext *avctx)
         if (mjpeg_init(s) < 0)
             return -1;
         avctx->delay=0;
+        s->low_delay=1;
         break;
+#ifdef CONFIG_RISKY
     case CODEC_ID_H263:
         if (h263_get_picture_format(s->width, s->height) == 7) {
             printf("Input picture size isn't suitable for h263 codec! try h263+\n");
@@ -459,32 +583,32 @@ int MPV_encode_init(AVCodecContext *avctx)
         }
         s->out_format = FMT_H263;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_H263P:
         s->out_format = FMT_H263;
-        s->rtp_mode = 1;
-        s->rtp_payload_size = 1200; 
         s->h263_plus = 1;
-        s->unrestricted_mv = 1;
-        s->h263_aic = 1;
-        
+       /* Fx */
+       s->unrestricted_mv=(avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
+       s->h263_aic= (avctx->flags & CODEC_FLAG_H263P_AIC) ? 1:0;
+       /* /Fx */
         /* These are just to be sure */
-        s->umvplus = 0;
-        s->umvplus_dec = 0;
+        s->umvplus = 1;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_RV10:
         s->out_format = FMT_H263;
         s->h263_rv10 = 1;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_MPEG4:
         s->out_format = FMT_H263;
         s->h263_pred = 1;
         s->unrestricted_mv = 1;
-        s->has_b_frames= s->max_b_frames ? 1 : 0;
-        s->low_delay=0;
-        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1); 
+        s->low_delay= s->max_b_frames ? 0 : 1;
+        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
         break;
     case CODEC_ID_MSMPEG4V1:
         s->out_format = FMT_H263;
@@ -493,6 +617,7 @@ int MPV_encode_init(AVCodecContext *avctx)
         s->unrestricted_mv = 1;
         s->msmpeg4_version= 1;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_MSMPEG4V2:
         s->out_format = FMT_H263;
@@ -501,6 +626,7 @@ int MPV_encode_init(AVCodecContext *avctx)
         s->unrestricted_mv = 1;
         s->msmpeg4_version= 2;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_MSMPEG4V3:
         s->out_format = FMT_H263;
@@ -509,6 +635,7 @@ int MPV_encode_init(AVCodecContext *avctx)
         s->unrestricted_mv = 1;
         s->msmpeg4_version= 3;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_WMV1:
         s->out_format = FMT_H263;
@@ -517,6 +644,7 @@ int MPV_encode_init(AVCodecContext *avctx)
         s->unrestricted_mv = 1;
         s->msmpeg4_version= 4;
         avctx->delay=0;
+        s->low_delay=1;
         break;
     case CODEC_ID_WMV2:
         s->out_format = FMT_H263;
@@ -525,7 +653,9 @@ int MPV_encode_init(AVCodecContext *avctx)
         s->unrestricted_mv = 1;
         s->msmpeg4_version= 5;
         avctx->delay=0;
+        s->low_delay=1;
         break;
+#endif
     default:
         return -1;
     }
@@ -535,28 +665,24 @@ int MPV_encode_init(AVCodecContext *avctx)
         if(!done){
             int i;
             done=1;
-            memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
-            memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));
+
+            default_mv_penalty= av_mallocz( sizeof(uint16_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
+            memset(default_mv_penalty, 0, sizeof(uint16_t)*(MAX_FCODE+1)*(2*MAX_MV+1));
+            memset(default_fcode_tab , 0, sizeof(uint8_t)*(2*MAX_MV+1));
 
             for(i=-16; i<16; i++){
                 default_fcode_tab[i + MAX_MV]= 1;
             }
         }
     }
-    s->mv_penalty= default_mv_penalty;
+    s->me.mv_penalty= default_mv_penalty;
     s->fcode_tab= default_fcode_tab;
     s->y_dc_scale_table=
     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
  
-    if (s->out_format == FMT_H263)
-        h263_encode_init(s);
-    else if (s->out_format == FMT_MPEG1)
-        ff_mpeg1_encode_init(s);
-    if(s->msmpeg4_version)
-        ff_msmpeg4_encode_init(s);
-
     /* dont use mv_penalty table for crap MV as it would be confused */
-    if (s->me_method < ME_EPZS) s->mv_penalty = default_mv_penalty;
+    //FIXME remove after fixing / removing old ME
+    if (s->me_method < ME_EPZS) s->me.mv_penalty = default_mv_penalty;
 
     s->encoding = 1;
 
@@ -564,17 +690,34 @@ int MPV_encode_init(AVCodecContext *avctx)
     if (MPV_common_init(s) < 0)
         return -1;
     
+    ff_init_me(s);
+
+#ifdef CONFIG_ENCODERS
+#ifdef CONFIG_RISKY
+    if (s->out_format == FMT_H263)
+        h263_encode_init(s);
+    if(s->msmpeg4_version)
+        ff_msmpeg4_encode_init(s);
+#endif
+    if (s->out_format == FMT_MPEG1)
+        ff_mpeg1_encode_init(s);
+#endif
+
     /* init default q matrix */
     for(i=0;i<64;i++) {
+        int j= s->dsp.idct_permutation[i];
+#ifdef CONFIG_RISKY
         if(s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
-            s->intra_matrix[i] = ff_mpeg4_default_intra_matrix[i];
-            s->inter_matrix[i] = ff_mpeg4_default_non_intra_matrix[i];
+            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
+            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
         }else if(s->out_format == FMT_H263){
-            s->intra_matrix[i] =
-            s->inter_matrix[i] = ff_mpeg1_default_non_intra_matrix[i];
-        }else{ /* mpeg1 */
-            s->intra_matrix[i] = ff_mpeg1_default_intra_matrix[i];
-            s->inter_matrix[i] = ff_mpeg1_default_non_intra_matrix[i];
+            s->intra_matrix[j] =
+            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
+        }else
+#endif
+        { /* mpeg1 */
+            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
+            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
         }
     }
 
@@ -582,9 +725,9 @@ int MPV_encode_init(AVCodecContext *avctx)
     /* for mjpeg, we do include qscale in the matrix */
     if (s->out_format != FMT_MJPEG) {
         convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, s->q_intra_matrix16_bias, 
-                       s->intra_matrix, s->intra_quant_bias);
+                       s->intra_matrix, s->intra_quant_bias, 1, 31);
         convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16, s->q_inter_matrix16_bias, 
-                       s->inter_matrix, s->inter_quant_bias);
+                       s->inter_matrix, s->inter_quant_bias, 1, 31);
     }
 
     if(ff_rate_control_init(s) < 0)
@@ -617,11 +760,51 @@ int MPV_encode_end(AVCodecContext *avctx)
     return 0;
 }
 
+#endif //CONFIG_ENCODERS
+
+void init_rl(RLTable *rl)
+{
+    int8_t max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
+    uint8_t index_run[MAX_RUN+1];
+    int last, run, level, start, end, i;
+
+    /* compute max_level[], max_run[] and index_run[] */
+    for(last=0;last<2;last++) {
+        if (last == 0) {
+            start = 0;
+            end = rl->last;
+        } else {
+            start = rl->last;
+            end = rl->n;
+        }
+
+        memset(max_level, 0, MAX_RUN + 1);
+        memset(max_run, 0, MAX_LEVEL + 1);
+        memset(index_run, rl->n, MAX_RUN + 1);
+        for(i=start;i<end;i++) {
+            run = rl->table_run[i];
+            level = rl->table_level[i];
+            if (index_run[run] == rl->n)
+                index_run[run] = i;
+            if (level > max_level[run])
+                max_level[run] = level;
+            if (run > max_run[level])
+                max_run[level] = run;
+        }
+        rl->max_level[last] = av_malloc(MAX_RUN + 1);
+        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
+        rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
+        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
+        rl->index_run[last] = av_malloc(MAX_RUN + 1);
+        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
+    }
+}
+
 /* draw the edges of width 'w' of an image of size width, height */
 //FIXME check that this is ok for mpeg4 interlaced
-static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
+static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
 {
-    UINT8 *ptr, *last_line;
+    uint8_t *ptr, *last_line;
     int i;
 
     last_line = buf + (height - 1) * wrap;
@@ -646,62 +829,84 @@ static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
     }
 }
 
+static int find_unused_picture(MpegEncContext *s, int shared){
+    int i;
+    
+    if(shared){
+        for(i=0; i<MAX_PICTURE_COUNT; i++){
+            if(s->picture[i].data[0]==NULL && s->picture[i].type==0) break;
+        }
+    }else{
+        for(i=0; i<MAX_PICTURE_COUNT; i++){
+            if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) break;
+        }
+        for(i=0; i<MAX_PICTURE_COUNT; i++){
+            if(s->picture[i].data[0]==NULL) break;
+        }
+    }
+
+    assert(i<MAX_PICTURE_COUNT);
+    return i;
+}
+
 /* generic function for encode/decode called before a frame is coded/decoded */
-void MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
+int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
 {
     int i;
-    UINT8 *tmp;
+    AVFrame *pic;
 
     s->mb_skiped = 0;
-    s->decoding_error=0;
-    avctx->mbskip_table= s->mbskip_table;
-
-    if(avctx->flags&CODEC_FLAG_DR1){
-        avctx->get_buffer_callback(avctx, s->width, s->height, s->pict_type);
-
-        s->linesize  = avctx->dr_stride;
-        s->uvlinesize= avctx->dr_uvstride;
-        s->ip_buffer_count= avctx->dr_ip_buffer_count;
-    }
-    avctx->dr_ip_buffer_count= s->ip_buffer_count;
     
-    if (s->pict_type == B_TYPE) {
-        for(i=0;i<3;i++) {
-            if(avctx->flags&CODEC_FLAG_DR1)
-                s->aux_picture[i]= avctx->dr_buffer[i];
-            
-            //FIXME the following should never be needed, the decoder should drop b frames if no reference is available
-            if(s->next_picture[i]==NULL)
-                s->next_picture[i]= s->aux_picture[i];
-            if(s->last_picture[i]==NULL)
-                s->last_picture[i]= s->next_picture[i];
-
-            s->current_picture[i] = s->aux_picture[i];
+    /* mark&release old frames */
+    if (s->pict_type != B_TYPE && s->last_picture.data[0]) {
+        for(i=0; i<MAX_PICTURE_COUNT; i++){
+//printf("%8X %d %d %X %X\n", s->picture[i].data[0], s->picture[i].type, i, s->next_picture.data[0], s->last_picture.data[0]);
+            if(s->picture[i].data[0] == s->last_picture.data[0]){
+//                s->picture[i].reference=0;
+                avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
+                break;
+            }    
         }
-    } else {
-        for(i=0;i<3;i++) {
-            /* swap next and last */
-            if(avctx->flags&CODEC_FLAG_DR1)
-                tmp= avctx->dr_buffer[i];
-            else
-                tmp = s->last_picture[i];
-
-            s->last_picture[i] = s->next_picture[i];
-            s->next_picture[i] = tmp;
-            s->current_picture[i] = tmp;
-
-            if(s->last_picture[i]==NULL)
-                s->last_picture[i]= s->next_picture[i];
+        assert(i<MAX_PICTURE_COUNT);
+
+        /* release forgotten pictures */
+        /* if(mpeg124/h263) */
+        if(!s->encoding){
+            for(i=0; i<MAX_PICTURE_COUNT; i++){
+                if(s->picture[i].data[0] && s->picture[i].data[0] != s->next_picture.data[0] && s->picture[i].reference){
+                    fprintf(stderr, "releasing zombie picture\n");
+                    avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);                
+                }
+            }
+        }
+    }
+alloc:
+    if(!s->encoding){
+        i= find_unused_picture(s, 0);
+    
+        pic= (AVFrame*)&s->picture[i];
+        pic->reference= s->pict_type != B_TYPE;
+        pic->coded_picture_number= s->current_picture.coded_picture_number+1;
+        
+        alloc_picture(s, (Picture*)pic, 0);
 
-            s->last_dr_opaque= s->next_dr_opaque;
-            s->next_dr_opaque= avctx->dr_opaque_frame;
+        s->current_picture= s->picture[i];
+    }
 
-            if(s->has_b_frames && s->last_dr_opaque && s->codec_id!=CODEC_ID_SVQ1)
-                avctx->dr_opaque_frame= s->last_dr_opaque;
-            else
-                avctx->dr_opaque_frame= s->next_dr_opaque;
-        }
+    if (s->pict_type != B_TYPE) {
+        s->last_picture= s->next_picture;
+        s->next_picture= s->current_picture;
+    }
+    
+    if(s->pict_type != I_TYPE && s->last_picture.data[0]==NULL){
+        fprintf(stderr, "warning: first frame is no keyframe\n");
+        assert(s->pict_type != B_TYPE); //these should have been dropped if we dont have a reference
+        goto alloc;
     }
+   
+    s->hurry_up= s->avctx->hurry_up;
+    s->error_resilience= avctx->error_resilience;
+
     /* set dequantizer, we cant do it during init as it might change for mpeg4
        and we cant do it in the header decode as init isnt called for mpeg4 there yet */
     if(s->out_format == FMT_H263){
@@ -711,105 +916,301 @@ void MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
             s->dct_unquantize = s->dct_unquantize_h263;
     }else 
         s->dct_unquantize = s->dct_unquantize_mpeg1;
+
+    return 0;
 }
 
 /* generic function for encode/decode called after a frame has been coded/decoded */
 void MPV_frame_end(MpegEncContext *s)
 {
-//    if((s->picture_number%100)==0 && s->encoding) printf("sads:%d //\n", sads);
-
+    int i;
     /* draw edge for correct motion prediction if outside */
-    if (s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
-        draw_edges(s->current_picture[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
-        draw_edges(s->current_picture[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
-        draw_edges(s->current_picture[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
+    if(s->codec_id!=CODEC_ID_SVQ1){
+        if (s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
+            draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
+            draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
+            draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
+        }
     }
     emms_c();
     
     s->last_pict_type    = s->pict_type;
     if(s->pict_type!=B_TYPE){
         s->last_non_b_pict_type= s->pict_type;
-        s->num_available_buffers++;
-        if(s->num_available_buffers>2) s->num_available_buffers= 2;
+    }
+    
+    s->current_picture.quality= s->qscale; //FIXME get average of qscale_table
+    s->current_picture.pict_type= s->pict_type;
+    s->current_picture.key_frame= s->pict_type == I_TYPE;
+    
+    /* copy back current_picture variables */
+    for(i=0; i<MAX_PICTURE_COUNT; i++){
+        if(s->picture[i].data[0] == s->current_picture.data[0]){
+            s->picture[i]= s->current_picture;
+            break;
+        }    
+    }
+    assert(i<MAX_PICTURE_COUNT);
+
+    /* release non refernce frames */
+    for(i=0; i<MAX_PICTURE_COUNT; i++){
+        if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/)
+            s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
+    }
+    if(s->avctx->debug&FF_DEBUG_SKIP){
+        int x,y;        
+        for(y=0; y<s->mb_height; y++){
+            for(x=0; x<s->mb_width; x++){
+                int count= s->mbskip_table[x + y*s->mb_width];
+                if(count>9) count=9;
+                printf(" %1d", count);
+            }
+            printf("\n");
+        }
+        printf("pict type: %d\n", s->pict_type);
     }
 }
 
-/* reorder input for encoding */
-void reorder_input(MpegEncContext *s, AVPicture *pict)
-{
-    int i, j, index;
+#ifdef CONFIG_ENCODERS
+
+static int get_sae(uint8_t *src, int ref, int stride){
+    int x,y;
+    int acc=0;
+    
+    for(y=0; y<16; y++){
+        for(x=0; x<16; x++){
+            acc+= ABS(src[x+y*stride] - ref);
+        }
+    }
+    
+    return acc;
+}
+
+static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
+    int x, y, w, h;
+    int acc=0;
+    
+    w= s->width &~15;
+    h= s->height&~15;
+    
+    for(y=0; y<h; y+=16){
+        for(x=0; x<w; x+=16){
+            int offset= x + y*stride;
+            int sad = s->dsp.pix_abs16x16(src + offset, ref + offset, stride);
+            int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
+            int sae = get_sae(src + offset, mean, stride);
             
-    if(s->max_b_frames > FF_MAX_B_FRAMES) s->max_b_frames= FF_MAX_B_FRAMES;
-
-//        delay= s->max_b_frames+1; (or 0 if no b frames cuz decoder diff)
-
-    for(j=0; j<REORDER_BUFFER_SIZE-1; j++){
-        s->coded_order[j]= s->coded_order[j+1];
-    }
-    s->coded_order[j].picture[0]= s->coded_order[j].picture[1]= s->coded_order[j].picture[2]= NULL; //catch uninitalized buffers
-    s->coded_order[j].pict_type=0;
-
-    switch(s->input_pict_type){
-    default: 
-    case I_TYPE:
-    case S_TYPE:
-    case P_TYPE:
-        index= s->max_b_frames - s->b_frames_since_non_b;
-        s->b_frames_since_non_b=0;
-        break;            
-    case B_TYPE:
-        index= s->max_b_frames + 1;
-        s->b_frames_since_non_b++;
-        break;          
-    }
-//printf("index:%d type:%d strides: %d %d\n", index, s->input_pict_type, pict->linesize[0], s->linesize);
-    if(   (index==0 || (s->flags&CODEC_FLAG_INPUT_PRESERVED))
-       && pict->linesize[0] == s->linesize
-       && pict->linesize[1] == s->uvlinesize
-       && pict->linesize[2] == s->uvlinesize){
-//printf("ptr\n");
-        for(i=0; i<3; i++){
-            s->coded_order[index].picture[i]= pict->data[i];
+            acc+= sae + 500 < sad;
+        }
+    }
+    return acc;
+}
+
+
+static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
+    AVFrame *pic;
+    int i;
+    const int encoding_delay= s->max_b_frames;
+    int direct=1;
+
+    if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
+    if(pic_arg->linesize[0] != s->linesize) direct=0;
+    if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
+    if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
+  
+//    printf("%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
+    
+    if(direct){
+        i= find_unused_picture(s, 1);
+
+        pic= (AVFrame*)&s->picture[i];
+        pic->reference= 1;
+    
+        for(i=0; i<4; i++){
+            pic->data[i]= pic_arg->data[i];
+            pic->linesize[i]= pic_arg->linesize[i];
         }
+        alloc_picture(s, (Picture*)pic, 1);
     }else{
-//printf("copy\n");
-        for(i=0; i<3; i++){
-            uint8_t *src = pict->data[i];
-            uint8_t *dest;
-            int src_wrap = pict->linesize[i];
-            int dest_wrap = s->linesize;
-            int w = s->width;
-            int h = s->height;
-
-            if(index==0) dest= s->last_picture[i]+16; //is current_picture indeed but the switch hapens after reordering
-            else         dest= s->picture_buffer[s->picture_buffer_index][i];
-
-            if (i >= 1) {
-                dest_wrap >>= 1;
-                w >>= 1;
-                h >>= 1;
-            }
+        i= find_unused_picture(s, 0);
+
+        pic= (AVFrame*)&s->picture[i];
+        pic->reference= 1;
 
-            s->coded_order[index].picture[i]= dest;
-            for(j=0;j<h;j++) {
-                memcpy(dest, src, w);
-                dest += dest_wrap;
-                src += src_wrap;
+        alloc_picture(s, (Picture*)pic, 0);
+
+        if(   pic->data[0] == pic_arg->data[0] 
+           && pic->data[1] == pic_arg->data[1]
+           && pic->data[2] == pic_arg->data[2]){
+       // empty
+        }else{
+            int h_chroma_shift, v_chroma_shift;
+        
+            avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
+        
+            for(i=0; i<3; i++){
+                int src_stride= pic_arg->linesize[i];
+                int dst_stride= i ? s->uvlinesize : s->linesize;
+                int h_shift= i ? h_chroma_shift : 0;
+                int v_shift= i ? v_chroma_shift : 0;
+                int w= s->width >>h_shift;
+                int h= s->height>>v_shift;
+                uint8_t *src= pic_arg->data[i];
+                uint8_t *dst= pic->data[i];
+            
+                if(src_stride==dst_stride)
+                    memcpy(dst, src, src_stride*h);
+                else{
+                    while(h--){
+                        memcpy(dst, src, w);
+                        dst += dst_stride;
+                        src += src_stride;
+                    }
+                }
             }
         }
-        if(index!=0){
-            s->picture_buffer_index++;
-            if(s->picture_buffer_index >= REORDER_BUFFER_SIZE) s->picture_buffer_index=0;
+    }
+    pic->quality= pic_arg->quality;
+    pic->pict_type= pic_arg->pict_type;
+    pic->pts = pic_arg->pts;
+    
+    if(s->input_picture[encoding_delay])
+        pic->display_picture_number= s->input_picture[encoding_delay]->display_picture_number + 1;
+
+    /* shift buffer entries */
+    for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
+        s->input_picture[i-1]= s->input_picture[i];
+        
+    s->input_picture[encoding_delay]= (Picture*)pic;
+
+    return 0;
+}
+
+static void select_input_picture(MpegEncContext *s){
+    int i;
+    const int encoding_delay= s->max_b_frames;
+    int coded_pic_num=0;    
+
+    if(s->reordered_input_picture[0])
+        coded_pic_num= s->reordered_input_picture[0]->coded_picture_number + 1;
+
+    for(i=1; i<MAX_PICTURE_COUNT; i++)
+        s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
+    s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
+
+    /* set next picture types & ordering */
+    if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
+        if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture.data[0]==NULL || s->intra_only){
+            s->reordered_input_picture[0]= s->input_picture[0];
+            s->reordered_input_picture[0]->pict_type= I_TYPE;
+            s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
+        }else{
+            int b_frames;
+            
+            if(s->flags&CODEC_FLAG_PASS2){
+                for(i=0; i<s->max_b_frames+1; i++){
+                    int pict_num= s->input_picture[0]->display_picture_number + i;
+                    int pict_type= s->rc_context.entry[pict_num].new_pict_type;
+                    s->input_picture[i]->pict_type= pict_type;
+                    
+                    if(i + 1 >= s->rc_context.num_entries) break;
+                }
+            }
+
+            if(s->input_picture[0]->pict_type){
+                /* user selected pict_type */
+                for(b_frames=0; b_frames<s->max_b_frames+1; b_frames++){
+                    if(s->input_picture[b_frames]->pict_type!=B_TYPE) break;
+                }
+            
+                if(b_frames > s->max_b_frames){
+                    fprintf(stderr, "warning, too many bframes in a row\n");
+                    b_frames = s->max_b_frames;
+                }
+            }else if(s->b_frame_strategy==0){
+                b_frames= s->max_b_frames;
+            }else if(s->b_frame_strategy==1){
+                for(i=1; i<s->max_b_frames+1; i++){
+                    if(s->input_picture[i]->b_frame_score==0){
+                        s->input_picture[i]->b_frame_score= 
+                            get_intra_count(s, s->input_picture[i  ]->data[0], 
+                                               s->input_picture[i-1]->data[0], s->linesize) + 1;
+                    }
+                }
+                for(i=0; i<s->max_b_frames; i++){
+                    if(s->input_picture[i]->b_frame_score - 1 > s->mb_num/40) break;
+                }
+                                
+                b_frames= FFMAX(0, i-1);
+                
+                /* reset scores */
+                for(i=0; i<b_frames+1; i++){
+                    s->input_picture[i]->b_frame_score=0;
+                }
+            }else{
+                fprintf(stderr, "illegal b frame strategy\n");
+                b_frames=0;
+            }
+
+            emms_c();
+//static int b_count=0;
+//b_count+= b_frames;
+//printf("b_frames: %d\n", b_count);
+                        
+            s->reordered_input_picture[0]= s->input_picture[b_frames];
+            if(   s->picture_in_gop_number + b_frames >= s->gop_size 
+               || s->reordered_input_picture[0]->pict_type== I_TYPE)
+                s->reordered_input_picture[0]->pict_type= I_TYPE;
+            else
+                s->reordered_input_picture[0]->pict_type= P_TYPE;
+            s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
+            for(i=0; i<b_frames; i++){
+                coded_pic_num++;
+                s->reordered_input_picture[i+1]= s->input_picture[i];
+                s->reordered_input_picture[i+1]->pict_type= B_TYPE;
+                s->reordered_input_picture[i+1]->coded_picture_number= coded_pic_num;
+            }
         }
     }
-    s->coded_order[index].pict_type = s->input_pict_type;
-    s->coded_order[index].qscale    = s->input_qscale;
-    s->coded_order[index].force_type= s->force_input_type;
-    s->coded_order[index].picture_in_gop_number= s->input_picture_in_gop_number;
-    s->coded_order[index].picture_number= s->input_picture_number;
+    
+    if(s->reordered_input_picture[0]){
+       s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=B_TYPE;
 
-    for(i=0; i<3; i++){
-        s->new_picture[i]= s->coded_order[0].picture[i];
+        if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
+            int i= find_unused_picture(s, 0);
+            Picture *pic= &s->picture[i];
+
+            s->new_picture= *s->reordered_input_picture[0];
+
+            /* mark us unused / free shared pic */
+            for(i=0; i<4; i++)
+                s->reordered_input_picture[0]->data[i]= NULL;
+            s->reordered_input_picture[0]->type= 0;
+            
+            pic->pict_type = s->reordered_input_picture[0]->pict_type;
+            pic->quality   = s->reordered_input_picture[0]->quality;
+            pic->coded_picture_number = s->reordered_input_picture[0]->coded_picture_number;
+            pic->reference = s->reordered_input_picture[0]->reference;
+            
+            alloc_picture(s, pic, 0);
+
+            s->current_picture= *pic;
+        }else{
+            assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER 
+                   || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
+            
+            s->new_picture= *s->reordered_input_picture[0];
+
+            for(i=0; i<4; i++){
+                s->reordered_input_picture[0]->data[i]-=16; //FIXME dirty
+            }
+            s->current_picture= *s->reordered_input_picture[0];
+        }
+    
+        s->picture_number= s->new_picture.display_picture_number;
+//printf("dpn:%d\n", s->picture_number);
+    }else{
+       memset(&s->new_picture, 0, sizeof(Picture));
     }
 }
 
@@ -817,57 +1218,31 @@ int MPV_encode_picture(AVCodecContext *avctx,
                        unsigned char *buf, int buf_size, void *data)
 {
     MpegEncContext *s = avctx->priv_data;
-    AVPicture *pict = data;
-
-    s->input_qscale = avctx->quality;
+    AVFrame *pic_arg = data;
+    int i;
 
     init_put_bits(&s->pb, buf, buf_size, NULL, NULL);
 
-    if(avctx->flags&CODEC_FLAG_TYPE){
-        s->input_pict_type=
-        s->force_input_type= avctx->key_frame ? I_TYPE : P_TYPE;
-    }else if(s->flags&CODEC_FLAG_PASS2){
-        s->input_pict_type=
-        s->force_input_type= s->rc_context.entry[s->input_picture_number].new_pict_type;
-    }else{
-        s->force_input_type=0;
-        if (!s->intra_only) {
-            /* first picture of GOP is intra */
-            if (s->input_picture_in_gop_number % s->gop_size==0){
-                s->input_pict_type = I_TYPE;
-            }else if(s->max_b_frames==0){
-                s->input_pict_type = P_TYPE;
-            }else{
-                if(s->b_frames_since_non_b < s->max_b_frames) //FIXME more IQ
-                    s->input_pict_type = B_TYPE;
-                else
-                    s->input_pict_type = P_TYPE;
-            }
-        } else {
-            s->input_pict_type = I_TYPE;
-        }
-    }
+    s->picture_in_gop_number++;
 
-    if(s->input_pict_type==I_TYPE)
-        s->input_picture_in_gop_number=0;
+    load_input_picture(s, pic_arg);
     
-    reorder_input(s, pict);
+    select_input_picture(s);
     
     /* output? */
-    if(s->coded_order[0].picture[0]){
-
-        s->pict_type= s->coded_order[0].pict_type;
-        if (s->fixed_qscale) /* the ratecontrol needs the last qscale so we dont touch it for CBR */
-            s->qscale= s->coded_order[0].qscale;
-        s->force_type= s->coded_order[0].force_type;
-        s->picture_in_gop_number= s->coded_order[0].picture_in_gop_number;
-        s->picture_number= s->coded_order[0].picture_number;
+    if(s->new_picture.data[0]){
 
+        s->pict_type= s->new_picture.pict_type;
+        if (s->fixed_qscale){ /* the ratecontrol needs the last qscale so we dont touch it for CBR */
+            s->qscale= (int)(s->new_picture.quality+0.5);
+            assert(s->qscale);
+        }
+//emms_c();
+//printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
         MPV_frame_start(s, avctx);
 
         encode_picture(s, s->picture_number);
-        avctx->key_frame   = (s->pict_type == I_TYPE);
-        avctx->pict_type   = s->pict_type;
+        
         avctx->real_pict_num  = s->picture_number;
         avctx->header_bits = s->header_bits;
         avctx->mv_bits     = s->mv_bits;
@@ -875,64 +1250,45 @@ int MPV_encode_picture(AVCodecContext *avctx,
         avctx->i_tex_bits  = s->i_tex_bits;
         avctx->p_tex_bits  = s->p_tex_bits;
         avctx->i_count     = s->i_count;
-        avctx->p_count     = s->p_count;
+        avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
         avctx->skip_count  = s->skip_count;
 
         MPV_frame_end(s);
 
         if (s->out_format == FMT_MJPEG)
             mjpeg_picture_trailer(s);
-
-        avctx->quality = s->qscale;
         
         if(s->flags&CODEC_FLAG_PASS1)
             ff_write_pass1_stats(s);
-    
     }
 
     s->input_picture_number++;
-    s->input_picture_in_gop_number++;
 
     flush_put_bits(&s->pb);
     s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
     
     s->total_bits += s->frame_bits;
-    avctx->frame_bits  = s->frame_bits;
-//printf("fcode: %d, type: %d, head: %d, mv: %d, misc: %d, frame: %d, itex: %d, ptex: %d\n", 
-//s->f_code, avctx->key_frame, s->header_bits, s->mv_bits, s->misc_bits, s->frame_bits, s->i_tex_bits, s->p_tex_bits);
-#if 0 //dump some stats to stats.txt for testing/debuging
-if(s->max_b_frames==0)
-{
-    static FILE *f=NULL;
-    if(!f) f= fopen("stats.txt", "wb");
-    get_psnr(pict->data, s->current_picture,
-             pict->linesize, s->linesize, avctx);
-    fprintf(f, "%7d, %7d, %2.4f\n", pbBufPtr(&s->pb) - s->pb.buf, s->qscale, avctx->psnr_y);
-}
-#endif
+    avctx->frame_bits  = s->frame_bits;
 
-    if (avctx->get_psnr) {
-        /* At this point pict->data should have the original frame   */
-        /* an s->current_picture should have the coded/decoded frame */
-        get_psnr(pict->data, s->current_picture,
-                 pict->linesize, s->linesize, avctx);
-//        printf("%f\n", avctx->psnr_y);
+    for(i=0; i<4; i++){
+        avctx->error[i] += s->current_picture.error[i];
     }
+    
     return pbBufPtr(&s->pb) - s->pb.buf;
 }
 
+#endif //CONFIG_ENCODERS
+
 static inline void gmc1_motion(MpegEncContext *s,
-                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
+                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
                                int dest_offset,
-                               UINT8 **ref_picture, int src_offset,
-                               int h)
+                               uint8_t **ref_picture, int src_offset)
 {
-    UINT8 *ptr;
+    uint8_t *ptr;
     int offset, src_x, src_y, linesize, uvlinesize;
     int motion_x, motion_y;
     int emu=0;
 
-    if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
     motion_x= s->sprite_offset[0][0];
     motion_y= s->sprite_offset[0][1];
     src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
@@ -945,22 +1301,36 @@ static inline void gmc1_motion(MpegEncContext *s,
     src_y = clip(src_y, -16, s->height);
     if (src_y == s->height)
         motion_y =0;
-    
+
     linesize = s->linesize;
     uvlinesize = s->uvlinesize;
+    
     ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
 
     dest_y+=dest_offset;
     if(s->flags&CODEC_FLAG_EMU_EDGE){
-        if(src_x<0 || src_y<0 || src_x + (motion_x&15) + 16 > s->h_edge_pos
-                              || src_y + (motion_y&15) + h  > s->v_edge_pos){
-            emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
+        if(src_x<0 || src_y<0 || src_x + 17 >= s->h_edge_pos
+                              || src_y + 17 >= s->v_edge_pos){
+            ff_emulated_edge_mc(s, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
             ptr= s->edge_emu_buffer;
-            emu=1;
         }
     }
-    gmc1(dest_y  , ptr  , linesize, h, motion_x&15, motion_y&15, s->no_rounding);
-    gmc1(dest_y+8, ptr+8, linesize, h, motion_x&15, motion_y&15, s->no_rounding);
+    
+    if((motion_x|motion_y)&7){
+        s->dsp.gmc1(dest_y  , ptr  , linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
+        s->dsp.gmc1(dest_y+8, ptr+8, linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
+    }else{
+        int dxy;
+        
+        dxy= ((motion_x>>3)&1) | ((motion_y>>2)&2);
+        if (s->no_rounding){
+           s->dsp.put_no_rnd_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
+        }else{
+            s->dsp.put_pixels_tab       [0][dxy](dest_y, ptr, linesize, 16);
+        }
+    }
+    
+    if(s->flags&CODEC_FLAG_GRAY) return;
 
     motion_x= s->sprite_offset[1][0];
     motion_y= s->sprite_offset[1][1];
@@ -977,28 +1347,96 @@ static inline void gmc1_motion(MpegEncContext *s,
 
     offset = (src_y * uvlinesize) + src_x + (src_offset>>1);
     ptr = ref_picture[1] + offset;
-    if(emu){
-        emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
-        ptr= s->edge_emu_buffer;
+    if(s->flags&CODEC_FLAG_EMU_EDGE){
+        if(src_x<0 || src_y<0 || src_x + 9 >= s->h_edge_pos>>1
+                              || src_y + 9 >= s->v_edge_pos>>1){
+            ff_emulated_edge_mc(s, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+            ptr= s->edge_emu_buffer;
+            emu=1;
+        }
     }
-    gmc1(dest_cb + (dest_offset>>1), ptr, uvlinesize, h>>1, motion_x&15, motion_y&15, s->no_rounding);
+    s->dsp.gmc1(dest_cb + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
     
     ptr = ref_picture[2] + offset;
     if(emu){
-        emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        ff_emulated_edge_mc(s, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
         ptr= s->edge_emu_buffer;
     }
-    gmc1(dest_cr + (dest_offset>>1), ptr, uvlinesize, h>>1, motion_x&15, motion_y&15, s->no_rounding);
+    s->dsp.gmc1(dest_cr + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
     
     return;
 }
 
-static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int block_w, int block_h, 
+static inline void gmc_motion(MpegEncContext *s,
+                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
+                               int dest_offset,
+                               uint8_t **ref_picture, int src_offset)
+{
+    uint8_t *ptr;
+    int linesize, uvlinesize;
+    const int a= s->sprite_warping_accuracy;
+    int ox, oy;
+
+    linesize = s->linesize;
+    uvlinesize = s->uvlinesize;
+
+    ptr = ref_picture[0] + src_offset;
+
+    dest_y+=dest_offset;
+    
+    ox= s->sprite_offset[0][0] + s->sprite_delta[0][0]*s->mb_x*16 + s->sprite_delta[0][1]*s->mb_y*16;
+    oy= s->sprite_offset[0][1] + s->sprite_delta[1][0]*s->mb_x*16 + s->sprite_delta[1][1]*s->mb_y*16;
+
+    s->dsp.gmc(dest_y, ptr, linesize, 16,
+           ox, 
+           oy, 
+           s->sprite_delta[0][0], s->sprite_delta[0][1],
+           s->sprite_delta[1][0], s->sprite_delta[1][1], 
+           a+1, (1<<(2*a+1)) - s->no_rounding,
+           s->h_edge_pos, s->v_edge_pos);
+    s->dsp.gmc(dest_y+8, ptr, linesize, 16,
+           ox + s->sprite_delta[0][0]*8, 
+           oy + s->sprite_delta[1][0]*8, 
+           s->sprite_delta[0][0], s->sprite_delta[0][1],
+           s->sprite_delta[1][0], s->sprite_delta[1][1], 
+           a+1, (1<<(2*a+1)) - s->no_rounding,
+           s->h_edge_pos, s->v_edge_pos);
+
+    if(s->flags&CODEC_FLAG_GRAY) return;
+
+
+    dest_cb+=dest_offset>>1;
+    dest_cr+=dest_offset>>1;
+    
+    ox= s->sprite_offset[1][0] + s->sprite_delta[0][0]*s->mb_x*8 + s->sprite_delta[0][1]*s->mb_y*8;
+    oy= s->sprite_offset[1][1] + s->sprite_delta[1][0]*s->mb_x*8 + s->sprite_delta[1][1]*s->mb_y*8;
+
+    ptr = ref_picture[1] + (src_offset>>1);
+    s->dsp.gmc(dest_cb, ptr, uvlinesize, 8,
+           ox, 
+           oy, 
+           s->sprite_delta[0][0], s->sprite_delta[0][1],
+           s->sprite_delta[1][0], s->sprite_delta[1][1], 
+           a+1, (1<<(2*a+1)) - s->no_rounding,
+           s->h_edge_pos>>1, s->v_edge_pos>>1);
+    
+    ptr = ref_picture[2] + (src_offset>>1);
+    s->dsp.gmc(dest_cr, ptr, uvlinesize, 8,
+           ox, 
+           oy, 
+           s->sprite_delta[0][0], s->sprite_delta[0][1],
+           s->sprite_delta[1][0], s->sprite_delta[1][1], 
+           a+1, (1<<(2*a+1)) - s->no_rounding,
+           s->h_edge_pos>>1, s->v_edge_pos>>1);
+}
+
+
+void ff_emulated_edge_mc(MpegEncContext *s, uint8_t *src, int linesize, int block_w, int block_h, 
                                     int src_x, int src_y, int w, int h){
     int x, y;
     int start_y, start_x, end_y, end_x;
-    UINT8 *buf= s->edge_emu_buffer;
-    
+    uint8_t *buf= s->edge_emu_buffer;
+
     if(src_y>= h){
         src+= (h-1-src_y)*linesize;
         src_y=h-1;
@@ -1014,10 +1452,10 @@ static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int bl
         src_x=1-block_w;
     }
 
-    start_y= MAX(0, -src_y);
-    start_x= MAX(0, -src_x);
-    end_y= MIN(block_h, h-src_y);
-    end_x= MIN(block_w, w-src_x);
+    start_y= FFMAX(0, -src_y);
+    start_x= FFMAX(0, -src_x);
+    end_y= FFMIN(block_h, h-src_y);
+    end_x= FFMIN(block_w, w-src_x);
 
     // copy existing part
     for(y=start_y; y<end_y; y++){
@@ -1056,21 +1494,22 @@ static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int bl
 
 /* apply one mpeg motion vector to the three components */
 static inline void mpeg_motion(MpegEncContext *s,
-                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
+                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
                                int dest_offset,
-                               UINT8 **ref_picture, int src_offset,
-                               int field_based, op_pixels_func *pix_op,
+                               uint8_t **ref_picture, int src_offset,
+                               int field_based, op_pixels_func (*pix_op)[4],
                                int motion_x, int motion_y, int h)
 {
-    UINT8 *ptr;
+    uint8_t *ptr;
     int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
     int emu=0;
-    
+#if 0    
 if(s->quarter_sample)
 {
     motion_x>>=1;
     motion_y>>=1;
 }
+#endif
     dxy = ((motion_y & 1) << 1) | (motion_x & 1);
     src_x = s->mb_x * 16 + (motion_x >> 1);
     src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
@@ -1092,13 +1531,13 @@ if(s->quarter_sample)
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 16 > s->h_edge_pos
                               || src_y + (motion_y&1) + h  > v_edge_pos){
-            emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, v_edge_pos);
-            ptr= s->edge_emu_buffer;
+            ff_emulated_edge_mc(s, ptr - src_offset, s->linesize, 17, 17+field_based, 
+                             src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
+            ptr= s->edge_emu_buffer + src_offset;
             emu=1;
         }
     }
-    pix_op[dxy](dest_y, ptr, linesize, h);
-    pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
+    pix_op[0][dxy](dest_y, ptr, linesize, h);
 
     if(s->flags&CODEC_FLAG_GRAY) return;
 
@@ -1129,29 +1568,31 @@ if(s->quarter_sample)
     offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
     ptr = ref_picture[1] + offset;
     if(emu){
-        emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
-        ptr= s->edge_emu_buffer;
+        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based, 
+                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        ptr= s->edge_emu_buffer + (src_offset >> 1);
     }
-    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
+    pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
 
     ptr = ref_picture[2] + offset;
     if(emu){
-        emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
-        ptr= s->edge_emu_buffer;
+        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based, 
+                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        ptr= s->edge_emu_buffer + (src_offset >> 1);
     }
-    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
+    pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
 }
 
 static inline void qpel_motion(MpegEncContext *s,
-                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
+                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
                                int dest_offset,
-                               UINT8 **ref_picture, int src_offset,
-                               int field_based, op_pixels_func *pix_op,
-                               qpel_mc_func *qpix_op,
+                               uint8_t **ref_picture, int src_offset,
+                               int field_based, op_pixels_func (*pix_op)[4],
+                               qpel_mc_func (*qpix_op)[16],
                                int motion_x, int motion_y, int h)
 {
-    UINT8 *ptr;
-    int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize;
+    uint8_t *ptr;
+    int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
     int emu=0;
 
     dxy = ((motion_y & 3) << 2) | (motion_x & 3);
@@ -1167,6 +1608,7 @@ static inline void qpel_motion(MpegEncContext *s,
     if (src_y == height)
         dxy &= ~12;
     linesize = s->linesize << field_based;
+    uvlinesize = s->uvlinesize << field_based;
     ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
     dest_y += dest_offset;
 //printf("%d %d %d\n", src_x, src_y, dxy);
@@ -1174,29 +1616,44 @@ static inline void qpel_motion(MpegEncContext *s,
     if(s->flags&CODEC_FLAG_EMU_EDGE){
         if(src_x<0 || src_y<0 || src_x + (motion_x&3) + 16 > s->h_edge_pos
                               || src_y + (motion_y&3) + h  > v_edge_pos){
-            emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, v_edge_pos);
-            ptr= s->edge_emu_buffer;
+            ff_emulated_edge_mc(s, ptr - src_offset, s->linesize, 17, 17+field_based, 
+                             src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
+            ptr= s->edge_emu_buffer + src_offset;
             emu=1;
         }
     }
-    qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
-    qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
-    qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
-    qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
-    
+    if(!field_based)
+        qpix_op[0][dxy](dest_y, ptr, linesize);
+    else{
+        //damn interlaced mode
+        //FIXME boundary mirroring is not exactly correct here
+        qpix_op[1][dxy](dest_y  , ptr  , linesize);
+        qpix_op[1][dxy](dest_y+8, ptr+8, linesize);
+    }
+
     if(s->flags&CODEC_FLAG_GRAY) return;
 
-    mx= (motion_x>>1) | (motion_x&1);
-    my= (motion_y>>1) | (motion_y&1);
+    if(field_based){
+        mx= motion_x/2;
+        my= motion_y>>1;
+    }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA2){
+        static const int rtab[8]= {0,0,1,1,0,0,0,1};
+        mx= (motion_x>>1) + rtab[motion_x&7];
+        my= (motion_y>>1) + rtab[motion_y&7];
+    }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA){
+        mx= (motion_x>>1)|(motion_x&1);
+        my= (motion_y>>1)|(motion_y&1);
+    }else{
+        mx= motion_x/2;
+        my= motion_y/2;
+    }
+    mx= (mx>>1)|(mx&1);
+    my= (my>>1)|(my&1);
+
+    dxy= (mx&1) | ((my&1)<<1);
+    mx>>=1;
+    my>>=1;
 
-    dxy = 0;
-    if ((mx & 3) != 0)
-        dxy |= 1;
-    if ((my & 3) != 0)
-        dxy |= 2;
-    mx = mx >> 2;
-    my = my >> 2;
-    
     src_x = s->mb_x * 8 + mx;
     src_y = s->mb_y * (8 >> field_based) + my;
     src_x = clip(src_x, -8, s->width >> 1);
@@ -1206,31 +1663,41 @@ static inline void qpel_motion(MpegEncContext *s,
     if (src_y == (height >> 1))
         dxy &= ~2;
 
-    offset = (src_y * s->uvlinesize) + src_x + (src_offset >> 1);
+    offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
     ptr = ref_picture[1] + offset;
     if(emu){
-        emulated_edge_mc(s, ptr,  s->uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
-        ptr= s->edge_emu_buffer;
+        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based, 
+                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        ptr= s->edge_emu_buffer + (src_offset >> 1);
     }
-    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr,  s->uvlinesize, h >> 1);
+    pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr,  uvlinesize, h >> 1);
     
     ptr = ref_picture[2] + offset;
     if(emu){
-        emulated_edge_mc(s, ptr,  s->uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
-        ptr= s->edge_emu_buffer;
+        ff_emulated_edge_mc(s, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based, 
+                         src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
+        ptr= s->edge_emu_buffer + (src_offset >> 1);
     }
-    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr,  s->uvlinesize, h >> 1);
+    pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr,  uvlinesize, h >> 1);
 }
 
+inline int ff_h263_round_chroma(int x){
+    if (x >= 0)
+        return  (h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
+    else {
+        x = -x;
+        return -(h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
+    }
+}
 
 static inline void MPV_motion(MpegEncContext *s, 
-                              UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
-                              int dir, UINT8 **ref_picture, 
-                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
+                              uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
+                              int dir, uint8_t **ref_picture, 
+                              op_pixels_func (*pix_op)[4], qpel_mc_func (*qpix_op)[16])
 {
     int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
     int mb_x, mb_y, i;
-    UINT8 *ptr, *dest;
+    uint8_t *ptr, *dest;
     int emu=0;
 
     mb_x = s->mb_x;
@@ -1238,25 +1705,27 @@ static inline void MPV_motion(MpegEncContext *s,
 
     switch(s->mv_type) {
     case MV_TYPE_16X16:
+#ifdef CONFIG_RISKY
         if(s->mcsel){
-#if 0
-            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
-                        ref_picture, 0,
-                        0, pix_op,
-                        s->sprite_offset[0][0]>>3,
-                        s->sprite_offset[0][1]>>3,
-                        16);
-#else
-            gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
-                        ref_picture, 0,
-                        16);
-#endif
-        }else if(s->quarter_sample && dir==0){ //FIXME
+            if(s->real_sprite_warping_points==1){
+                gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
+                            ref_picture, 0);
+            }else{
+                gmc_motion(s, dest_y, dest_cb, dest_cr, 0,
+                            ref_picture, 0);
+            }
+        }else if(s->quarter_sample){
             qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
                         ref_picture, 0,
                         0, pix_op, qpix_op,
                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
-        }else{
+        }else if(s->mspel){
+            ff_mspel_motion(s, dest_y, dest_cb, dest_cr,
+                        ref_picture, pix_op,
+                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
+        }else
+#endif
+        {
             mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
                         ref_picture, 0,
                         0, pix_op,
@@ -1264,55 +1733,77 @@ static inline void MPV_motion(MpegEncContext *s,
         }           
         break;
     case MV_TYPE_8X8:
-        for(i=0;i<4;i++) {
-            motion_x = s->mv[dir][i][0];
-            motion_y = s->mv[dir][i][1];
+        mx = 0;
+        my = 0;
+        if(s->quarter_sample){
+            for(i=0;i<4;i++) {
+                motion_x = s->mv[dir][i][0];
+                motion_y = s->mv[dir][i][1];
+
+                dxy = ((motion_y & 3) << 2) | (motion_x & 3);
+                src_x = mb_x * 16 + (motion_x >> 2) + (i & 1) * 8;
+                src_y = mb_y * 16 + (motion_y >> 2) + (i >>1) * 8;
+                    
+                /* WARNING: do no forget half pels */
+                src_x = clip(src_x, -16, s->width);
+                if (src_x == s->width)
+                    dxy &= ~3;
+                src_y = clip(src_y, -16, s->height);
+                if (src_y == s->height)
+                    dxy &= ~12;
+                    
+                ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
+                if(s->flags&CODEC_FLAG_EMU_EDGE){
+                    if(src_x<0 || src_y<0 || src_x + (motion_x&3) + 8 > s->h_edge_pos
+                                          || src_y + (motion_y&3) + 8 > s->v_edge_pos){
+                        ff_emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
+                        ptr= s->edge_emu_buffer;
+                    }
+                }
+                dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
+                qpix_op[1][dxy](dest, ptr, s->linesize);
 
-            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
-            src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
-            src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
+                mx += s->mv[dir][i][0]/2;
+                my += s->mv[dir][i][1]/2;
+            }
+        }else{
+            for(i=0;i<4;i++) {
+                motion_x = s->mv[dir][i][0];
+                motion_y = s->mv[dir][i][1];
+
+                dxy = ((motion_y & 1) << 1) | (motion_x & 1);
+                src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
+                src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
                     
-            /* WARNING: do no forget half pels */
-            src_x = clip(src_x, -16, s->width);
-            if (src_x == s->width)
-                dxy &= ~1;
-            src_y = clip(src_y, -16, s->height);
-            if (src_y == s->height)
-                dxy &= ~2;
+                /* WARNING: do no forget half pels */
+                src_x = clip(src_x, -16, s->width);
+                if (src_x == s->width)
+                    dxy &= ~1;
+                src_y = clip(src_y, -16, s->height);
+                if (src_y == s->height)
+                    dxy &= ~2;
                     
-            ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
-            if(s->flags&CODEC_FLAG_EMU_EDGE){
-                if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 8 > s->h_edge_pos
-                                      || src_y + (motion_y&1) + 8 > s->v_edge_pos){
-                    emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
-                    ptr= s->edge_emu_buffer;
+                ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
+                if(s->flags&CODEC_FLAG_EMU_EDGE){
+                    if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 8 > s->h_edge_pos
+                                          || src_y + (motion_y&1) + 8 > s->v_edge_pos){
+                        ff_emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
+                        ptr= s->edge_emu_buffer;
+                    }
                 }
+                dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
+                pix_op[1][dxy](dest, ptr, s->linesize, 8);
+
+                mx += s->mv[dir][i][0];
+                my += s->mv[dir][i][1];
             }
-            dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
-            pix_op[dxy](dest, ptr, s->linesize, 8);
         }
-    
+
         if(s->flags&CODEC_FLAG_GRAY) break;
         /* In case of 8X8, we construct a single chroma motion vector
            with a special rounding */
-        mx = 0;
-        my = 0;
-        for(i=0;i<4;i++) {
-            mx += s->mv[dir][i][0];
-            my += s->mv[dir][i][1];
-        }
-        if (mx >= 0)
-            mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
-        else {
-            mx = -mx;
-            mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
-        }
-        if (my >= 0)
-            my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
-        else {
-            my = -my;
-            my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
-        }
+        mx= ff_h263_round_chroma(mx);
+        my= ff_h263_round_chroma(my);
         dxy = ((my & 1) << 1) | (mx & 1);
         mx >>= 1;
         my >>= 1;
@@ -1331,35 +1822,58 @@ static inline void MPV_motion(MpegEncContext *s,
         if(s->flags&CODEC_FLAG_EMU_EDGE){
                 if(src_x<0 || src_y<0 || src_x + (dxy &1) + 8 > s->h_edge_pos>>1
                                       || src_y + (dxy>>1) + 8 > s->v_edge_pos>>1){
-                    emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+                    ff_emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
                     ptr= s->edge_emu_buffer;
                     emu=1;
                 }
             }
-        pix_op[dxy](dest_cb, ptr, s->uvlinesize, 8);
+        pix_op[1][dxy](dest_cb, ptr, s->uvlinesize, 8);
 
         ptr = ref_picture[2] + offset;
         if(emu){
-            emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
+            ff_emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
             ptr= s->edge_emu_buffer;
         }
-        pix_op[dxy](dest_cr, ptr, s->uvlinesize, 8);
+        pix_op[1][dxy](dest_cr, ptr, s->uvlinesize, 8);
         break;
     case MV_TYPE_FIELD:
         if (s->picture_structure == PICT_FRAME) {
-            /* top field */
-            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
-                        ref_picture, s->field_select[dir][0] ? s->linesize : 0,
-                        1, pix_op,
-                        s->mv[dir][0][0], s->mv[dir][0][1], 8);
-            /* bottom field */
-            mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
-                        ref_picture, s->field_select[dir][1] ? s->linesize : 0,
-                        1, pix_op,
-                        s->mv[dir][1][0], s->mv[dir][1][1], 8);
+            if(s->quarter_sample){
+                /* top field */
+                qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
+                            ref_picture, s->field_select[dir][0] ? s->linesize : 0,
+                            1, pix_op, qpix_op,
+                            s->mv[dir][0][0], s->mv[dir][0][1], 8);
+                /* bottom field */
+                qpel_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
+                            ref_picture, s->field_select[dir][1] ? s->linesize : 0,
+                            1, pix_op, qpix_op,
+                            s->mv[dir][1][0], s->mv[dir][1][1], 8);
+            }else{
+                /* top field */       
+                mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
+                            ref_picture, s->field_select[dir][0] ? s->linesize : 0,
+                            1, pix_op,
+                            s->mv[dir][0][0], s->mv[dir][0][1], 8);
+                /* bottom field */
+                mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
+                            ref_picture, s->field_select[dir][1] ? s->linesize : 0,
+                            1, pix_op,
+                            s->mv[dir][1][0], s->mv[dir][1][1], 8);
+            }
         } else {
-            
+            int offset;
+            if(s->picture_structure == s->field_select[dir][0] + 1 || s->pict_type == B_TYPE || s->first_field){
+                offset= s->field_select[dir][0] ? s->linesize/2 : 0;
+            }else{
+                ref_picture= s->current_picture.data;
+                offset= s->field_select[dir][0] ? s->linesize/2 : -s->linesize/2; 
+            } 
 
+            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
+                        ref_picture, offset,
+                        0, pix_op,
+                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
         }
         break;
     }
@@ -1368,29 +1882,28 @@ static inline void MPV_motion(MpegEncContext *s,
 
 /* put block[] to dest[] */
 static inline void put_dct(MpegEncContext *s, 
-                           DCTELEM *block, int i, UINT8 *dest, int line_size)
+                           DCTELEM *block, int i, uint8_t *dest, int line_size)
 {
-    if (!s->mpeg2)
-        s->dct_unquantize(s, block, i, s->qscale);
-    ff_idct_put (dest, line_size, block);
+    s->dct_unquantize(s, block, i, s->qscale);
+    s->dsp.idct_put (dest, line_size, block);
 }
 
 /* add block[] to dest[] */
 static inline void add_dct(MpegEncContext *s, 
-                           DCTELEM *block, int i, UINT8 *dest, int line_size)
+                           DCTELEM *block, int i, uint8_t *dest, int line_size)
 {
     if (s->block_last_index[i] >= 0) {
-        ff_idct_add (dest, line_size, block);
+        s->dsp.idct_add (dest, line_size, block);
     }
 }
 
 static inline void add_dequant_dct(MpegEncContext *s, 
-                           DCTELEM *block, int i, UINT8 *dest, int line_size)
+                           DCTELEM *block, int i, uint8_t *dest, int line_size)
 {
     if (s->block_last_index[i] >= 0) {
         s->dct_unquantize(s, block, i, s->qscale);
 
-        ff_idct_add (dest, line_size, block);
+        s->dsp.idct_add (dest, line_size, block);
     }
 }
 
@@ -1407,8 +1920,8 @@ void ff_clean_intra_table_entries(MpegEncContext *s)
     s->dc_val[0][xy     + wrap] =
     s->dc_val[0][xy + 1 + wrap] = 1024;
     /* ac pred */
-    memset(s->ac_val[0][xy       ], 0, 32 * sizeof(INT16));
-    memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(INT16));
+    memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
+    memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
     if (s->msmpeg4_version>=3) {
         s->coded_block[xy           ] =
         s->coded_block[xy + 1       ] =
@@ -1421,8 +1934,8 @@ void ff_clean_intra_table_entries(MpegEncContext *s)
     s->dc_val[1][xy] =
     s->dc_val[2][xy] = 1024;
     /* ac pred */
-    memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
-    memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
+    memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
+    memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
     
     s->mbintra_table[s->mb_x + s->mb_y*s->mb_width]= 0;
 }
@@ -1445,15 +1958,7 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
     mb_x = s->mb_x;
     mb_y = s->mb_y;
 
-#ifdef FF_POSTPROCESS
-    /* Obsolete. Exists for compatibility with mplayer only. */
-    quant_store[mb_y][mb_x]=s->qscale;
-    //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
-#else
-    /* even more obsolete, exists for mplayer xp only */
-    if(s->avctx->quant_store) s->avctx->quant_store[mb_y*s->avctx->qstride+mb_x] = s->qscale;
-#endif
-    s->qscale_table[mb_xy]= s->qscale;
+    s->current_picture.qscale_table[mb_xy]= s->qscale;
 
     /* update DC predictors for P macroblocks */
     if (!s->mb_intra) {
@@ -1471,24 +1976,35 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
 
     /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
     if (s->out_format == FMT_H263 && s->pict_type!=B_TYPE) { //FIXME move into h263.c if possible, format specific stuff shouldnt be here
-        
+        //FIXME a lot of thet is only needed for !low_delay
         const int wrap = s->block_wrap[0];
         const int xy = s->block_index[0];
+        const int mb_index= s->mb_x + s->mb_y*s->mb_width;
         if(s->mv_type == MV_TYPE_8X8){
-            s->non_b_mv4_table[xy]=1;
+            s->co_located_type_table[mb_index]= CO_LOCATED_TYPE_4MV;
         } else {
             int motion_x, motion_y;
             if (s->mb_intra) {
                 motion_x = 0;
                 motion_y = 0;
+                if(s->co_located_type_table)
+                    s->co_located_type_table[mb_index]= 0;
             } else if (s->mv_type == MV_TYPE_16X16) {
                 motion_x = s->mv[0][0][0];
                 motion_y = s->mv[0][0][1];
+                if(s->co_located_type_table)
+                    s->co_located_type_table[mb_index]= 0;
             } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
+                int i;
                 motion_x = s->mv[0][0][0] + s->mv[0][1][0];
                 motion_y = s->mv[0][0][1] + s->mv[0][1][1];
                 motion_x = (motion_x>>1) | (motion_x&1);
-                motion_y = (motion_y>>1) | (motion_y&1);
+                for(i=0; i<2; i++){
+                    s->field_mv_table[mb_index][i][0]= s->mv[0][i][0];
+                    s->field_mv_table[mb_index][i][1]= s->mv[0][i][1];
+                    s->field_select_table[mb_index][i]= s->field_select[0][i];
+                }
+                s->co_located_type_table[mb_index]= CO_LOCATED_TYPE_FIELDMV;
             }
             /* no update if 8X8 because it has been done during parsing */
             s->motion_val[xy][0] = motion_x;
@@ -1499,38 +2015,56 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
             s->motion_val[xy + wrap][1] = motion_y;
             s->motion_val[xy + 1 + wrap][0] = motion_x;
             s->motion_val[xy + 1 + wrap][1] = motion_y;
-            s->non_b_mv4_table[xy]=0;
         }
     }
     
-    if (!(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) {
-        UINT8 *dest_y, *dest_cb, *dest_cr;
+    if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) { //FIXME precalc
+        uint8_t *dest_y, *dest_cb, *dest_cr;
         int dct_linesize, dct_offset;
-        op_pixels_func *op_pix;
-        qpel_mc_func *op_qpix;
+        op_pixels_func (*op_pix)[4];
+        qpel_mc_func (*op_qpix)[16];
 
-        /* avoid copy if macroblock skipped in last frame too 
-           dont touch it for B-frames as they need the skip info from the next p-frame */
+        /* avoid copy if macroblock skipped in last frame too */
         if (s->pict_type != B_TYPE) {
-            UINT8 *mbskip_ptr = &s->mbskip_table[mb_xy];
-            if (s->mb_skiped) {
-                s->mb_skiped = 0;
+            s->current_picture.mbskip_table[mb_xy]= s->mb_skiped;
+        }
+
+        /* skip only during decoding as we might trash the buffers during encoding a bit */
+        if(!s->encoding){
+            uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
+            const int age= s->current_picture.age;
 
+            assert(age);
+
+            if (s->mb_skiped) {
+                s->mb_skiped= 0;
+                assert(s->pict_type!=I_TYPE);
                 (*mbskip_ptr) ++; /* indicate that this time we skiped it */
                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
 
-                /* if previous was skipped too, then nothing to do ! 
-                   skip only during decoding as we might trash the buffers during encoding a bit */
-                if (*mbskip_ptr >= s->ip_buffer_count  && !s->encoding) 
-                    goto the_end;
-            } else {
+                /* if previous was skipped too, then nothing to do !  */
+                if (*mbskip_ptr >= age && s->current_picture.reference){
+                    return;
+                }
+            } else if(!s->current_picture.reference){
+                (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */
+                if(*mbskip_ptr >99) *mbskip_ptr= 99;
+            } else{
                 *mbskip_ptr = 0; /* not skipped */
             }
-        }
+        }else
+            s->mb_skiped= 0;
 
-        dest_y = s->current_picture [0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
-        dest_cb = s->current_picture[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
-        dest_cr = s->current_picture[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
+        if(s->pict_type==B_TYPE && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME){ //FIXME precalc
+            dest_y  = s->current_picture.data[0] + mb_x * 16;
+            dest_cb = s->current_picture.data[1] + mb_x * 8;
+            dest_cr = s->current_picture.data[2] + mb_x * 8;
+        }else{
+            dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
+            dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
+            dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
+        }
 
         if (s->interlaced_dct) {
             dct_linesize = s->linesize * 2;
@@ -1545,30 +2079,29 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
             /* decoding or more than one mb_type (MC was allready done otherwise) */
             if((!s->encoding) || (s->mb_type[mb_xy]&(s->mb_type[mb_xy]-1))){
                 if ((!s->no_rounding) || s->pict_type==B_TYPE){                
-                    op_pix = put_pixels_tab;
-                    op_qpix= qpel_mc_rnd_tab;
+                   op_pix = s->dsp.put_pixels_tab;
+                    op_qpix= s->dsp.put_qpel_pixels_tab;
                 }else{
-                    op_pix = put_no_rnd_pixels_tab;
-                    op_qpix= qpel_mc_no_rnd_tab;
+                    op_pix = s->dsp.put_no_rnd_pixels_tab;
+                    op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
                 }
 
                 if (s->mv_dir & MV_DIR_FORWARD) {
-                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
-                    if ((!s->no_rounding) || s->pict_type==B_TYPE)
-                        op_pix = avg_pixels_tab;
-                    else
-                        op_pix = avg_no_rnd_pixels_tab;
+                    MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
+                   op_pix = s->dsp.avg_pixels_tab;
+                    op_qpix= s->dsp.avg_qpel_pixels_tab;
                 }
                 if (s->mv_dir & MV_DIR_BACKWARD) {
-                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
+                    MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
                 }
             }
 
             /* skip dequant / idct if we are really late ;) */
-            if(s->hurry_up>1) goto the_end;
+            if(s->hurry_up>1) return;
 
             /* add dct residue */
-            if(s->encoding || !(s->mpeg2 || s->h263_msmpeg4 || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
+            if(s->encoding || !(   s->mpeg2 || s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO 
+                                || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
                 add_dequant_dct(s, block[0], 0, dest_y, dct_linesize);
                 add_dequant_dct(s, block[1], 1, dest_y + 8, dct_linesize);
                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
@@ -1578,7 +2111,7 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
                     add_dequant_dct(s, block[4], 4, dest_cb, s->uvlinesize);
                     add_dequant_dct(s, block[5], 5, dest_cr, s->uvlinesize);
                 }
-            } else {
+            } else if(s->codec_id != CODEC_ID_WMV2){
                 add_dct(s, block[0], 0, dest_y, dct_linesize);
                 add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
                 add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
@@ -1588,24 +2121,41 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
                     add_dct(s, block[4], 4, dest_cb, s->uvlinesize);
                     add_dct(s, block[5], 5, dest_cr, s->uvlinesize);
                 }
+            } 
+#ifdef CONFIG_RISKY
+            else{
+                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
             }
+#endif
         } else {
             /* dct only in intra block */
-            put_dct(s, block[0], 0, dest_y, dct_linesize);
-            put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
-            put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
-            put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
-
-            if(!(s->flags&CODEC_FLAG_GRAY)){
-                put_dct(s, block[4], 4, dest_cb, s->uvlinesize);
-                put_dct(s, block[5], 5, dest_cr, s->uvlinesize);
+            if(s->encoding || !(s->mpeg2 || s->codec_id==CODEC_ID_MPEG1VIDEO)){
+                put_dct(s, block[0], 0, dest_y, dct_linesize);
+                put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
+                put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
+                put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
+
+                if(!(s->flags&CODEC_FLAG_GRAY)){
+                    put_dct(s, block[4], 4, dest_cb, s->uvlinesize);
+                    put_dct(s, block[5], 5, dest_cr, s->uvlinesize);
+                }
+            }else{
+                s->dsp.idct_put(dest_y                 , dct_linesize, block[0]);
+                s->dsp.idct_put(dest_y              + 8, dct_linesize, block[1]);
+                s->dsp.idct_put(dest_y + dct_offset    , dct_linesize, block[2]);
+                s->dsp.idct_put(dest_y + dct_offset + 8, dct_linesize, block[3]);
+
+                if(!(s->flags&CODEC_FLAG_GRAY)){
+                    s->dsp.idct_put(dest_cb, s->uvlinesize, block[4]);
+                    s->dsp.idct_put(dest_cr, s->uvlinesize, block[5]);
+                }
             }
         }
     }
- the_end:
-    emms_c(); //FIXME remove
 }
 
+#ifdef CONFIG_ENCODERS
+
 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
 {
     static const char tab[64]=
@@ -1634,7 +2184,7 @@ static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int th
     if(last_index<=skip_dc - 1) return;
 
     for(i=0; i<=last_index; i++){
-        const int j = zigzag_direct[i];
+        const int j = s->intra_scantable.permutated[i];
         const int level = ABS(block[j]);
         if(level==1){
             if(skip_dc && i==0) continue;
@@ -1648,7 +2198,7 @@ static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int th
     }
     if(score >= threshold) return;
     for(i=skip_dc; i<=last_index; i++){
-        const int j = zigzag_direct[i];
+        const int j = s->intra_scantable.permutated[i];
         block[j]=0;
     }
     if(block[0]) s->block_last_index[n]= 0;
@@ -1660,140 +2210,294 @@ static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index
     int i;
     const int maxlevel= s->max_qcoeff;
     const int minlevel= s->min_qcoeff;
-        
-    for(i=0;i<=last_index; i++){
-        const int j = zigzag_direct[i];
+    
+    if(s->mb_intra){
+        i=1; //skip clipping of intra dc
+    }else
+        i=0;
+    
+    for(;i<=last_index; i++){
+        const int j= s->intra_scantable.permutated[i];
         int level = block[j];
        
         if     (level>maxlevel) level=maxlevel;
         else if(level<minlevel) level=minlevel;
+
         block[j]= level;
     }
 }
 
+#if 0
+static int pix_vcmp16x8(uint8_t *s, int stride){ //FIXME move to dsputil & optimize
+    int score=0;
+    int x,y;
+    
+    for(y=0; y<7; y++){
+        for(x=0; x<16; x+=4){
+            score+= ABS(s[x  ] - s[x  +stride]) + ABS(s[x+1] - s[x+1+stride]) 
+                   +ABS(s[x+2] - s[x+2+stride]) + ABS(s[x+3] - s[x+3+stride]);
+        }
+        s+= stride;
+    }
+    
+    return score;
+}
+
+static int pix_diff_vcmp16x8(uint8_t *s1, uint8_t*s2, int stride){ //FIXME move to dsputil & optimize
+    int score=0;
+    int x,y;
+    
+    for(y=0; y<7; y++){
+        for(x=0; x<16; x++){
+            score+= ABS(s1[x  ] - s2[x ] - s1[x  +stride] + s2[x +stride]);
+        }
+        s1+= stride;
+        s2+= stride;
+    }
+    
+    return score;
+}
+#else
+#define SQ(a) ((a)*(a))
+
+static int pix_vcmp16x8(uint8_t *s, int stride){ //FIXME move to dsputil & optimize
+    int score=0;
+    int x,y;
+    
+    for(y=0; y<7; y++){
+        for(x=0; x<16; x+=4){
+            score+= SQ(s[x  ] - s[x  +stride]) + SQ(s[x+1] - s[x+1+stride]) 
+                   +SQ(s[x+2] - s[x+2+stride]) + SQ(s[x+3] - s[x+3+stride]);
+        }
+        s+= stride;
+    }
+    
+    return score;
+}
+
+static int pix_diff_vcmp16x8(uint8_t *s1, uint8_t*s2, int stride){ //FIXME move to dsputil & optimize
+    int score=0;
+    int x,y;
+    
+    for(y=0; y<7; y++){
+        for(x=0; x<16; x++){
+            score+= SQ(s1[x  ] - s2[x ] - s1[x  +stride] + s2[x +stride]);
+        }
+        s1+= stride;
+        s2+= stride;
+    }
+    
+    return score;
+}
+
+#endif
+
+#endif //CONFIG_ENCODERS
+
+/**
+ *
+ * @param h is the normal height, this will be reduced automatically if needed for the last row
+ */
+void ff_draw_horiz_band(MpegEncContext *s, int y, int h){
+    if (    s->avctx->draw_horiz_band 
+        && (s->last_picture.data[0] || s->low_delay) ) {
+        uint8_t *src_ptr[3];
+        int offset;
+        h= FFMIN(h, s->height - y);
+
+        if(s->pict_type==B_TYPE && s->picture_structure == PICT_FRAME)
+            offset = 0;
+        else
+            offset = y * s->linesize;
+
+        if(s->pict_type==B_TYPE || s->low_delay){
+            src_ptr[0] = s->current_picture.data[0] + offset;
+            src_ptr[1] = s->current_picture.data[1] + (offset >> 2);
+            src_ptr[2] = s->current_picture.data[2] + (offset >> 2);
+        } else {
+            src_ptr[0] = s->last_picture.data[0] + offset;
+            src_ptr[1] = s->last_picture.data[1] + (offset >> 2);
+            src_ptr[2] = s->last_picture.data[2] + (offset >> 2);
+        }
+        emms_c();
+
+        s->avctx->draw_horiz_band(s->avctx, src_ptr, s->linesize,
+                               y, s->width, h);
+    }
+}
+
+#ifdef CONFIG_ENCODERS
+
 static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
 {
     const int mb_x= s->mb_x;
     const int mb_y= s->mb_y;
     int i;
     int skip_dct[6];
-#if 0
-        if (s->interlaced_dct) {
-            dct_linesize = s->linesize * 2;
-            dct_offset = s->linesize;
-        } else {
-            dct_linesize = s->linesize;
-            dct_offset = s->linesize * 8;
-        }
-#endif
+    int dct_offset   = s->linesize*8; //default for progressive frames
+    
     for(i=0; i<6; i++) skip_dct[i]=0;
+    
+    if(s->adaptive_quant){
+        s->dquant= s->current_picture.qscale_table[mb_x + mb_y*s->mb_width] - s->qscale;
+
+        if(s->out_format==FMT_H263){
+            if     (s->dquant> 2) s->dquant= 2;
+            else if(s->dquant<-2) s->dquant=-2;
+        }
+            
+        if(s->codec_id==CODEC_ID_MPEG4){        
+            if(!s->mb_intra){
+                assert(s->dquant==0 || s->mv_type!=MV_TYPE_8X8);
+
+                if(s->mv_dir&MV_DIRECT)
+                    s->dquant=0;
+            }
+        }
+        s->qscale+= s->dquant;
+        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
+        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
+    }
 
     if (s->mb_intra) {
-        UINT8 *ptr;
-        int wrap;
+        uint8_t *ptr;
+        int wrap_y;
         int emu=0;
 
-        wrap = s->linesize;
-        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
+        wrap_y = s->linesize;
+        ptr = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
+
         if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
-            emulated_edge_mc(s, ptr, wrap, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
+            ff_emulated_edge_mc(s, ptr, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
             ptr= s->edge_emu_buffer;
             emu=1;
         }
-        get_pixels(s->block[0], ptr               , wrap);
-        get_pixels(s->block[1], ptr            + 8, wrap);
-        get_pixels(s->block[2], ptr + 8 * wrap    , wrap);
-        get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
+        
+        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
+            int progressive_score, interlaced_score;
+            
+            progressive_score= pix_vcmp16x8(ptr, wrap_y  ) + pix_vcmp16x8(ptr + wrap_y*8, wrap_y );
+            interlaced_score = pix_vcmp16x8(ptr, wrap_y*2) + pix_vcmp16x8(ptr + wrap_y  , wrap_y*2);
+            
+            if(progressive_score > interlaced_score + 100){
+                s->interlaced_dct=1;
+            
+                dct_offset= wrap_y;
+                wrap_y<<=1;
+            }else
+                s->interlaced_dct=0;
+        }
+        
+       s->dsp.get_pixels(s->block[0], ptr                 , wrap_y);
+        s->dsp.get_pixels(s->block[1], ptr              + 8, wrap_y);
+        s->dsp.get_pixels(s->block[2], ptr + dct_offset    , wrap_y);
+        s->dsp.get_pixels(s->block[3], ptr + dct_offset + 8, wrap_y);
 
         if(s->flags&CODEC_FLAG_GRAY){
             skip_dct[4]= 1;
             skip_dct[5]= 1;
         }else{
-            wrap >>=1;
-            ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
+            int wrap_c = s->uvlinesize;
+            ptr = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
             if(emu){
-                emulated_edge_mc(s, ptr, wrap, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+                ff_emulated_edge_mc(s, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
                 ptr= s->edge_emu_buffer;
             }
-            get_pixels(s->block[4], ptr, wrap);
+           s->dsp.get_pixels(s->block[4], ptr, wrap_c);
 
-            ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
+            ptr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
             if(emu){
-                emulated_edge_mc(s, ptr, wrap, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+                ff_emulated_edge_mc(s, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
                 ptr= s->edge_emu_buffer;
             }
-            get_pixels(s->block[5], ptr, wrap);
+            s->dsp.get_pixels(s->block[5], ptr, wrap_c);
         }
     }else{
-        op_pixels_func *op_pix;
-        qpel_mc_func *op_qpix;
-        UINT8 *dest_y, *dest_cb, *dest_cr;
-        UINT8 *ptr_y, *ptr_cb, *ptr_cr;
+        op_pixels_func (*op_pix)[4];
+        qpel_mc_func (*op_qpix)[16];
+        uint8_t *dest_y, *dest_cb, *dest_cr;
+        uint8_t *ptr_y, *ptr_cb, *ptr_cr;
         int wrap_y, wrap_c;
         int emu=0;
 
-        dest_y  = s->current_picture[0] + (mb_y * 16 * s->linesize       ) + mb_x * 16;
-        dest_cb = s->current_picture[1] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
-        dest_cr = s->current_picture[2] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
+        dest_y  = s->current_picture.data[0] + (mb_y * 16 * s->linesize    ) + mb_x * 16;
+        dest_cb = s->current_picture.data[1] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
+        dest_cr = s->current_picture.data[2] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
         wrap_y = s->linesize;
-        wrap_c = wrap_y>>1;
-        ptr_y  = s->new_picture[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
-        ptr_cb = s->new_picture[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
-        ptr_cr = s->new_picture[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
+        wrap_c = s->uvlinesize;
+        ptr_y  = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
+        ptr_cb = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
+        ptr_cr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
 
         if ((!s->no_rounding) || s->pict_type==B_TYPE){
-            op_pix = put_pixels_tab;
-            op_qpix= qpel_mc_rnd_tab;
+           op_pix = s->dsp.put_pixels_tab;
+            op_qpix= s->dsp.put_qpel_pixels_tab;
         }else{
-            op_pix = put_no_rnd_pixels_tab;
-            op_qpix= qpel_mc_no_rnd_tab;
+            op_pix = s->dsp.put_no_rnd_pixels_tab;
+            op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
         }
 
         if (s->mv_dir & MV_DIR_FORWARD) {
-            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
-           if ((!s->no_rounding) || s->pict_type==B_TYPE)
-                op_pix = avg_pixels_tab;
-            else
-                op_pix = avg_no_rnd_pixels_tab;
+            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
+            op_pix = s->dsp.avg_pixels_tab;
+            op_qpix= s->dsp.avg_qpel_pixels_tab;
         }
         if (s->mv_dir & MV_DIR_BACKWARD) {
-            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
+            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
         }
 
         if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
-            emulated_edge_mc(s, ptr_y, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
+            ff_emulated_edge_mc(s, ptr_y, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
             ptr_y= s->edge_emu_buffer;
             emu=1;
         }
-        diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
-        diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
-        diff_pixels(s->block[2], ptr_y + 8 * wrap_y    , dest_y + 8 * wrap_y    , wrap_y);
-        diff_pixels(s->block[3], ptr_y + 8 * wrap_y + 8, dest_y + 8 * wrap_y + 8, wrap_y);
+        
+        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
+            int progressive_score, interlaced_score;
+            
+            progressive_score= pix_diff_vcmp16x8(ptr_y           , dest_y           , wrap_y  ) 
+                             + pix_diff_vcmp16x8(ptr_y + wrap_y*8, dest_y + wrap_y*8, wrap_y  );
+            interlaced_score = pix_diff_vcmp16x8(ptr_y           , dest_y           , wrap_y*2)
+                             + pix_diff_vcmp16x8(ptr_y + wrap_y  , dest_y + wrap_y  , wrap_y*2);
+            
+            if(progressive_score > interlaced_score + 600){
+                s->interlaced_dct=1;
+            
+                dct_offset= wrap_y;
+                wrap_y<<=1;
+            }else
+                s->interlaced_dct=0;
+        }
+        
+       s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
+        s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
+        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
+        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
         
         if(s->flags&CODEC_FLAG_GRAY){
             skip_dct[4]= 1;
             skip_dct[5]= 1;
         }else{
             if(emu){
-                emulated_edge_mc(s, ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+                ff_emulated_edge_mc(s, ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
                 ptr_cb= s->edge_emu_buffer;
             }
-            diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
+            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
             if(emu){
-                emulated_edge_mc(s, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
+                ff_emulated_edge_mc(s, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
                 ptr_cr= s->edge_emu_buffer;
             }
-            diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
+            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
         }
-
         /* pre quantization */         
-        if(s->mc_mb_var[s->mb_width*mb_y+ mb_x]<2*s->qscale*s->qscale){
-            if(pix_abs8x8(ptr_y               , dest_y               , wrap_y) < 20*s->qscale) skip_dct[0]= 1;
-            if(pix_abs8x8(ptr_y            + 8, dest_y            + 8, wrap_y) < 20*s->qscale) skip_dct[1]= 1;
-            if(pix_abs8x8(ptr_y + 8*wrap_y    , dest_y + 8*wrap_y    , wrap_y) < 20*s->qscale) skip_dct[2]= 1;
-            if(pix_abs8x8(ptr_y + 8*wrap_y + 8, dest_y + 8*wrap_y + 8, wrap_y) < 20*s->qscale) skip_dct[3]= 1;
-            if(pix_abs8x8(ptr_cb              , dest_cb              , wrap_y) < 20*s->qscale) skip_dct[4]= 1;
-            if(pix_abs8x8(ptr_cr              , dest_cr              , wrap_y) < 20*s->qscale) skip_dct[5]= 1;
+        if(s->current_picture.mc_mb_var[s->mb_width*mb_y+ mb_x]<2*s->qscale*s->qscale){
+            //FIXME optimize
+           if(s->dsp.pix_abs8x8(ptr_y               , dest_y               , wrap_y) < 20*s->qscale) skip_dct[0]= 1;
+            if(s->dsp.pix_abs8x8(ptr_y            + 8, dest_y            + 8, wrap_y) < 20*s->qscale) skip_dct[1]= 1;
+            if(s->dsp.pix_abs8x8(ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y) < 20*s->qscale) skip_dct[2]= 1;
+            if(s->dsp.pix_abs8x8(ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y) < 20*s->qscale) skip_dct[3]= 1;
+            if(s->dsp.pix_abs8x8(ptr_cb              , dest_cb              , wrap_c) < 20*s->qscale) skip_dct[4]= 1;
+            if(s->dsp.pix_abs8x8(ptr_cr              , dest_cr              , wrap_c) < 20*s->qscale) skip_dct[5]= 1;
 #if 0
 {
  static int stat[7];
@@ -1857,29 +2561,67 @@ static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
         s->block_last_index[4]=
         s->block_last_index[5]= 0;
         s->block[4][0]=
-        s->block[5][0]= 128;
+        s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
     }
 
     /* huffman encode */
-    switch(s->out_format) {
-    case FMT_MPEG1:
-        mpeg1_encode_mb(s, s->block, motion_x, motion_y);
-        break;
-    case FMT_H263:
-        if (s->h263_msmpeg4)
-            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
-        else if(s->h263_pred)
-            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
-        else
-            h263_encode_mb(s, s->block, motion_x, motion_y);
-        break;
-    case FMT_MJPEG:
-        mjpeg_encode_mb(s, s->block);
-        break;
+    switch(s->codec_id){ //FIXME funct ptr could be slightly faster
+    case CODEC_ID_MPEG1VIDEO:
+        mpeg1_encode_mb(s, s->block, motion_x, motion_y); break;
+#ifdef CONFIG_RISKY
+    case CODEC_ID_MPEG4:
+        mpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
+    case CODEC_ID_MSMPEG4V2:
+    case CODEC_ID_MSMPEG4V3:
+    case CODEC_ID_WMV1:
+        msmpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
+    case CODEC_ID_WMV2:
+         ff_wmv2_encode_mb(s, s->block, motion_x, motion_y); break;
+    case CODEC_ID_H263:
+    case CODEC_ID_H263P:
+    case CODEC_ID_RV10:
+        h263_encode_mb(s, s->block, motion_x, motion_y); break;
+#endif
+    case CODEC_ID_MJPEG:
+        mjpeg_encode_mb(s, s->block); break;
+    default:
+        assert(0);
+    }
+}
+
+#endif //CONFIG_ENCODERS
+
+/**
+ * combines the (truncated) bitstream to a complete frame
+ * @returns -1 if no complete frame could be created
+ */
+int ff_combine_frame( MpegEncContext *s, int next, uint8_t **buf, int *buf_size){
+    ParseContext *pc= &s->parse_context;
+        
+    pc->last_index= pc->index;
+
+    if(next==-1){
+        pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
+
+        memcpy(&pc->buffer[pc->index], *buf, *buf_size);
+        pc->index += *buf_size;
+        return -1;
+    }
+
+    if(pc->index){
+        pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
+
+        memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
+        pc->index = 0;
+        *buf= pc->buffer;
+        *buf_size= pc->last_index + next;
     }
+
+    return 0;
 }
 
-void ff_copy_bits(PutBitContext *pb, UINT8 *src, int length)
+#ifdef CONFIG_ENCODERS
+void ff_copy_bits(PutBitContext *pb, uint8_t *src, int length)
 {
     int bytes= length>>4;
     int bits= length&15;
@@ -1906,12 +2648,14 @@ static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext
     d->i_tex_bits= s->i_tex_bits;
     d->p_tex_bits= s->p_tex_bits;
     d->i_count= s->i_count;
-    d->p_count= s->p_count;
+    d->f_count= s->f_count;
+    d->b_count= s->b_count;
     d->skip_count= s->skip_count;
     d->misc_bits= s->misc_bits;
     d->last_bits= 0;
 
     d->mb_skiped= s->mb_skiped;
+    d->qscale= s->qscale;
 }
 
 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
@@ -1930,7 +2674,8 @@ static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *
     d->i_tex_bits= s->i_tex_bits;
     d->p_tex_bits= s->p_tex_bits;
     d->i_count= s->i_count;
-    d->p_count= s->p_count;
+    d->f_count= s->f_count;
+    d->b_count= s->b_count;
     d->skip_count= s->skip_count;
     d->misc_bits= s->misc_bits;
 
@@ -1946,6 +2691,8 @@ static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *
     d->block= s->block;
     for(i=0; i<6; i++)
         d->block_last_index[i]= s->block_last_index[i];
+    d->interlaced_dct= s->interlaced_dct;
+    d->qscale= s->qscale;
 }
 
 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type, 
@@ -1978,16 +2725,37 @@ static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegE
         copy_context_after_encode(best, s, type);
     }
 }
+                
+static inline int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
+    uint32_t *sq = squareTbl + 256;
+    int acc=0;
+    int x,y;
+    
+    if(w==16 && h==16) 
+        return s->dsp.sse[0](NULL, src1, src2, stride);
+    else if(w==8 && h==8)
+        return s->dsp.sse[1](NULL, src1, src2, stride);
+    
+    for(y=0; y<h; y++){
+        for(x=0; x<w; x++){
+            acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
+        } 
+    }
+    
+    assert(acc>=0);
+    
+    return acc;
+}
 
 static void encode_picture(MpegEncContext *s, int picture_number)
 {
-    int mb_x, mb_y, last_gob, pdif = 0;
+    int mb_x, mb_y, pdif = 0;
     int i;
     int bits;
     MpegEncContext best_s, backup_s;
-    UINT8 bit_buf[2][3000];
-    UINT8 bit_buf2[2][3000];
-    UINT8 bit_buf_tex[2][3000];
+    uint8_t bit_buf[2][3000];
+    uint8_t bit_buf2[2][3000];
+    uint8_t bit_buf_tex[2][3000];
     PutBitContext pb[2], pb2[2], tex_pb[2];
 
     for(i=0; i<2; i++){
@@ -2006,17 +2774,48 @@ static void encode_picture(MpegEncContext *s, int picture_number)
     s->block_wrap[5]= s->mb_width + 2;
     
     /* Reset the average MB variance */
-    s->mb_var_sum = 0;
-    s->mc_mb_var_sum = 0;
+    s->current_picture.mb_var_sum = 0;
+    s->current_picture.mc_mb_var_sum = 0;
 
+#ifdef CONFIG_RISKY
     /* we need to initialize some time vars before we can encode b-frames */
-    if (s->h263_pred && !s->h263_msmpeg4)
+    // RAL: Condition added for MPEG1VIDEO
+    if (s->codec_id == CODEC_ID_MPEG1VIDEO || (s->h263_pred && !s->h263_msmpeg4))
         ff_set_mpeg4_time(s, s->picture_number); 
-
+#endif
+        
     s->scene_change_score=0;
-
+    
+    s->qscale= (int)(s->frame_qscale + 0.5); //FIXME qscale / ... stuff for ME ratedistoration
+    
+    if(s->pict_type==I_TYPE){
+        if(s->msmpeg4_version) s->no_rounding=1;
+        else                   s->no_rounding=0;
+    }else if(s->pict_type!=B_TYPE){
+        if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
+            s->no_rounding ^= 1;          
+    }
+    
     /* Estimate motion for every MB */
+    s->mb_intra=0; //for the rate distoration & bit compare functions
     if(s->pict_type != I_TYPE){
+        if(s->pict_type != B_TYPE){
+            if((s->avctx->pre_me && s->last_non_b_pict_type==I_TYPE) || s->avctx->pre_me==2){
+                s->me.pre_pass=1;
+                s->me.dia_size= s->avctx->pre_dia_size;
+
+                for(mb_y=s->mb_height-1; mb_y >=0 ; mb_y--) {
+                    for(mb_x=s->mb_width-1; mb_x >=0 ; mb_x--) {
+                        s->mb_x = mb_x;
+                        s->mb_y = mb_y;
+                        ff_pre_estimate_p_frame_motion(s, mb_x, mb_y);
+                    }
+                }
+                s->me.pre_pass=0;
+            }
+        }
+
+        s->me.dia_size= s->avctx->dia_size;
         for(mb_y=0; mb_y < s->mb_height; mb_y++) {
             s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
             s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
@@ -2029,22 +2828,20 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                 s->block_index[1]+=2;
                 s->block_index[2]+=2;
                 s->block_index[3]+=2;
-
+                
                 /* compute motion vector & mb_type and store in context */
                 if(s->pict_type==B_TYPE)
                     ff_estimate_b_frame_motion(s, mb_x, mb_y);
                 else
                     ff_estimate_p_frame_motion(s, mb_x, mb_y);
-//                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
             }
         }
-        emms_c();
     }else /* if(s->pict_type == I_TYPE) */{
         /* I-Frame */
         //FIXME do we need to zero them?
-        memset(s->motion_val[0], 0, sizeof(INT16)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
-        memset(s->p_mv_table   , 0, sizeof(INT16)*(s->mb_width+2)*(s->mb_height+2)*2);
-        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
+        memset(s->motion_val[0], 0, sizeof(int16_t)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
+        memset(s->p_mv_table   , 0, sizeof(int16_t)*(s->mb_width+2)*(s->mb_height+2)*2);
+        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(uint8_t)*s->mb_width*s->mb_height);
         
         if(!s->fixed_qscale){
             /* finding spatial complexity for I-frame rate control */
@@ -2052,64 +2849,103 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                 for(mb_x=0; mb_x < s->mb_width; mb_x++) {
                     int xx = mb_x * 16;
                     int yy = mb_y * 16;
-                    uint8_t *pix = s->new_picture[0] + (yy * s->linesize) + xx;
+                    uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
                     int varc;
-                    int sum = pix_sum(pix, s->linesize);
+                   int sum = s->dsp.pix_sum(pix, s->linesize);
     
-                    sum= (sum+8)>>4;
-                    varc = (pix_norm1(pix, s->linesize) - sum*sum + 500 + 128)>>8;
+                   varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
 
-                    s->mb_var[s->mb_width * mb_y + mb_x] = varc;
-                    s->mb_var_sum    += varc;
+                    s->current_picture.mb_var [s->mb_width * mb_y + mb_x] = varc;
+                    s->current_picture.mb_mean[s->mb_width * mb_y + mb_x] = (sum+128)>>8;
+                    s->current_picture.mb_var_sum    += varc;
                 }
             }
         }
     }
+    emms_c();
+
     if(s->scene_change_score > 0 && s->pict_type == P_TYPE){
         s->pict_type= I_TYPE;
-        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
-        if(s->max_b_frames==0){
-            s->input_pict_type= I_TYPE;
-            s->input_picture_in_gop_number=0;
-        }
-//printf("Scene change detected, encoding as I Frame %d %d\n", s->mb_var_sum, s->mc_mb_var_sum);
+        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(uint8_t)*s->mb_width*s->mb_height);
+//printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
     }
-    
-    if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) 
-        s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
-        ff_fix_long_p_mvs(s);
-    if(s->pict_type==B_TYPE){
-        s->f_code= ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
-        s->b_code= ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
 
-        ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
-        ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
-        ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
-        ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
+    if(!s->umvplus){
+        if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) {
+            s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
+        
+            ff_fix_long_p_mvs(s);
+        }
+
+        if(s->pict_type==B_TYPE){
+            int a, b;
+
+            a = ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
+            b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, MB_TYPE_BIDIR);
+            s->f_code = FFMAX(a, b);
+
+            a = ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
+            b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, MB_TYPE_BIDIR);
+            s->b_code = FFMAX(a, b);
+
+            ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
+            ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
+            ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
+            ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
+        }
     }
     
-//printf("f_code %d ///\n", s->f_code);
-
-//    printf("%d %d\n", s->avg_mb_var, s->mc_mb_var);
-    if (!s->fixed_qscale) 
-        s->qscale = ff_rate_estimate_qscale(s);
+    if (s->fixed_qscale) 
+        s->frame_qscale = s->current_picture.quality;
+    else
+        s->frame_qscale = ff_rate_estimate_qscale(s);
+
+    if(s->adaptive_quant){
+#ifdef CONFIG_RISKY
+        switch(s->codec_id){
+        case CODEC_ID_MPEG4:
+            ff_clean_mpeg4_qscales(s);
+            break;
+        case CODEC_ID_H263:
+        case CODEC_ID_H263P:
+            ff_clean_h263_qscales(s);
+            break;
+        }
+#endif
 
+        s->qscale= s->current_picture.qscale_table[0];
+    }else
+        s->qscale= (int)(s->frame_qscale + 0.5);
+        
     if (s->out_format == FMT_MJPEG) {
         /* for mjpeg, we do include qscale in the matrix */
         s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
-        for(i=1;i<64;i++)
-            s->intra_matrix[i] = CLAMP_TO_8BIT((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
+        for(i=1;i<64;i++){
+            int j= s->dsp.idct_permutation[i];
+
+            s->intra_matrix[j] = CLAMP_TO_8BIT((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
+        }
         convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, 
-                       s->q_intra_matrix16_bias, s->intra_matrix, s->intra_quant_bias);
+                       s->q_intra_matrix16_bias, s->intra_matrix, s->intra_quant_bias, 8, 8);
     }
+    
+    //FIXME var duplication
+    s->current_picture.key_frame= s->pict_type == I_TYPE;
+    s->current_picture.pict_type= s->pict_type;
+
+    if(s->current_picture.key_frame)
+        s->picture_in_gop_number=0;
 
     s->last_bits= get_bit_count(&s->pb);
     switch(s->out_format) {
     case FMT_MJPEG:
         mjpeg_picture_header(s);
         break;
+#ifdef CONFIG_RISKY
     case FMT_H263:
-        if (s->h263_msmpeg4) 
+        if (s->codec_id == CODEC_ID_WMV2) 
+            ff_wmv2_encode_picture_header(s, picture_number);
+        else if (s->h263_msmpeg4) 
             msmpeg4_encode_picture_header(s, picture_number);
         else if (s->h263_pred)
             mpeg4_encode_picture_header(s, picture_number);
@@ -2118,6 +2954,7 @@ static void encode_picture(MpegEncContext *s, int picture_number)
         else
             h263_encode_picture_header(s, picture_number);
         break;
+#endif
     case FMT_MPEG1:
         mpeg1_encode_picture_header(s, picture_number);
         break;
@@ -2130,55 +2967,39 @@ static void encode_picture(MpegEncContext *s, int picture_number)
     s->i_tex_bits=0;
     s->p_tex_bits=0;
     s->i_count=0;
-    s->p_count=0;
+    s->f_count=0;
+    s->b_count=0;
     s->skip_count=0;
 
-    /* init last dc values */
-    /* note: quant matrix value (8) is implied here */
-    s->last_dc[0] = 128;
-    s->last_dc[1] = 128;
-    s->last_dc[2] = 128;
+    for(i=0; i<3; i++){
+        /* init last dc values */
+        /* note: quant matrix value (8) is implied here */
+        s->last_dc[i] = 128;
+        
+        s->current_picture.error[i] = 0;
+    }
     s->mb_incr = 1;
     s->last_mv[0][0][0] = 0;
     s->last_mv[0][0][1] = 0;
+    s->last_mv[1][0][0] = 0;
+    s->last_mv[1][0][1] = 0;
+     
+    s->last_mv_dir = 0;
 
-    /* Get the GOB height based on picture height */
-    if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
-        if (s->height <= 400)
-            s->gob_index = 1;
-        else if (s->height <= 800)
-            s->gob_index = 2;
-        else
-            s->gob_index = 4;
-    }else if(s->codec_id==CODEC_ID_MPEG4){
-        s->gob_index = 1;
-    }
+#ifdef CONFIG_RISKY
+    if (s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P)
+        s->gob_index = ff_h263_get_gob_height(s);
 
-    if(s->codec_id==CODEC_ID_MPEG4 && s->data_partitioning && s->pict_type!=B_TYPE)
+    if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame)
         ff_mpeg4_init_partitions(s);
+#endif
 
     s->resync_mb_x=0;
     s->resync_mb_y=0;
+    s->first_slice_line = 1;
+    s->ptr_lastgob = s->pb.buf;
+    s->ptr_last_mb_line = s->pb.buf;
     for(mb_y=0; mb_y < s->mb_height; mb_y++) {
-        /* Put GOB header based on RTP MTU for formats which support it per line (H263*)*/
-        /* TODO: Put all this stuff in a separate generic function */
-        if (s->rtp_mode) {
-            if (!mb_y) {
-                s->ptr_lastgob = s->pb.buf;
-                s->ptr_last_mb_line = s->pb.buf;
-            } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
-                // MN: we could move the space check from h263 -> here, as its not h263 specific
-                last_gob = h263_encode_gob_header(s, mb_y);
-                if (last_gob) {
-                    s->first_slice_line = 1;
-                }else{
-                    /*MN: we reset it here instead at the end of each line cuz mpeg4 can have 
-                          slice lines starting & ending in the middle*/
-                    s->first_slice_line = 0;
-                }
-            }
-        }
-
         s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
         s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
         
@@ -2189,7 +3010,7 @@ static void encode_picture(MpegEncContext *s, int picture_number)
         s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
         s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
-            const int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
+            int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
             const int xy= (mb_y+1) * (s->mb_width+2) + mb_x + 1;
 //            int d;
             int dmin=10000000;
@@ -2202,15 +3023,20 @@ static void encode_picture(MpegEncContext *s, int picture_number)
             s->block_index[3]+=2;
             s->block_index[4]++;
             s->block_index[5]++;
-            
-            /* write gob / video packet header for formats which support it at any MB (MPEG4) */
-            if(s->rtp_mode && s->mb_y>0 && s->codec_id==CODEC_ID_MPEG4){
-                int pdif= pbBufPtr(&s->pb) - s->ptr_lastgob;
-
-                //the *2 is there so we stay below the requested size
-                if(pdif + s->mb_line_avgsize/s->mb_width >= s->rtp_payload_size){ 
-                    if(s->codec_id==CODEC_ID_MPEG4){
-                        if(s->data_partitioning && s->pict_type!=B_TYPE){
+
+            /* write gob / video packet header  */
+#ifdef CONFIG_RISKY
+            if(s->rtp_mode){
+                int current_packet_size, is_gob_start;
+                
+                current_packet_size= pbBufPtr(&s->pb) - s->ptr_lastgob;
+                is_gob_start=0;
+                
+                if(s->codec_id==CODEC_ID_MPEG4){
+                    if(current_packet_size + s->mb_line_avgsize/s->mb_width >= s->rtp_payload_size
+                       && s->mb_y + s->mb_x>0){
+
+                        if(s->partitioned_frame){
                             ff_mpeg4_merge_partitions(s);
                             ff_mpeg4_init_partitions(s);
                         }
@@ -2222,17 +3048,29 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                             s->last_bits= bits;
                         }
                         ff_mpeg4_clean_buffers(s);
+                        is_gob_start=1;
+                    }
+                }else{
+                    if(current_packet_size + s->mb_line_avgsize*s->gob_index >= s->rtp_payload_size
+                       && s->mb_x==0 && s->mb_y>0 && s->mb_y%s->gob_index==0){
+                       
+                        h263_encode_gob_header(s, mb_y);                       
+                        is_gob_start=1;
                     }
+                }
+
+                if(is_gob_start){
                     s->ptr_lastgob = pbBufPtr(&s->pb);
                     s->first_slice_line=1;
                     s->resync_mb_x=mb_x;
                     s->resync_mb_y=mb_y;
                 }
+            }
+#endif
 
-                if(  (s->resync_mb_x   == s->mb_x)
-                   && s->resync_mb_y+1 == s->mb_y){
-                    s->first_slice_line=0; 
-                }
+            if(  (s->resync_mb_x   == s->mb_x)
+               && s->resync_mb_y+1 == s->mb_y){
+                s->first_slice_line=0; 
             }
 
             if(mb_type & (mb_type-1)){ // more than 1 MB type possible
@@ -2242,6 +3080,7 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                 copy_context_before_encode(&backup_s, s, -1);
                 backup_s.pb= s->pb;
                 best_s.data_partitioning= s->data_partitioning;
+                best_s.partitioned_frame= s->partitioned_frame;
                 if(s->data_partitioning){
                     backup_s.pb2= s->pb2;
                     backup_s.tex_pb= s->tex_pb;
@@ -2297,18 +3136,19 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                                  &dmin, &next_block, 0, 0);
                 }
                 if(mb_type&MB_TYPE_DIRECT){
+                    int mx= s->b_direct_mv_table[xy][0];
+                    int my= s->b_direct_mv_table[xy][1];
+                    
                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
-                    s->mv_type = MV_TYPE_16X16; //FIXME
                     s->mb_intra= 0;
-                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
-                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
-                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
-                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
+#ifdef CONFIG_RISKY
+                    ff_mpeg4_set_direct_mv(s, mx, my);
+#endif
                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_DIRECT, pb, pb2, tex_pb, 
-                                 &dmin, &next_block, s->b_direct_mv_table[xy][0], s->b_direct_mv_table[xy][1]);
+                                 &dmin, &next_block, mx, my);
                 }
                 if(mb_type&MB_TYPE_INTRA){
-                    s->mv_dir = MV_DIR_FORWARD;
+                    s->mv_dir = 0;
                     s->mv_type = MV_TYPE_16X16;
                     s->mb_intra= 1;
                     s->mv[0][0][0] = 0;
@@ -2340,11 +3180,96 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                 s->last_bits= get_bit_count(&s->pb);
             } else {
                 int motion_x, motion_y;
+                int intra_score;
+                int inter_score= s->current_picture.mb_cmp_score[mb_x + mb_y*s->mb_width];
+                
+              if(!(s->flags&CODEC_FLAG_HQ) && s->pict_type==P_TYPE){
+                /* get luma score */
+                if((s->avctx->mb_cmp&0xFF)==FF_CMP_SSE){
+                    intra_score= (s->current_picture.mb_var[mb_x + mb_y*s->mb_width]<<8) - 500; //FIXME dont scale it down so we dont have to fix it
+                }else{
+                    uint8_t *dest_y;
+
+                    int mean= s->current_picture.mb_mean[mb_x + mb_y*s->mb_width]; //FIXME
+                    mean*= 0x01010101;
+                    
+                    dest_y  = s->new_picture.data[0] + (mb_y * 16 * s->linesize    ) + mb_x * 16;
+                
+                    for(i=0; i<16; i++){
+                        *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 0]) = mean;
+                        *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 4]) = mean;
+                        *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 8]) = mean;
+                        *(uint32_t*)(&s->me.scratchpad[i*s->linesize+12]) = mean;
+                    }
+
+                    s->mb_intra=1;
+                    intra_score= s->dsp.mb_cmp[0](s, s->me.scratchpad, dest_y, s->linesize);
+                                        
+/*                    printf("intra:%7d inter:%7d var:%7d mc_var.%7d\n", intra_score>>8, inter_score>>8, 
+                        s->current_picture.mb_var[mb_x + mb_y*s->mb_width],
+                        s->current_picture.mc_mb_var[mb_x + mb_y*s->mb_width]);*/
+                }
+                
+                /* get chroma score */
+                if(s->avctx->mb_cmp&FF_CMP_CHROMA){
+                    int i;
+                    
+                    s->mb_intra=1;
+                    for(i=1; i<3; i++){
+                        uint8_t *dest_c;
+                        int mean;
+                        
+                        if(s->out_format == FMT_H263){
+                            mean= (s->dc_val[i][mb_x + (mb_y+1)*(s->mb_width+2)] + 4)>>3; //FIXME not exact but simple ;)
+                        }else{
+                            mean= (s->last_dc[i] + 4)>>3;
+                        }
+                        dest_c = s->new_picture.data[i] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
+                        
+                        mean*= 0x01010101;
+                        for(i=0; i<8; i++){
+                            *(uint32_t*)(&s->me.scratchpad[i*s->uvlinesize+ 0]) = mean;
+                            *(uint32_t*)(&s->me.scratchpad[i*s->uvlinesize+ 4]) = mean;
+                        }
+                        
+                        intra_score+= s->dsp.mb_cmp[1](s, s->me.scratchpad, dest_c, s->uvlinesize);
+                    }                
+                }
+
+                /* bias */
+                switch(s->avctx->mb_cmp&0xFF){
+                default:
+                case FF_CMP_SAD:
+                    intra_score+= 32*s->qscale;
+                    break;
+                case FF_CMP_SSE:
+                    intra_score+= 24*s->qscale*s->qscale;
+                    break;
+                case FF_CMP_SATD:
+                    intra_score+= 96*s->qscale;
+                    break;
+                case FF_CMP_DCT:
+                    intra_score+= 48*s->qscale;
+                    break;
+                case FF_CMP_BIT:
+                    intra_score+= 16;
+                    break;
+                case FF_CMP_PSNR:
+                case FF_CMP_RD:
+                    intra_score+= (s->qscale*s->qscale*109*8 + 64)>>7;
+                    break;
+                }
+
+                if(intra_score < inter_score)
+                    mb_type= MB_TYPE_INTRA;
+              }  
+                
                 s->mv_type=MV_TYPE_16X16;
                 // only one MB-Type possible
+                
                 switch(mb_type){
                 case MB_TYPE_INTRA:
-                    s->mv_dir = MV_DIR_FORWARD;
+                    s->mv_dir = 0;
                     s->mb_intra= 1;
                     motion_x= s->mv[0][0][0] = 0;
                     motion_y= s->mv[0][0][1] = 0;
@@ -2370,10 +3295,9 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                     s->mb_intra= 0;
                     motion_x=s->b_direct_mv_table[xy][0];
                     motion_y=s->b_direct_mv_table[xy][1];
-                    s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
-                    s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
-                    s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
-                    s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
+#ifdef CONFIG_RISKY
+                    ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
+#endif
                     break;
                 case MB_TYPE_BIDIR:
                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
@@ -2402,8 +3326,13 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                     motion_x=motion_y=0; //gcc warning fix
                     printf("illegal MB type\n");
                 }
+
                 encode_mb(s, motion_x, motion_y);
+
+                // RAL: Update last macrobloc type
+                s->last_mv_dir = s->mv_dir;
             }
+
             /* clean the MV table in IPS frames for direct mode in B frames */
             if(s->mb_intra /* && I,P,S_TYPE */){
                 s->p_mv_table[xy][0]=0;
@@ -2411,26 +3340,48 @@ static void encode_picture(MpegEncContext *s, int picture_number)
             }
 
             MPV_decode_mb(s, s->block);
+            
+            if(s->flags&CODEC_FLAG_PSNR){
+                int w= 16;
+                int h= 16;
+
+                if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
+                if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
+
+                s->current_picture.error[0] += sse(
+                    s,
+                    s->new_picture    .data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
+                    s->current_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
+                    w, h, s->linesize);
+                s->current_picture.error[1] += sse(
+                    s,
+                    s->new_picture    .data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
+                    s->current_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
+                    w>>1, h>>1, s->uvlinesize);
+                s->current_picture.error[2] += sse(
+                    s,
+                    s->new_picture    .data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
+                    s->current_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,
+                    w>>1, h>>1, s->uvlinesize);
+            }
 //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_width, get_bit_count(&s->pb));
         }
 
 
-        /* Obtain average GOB size for RTP */
+        /* Obtain average mb_row size for RTP */
         if (s->rtp_mode) {
-            if (!mb_y)
+            if (mb_y==0)
                 s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
-            else if (!(mb_y % s->gob_index)) {    
+            else {    
                 s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
-                s->ptr_last_mb_line = pbBufPtr(&s->pb);
             }
-            //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
-            //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
-            if(s->codec_id!=CODEC_ID_MPEG4) s->first_slice_line = 0; //FIXME clean
+            s->ptr_last_mb_line = pbBufPtr(&s->pb);
         }
     }
     emms_c();
 
-    if(s->codec_id==CODEC_ID_MPEG4 && s->data_partitioning && s->pict_type!=B_TYPE)
+#ifdef CONFIG_RISKY
+    if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame)
         ff_mpeg4_merge_partitions(s);
 
     if (s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
@@ -2438,6 +3389,7 @@ static void encode_picture(MpegEncContext *s, int picture_number)
 
     if(s->codec_id==CODEC_ID_MPEG4) 
         ff_mpeg4_stuffing(&s->pb);
+#endif
 
     //if (s->gob_number)
     //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
@@ -2454,21 +3406,266 @@ static void encode_picture(MpegEncContext *s, int picture_number)
     }
 }
 
+static int dct_quantize_trellis_c(MpegEncContext *s, 
+                        DCTELEM *block, int n,
+                        int qscale, int *overflow){
+    const int *qmat;
+    const uint8_t *scantable= s->intra_scantable.scantable;
+    int max=0;
+    unsigned int threshold1, threshold2;
+    int bias=0;
+    int run_tab[65];
+    int level_tab[65];
+    int score_tab[65];
+    int last_run=0;
+    int last_level=0;
+    int last_score= 0;
+    int last_i= 0;
+    int coeff[3][64];
+    int coeff_count[64];
+    int lambda, qmul, qadd, start_i, last_non_zero, i;
+    const int esc_length= s->ac_esc_length;
+    uint8_t * length;
+    uint8_t * last_length;
+    int score_limit=0;
+    int left_limit= 0;
+        
+    s->dsp.fdct (block);
+
+    qmul= qscale*16;
+    qadd= ((qscale-1)|1)*8;
+
+    if (s->mb_intra) {
+        int q;
+        if (!s->h263_aic) {
+            if (n < 4)
+                q = s->y_dc_scale;
+            else
+                q = s->c_dc_scale;
+            q = q << 3;
+        } else{
+            /* For AIC we skip quant/dequant of INTRADC */
+            q = 1 << 3;
+            qadd=0;
+        }
+            
+        /* note: block[0] is assumed to be positive */
+        block[0] = (block[0] + (q >> 1)) / q;
+        start_i = 1;
+        last_non_zero = 0;
+        qmat = s->q_intra_matrix[qscale];
+        if(s->mpeg_quant || s->codec_id== CODEC_ID_MPEG1VIDEO)
+            bias= 1<<(QMAT_SHIFT-1);
+        length     = s->intra_ac_vlc_length;
+        last_length= s->intra_ac_vlc_last_length;
+    } else {
+        start_i = 0;
+        last_non_zero = -1;
+        qmat = s->q_inter_matrix[qscale];
+        length     = s->inter_ac_vlc_length;
+        last_length= s->inter_ac_vlc_last_length;
+    }
+
+    threshold1= (1<<QMAT_SHIFT) - bias - 1;
+    threshold2= (threshold1<<1);
+
+    for(i=start_i; i<64; i++) {
+        const int j = scantable[i];
+        const int k= i-start_i;
+        int level = block[j];
+        level = level * qmat[j];
+
+//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
+//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
+        if(((unsigned)(level+threshold1))>threshold2){
+            if(level>0){
+                level= (bias + level)>>QMAT_SHIFT;
+                coeff[0][k]= level;
+                coeff[1][k]= level-1;
+//                coeff[2][k]= level-2;
+            }else{
+                level= (bias - level)>>QMAT_SHIFT;
+                coeff[0][k]= -level;
+                coeff[1][k]= -level+1;
+//                coeff[2][k]= -level+2;
+            }
+            coeff_count[k]= FFMIN(level, 2);
+            max |=level;
+            last_non_zero = i;
+        }else{
+            coeff[0][k]= (level>>31)|1;
+            coeff_count[k]= 1;
+        }
+    }
+    
+    *overflow= s->max_qcoeff < max; //overflow might have happend
+    
+    if(last_non_zero < start_i){
+        memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
+        return last_non_zero;
+    }
+
+    lambda= (qscale*qscale*64*105 + 64)>>7; //FIXME finetune
+        
+    score_tab[0]= 0;
+    for(i=0; i<=last_non_zero - start_i; i++){
+        int level_index, run, j;
+        const int dct_coeff= block[ scantable[i + start_i] ];
+        const int zero_distoration= dct_coeff*dct_coeff;
+        int best_score=256*256*256*120;
+
+        last_score += zero_distoration;
+        for(level_index=0; level_index < coeff_count[i]; level_index++){
+            int distoration;
+            int level= coeff[level_index][i];
+            int unquant_coeff;
+            
+            assert(level);
+
+            if(s->out_format == FMT_H263){
+                if(level>0){
+                    unquant_coeff= level*qmul + qadd;
+                }else{
+                    unquant_coeff= level*qmul - qadd;
+                }
+            }else{ //MPEG1
+                j= s->dsp.idct_permutation[ scantable[i + start_i] ]; //FIXME optimize
+                if(s->mb_intra){
+                    if (level < 0) {
+                        unquant_coeff = (int)((-level) * qscale * s->intra_matrix[j]) >> 3;
+                        unquant_coeff = -((unquant_coeff - 1) | 1);
+                    } else {
+                        unquant_coeff = (int)(  level  * qscale * s->intra_matrix[j]) >> 3;
+                        unquant_coeff =   (unquant_coeff - 1) | 1;
+                    }
+                }else{
+                    if (level < 0) {
+                        unquant_coeff = ((((-level) << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
+                        unquant_coeff = -((unquant_coeff - 1) | 1);
+                    } else {
+                        unquant_coeff = (((  level  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
+                        unquant_coeff =   (unquant_coeff - 1) | 1;
+                    }
+                }
+                unquant_coeff<<= 3;
+            }
+
+            distoration= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff);
+            level+=64;
+            if((level&(~127)) == 0){
+                for(run=0; run<=i - left_limit; run++){
+                    int score= distoration + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
+                    score += score_tab[i-run];
+                    
+                    if(score < best_score){
+                        best_score= 
+                        score_tab[i+1]= score;
+                        run_tab[i+1]= run;
+                        level_tab[i+1]= level-64;
+                    }
+                }
+
+                if(s->out_format == FMT_H263){
+                    for(run=0; run<=i - left_limit; run++){
+                        int score= distoration + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
+                        score += score_tab[i-run];
+                        if(score < last_score){
+                            last_score= score;
+                            last_run= run;
+                            last_level= level-64;
+                            last_i= i+1;
+                        }
+                    }
+                }
+            }else{
+                distoration += esc_length*lambda;
+                for(run=0; run<=i - left_limit; run++){
+                    int score= distoration + score_tab[i-run];
+                    
+                    if(score < best_score){
+                        best_score= 
+                        score_tab[i+1]= score;
+                        run_tab[i+1]= run;
+                        level_tab[i+1]= level-64;
+                    }
+                }
+
+                if(s->out_format == FMT_H263){
+                    for(run=0; run<=i - left_limit; run++){
+                        int score= distoration + score_tab[i-run];
+                        if(score < last_score){
+                            last_score= score;
+                            last_run= run;
+                            last_level= level-64;
+                            last_i= i+1;
+                        }
+                    }
+                }
+            }
+        }
+
+        for(j=left_limit; j<=i; j++){
+            score_tab[j] += zero_distoration;
+        }
+        score_limit+= zero_distoration;
+        if(score_tab[i+1] < score_limit)
+            score_limit= score_tab[i+1];
+        
+        //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
+        while(score_tab[ left_limit ] > score_limit + lambda) left_limit++;
+    }
+
+        //FIXME add some cbp penalty
+
+    if(s->out_format != FMT_H263){
+        last_score= 256*256*256*120;
+        for(i= left_limit; i<=last_non_zero - start_i + 1; i++){
+            int score= score_tab[i];
+            if(i) score += lambda*2; //FIXME exacter?
+
+            if(score < last_score){
+                last_score= score;
+                last_i= i;
+                last_level= level_tab[i];
+                last_run= run_tab[i];
+            }
+        }
+    }
+    
+    last_non_zero= last_i - 1 + start_i;
+    memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
+    
+    if(last_non_zero < start_i)
+        return last_non_zero;
+    
+    i= last_i;
+    assert(last_level);
+//FIXME use permutated scantable
+    block[ s->dsp.idct_permutation[ scantable[last_non_zero] ] ]= last_level;
+    i -= last_run + 1;
+    
+    for(;i>0 ; i -= run_tab[i] + 1){
+        const int j= s->dsp.idct_permutation[ scantable[i - 1 + start_i] ];
+    
+        block[j]= level_tab[i];
+        assert(block[j]);
+    }
+
+    return last_non_zero;
+}
+
 static int dct_quantize_c(MpegEncContext *s, 
                         DCTELEM *block, int n,
                         int qscale, int *overflow)
 {
     int i, j, level, last_non_zero, q;
     const int *qmat;
+    const uint8_t *scantable= s->intra_scantable.scantable;
     int bias;
     int max=0;
     unsigned int threshold1, threshold2;
-    
-    s->fdct (block);
 
-    /* we need this permutation so that we correct the IDCT
-       permutation. will be moved into DCT code */
-    block_permute(block);
+    s->dsp.fdct (block);
 
     if (s->mb_intra) {
         if (!s->h263_aic) {
@@ -2497,7 +3694,7 @@ static int dct_quantize_c(MpegEncContext *s,
     threshold2= (threshold1<<1);
 
     for(;i<64;i++) {
-        j = zigzag_direct[i];
+        j = scantable[i];
         level = block[j];
         level = level * qmat[j];
 
@@ -2519,17 +3716,22 @@ static int dct_quantize_c(MpegEncContext *s,
     }
     *overflow= s->max_qcoeff < max; //overflow might have happend
     
+    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
+    if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
+       ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
+
     return last_non_zero;
 }
 
+#endif //CONFIG_ENCODERS
+
 static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
                                    DCTELEM *block, int n, int qscale)
 {
     int i, level, nCoeffs;
-    const UINT16 *quant_matrix;
+    const uint16_t *quant_matrix;
 
-    if(s->alternate_scan) nCoeffs= 64;
-    else nCoeffs= s->block_last_index[n]+1;
+    nCoeffs= s->block_last_index[n];
     
     if (s->mb_intra) {
         if (n < 4) 
@@ -2538,8 +3740,8 @@ static void dct_unquantize_mpeg1_c(MpegEncContext *s,
             block[0] = block[0] * s->c_dc_scale;
         /* XXX: only mpeg1 */
         quant_matrix = s->intra_matrix;
-        for(i=1;i<nCoeffs;i++) {
-            int j= zigzag_direct[i];
+        for(i=1;i<=nCoeffs;i++) {
+            int j= s->intra_scantable.permutated[i];
             level = block[j];
             if (level) {
                 if (level < 0) {
@@ -2561,8 +3763,8 @@ static void dct_unquantize_mpeg1_c(MpegEncContext *s,
     } else {
         i = 0;
         quant_matrix = s->inter_matrix;
-        for(;i<nCoeffs;i++) {
-            int j= zigzag_direct[i];
+        for(;i<=nCoeffs;i++) {
+            int j= s->intra_scantable.permutated[i];
             level = block[j];
             if (level) {
                 if (level < 0) {
@@ -2590,10 +3792,10 @@ static void dct_unquantize_mpeg2_c(MpegEncContext *s,
                                    DCTELEM *block, int n, int qscale)
 {
     int i, level, nCoeffs;
-    const UINT16 *quant_matrix;
+    const uint16_t *quant_matrix;
 
-    if(s->alternate_scan) nCoeffs= 64;
-    else nCoeffs= s->block_last_index[n]+1;
+    if(s->alternate_scan) nCoeffs= 63;
+    else nCoeffs= s->block_last_index[n];
     
     if (s->mb_intra) {
         if (n < 4) 
@@ -2601,8 +3803,8 @@ static void dct_unquantize_mpeg2_c(MpegEncContext *s,
         else
             block[0] = block[0] * s->c_dc_scale;
         quant_matrix = s->intra_matrix;
-        for(i=1;i<nCoeffs;i++) {
-            int j= zigzag_direct[i];
+        for(i=1;i<=nCoeffs;i++) {
+            int j= s->intra_scantable.permutated[i];
             level = block[j];
             if (level) {
                 if (level < 0) {
@@ -2623,8 +3825,8 @@ static void dct_unquantize_mpeg2_c(MpegEncContext *s,
         int sum=-1;
         i = 0;
         quant_matrix = s->inter_matrix;
-        for(;i<nCoeffs;i++) {
-            int j= zigzag_direct[i];
+        for(;i<=nCoeffs;i++) {
+            int j= s->intra_scantable.permutated[i];
             level = block[j];
             if (level) {
                 if (level < 0) {
@@ -2655,27 +3857,27 @@ static void dct_unquantize_h263_c(MpegEncContext *s,
     int i, level, qmul, qadd;
     int nCoeffs;
     
+    assert(s->block_last_index[n]>=0);
+    
+    qadd = (qscale - 1) | 1;
+    qmul = qscale << 1;
+    
     if (s->mb_intra) {
         if (!s->h263_aic) {
             if (n < 4) 
                 block[0] = block[0] * s->y_dc_scale;
             else
                 block[0] = block[0] * s->c_dc_scale;
-        }
+        }else
+            qadd = 0;
         i = 1;
-        nCoeffs= 64; //does not allways use zigzag table 
+        nCoeffs= 63; //does not allways use zigzag table 
     } else {
         i = 0;
-        nCoeffs= zigzag_end[ s->block_last_index[n] ];
+        nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
     }
 
-    qmul = s->qscale << 1;
-    if (s->h263_aic && s->mb_intra)
-        qadd = 0;
-    else
-        qadd = (s->qscale - 1) | 1;
-
-    for(;i<nCoeffs;i++) {
+    for(;i<=nCoeffs;i++) {
         level = block[i];
         if (level) {
             if (level < 0) {
@@ -2692,118 +3894,42 @@ static void dct_unquantize_h263_c(MpegEncContext *s,
     }
 }
 
-static void remove_ac(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr, int mb_x, int mb_y)
-{
-    int dc, dcb, dcr, y, i;
-    for(i=0; i<4; i++){
-        dc= s->dc_val[0][mb_x*2+1 + (i&1) + (mb_y*2+1 + (i>>1))*(s->mb_width*2+2)];
-        for(y=0; y<8; y++){
-            int x;
-            for(x=0; x<8; x++){
-                dest_y[x + (i&1)*8 + (y + (i>>1)*8)*s->linesize]= dc/8;
-            }
-        }
-    }
-    dcb = s->dc_val[1][mb_x+1 + (mb_y+1)*(s->mb_width+2)];
-    dcr= s->dc_val[2][mb_x+1 + (mb_y+1)*(s->mb_width+2)];
-    for(y=0; y<8; y++){
-        int x;
-        for(x=0; x<8; x++){
-            dest_cb[x + y*(s->uvlinesize)]= dcb/8;
-            dest_cr[x + y*(s->uvlinesize)]= dcr/8;
-        }
+
+char ff_get_pict_type_char(int pict_type){
+    switch(pict_type){
+    case I_TYPE: return 'I'; 
+    case P_TYPE: return 'P'; 
+    case B_TYPE: return 'B'; 
+    case S_TYPE: return 'S'; 
+    default:     return '?';
     }
 }
 
-/**
- * will conceal past errors, and allso drop b frames if needed
- *
- */
-void ff_conceal_past_errors(MpegEncContext *s, int unknown_pos)
+extern const AVOption common_options[2];
+static const AVOption mpeg4_options[] =
 {
-    int mb_x= s->mb_x;
-    int mb_y= s->mb_y;
-    int mb_dist=0;
-    int i, intra_count=0, inter_count=0;
-    int intra_conceal= s->msmpeg4_version ? 50 : 50; //FIXME finetune
-    int inter_conceal= s->msmpeg4_version ? 50 : 50;
-
-    // for last block
-    if(mb_x>=s->mb_width)  mb_x= s->mb_width -1;
-    if(mb_y>=s->mb_height) mb_y= s->mb_height-1;
-
-    if(s->decoding_error==0 && unknown_pos){
-        if(s->data_partitioning && s->pict_type!=B_TYPE)
-                s->decoding_error= DECODING_AC_LOST;
-        else
-                s->decoding_error= DECODING_DESYNC;
-    }
-
-    if(s->decoding_error==DECODING_DESYNC && s->pict_type!=B_TYPE) s->next_p_frame_damaged=1;
-
-    for(i=mb_x + mb_y*s->mb_width; i>=0; i--){
-        if(s->mbintra_table[i]) intra_count++;
-        else                    inter_count++;
-    }
-    
-    if(s->decoding_error==DECODING_AC_LOST){
-        intra_conceal*=2;
-        inter_conceal*=2;
-    }else if(s->decoding_error==DECODING_ACDC_LOST){
-        intra_conceal*=2;
-        inter_conceal*=2;
-    }
-
-    if(unknown_pos && (intra_count<inter_count)){
-        intra_conceal= inter_conceal= s->mb_num; 
-//        printf("%d %d\n",intra_count, inter_count);
-    }
-
-    fprintf(stderr, "concealing errors\n");
-
-    /* for all MBs from the current one back until the last resync marker */
-    for(; mb_y>=0 && mb_y>=s->resync_mb_y; mb_y--){
-        for(; mb_x>=0; mb_x--){
-            uint8_t *dest_y  = s->current_picture[0] + (mb_y * 16*  s->linesize      ) + mb_x * 16;
-            uint8_t *dest_cb = s->current_picture[1] + (mb_y * 8 * (s->uvlinesize)) + mb_x * 8;
-            uint8_t *dest_cr = s->current_picture[2] + (mb_y * 8 * (s->uvlinesize)) + mb_x * 8;
-            int mb_x_backup= s->mb_x; //FIXME pass xy to mpeg_motion
-            int mb_y_backup= s->mb_y;
-            s->mb_x=mb_x;
-            s->mb_y=mb_y;
-            if(s->mbintra_table[mb_y*s->mb_width + mb_x] && mb_dist<intra_conceal){
-                if(s->decoding_error==DECODING_AC_LOST){
-                    remove_ac(s, dest_y, dest_cb, dest_cr, mb_x, mb_y);
-//                    printf("remove ac to %d %d\n", mb_x, mb_y);
-                }else{
-                    mpeg_motion(s, dest_y, dest_cb, dest_cr, 0, 
-                                s->last_picture, 0, 0, put_pixels_tab,
-                                0/*mx*/, 0/*my*/, 16);
-                }
-            }
-            else if(!s->mbintra_table[mb_y*s->mb_width + mb_x] && mb_dist<inter_conceal){
-                int mx=0;
-                int my=0;
-
-                if(s->decoding_error!=DECODING_DESYNC){
-                    int xy= mb_x*2+1 + (mb_y*2+1)*(s->mb_width*2+2);
-                    mx= s->motion_val[ xy ][0];
-                    my= s->motion_val[ xy ][1];
-                }
-
-                mpeg_motion(s, dest_y, dest_cb, dest_cr, 0, 
-                            s->last_picture, 0, 0, put_pixels_tab,
-                            mx, my, 16);
-            }
-            s->mb_x= mb_x_backup;
-            s->mb_y= mb_y_backup;
+    AVOPTION_CODEC_INT("bitrate", "desired video bitrate", bit_rate, 4, 240000000, 800000),
+    AVOPTION_CODEC_FLAG("vhq", "very high quality", flags, CODEC_FLAG_HQ, 0),
+    AVOPTION_CODEC_INT("ratetol", "number of bits the bitstream is allowed to diverge from the reference"
+                      "the reference can be CBR (for CBR pass1) or VBR (for pass2)",
+                      bit_rate_tolerance, 4, 240000000, 8000),
+    AVOPTION_CODEC_INT("qmin", "minimum quantizer", qmin, 1, 31, 2),
+    AVOPTION_CODEC_INT("qmax", "maximum quantizer", qmax, 1, 31, 31),
+    AVOPTION_CODEC_STRING("rc_eq", "rate control equation",
+                         rc_eq, "tex^qComp,option1,options2", 0),
+    AVOPTION_CODEC_INT("rc_minrate", "rate control minimum bitrate",
+                      rc_min_rate, 4, 24000000, 0),
+    AVOPTION_CODEC_INT("rc_maxrate", "rate control maximum bitrate",
+                      rc_max_rate, 4, 24000000, 0),
+    AVOPTION_CODEC_FLAG("psnr", "calculate PSNR of compressed frames",
+                       flags, CODEC_FLAG_PSNR, 0),
+    AVOPTION_CODEC_RCOVERRIDE("rc_override", "ratecontrol override (=startframe,endframe,qscale,quality_factor)",
+                             rc_override),
+    AVOPTION_SUB(common_options),
+    AVOPTION_END()
+};
 
-            if(mb_x== s->resync_mb_x && mb_y== s->resync_mb_y) return;
-            if(!s->mbskip_table[mb_x + mb_y*s->mb_width]) mb_dist++;
-        }
-        mb_x=s->mb_width-1;
-    }
-}
+#ifdef CONFIG_ENCODERS
 
 AVCodec mpeg1video_encoder = {
     "mpeg1video",
@@ -2815,6 +3941,8 @@ AVCodec mpeg1video_encoder = {
     MPV_encode_end,
 };
 
+#ifdef CONFIG_RISKY
+
 AVCodec h263_encoder = {
     "h263",
     CODEC_TYPE_VIDEO,
@@ -2845,16 +3973,6 @@ AVCodec rv10_encoder = {
     MPV_encode_end,
 };
 
-AVCodec mjpeg_encoder = {
-    "mjpeg",
-    CODEC_TYPE_VIDEO,
-    CODEC_ID_MJPEG,
-    sizeof(MpegEncContext),
-    MPV_encode_init,
-    MPV_encode_picture,
-    MPV_encode_end,
-};
-
 AVCodec mpeg4_encoder = {
     "mpeg4",
     CODEC_TYPE_VIDEO,
@@ -2863,6 +3981,7 @@ AVCodec mpeg4_encoder = {
     MPV_encode_init,
     MPV_encode_picture,
     MPV_encode_end,
+    .options = mpeg4_options,
 };
 
 AVCodec msmpeg4v1_encoder = {
@@ -2905,12 +4024,17 @@ AVCodec wmv1_encoder = {
     MPV_encode_end,
 };
 
-AVCodec wmv2_encoder = {
-    "wmv2",
+#endif
+
+AVCodec mjpeg_encoder = {
+    "mjpeg",
     CODEC_TYPE_VIDEO,
-    CODEC_ID_WMV2,
+    CODEC_ID_MJPEG,
     sizeof(MpegEncContext),
     MPV_encode_init,
     MPV_encode_picture,
     MPV_encode_end,
 };
+
+#endif //CONFIG_ENCODERS
+