]> git.sesse.net Git - ffmpeg/blobdiff - libavcodec/mpegvideo.c
mpeg4 4MV encoding
[ffmpeg] / libavcodec / mpegvideo.c
index 4c86c52372b73f1bc7a1e05849c284f43521c992..1c8bcbdfa660f331e45e1b01939e466764c7ac9a 100644 (file)
@@ -15,6 +15,8 @@
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * 4MV & hq encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  */
 #include <stdlib.h>
 #include <stdio.h>
@@ -67,6 +69,9 @@ static UINT8 h263_chroma_roundtab[16] = {
     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];
+
 /* default motion estimation */
 int motion_estimation_method = ME_LOG;
 
@@ -115,6 +120,7 @@ int MPV_common_init(MpegEncContext *s)
 #endif
     s->mb_width = (s->width + 15) / 16;
     s->mb_height = (s->height + 15) / 16;
+    s->mb_num = s->mb_width * s->mb_height;
     s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;
 
     for(i=0;i<3;i++) {
@@ -146,8 +152,31 @@ int MPV_common_init(MpegEncContext *s)
             s->aux_picture[i] = pict + pict_start;
         }
     }
-
-    if (s->out_format == FMT_H263) {
+    
+    if (s->encoding) {
+        /* Allocate MB type table */
+        s->mb_type = av_mallocz(s->mb_num * sizeof(char));
+        if (s->mb_type == NULL) {
+            perror("malloc");
+            goto fail;
+        }
+        
+        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));
+        if (s->mb_var == NULL) {
+            perror("malloc");
+            goto fail;
+        }
+        /* Allocate MV table */
+        /* By now we just have one MV per MB */
+        s->mv_table[0] = av_mallocz(s->mb_num * sizeof(INT16));
+        s->mv_table[1] = av_mallocz(s->mb_num * sizeof(INT16));
+        if (s->mv_table[1] == NULL || s->mv_table[0] == NULL) {
+            perror("malloc");
+            goto fail;
+        }
+    }
+    
+    if (s->out_format == FMT_H263 || s->encoding) {
         int size;
         /* MV prediction */
         size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
@@ -157,7 +186,7 @@ int MPV_common_init(MpegEncContext *s)
         memset(s->motion_val, 0, size * 2 * sizeof(INT16));
     }
 
-    if (s->h263_pred) {
+    if (s->h263_pred || s->h263_plus) {
         int y_size, c_size, i, size;
         
         /* dc values */
@@ -186,44 +215,27 @@ int MPV_common_init(MpegEncContext *s)
             goto fail;
 
         /* which mb is a intra block */
-        s->mbintra_table = av_mallocz(s->mb_width * s->mb_height);
+        s->mbintra_table = av_mallocz(s->mb_num);
         if (!s->mbintra_table)
             goto fail;
-        memset(s->mbintra_table, 1, s->mb_width * s->mb_height);
+        memset(s->mbintra_table, 1, s->mb_num);
     }
     /* default structure is frame */
     s->picture_structure = PICT_FRAME;
 
     /* init macroblock skip table */
     if (!s->encoding) {
-        s->mbskip_table = av_mallocz(s->mb_width * s->mb_height);
+        s->mbskip_table = av_mallocz(s->mb_num);
         if (!s->mbskip_table)
             goto fail;
     }
+    
+    s->block= s->intra_block;
 
     s->context_initialized = 1;
     return 0;
  fail:
-    if (s->motion_val)
-        free(s->motion_val);
-    if (s->dc_val[0])
-        free(s->dc_val[0]);
-    if (s->ac_val[0])
-        free(s->ac_val[0]);
-    if (s->coded_block)
-        free(s->coded_block);
-    if (s->mbintra_table)
-        free(s->mbintra_table);
-    if (s->mbskip_table)
-        free(s->mbskip_table);
-    for(i=0;i<3;i++) {
-        if (s->last_picture_base[i])
-            free(s->last_picture_base[i]);
-        if (s->next_picture_base[i])
-            free(s->next_picture_base[i]);
-        if (s->aux_picture_base[i])
-            free(s->aux_picture_base[i]);
-    }
+    MPV_common_end(s);
     return -1;
 }
 
@@ -232,19 +244,32 @@ void MPV_common_end(MpegEncContext *s)
 {
     int i;
 
+    if (s->mb_type)
+        free(s->mb_type);
+    if (s->mb_var)
+        free(s->mb_var);
+    if (s->mv_table[0])
+        free(s->mv_table[0]);
+    if (s->mv_table[1])
+        free(s->mv_table[1]);
     if (s->motion_val)
         free(s->motion_val);
-    if (s->h263_pred) {
+    if (s->dc_val[0])
         free(s->dc_val[0]);
+    if (s->ac_val[0])
         free(s->ac_val[0]);
+    if (s->coded_block)
         free(s->coded_block);
+    if (s->mbintra_table)
         free(s->mbintra_table);
-    }
+
     if (s->mbskip_table)
         free(s->mbskip_table);
     for(i=0;i<3;i++) {
-        free(s->last_picture_base[i]);
-        free(s->next_picture_base[i]);
+        if (s->last_picture_base[i])
+           free(s->last_picture_base[i]);
+       if (s->next_picture_base[i])
+           free(s->next_picture_base[i]);
         if (s->has_b_frames)
             free(s->aux_picture_base[i]);
     }
@@ -258,6 +283,7 @@ int MPV_encode_init(AVCodecContext *avctx)
     int i;
 
     s->bit_rate = avctx->bit_rate;
+    s->bit_rate_tolerance = avctx->bit_rate_tolerance;
     s->frame_rate = avctx->frame_rate;
     s->width = avctx->width;
     s->height = avctx->height;
@@ -266,7 +292,14 @@ int MPV_encode_init(AVCodecContext *avctx)
     s->rtp_payload_size = avctx->rtp_payload_size;
     if (avctx->rtp_callback)
         s->rtp_callback = avctx->rtp_callback;
+    s->qmin= avctx->qmin;
+    s->qmax= avctx->qmax;
+    s->max_qdiff= avctx->max_qdiff;
+    s->qcompress= avctx->qcompress;
+    s->qblur= avctx->qblur;
     s->avctx = avctx;
+    s->aspect_ratio_info= avctx->aspect_ratio_info;
+    s->flags= avctx->flags;
     
     if (s->gop_size <= 1) {
         s->intra_only = 1;
@@ -277,7 +310,7 @@ int MPV_encode_init(AVCodecContext *avctx)
     s->full_search = motion_estimation_method;
 
     s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
-
+    
     switch(avctx->codec->id) {
     case CODEC_ID_MPEG1VIDEO:
         s->out_format = FMT_MPEG1;
@@ -285,21 +318,21 @@ int MPV_encode_init(AVCodecContext *avctx)
     case CODEC_ID_MJPEG:
         s->out_format = FMT_MJPEG;
         s->intra_only = 1; /* force intra only for jpeg */
-       s->mjpeg_write_tables = 1; /* write all tables */
-       s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
-       s->mjpeg_vsample[1] = 1; /* the only currently supported values */
-       s->mjpeg_vsample[2] = 1; 
-       s->mjpeg_hsample[0] = 2; 
-       s->mjpeg_hsample[1] = 1; 
-       s->mjpeg_hsample[2] = 1; 
+        s->mjpeg_write_tables = 1; /* write all tables */
+        s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
+        s->mjpeg_vsample[1] = 1; /* the only currently supported values */
+        s->mjpeg_vsample[2] = 1; 
+        s->mjpeg_hsample[0] = 2; 
+        s->mjpeg_hsample[1] = 1; 
+        s->mjpeg_hsample[2] = 1; 
         if (mjpeg_init(s) < 0)
             return -1;
         break;
     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");
+        if (h263_get_picture_format(s->width, s->height) == 7) {
+            printf("Input picture size isn't suitable for h263 codec! try h263+\n");
             return -1;
-       }
+        }
         s->out_format = FMT_H263;
         break;
     case CODEC_ID_H263P:
@@ -331,9 +364,35 @@ int MPV_encode_init(AVCodecContext *avctx)
     default:
         return -1;
     }
+    
+    if((s->flags&CODEC_FLAG_4MV) && !(s->flags&CODEC_FLAG_HQ)){
+        printf("4MV is currently only supported in HQ mode\n");
+        return -1;
+    }
+
+    { /* set up some save defaults, some codecs might override them later */
+        static int done=0;
+        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));
+
+            for(i=-16; i<16; i++){
+                default_fcode_tab[i + MAX_MV]= 1;
+            }
+        }
+    }
+    s->mv_penalty= default_mv_penalty;
+    s->fcode_tab= default_fcode_tab;
 
     if (s->out_format == FMT_H263)
-        h263_encode_init_vlc(s);
+        h263_encode_init(s);
+    else if (s->out_format == FMT_MPEG1)
+        mpeg1_encode_init(s);
+
+    /* dont use mv_penalty table for crap MV as it would be confused */
+    if(s->full_search<4) s->mv_penalty= default_mv_penalty;
 
     s->encoding = 1;
 
@@ -351,6 +410,7 @@ int MPV_encode_init(AVCodecContext *avctx)
     rate_control_init(s);
 
     s->picture_number = 0;
+    s->picture_in_gop_number = 0;
     s->fake_picture_number = 0;
     /* motion detector init */
     s->f_code = 1;
@@ -368,6 +428,7 @@ int MPV_encode_end(AVCodecContext *avctx)
     MPV_common_end(s);
     if (s->out_format == FMT_MJPEG)
         mjpeg_close(s);
+      
     return 0;
 }
 
@@ -411,6 +472,7 @@ void MPV_frame_start(MpegEncContext *s)
             s->current_picture[i] = s->aux_picture[i];
         }
     } else {
+        s->last_non_b_pict_type= s->pict_type;
         for(i=0;i<3;i++) {
             /* swap next and last */
             tmp = s->last_picture[i];
@@ -426,12 +488,12 @@ void MPV_frame_end(MpegEncContext *s)
 {
     /* draw edge for correct motion prediction if outside */
     if (s->pict_type != B_TYPE && !s->intra_only) {
-      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4){
+      if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4 || s->divx_version==500){
         draw_edges(s->current_picture[0], s->linesize, s->mb_width*16, s->mb_height*16, EDGE_WIDTH);
         draw_edges(s->current_picture[1], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
         draw_edges(s->current_picture[2], s->linesize/2, s->mb_width*8, s->mb_height*8, EDGE_WIDTH/2);
       }else{
-        /* OpenDivx, but i dunno how to distinguish it from mpeg4 */
+        /* mpeg4? / opendivx / xvid */
         draw_edges(s->current_picture[0], s->linesize, s->width, s->height, EDGE_WIDTH);
         draw_edges(s->current_picture[1], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
         draw_edges(s->current_picture[2], s->linesize/2, s->width/2, s->height/2, EDGE_WIDTH/2);
@@ -454,14 +516,14 @@ int MPV_encode_picture(AVCodecContext *avctx,
 
     if (!s->intra_only) {
         /* first picture of GOP is intra */
-        if ((s->picture_number % s->gop_size) == 0)
+        if (s->picture_in_gop_number % s->gop_size==0){
+            s->picture_in_gop_number=0;
             s->pict_type = I_TYPE;
-        else
+        }else
             s->pict_type = P_TYPE;
     } else {
         s->pict_type = I_TYPE;
     }
-    avctx->key_frame = (s->pict_type == I_TYPE);
     
     MPV_frame_start(s);
     
@@ -479,30 +541,52 @@ int MPV_encode_picture(AVCodecContext *avctx,
             h >>= 1;
         }
 
-       if(dest_wrap==src_wrap){
-           s->new_picture[i] = pict->data[i];
-       }else {
+        if(dest_wrap==src_wrap){
+            s->new_picture[i] = pict->data[i];
+        } else {
             for(j=0;j<h;j++) {
                 memcpy(dest, src, w);
                 dest += dest_wrap;
                 src += src_wrap;
             }
             s->new_picture[i] = s->current_picture[i];
-       }
+           }
     }
 
     encode_picture(s, s->picture_number);
-    
+    avctx->key_frame = (s->pict_type == I_TYPE);
+    avctx->header_bits = s->header_bits;
+    avctx->mv_bits     = s->mv_bits;
+    avctx->misc_bits   = s->misc_bits;
+    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->skip_count  = s->skip_count;
+
     MPV_frame_end(s);
     s->picture_number++;
+    s->picture_in_gop_number++;
 
     if (s->out_format == FMT_MJPEG)
         mjpeg_picture_trailer(s);
 
     flush_put_bits(&s->pb);
-    s->total_bits += (s->pb.buf_ptr - s->pb.buf) * 8;
+    s->last_frame_bits= s->frame_bits;
+    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);
+
     avctx->quality = s->qscale;
-    return s->pb.buf_ptr - s->pb.buf;
+    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);
+    }
+    return pbBufPtr(&s->pb) - s->pb.buf;
 }
 
 static inline int clip(int a, int amin, int amax)
@@ -515,6 +599,59 @@ static inline int clip(int a, int amin, int amax)
         return a;
 }
 
+static inline void gmc1_motion(MpegEncContext *s,
+                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
+                               int dest_offset,
+                               UINT8 **ref_picture, int src_offset,
+                               int h)
+{
+    UINT8 *ptr;
+    int dxy, offset, mx, my, src_x, src_y, height, linesize;
+    int motion_x, motion_y;
+
+    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));
+    src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
+    motion_x<<=(3-s->sprite_warping_accuracy);
+    motion_y<<=(3-s->sprite_warping_accuracy);
+    src_x = clip(src_x, -16, s->width);
+    if (src_x == s->width)
+        motion_x =0;
+    src_y = clip(src_y, -16, s->height);
+    if (src_y == s->height)
+        motion_y =0;
+    
+    linesize = s->linesize;
+    ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
+
+    dest_y+=dest_offset;
+    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);
+
+    motion_x= s->sprite_offset[1][0];
+    motion_y= s->sprite_offset[1][1];
+    src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
+    src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
+    motion_x<<=(3-s->sprite_warping_accuracy);
+    motion_y<<=(3-s->sprite_warping_accuracy);
+    src_x = clip(src_x, -8, s->width>>1);
+    if (src_x == s->width>>1)
+        motion_x =0;
+    src_y = clip(src_y, -8, s->height>>1);
+    if (src_y == s->height>>1)
+        motion_y =0;
+
+    offset = (src_y * linesize>>1) + src_x + (src_offset>>1);
+    ptr = ref_picture[1] + offset;
+    gmc1(dest_cb + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
+    ptr = ref_picture[2] + offset;
+    gmc1(dest_cr + (dest_offset>>1), ptr, linesize>>1, h>>1, motion_x&15, motion_y&15, s->no_rounding);
+    
+    return;
+}
+
 /* 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,
@@ -525,7 +662,11 @@ static inline void mpeg_motion(MpegEncContext *s,
 {
     UINT8 *ptr;
     int dxy, offset, mx, my, src_x, src_y, height, linesize;
-    
+if(s->quarter_sample)
+{
+    motion_x>>=1;
+    motion_y>>=1;
+}
     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);
@@ -576,10 +717,69 @@ static inline void mpeg_motion(MpegEncContext *s,
     pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
 }
 
+static inline void qpel_motion(MpegEncContext *s,
+                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
+                               int dest_offset,
+                               UINT8 **ref_picture, int src_offset,
+                               int field_based, op_pixels_func *pix_op,
+                               qpel_mc_func *qpix_op,
+                               int motion_x, int motion_y, int h)
+{
+    UINT8 *ptr;
+    int dxy, offset, mx, my, src_x, src_y, height, linesize;
+
+    dxy = ((motion_y & 3) << 2) | (motion_x & 3);
+    src_x = s->mb_x * 16 + (motion_x >> 2);
+    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
+
+    height = s->height >> field_based;
+    src_x = clip(src_x, -16, s->width);
+    if (src_x == s->width)
+        dxy &= ~3;
+    src_y = clip(src_y, -16, height);
+    if (src_y == height)
+        dxy &= ~12;
+    linesize = s->linesize << 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);
+    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);
+    
+    mx= (motion_x>>1) | (motion_x&1);
+    my= (motion_y>>1) | (motion_y&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);
+    if (src_x == (s->width >> 1))
+        dxy &= ~1;
+    src_y = clip(src_y, -8, height >> 1);
+    if (src_y == (height >> 1))
+        dxy &= ~2;
+
+    offset = (src_y * (linesize >> 1)) + src_x + (src_offset >> 1);
+    ptr = ref_picture[1] + offset;
+    pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, linesize >> 1, h >> 1);
+    ptr = ref_picture[2] + offset;
+    pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, linesize >> 1, h >> 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)
+                              op_pixels_func *pix_op, qpel_mc_func *qpix_op)
 {
     int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
     int mb_x, mb_y, i;
@@ -590,10 +790,30 @@ static inline void MPV_motion(MpegEncContext *s,
 
     switch(s->mv_type) {
     case MV_TYPE_16X16:
-        mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
-                    ref_picture, 0,
-                    0, pix_op,
-                    s->mv[dir][0][0], s->mv[dir][0][1], 16);
+        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
+            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{
+            mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
+                        ref_picture, 0,
+                        0, pix_op,
+                        s->mv[dir][0][0], s->mv[dir][0][1], 16);
+        }           
         break;
     case MV_TYPE_8X8:
         for(i=0;i<4;i++) {
@@ -602,7 +822,7 @@ static inline void MPV_motion(MpegEncContext *s,
 
             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) & 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);
@@ -711,9 +931,10 @@ static inline void add_dct(MpegEncContext *s,
  */
 void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
 {
-    int mb_x, mb_y, motion_x, motion_y;
+    int mb_x, mb_y;
     int dct_linesize, dct_offset;
     op_pixels_func *op_pix;
+    qpel_mc_func *op_qpix;
 
     mb_x = s->mb_x;
     mb_y = s->mb_y;
@@ -725,41 +946,38 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
 
     /* update DC predictors for P macroblocks */
     if (!s->mb_intra) {
-        if (s->h263_pred) {
+        if (s->h263_pred || s->h263_aic) {
           if(s->mbintra_table[mb_x + mb_y*s->mb_width])
           {
-            int wrap, xy, v;
+            int wrap, xy, v;
             s->mbintra_table[mb_x + mb_y*s->mb_width]=0;
-  
             wrap = 2 * s->mb_width + 2;
+            xy = 2 * mb_x + 1 +  (2 * mb_y + 1) * wrap;
             v = 1024;
-            x = 2 * mb_x + 1;
-            y = 2 * mb_y + 1;
             
-            s->dc_val[0][(x) + (y) * wrap] = v;
-            s->dc_val[0][(x + 1) + (y) * wrap] = v;
-            s->dc_val[0][(x) + (y + 1) * wrap] = v;
-            s->dc_val[0][(x + 1) + (y + 1) * wrap] = v;
+            s->dc_val[0][xy] = v;
+            s->dc_val[0][xy + 1] = v;
+            s->dc_val[0][xy + wrap] = v;
+            s->dc_val[0][xy + 1 + wrap] = v;
             /* ac pred */
-            memset(s->ac_val[0][(x) + (y) * wrap], 0, 16 * sizeof(INT16));
-            memset(s->ac_val[0][(x + 1) + (y) * wrap], 0, 16 * sizeof(INT16));
-            memset(s->ac_val[0][(x) + (y + 1) * wrap], 0, 16 * sizeof(INT16));
-            memset(s->ac_val[0][(x + 1) + (y + 1) * wrap], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[0][xy], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[0][xy + 1], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[0][xy + wrap], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[0][xy + 1 + wrap], 0, 16 * sizeof(INT16));
             if (s->h263_msmpeg4) {
-                s->coded_block[(x) + (y) * wrap] = 0;
-                s->coded_block[(x + 1) + (y) * wrap] = 0;
-                s->coded_block[(x) + (y + 1) * wrap] = 0;
-                s->coded_block[(x + 1) + (y + 1) * wrap] = 0;
+                s->coded_block[xy] = 0;
+                s->coded_block[xy + 1] = 0;
+                s->coded_block[xy + wrap] = 0;
+                s->coded_block[xy + 1 + wrap] = 0;
             }
             /* chroma */
             wrap = s->mb_width + 2;
-            x = mb_x + 1;
-            y = mb_y + 1;
-            s->dc_val[1][(x) + (y) * wrap] = v;
-            s->dc_val[2][(x) + (y) * wrap] = v;
+            xy = mb_x + 1 + (mb_y + 1) * wrap;
+            s->dc_val[1][xy] = v;
+            s->dc_val[2][xy] = v;
             /* ac pred */
-            memset(s->ac_val[1][(x) + (y) * wrap], 0, 16 * sizeof(INT16));
-            memset(s->ac_val[2][(x) + (y) * wrap], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
+            memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
           }
         } else {
             s->last_dc[0] = 128 << s->intra_dc_precision;
@@ -767,16 +985,16 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
             s->last_dc[2] = 128 << s->intra_dc_precision;
         }
     }
-    else if (s->h263_pred)
+    else if (s->h263_pred || s->h263_aic)
         s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
 
-    /* update motion predictor */
+    /* 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) {
-        int x, y, wrap;
+      if(s->pict_type!=B_TYPE){
+        int xy, wrap, motion_x, motion_y;
         
-        x = 2 * mb_x + 1;
-        y = 2 * mb_y + 1;
         wrap = 2 * s->mb_width + 2;
+        xy = 2 * mb_x + 1 + (2 * mb_y + 1) * wrap;
         if (s->mb_intra) {
             motion_x = 0;
             motion_y = 0;
@@ -786,15 +1004,16 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
             motion_y = s->mv[0][0][1];
         motion_init:
             /* no update if 8X8 because it has been done during parsing */
-            s->motion_val[(x) + (y) * wrap][0] = motion_x;
-            s->motion_val[(x) + (y) * wrap][1] = motion_y;
-            s->motion_val[(x + 1) + (y) * wrap][0] = motion_x;
-            s->motion_val[(x + 1) + (y) * wrap][1] = motion_y;
-            s->motion_val[(x) + (y + 1) * wrap][0] = motion_x;
-            s->motion_val[(x) + (y + 1) * wrap][1] = motion_y;
-            s->motion_val[(x + 1) + (y + 1) * wrap][0] = motion_x;
-            s->motion_val[(x + 1) + (y + 1) * wrap][1] = motion_y;
+            s->motion_val[xy][0] = motion_x;
+            s->motion_val[xy][1] = motion_y;
+            s->motion_val[xy + 1][0] = motion_x;
+            s->motion_val[xy + 1][1] = motion_y;
+            s->motion_val[xy + wrap][0] = motion_x;
+            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;
         }
+      }
     }
     
     if (!s->intra_only) {
@@ -829,20 +1048,23 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
 
         if (!s->mb_intra) {
             /* motion handling */
-            if (!s->no_rounding) 
+            if (!s->no_rounding){
                 op_pix = put_pixels_tab;
-            else
+                op_qpix= qpel_mc_rnd_tab;
+            }else{
                 op_pix = put_no_rnd_pixels_tab;
+                op_qpix= qpel_mc_no_rnd_tab;
+            }
 
             if (s->mv_dir & MV_DIR_FORWARD) {
-                MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix);
+                MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
                 if (!s->no_rounding) 
                     op_pix = avg_pixels_tab;
                 else
                     op_pix = avg_no_rnd_pixels_tab;
             }
             if (s->mv_dir & MV_DIR_BACKWARD) {
-                MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix);
+                MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
             }
 
             /* add dct residue */
@@ -865,16 +1087,326 @@ void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
         }
     }
  the_end:
-    emms_c();
+    emms_c(); //FIXME remove
 }
 
-static void encode_picture(MpegEncContext *s, int picture_number)
+static void encode_mb(MpegEncContext *s)
 {
-    int mb_x, mb_y, wrap, last_gob, pdif = 0;
+    int wrap;
+    const int mb_x= s->mb_x;
+    const int mb_y= s->mb_y;
     UINT8 *ptr;
-    int i, motion_x, motion_y;
+    const int motion_x= s->mv[0][0][0];
+    const int motion_y= s->mv[0][0][1];
+    int i;
+
+    /* get the pixels */
+    wrap = s->linesize;
+    ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
+    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);
+    wrap = s->linesize >> 1;
+    ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
+    get_pixels(s->block[4], ptr, wrap);
+
+    wrap = s->linesize >> 1;
+    ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
+    get_pixels(s->block[5], ptr, wrap);
+
+    /* subtract previous frame if non intra */
+    if (!s->mb_intra) {
+        int dxy, offset, mx, my;
+        
+        if(s->mv_type==MV_TYPE_16X16){
+            dxy = ((motion_y & 1) << 1) | (motion_x & 1);
+            ptr = s->last_picture[0] + 
+                ((mb_y * 16 + (motion_y >> 1)) * s->linesize) + 
+                (mb_x * 16 + (motion_x >> 1));
+
+            sub_pixels_2(s->block[0], ptr, s->linesize, dxy);
+            sub_pixels_2(s->block[1], ptr + 8, s->linesize, dxy);
+            sub_pixels_2(s->block[2], ptr + s->linesize * 8, s->linesize, dxy);
+            sub_pixels_2(s->block[3], ptr + 8 + s->linesize * 8, s->linesize ,dxy);
+
+            if (s->out_format == FMT_H263) {
+                /* special rounding for h263 */
+                dxy = 0;
+                if ((motion_x & 3) != 0)
+                    dxy |= 1;
+                if ((motion_y & 3) != 0)
+                    dxy |= 2;
+                mx = motion_x >> 2;
+                my = motion_y >> 2;
+            } else {
+                mx = motion_x / 2;
+                my = motion_y / 2;
+                dxy = ((my & 1) << 1) | (mx & 1);
+                mx >>= 1;
+                my >>= 1;
+            }
+            offset = ((mb_y * 8 + my) * (s->linesize >> 1)) + (mb_x * 8 + mx);
+            ptr = s->last_picture[1] + offset;
+            sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
+            ptr = s->last_picture[2] + offset;
+            sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
+        }else{
+            int src_x, src_y;
+
+            for(i=0;i<4;i++) {
+                int motion_x = s->mv[0][i][0];
+                int motion_y = s->mv[0][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;
+                        
+                ptr = s->last_picture[0] + (src_y * s->linesize) + (src_x);
+                sub_pixels_2(s->block[i], ptr, s->linesize, dxy);
+            }
+            /* 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[0][i][0];
+                my += s->mv[0][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));
+            }
+            dxy = ((my & 1) << 1) | (mx & 1);
+            mx >>= 1;
+            my >>= 1;
+
+            src_x = mb_x * 8 + mx;
+            src_y = mb_y * 8 + my;
+            src_x = clip(src_x, -8, s->width/2);
+            if (src_x == s->width/2)
+                dxy &= ~1;
+            src_y = clip(src_y, -8, s->height/2);
+            if (src_y == s->height/2)
+                dxy &= ~2;
+            
+            offset = (src_y * (s->linesize >> 1)) + src_x;
+            ptr = s->last_picture[1] + offset;
+            sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
+            ptr = s->last_picture[2] + offset;
+            sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
+        }
+    }
+            
+#if 0
+            {
+                float adap_parm;
+                
+                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
+                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
+            
+                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
+                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
+                        s->qscale, adap_parm, s->qscale*adap_parm,
+                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
+            }
+#endif
+    /* DCT & quantize */
+    if (s->h263_msmpeg4) {
+        msmpeg4_dc_scale(s);
+    } else if (s->h263_pred) {
+        h263_dc_scale(s);
+    } else {
+        /* default quantization values */
+        s->y_dc_scale = 8;
+        s->c_dc_scale = 8;
+    }
+    for(i=0;i<6;i++) {
+        s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
+    }
+
+    /* 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;
+    }
+}
+
+static void copy_bits(PutBitContext *pb, UINT8 *src, int length)
+{
+    int bytes= length>>3;
+    int bits= length&7;
+    int i;
+
+    for(i=0; i<bytes; i++) put_bits(pb, 8, src[i]);
+    put_bits(pb, bits, src[i]>>(8-bits));
+}
+
+static void encode_picture(MpegEncContext *s, int picture_number)
+{
+    int mb_x, mb_y, last_gob, pdif = 0;
+    int i;
+    int bits;
+    MpegEncContext best_s;
+    UINT8 bit_buf[4][3000]; //FIXME check that this is ALLWAYS large enogh for a MB
 
     s->picture_number = picture_number;
+
+    s->block_wrap[0]=
+    s->block_wrap[1]=
+    s->block_wrap[2]=
+    s->block_wrap[3]= s->mb_width*2 + 2;
+    s->block_wrap[4]=
+    s->block_wrap[5]= s->mb_width + 2;
+    
+    s->last_mc_mb_var = s->mc_mb_var;
+    /* Reset the average MB variance */
+    s->avg_mb_var = 0;
+    s->mc_mb_var = 0;
+    /* Estimate motion for every MB */
+    if(s->pict_type == P_TYPE){
+        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);
+            s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
+            s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
+            for(mb_x=0; mb_x < s->mb_width; mb_x++) {
+                s->mb_x = mb_x;
+                s->mb_y = mb_y;
+                s->block_index[0]+=2;
+                s->block_index[1]+=2;
+                s->block_index[2]+=2;
+                s->block_index[3]+=2;
+
+                /* compute motion vector & mb_type and store in context */
+                estimate_motion(s, mb_x, mb_y);
+//                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
+            }
+        }
+        emms_c();
+    }else{
+        /* 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->mv_table[0]  , 0, sizeof(INT16)*s->mb_width*s->mb_height);
+        memset(s->mv_table[1]  , 0, sizeof(INT16)*s->mb_width*s->mb_height);
+        memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
+    }
+
+    if(s->avg_mb_var < s->mc_mb_var && s->pict_type != B_TYPE){ //FIXME subtract MV bits
+        s->pict_type= I_TYPE;
+        s->picture_in_gop_number=0;
+        memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
+//printf("Scene change detected, encoding as I Frame\n");
+    }
+
+    /* find best f_code for ME which do unlimited searches */
+    if(s->pict_type==P_TYPE && s->full_search>3){
+        int mv_num[8];
+        int i;
+        int loose=0;
+        UINT8 * fcode_tab= s->fcode_tab;
+
+        for(i=0; i<8; i++) mv_num[i]=0;
+
+        for(i=0; i<s->mb_num; i++){
+            if(s->mb_type[i] & MB_TYPE_INTER){
+                mv_num[ fcode_tab[s->mv_table[0][i] + MAX_MV] ]++;
+                mv_num[ fcode_tab[s->mv_table[1][i] + MAX_MV] ]++;
+//printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);
+            }
+//else printf("I");
+        }
+
+        for(i=MAX_FCODE; i>1; i--){
+            loose+= mv_num[i];
+            if(loose > 10) break; //FIXME this is pretty ineffective
+        }
+        s->f_code= i;
+/*        for(i=0; i<=MAX_FCODE; i++){
+            printf("%d ", mv_num[i]);
+        }
+        printf("\n");*/
+    }else{
+        s->f_code= 1;
+    }
+
+//printf("f_code %d ///\n", s->f_code);
+    /* convert MBs with too long MVs to I-Blocks */
+    if(s->pict_type==P_TYPE){
+        int i, x, y;
+        const int f_code= s->f_code;
+        UINT8 * fcode_tab= s->fcode_tab;
+//FIXME try to clip instead of intra izing ;)
+        /* clip / convert to intra 16x16 type MVs */
+        for(i=0; i<s->mb_num; i++){
+            if(s->mb_type[i]&MB_TYPE_INTER){
+                if(   fcode_tab[s->mv_table[0][i] + MAX_MV] > f_code
+                   || fcode_tab[s->mv_table[0][i] + MAX_MV] == 0
+                   || fcode_tab[s->mv_table[1][i] + MAX_MV] > f_code
+                   || fcode_tab[s->mv_table[1][i] + MAX_MV] == 0 ){
+                    s->mb_type[i] &= ~MB_TYPE_INTER;
+                    s->mb_type[i] |= MB_TYPE_INTRA;
+                    s->mv_table[0][i] = 0;
+                    s->mv_table[1][i] = 0;
+                }
+            }
+        }
+
+        if(s->flags&CODEC_FLAG_4MV){
+            int wrap= 2+ s->mb_width*2;
+
+            /* clip / convert to intra 8x8 type MVs */
+            for(y=0; y<s->mb_height; y++){
+                int xy= (y*2 + 1)*wrap + 1;
+                i= y*s->mb_width;
+
+                for(x=0; x<s->mb_width; x++){
+                    if(s->mb_type[i]&MB_TYPE_INTER4V){
+                        int block;
+                        for(block=0; block<4; block++){
+                            int off= (block& 1) + (block>>1)*wrap;
+                            int mx= s->motion_val[ xy + off ][0];
+                            int my= s->motion_val[ xy + off ][1];
+
+                            if(   fcode_tab[mx + MAX_MV] > f_code
+                               || fcode_tab[mx + MAX_MV] == 0
+                               || fcode_tab[my + MAX_MV] > f_code
+                               || fcode_tab[my + MAX_MV] == 0 ){
+                                s->mb_type[i] &= ~MB_TYPE_INTER4V;
+                                s->mb_type[i] |= MB_TYPE_INTRA;
+                            }
+                        }
+                        xy+=2;
+                        i++;
+                    }
+                }
+            }
+        }
+    }
+
+//    printf("%d %d\n", s->avg_mb_var, s->mc_mb_var);
+
     if (!s->fixed_qscale) 
         s->qscale = rate_estimate_qscale(s);
 
@@ -890,6 +1422,7 @@ static void encode_picture(MpegEncContext *s, int picture_number)
         convert_matrix(s->q_non_intra_matrix, s->q_non_intra_matrix16, s->non_intra_matrix, s->qscale);
     }
 
+    s->last_bits= get_bit_count(&s->pb);
     switch(s->out_format) {
     case FMT_MJPEG:
         mjpeg_picture_header(s);
@@ -908,7 +1441,17 @@ static void encode_picture(MpegEncContext *s, int picture_number)
         mpeg1_encode_picture_header(s, picture_number);
         break;
     }
-        
+    bits= get_bit_count(&s->pb);
+    s->header_bits= bits - s->last_bits;
+    s->last_bits= bits;
+    s->mv_bits=0;
+    s->misc_bits=0;
+    s->i_tex_bits=0;
+    s->p_tex_bits=0;
+    s->i_count=0;
+    s->p_count=0;
+    s->skip_count=0;
+
     /* init last dc values */
     /* note: quant matrix value (8) is implied here */
     s->last_dc[0] = 128;
@@ -917,8 +1460,6 @@ static void encode_picture(MpegEncContext *s, int picture_number)
     s->mb_incr = 1;
     s->last_mv[0][0][0] = 0;
     s->last_mv[0][0][1] = 0;
-    s->mv_type = MV_TYPE_16X16;
-    s->mv_dir = MV_DIR_FORWARD;
 
     /* Get the GOB height based on picture height */
     if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
@@ -930,6 +1471,8 @@ static void encode_picture(MpegEncContext *s, int picture_number)
             s->gob_index = 4;
     }
         
+    s->avg_mb_var = s->avg_mb_var / s->mb_num;        
+    
     for(mb_y=0; mb_y < s->mb_height; mb_y++) {
         /* Put GOB header based on RTP MTU */
         /* TODO: Put all this stuff in a separate generic function */
@@ -944,126 +1487,155 @@ static void encode_picture(MpegEncContext *s, int picture_number)
                 }
             }
         }
+        
+        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);
+        s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
+        s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
+        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];
+            PutBitContext pb;
+            int d;
+            int dmin=10000000;
+            int best=0;
 
             s->mb_x = mb_x;
             s->mb_y = mb_y;
-
-            /* compute motion vector and macro block type (intra or non intra) */
-            motion_x = 0;
-            motion_y = 0;
-            if (s->pict_type == P_TYPE) {
-                s->mb_intra = estimate_motion(s, mb_x, mb_y,
-                                              &motion_x,
-                                              &motion_y);
-            } else {
-                s->mb_intra = 1;
-            }
-
-            /* get the pixels */
-            wrap = s->linesize;
-            ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
-            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);
-            wrap = s->linesize >> 1;
-            ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
-            get_pixels(s->block[4], ptr, wrap);
-
-            wrap = s->linesize >> 1;
-            ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
-            get_pixels(s->block[5], ptr, wrap);
-
-            /* subtract previous frame if non intra */
-            if (!s->mb_intra) {
-                int dxy, offset, mx, my;
-
-                dxy = ((motion_y & 1) << 1) | (motion_x & 1);
-                ptr = s->last_picture[0] + 
-                    ((mb_y * 16 + (motion_y >> 1)) * s->linesize) + 
-                    (mb_x * 16 + (motion_x >> 1));
-
-                sub_pixels_2(s->block[0], ptr, s->linesize, dxy);
-                sub_pixels_2(s->block[1], ptr + 8, s->linesize, dxy);
-                sub_pixels_2(s->block[2], ptr + s->linesize * 8, s->linesize, dxy);
-                sub_pixels_2(s->block[3], ptr + 8 + s->linesize * 8, s->linesize ,dxy);
-
-                if (s->out_format == FMT_H263) {
-                    /* special rounding for h263 */
-                    dxy = 0;
-                    if ((motion_x & 3) != 0)
-                        dxy |= 1;
-                    if ((motion_y & 3) != 0)
-                        dxy |= 2;
-                    mx = motion_x >> 2;
-                    my = motion_y >> 2;
-                } else {
-                    mx = motion_x / 2;
-                    my = motion_y / 2;
-                    dxy = ((my & 1) << 1) | (mx & 1);
-                    mx >>= 1;
-                    my >>= 1;
+            s->block_index[0]+=2;
+            s->block_index[1]+=2;
+            s->block_index[2]+=2;
+            s->block_index[3]+=2;
+            s->block_index[4]++;
+            s->block_index[5]++;
+
+            s->mv_dir = MV_DIR_FORWARD;
+            if(mb_type & (mb_type-1)){ // more than 1 MB type possible
+                pb= s->pb;
+                if(mb_type&MB_TYPE_INTER){
+                    s->mv_type = MV_TYPE_16X16;
+                    s->mb_intra= 0;
+                    s->mv[0][0][0] = s->mv_table[0][mb_y * s->mb_width + mb_x];
+                    s->mv[0][0][1] = s->mv_table[1][mb_y * s->mb_width + mb_x];
+                    init_put_bits(&s->pb, bit_buf[1], 3000, NULL, NULL);
+                    s->block= s->inter_block;
+
+                    encode_mb(s);
+                    d= get_bit_count(&s->pb);
+                    if(d<dmin){
+                        flush_put_bits(&s->pb);
+                        dmin=d;
+                        best_s.mv[0][0][0]= s->mv[0][0][0];
+                        best_s.mv[0][0][1]= s->mv[0][0][1];
+                        best_s.mb_intra= 0;
+                        best_s.mv_type = MV_TYPE_16X16;
+                        best_s.pb=s->pb;
+                        best_s.block= s->block;
+                        best=1;
+                        for(i=0; i<6; i++)
+                            best_s.block_last_index[i]= s->block_last_index[i];
+                    }
                 }
-                offset = ((mb_y * 8 + my) * (s->linesize >> 1)) + (mb_x * 8 + mx);
-                ptr = s->last_picture[1] + offset;
-                sub_pixels_2(s->block[4], ptr, s->linesize >> 1, dxy);
-                ptr = s->last_picture[2] + offset;
-                sub_pixels_2(s->block[5], ptr, s->linesize >> 1, dxy);
-            }
-            emms_c();
-
-            /* DCT & quantize */
-            if (s->h263_msmpeg4) {
-                msmpeg4_dc_scale(s);
-            } else if (s->h263_pred) {
-                h263_dc_scale(s);
+                if(mb_type&MB_TYPE_INTER4V){
+                    s->mv_type = MV_TYPE_8X8;
+                    s->mb_intra= 0;
+                    for(i=0; i<4; i++){
+                        s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
+                        s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
+                    }
+                    init_put_bits(&s->pb, bit_buf[2], 3000, NULL, NULL);
+                    s->block= s->inter4v_block;
+
+                    encode_mb(s);
+                    d= get_bit_count(&s->pb);
+                    if(d<dmin){
+                        flush_put_bits(&s->pb);
+                        dmin=d;
+                        for(i=0; i<4; i++){
+                            best_s.mv[0][i][0] = s->mv[0][i][0];
+                            best_s.mv[0][i][1] = s->mv[0][i][1];
+                        }
+                        best_s.mb_intra= 0;
+                        best_s.mv_type = MV_TYPE_8X8;
+                        best_s.pb=s->pb;
+                        best_s.block= s->block;
+                        best=2;
+                        for(i=0; i<6; i++)
+                            best_s.block_last_index[i]= s->block_last_index[i];
+                    }
+                }
+                if(mb_type&MB_TYPE_INTRA){
+                    s->mv_type = MV_TYPE_16X16;
+                    s->mb_intra= 1;
+                    s->mv[0][0][0] = 0;
+                    s->mv[0][0][1] = 0;
+                    init_put_bits(&s->pb, bit_buf[0], 3000, NULL, NULL);
+                    s->block= s->intra_block;
+                   
+                    encode_mb(s);
+                    d= get_bit_count(&s->pb);
+                    if(d<dmin){
+                        flush_put_bits(&s->pb);
+                        dmin=d;
+                        best_s.mv[0][0][0]= 0;
+                        best_s.mv[0][0][1]= 0;
+                        best_s.mb_intra= 1;
+                        best_s.mv_type = MV_TYPE_16X16;
+                        best_s.pb=s->pb;
+                        best_s.block= s->block;
+                        for(i=0; i<6; i++)
+                            best_s.block_last_index[i]= s->block_last_index[i];
+                        best=0;
+                    }
+                    /* force cleaning of ac/dc if needed ... */
+                    s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
+                }
+                for(i=0; i<4; i++){
+                   s->mv[0][i][0] =  best_s.mv[0][i][0];
+                   s->mv[0][i][1] =  best_s.mv[0][i][1];
+                }
+                s->mb_intra= best_s.mb_intra;
+                s->mv_type= best_s.mv_type;
+                for(i=0; i<6; i++)
+                   s->block_last_index[i]= best_s.block_last_index[i];
+                copy_bits(&pb, bit_buf[best], dmin);
+                s->block= best_s.block;
+                s->pb= pb;
             } else {
-                /* default quantization values */
-                s->y_dc_scale = 8;
-                s->c_dc_scale = 8;
-            }
-            for(i=0;i<6;i++) {
-                s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);
-            }
-
-            /* 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
-                    h263_encode_mb(s, s->block, motion_x, motion_y);
-                break;
-            case FMT_MJPEG:
-                mjpeg_encode_mb(s, s->block);
-                break;
+                // only one MB-Type possible
+                if(mb_type&MB_TYPE_INTRA){
+                    s->mb_intra= 1;
+                    s->mv[0][0][0] = 0;
+                    s->mv[0][0][1] = 0;
+                }else{
+                    s->mb_intra= 0;
+                    s->mv[0][0][0] = s->mv_table[0][mb_y * s->mb_width + mb_x];
+                    s->mv[0][0][1] = s->mv_table[1][mb_y * s->mb_width + mb_x];
+                }
+                encode_mb(s);
             }
 
-            /* decompress blocks so that we keep the state of the decoder */
-            s->mv[0][0][0] = motion_x;
-            s->mv[0][0][1] = motion_y;
-
             MPV_decode_mb(s, s->block);
         }
+
+
         /* Obtain average GOB size for RTP */
         if (s->rtp_mode) {
             if (!mb_y)
-                s->mb_line_avgsize = s->pb.buf_ptr - s->ptr_last_mb_line;
+                s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
             else if (!(mb_y % s->gob_index)) {    
-                s->mb_line_avgsize = (s->mb_line_avgsize + s->pb.buf_ptr - s->ptr_last_mb_line) >> 1;
-                s->ptr_last_mb_line = s->pb.buf_ptr;
+                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);
             s->first_gob_line = 0;
         }
     }
-    
-    if (s->h263_msmpeg4) 
+    emms_c();
+
+    if (s->h263_msmpeg4 && s->pict_type == I_TYPE)
         msmpeg4_encode_ext_header(s);
 
     //if (s->gob_number)
@@ -1072,14 +1644,13 @@ static void encode_picture(MpegEncContext *s, int picture_number)
     /* Send the last GOB if RTP */    
     if (s->rtp_mode) {
         flush_put_bits(&s->pb);
-        pdif = s->pb.buf_ptr - s->ptr_lastgob;
+        pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
         /* Call the RTP callback to send the last GOB */
         if (s->rtp_callback)
             s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
-        s->ptr_lastgob = s->pb.buf_ptr;
+        s->ptr_lastgob = pbBufPtr(&s->pb);
         //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
     }
-
 }
 
 static int dct_quantize_c(MpegEncContext *s, 
@@ -1262,12 +1833,14 @@ static void dct_unquantize_h263_c(MpegEncContext *s,
 {
     int i, level, qmul, qadd;
     int nCoeffs;
-
+    
     if (s->mb_intra) {
-        if (n < 4) 
-            block[0] = block[0] * s->y_dc_scale;
-        else
-            block[0] = block[0] * s->c_dc_scale;
+        if (!s->h263_aic) {
+            if (n < 4) 
+                block[0] = block[0] * s->y_dc_scale;
+            else
+                block[0] = block[0] * s->c_dc_scale;
+        }
         i = 1;
         nCoeffs= 64; //does not allways use zigzag table 
     } else {
@@ -1276,7 +1849,10 @@ static void dct_unquantize_h263_c(MpegEncContext *s,
     }
 
     qmul = s->qscale << 1;
-    qadd = (s->qscale - 1) | 1;
+    if (s->h263_aic && s->mb_intra)
+        qadd = 0;
+    else
+        qadd = (s->qscale - 1) | 1;
 
     for(;i<nCoeffs;i++) {
         level = block[i];
@@ -1303,6 +1879,22 @@ static void dct_unquantize_h263_c(MpegEncContext *s,
 
 static void rate_control_init(MpegEncContext *s)
 {
+#if 1
+    emms_c();
+
+    //initial values, they dont really matter as they will be totally different within a few frames
+    s->i_pred.coeff= s->p_pred.coeff= 7.0;
+    s->i_pred.count= s->p_pred.count= 1.0;
+    
+    s->i_pred.decay= s->p_pred.decay= 0.4;
+    
+    // use more bits at the beginning, otherwise high motion at the begin will look like shit
+    s->qsum=100;
+    s->qcount=100;
+
+    s->short_term_qsum=0.001;
+    s->short_term_qcount=0.001;
+#else
     s->wanted_bits = 0;
 
     if (s->intra_only) {
@@ -1313,24 +1905,123 @@ static void rate_control_init(MpegEncContext *s)
                                  (float)((float)s->frame_rate / FRAME_RATE_BASE * (I_FRAME_SIZE_RATIO + s->gop_size - 1)));
         s->I_frame_bits = (int)(s->P_frame_bits * I_FRAME_SIZE_RATIO);
     }
-    
+
 #if defined(DEBUG)
     printf("I_frame_size=%d P_frame_size=%d\n",
            s->I_frame_bits, s->P_frame_bits);
 #endif
+#endif
 }
 
+static double predict(Predictor *p, double q, double var)
+{
+    return p->coeff*var / (q*p->count);
+}
+
+static void update_predictor(Predictor *p, double q, double var, double size)
+{
+    double new_coeff= size*q / (var + 1);
+    if(var<1000) return;
+/*{
+int pred= predict(p, q, var);
+int error= abs(pred-size);
+static double sum=0;
+static int count=0;
+if(count>5) sum+=error;
+count++;
+if(256*256*256*64%count==0){
+    printf("%d %f %f\n", count, sum/count, p->coeff);
+}
+}*/
+    p->count*= p->decay;
+    p->coeff*= p->decay;
+    p->count++;
+    p->coeff+= new_coeff;
+}
 
-/*
- * This heuristic is rather poor, but at least we do not have to
- * change the qscale at every macroblock.
- */
 static int rate_estimate_qscale(MpegEncContext *s)
 {
-    INT64 diff, total_bits = s->total_bits;
+#if 1
+    int qmin= s->qmin;
+    int qmax= s->qmax;
+    int rate_q=5;
     float q;
-    int qscale, qmin;
+    int qscale;
+    float br_compensation;
+    double diff;
+    double short_term_q;
+    double long_term_q;
+    int last_qscale= s->qscale;
+    double fps;
+    INT64 wanted_bits;
+    emms_c();
+    
+    fps= (double)s->frame_rate / FRAME_RATE_BASE;
+    wanted_bits= s->bit_rate*(double)s->picture_number/fps;
+
+    
+    if(s->picture_number>2){
+        /* update predictors */
+        if(s->last_pict_type == I_TYPE){
+        //FIXME
+        }else{ //P Frame
+//printf("%d %d %d %f\n", s->qscale, s->last_mc_mb_var, s->frame_bits, s->p_pred.coeff);
+            update_predictor(&s->p_pred, s->qscale, s->last_mc_mb_var, s->frame_bits);
+        }
+    }
+
+    if(s->pict_type == I_TYPE){
+        //FIXME
+        rate_q= s->qsum/s->qcount;
+    }else{ //P Frame
+        int i;
+        int diff, best_diff=1000000000;
+        for(i=1; i<=31; i++){
+            diff= predict(&s->p_pred, i, s->mc_mb_var) - (double)s->bit_rate/fps;
+            if(diff<0) diff= -diff;
+            if(diff<best_diff){
+                best_diff= diff;
+                rate_q= i;
+            }
+        }
+    }
+
+    s->short_term_qsum*=s->qblur;
+    s->short_term_qcount*=s->qblur;
+
+    s->short_term_qsum+= rate_q;
+    s->short_term_qcount++;
+    short_term_q= s->short_term_qsum/s->short_term_qcount;
+    
+    long_term_q= s->qsum/s->qcount*s->total_bits/wanted_bits;
+
+//    q= (long_term_q - short_term_q)*s->qcompress + short_term_q;
+    q= 1/((1/long_term_q - 1/short_term_q)*s->qcompress + 1/short_term_q);
 
+    diff= s->total_bits - wanted_bits;
+    br_compensation= (s->bit_rate_tolerance - diff)/s->bit_rate_tolerance;
+    if(br_compensation<=0.0) br_compensation=0.001;
+    q/=br_compensation;
+
+    qscale= (int)(q + 0.5);
+    if     (qscale<qmin) qscale=qmin;
+    else if(qscale>qmax) qscale=qmax;
+    
+    if     (qscale<last_qscale-s->max_qdiff) qscale=last_qscale-s->max_qdiff;
+    else if(qscale>last_qscale+s->max_qdiff) qscale=last_qscale+s->max_qdiff;
+
+    s->qsum+= qscale;
+    s->qcount++;
+
+    s->last_pict_type= s->pict_type;
+//printf("q:%d diff:%d comp:%f rate_q:%d st_q:%d fvar:%d last_size:%d\n", qscale, (int)diff, br_compensation, 
+//       rate_q, (int)short_term_q, s->mc_mb_var, s->frame_bits);
+//printf("%d %d\n", s->bit_rate, (int)fps);
+    return qscale;
+#else
+    INT64 diff, total_bits = s->total_bits;
+    float q;
+    int qscale;
     if (s->pict_type == I_TYPE) {
         s->wanted_bits += s->I_frame_bits;
     } else {
@@ -1352,14 +2043,16 @@ static int rate_estimate_qscale(MpegEncContext *s)
         q = 31;
     qscale = (int)(q + 0.5);
 #if defined(DEBUG)
-    printf("%d: total=%0.0f br=%0.1f diff=%d qest=%0.1f\n", 
+    printf("\n%d: total=%0.0f wanted=%0.0f br=%0.1f diff=%d qest=%2.1f\n", 
            s->picture_number, 
            (double)total_bits, 
+           (double)s->wanted_bits,
            (float)s->frame_rate / FRAME_RATE_BASE * 
            total_bits / s->picture_number, 
-           diff, q);
+           (int)diff, q);
 #endif
     return qscale;
+#endif
 }
 
 AVCodec mpeg1video_encoder = {