[xiph-commits] r16314 - branches/theora-thusnelda/lib/enc

tterribe at svn.xiph.org tterribe at svn.xiph.org
Tue Jul 21 18:56:26 PDT 2009


Author: tterribe
Date: 2009-07-21 18:56:26 -0700 (Tue, 21 Jul 2009)
New Revision: 16314

Modified:
   branches/theora-thusnelda/lib/enc/analyze.c
   branches/theora-thusnelda/lib/enc/encfrag.c
   branches/theora-thusnelda/lib/enc/encint.h
   branches/theora-thusnelda/lib/enc/encode.c
   branches/theora-thusnelda/lib/enc/enquant.c
   branches/theora-thusnelda/lib/enc/huffenc.c
   branches/theora-thusnelda/lib/enc/mcenc.c
   branches/theora-thusnelda/lib/enc/rate.c
   branches/theora-thusnelda/lib/enc/tokenize.c
Log:
Initial implementation of adaptive quantization, along with early SKIP and a
 number of other minor bugfixes.

Currently we just choose quantizers based on estimated R-D cost, using the same
 tables currently used for mode decision.
This is mostly beneficial at high rates.
In the future, we are likely to get bigger gains through more psychovisual
 criteria (taking into account that there's more masking in complex textures,
 less in edges next to smooth regions, etc.).
Those things can be incorporated into any generic R-D optimization framework,
 but AQ provides the flexibility to make them work.

Early SKIP detection provides large speed gains (as much as 17% on low bitrate
 clips), and allows us to make better mode decision choices.
It has a negligible effect on luma PSNR, but there's still a non-trivial
 decrease in chroma PSNR.
This may be due to a bug, but the visual impact is small, if any, so it's
 worth keeping enabled for now.


Modified: branches/theora-thusnelda/lib/enc/analyze.c
===================================================================
--- branches/theora-thusnelda/lib/enc/analyze.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/analyze.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -22,6 +22,7 @@
 
 
 typedef struct oc_fr_state           oc_fr_state;
+typedef struct oc_qii_state          oc_qii_state;
 typedef struct oc_enc_pipeline_state oc_enc_pipeline_state;
 typedef struct oc_rd_metric          oc_rd_metric;
 typedef struct oc_mode_choice        oc_mode_choice;
@@ -212,168 +213,174 @@
 
 /*State to track coded block flags and their bit cost.*/
 struct oc_fr_state{
+  ptrdiff_t  bits;
   unsigned   sb_partial_count:16;
   unsigned   sb_full_count:16;
+  unsigned   b_coded_count_prev:8;
+  unsigned   b_coded_count:8;
   unsigned   b_count:8;
-  unsigned   b_pend:8;
-  signed int sb_partial_last:2;
-  signed int sb_full_last:2;
-  signed int b_last:2;
-  unsigned   sb_partial:1;
-  unsigned   sb_coded:1;
-  unsigned   sb_partial_break:1;
-  unsigned   sb_full_break:1;
-  ptrdiff_t  bits;
+  signed int sb_partial:2;
+  signed int sb_full:2;
+  signed int b_coded_prev:2;
+  signed int b_coded:2;
 };
 
 
 
 static void oc_fr_state_init(oc_fr_state *_fr){
-  _fr->sb_partial_last=-1;
+  _fr->bits=0;
   _fr->sb_partial_count=0;
-  _fr->sb_partial_break=0;
-  _fr->sb_full_last=-1;
   _fr->sb_full_count=0;
-  _fr->sb_full_break=0;
-  _fr->b_last=-1;
+  _fr->b_coded_count_prev=0;
+  _fr->b_coded_count=0;
   _fr->b_count=0;
-  _fr->b_pend=0;
-  _fr->sb_partial=0;
-  _fr->sb_coded=0;
-  _fr->bits=0;
+  _fr->sb_partial=-1;
+  _fr->sb_full=-1;
+  _fr->b_coded_prev=-1;
+  _fr->b_coded=-1;
 }
 
 
-static void oc_fr_skip_block(oc_fr_state *_fr){
-  if(_fr->sb_coded){
-    if(!_fr->sb_partial){
-      /*The super block was previously fully coded.*/
-      if(_fr->b_last==-1){
-        /*First run of the frame...*/
-        _fr->bits++;
-        _fr->b_last=1;
+static void oc_fr_state_advance_sb(oc_fr_state *_fr,
+ int _sb_partial,int _sb_full){
+  ptrdiff_t bits;
+  int       sb_partial_count;
+  int       sb_full_count;
+  bits=_fr->bits;
+  /*Extend the sb_partial run, or start a new one.*/
+  sb_partial_count=_fr->sb_partial;
+  if(_fr->sb_partial==_sb_partial){
+    if(sb_partial_count>=4129){
+      bits++;
+      sb_partial_count=0;
+    }
+    else bits-=oc_sb_run_bits(sb_partial_count);
+  }
+  else sb_partial_count=0;
+  sb_partial_count++;
+  bits+=oc_sb_run_bits(sb_partial_count);
+  if(!_sb_partial){
+    /*Extend the sb_full run, or start a new one.*/
+    sb_full_count=_fr->sb_full_count;
+    if(_fr->sb_full==_sb_full){
+      if(sb_full_count>=4129){
+        bits++;
+        sb_full_count=0;
       }
-      if(_fr->b_last==1){
-        /*The in-progress run is also a coded run.*/
-        _fr->b_count+=_fr->b_pend;
-      }
-      else{
-        /*The in-progress run is an uncoded run; flush.*/
-        _fr->bits+=oc_block_run_bits(_fr->b_count);
-        _fr->b_count=_fr->b_pend;
-        _fr->b_last=1;
-      }
+      else bits-=oc_sb_run_bits(sb_full_count);
     }
-    /*Add a skip block.*/
-    if(_fr->b_last==0)_fr->b_count++;
-    else{
-      if(_fr->b_count)_fr->bits+=oc_block_run_bits(_fr->b_count);
-      _fr->b_count=1;
-      _fr->b_last=0;
-    }
+    else sb_full_count=0;
+    sb_full_count++;
+    bits+=oc_sb_run_bits(sb_full_count);
+    _fr->sb_full=_sb_full;
+    _fr->sb_full_count=sb_full_count;
   }
-  _fr->b_pend++;
-  _fr->sb_partial=1;
+  _fr->bits=bits;
+  _fr->sb_partial=_sb_partial;
+  _fr->sb_partial_count=sb_partial_count;
 }
 
-static void oc_fr_code_block(oc_fr_state *_fr){
-  if(_fr->sb_partial){
-    if(!_fr->sb_coded){
-      /*The super block was previously completely uncoded...*/
-      if(_fr->b_last==-1){
-        /*First run of the frame...*/
-        _fr->bits++;
-        _fr->b_last=0;
-      }
-      if(_fr->b_last==0){
-        /*The in-progress run is also an uncoded run.*/
-        _fr->b_count += _fr->b_pend;
-      }
-      else{
-        /*The in-progress run is a coded run; flush.*/
-        _fr->bits+=oc_block_run_bits(_fr->b_count);
-        _fr->b_count=_fr->b_pend;
-        _fr->b_last=0;
-      }
+/*Flush any outstanding block flags for a SB (e.g., one with fewer than 16
+   blocks).*/
+static void oc_fr_state_flush_sb(oc_fr_state *_fr){
+  ptrdiff_t bits;
+  int       sb_partial;
+  int       sb_full=sb_full;
+  int       b_coded_count;
+  int       b_coded;
+  int       b_count;
+  b_count=_fr->b_count;
+  if(b_count>0){
+    bits=_fr->bits;
+    b_coded=_fr->b_coded;
+    b_coded_count=_fr->b_coded_count;
+    if(b_coded_count>=b_count){
+      /*This SB was fully coded/uncoded; roll back the partial block flags.*/
+      bits-=oc_block_run_bits(b_coded_count);
+      if(b_coded_count>b_count)bits+=oc_block_run_bits(b_coded_count-b_count);
+      sb_partial=0;
+      sb_full=b_coded;
+      b_coded=_fr->b_coded_prev;
+      b_coded_count=_fr->b_coded_count_prev;
     }
-    /*Add a coded block.*/
-    if(_fr->b_last==1)_fr->b_count++;
     else{
-      _fr->bits+=oc_block_run_bits(_fr->b_count);
-      _fr->b_count=1;
-      _fr->b_last=1;
+      /*It was partially coded.*/
+      sb_partial=1;
+      /*sb_full is unused.*/
     }
+    _fr->bits=bits;
+    _fr->b_coded_count=b_coded_count;
+    _fr->b_coded_count_prev=b_coded_count;
+    _fr->b_count=0;
+    _fr->b_coded=b_coded;
+    _fr->b_coded_prev=b_coded;
+    oc_fr_state_advance_sb(_fr,sb_partial,sb_full);
   }
-  _fr->b_pend++;
-  _fr->sb_coded=1;
 }
 
-static void oc_fr_finish_sb(oc_fr_state *_fr){
-  /*Update the partial flag.*/
-  int partial;
-  partial=_fr->sb_partial&_fr->sb_coded;
-  if(_fr->sb_partial_last==-1){
-    _fr->bits++;
-    _fr->sb_partial_last=partial;
-  }
-  if(_fr->sb_partial_break){
-    _fr->bits++;
-    _fr->sb_partial_break=0;
-  }
-  if(_fr->sb_partial_last==partial&&_fr->sb_partial_count<4129){
-    _fr->sb_partial_count++;
-  }
-  else{
-    _fr->bits+=oc_sb_run_bits(_fr->sb_partial_count);
-    if(_fr->sb_partial_count>=4129)_fr->sb_partial_break=1;
-    _fr->sb_partial_count=1;
-  }
-  _fr->sb_partial_last=partial;
-  /*Fully coded/uncoded state.*/
-  if(!_fr->sb_partial||!_fr->sb_coded){
-    if(_fr->sb_full_last==-1){
-      _fr->bits++;
-      _fr->sb_full_last=_fr->sb_coded;
+static void oc_fr_state_advance_block(oc_fr_state *_fr,int _b_coded){
+  ptrdiff_t bits;
+  int       b_coded_count;
+  int       b_count;
+  int       sb_partial;
+  int       sb_full=sb_full;
+  bits=_fr->bits;
+  /*Extend the b_coded run, or start a new one.*/
+  b_coded_count=_fr->b_coded_count;
+  if(_fr->b_coded==_b_coded)bits-=oc_block_run_bits(b_coded_count);
+  else b_coded_count=0;
+  b_coded_count++;
+  b_count=_fr->b_count+1;
+  if(b_count>=16){
+    /*We finished a superblock.*/
+    if(b_coded_count>=16){
+      /*It was fully coded/uncoded; roll back the partial block flags.*/
+      if(b_coded_count>16)bits+=oc_block_run_bits(b_coded_count-16);
+      sb_partial=0;
+      sb_full=_b_coded;
+      _b_coded=_fr->b_coded_prev;
+      b_coded_count=_fr->b_coded_count_prev;
     }
-    if(_fr->sb_full_break){
-      _fr->bits++;
-      _fr->sb_full_break=0;
-    }
-    if(_fr->sb_full_last==_fr->sb_coded&&_fr->sb_full_count<4129){
-      _fr->sb_full_count++;
-    }
     else{
-      _fr->bits+=oc_sb_run_bits( _fr->sb_full_count);
-      if(_fr->sb_full_count>=4129)_fr->sb_full_break=1;
-      _fr->sb_full_count=1;
+      bits+=oc_block_run_bits(b_coded_count);
+      /*It was partially coded.*/
+      sb_partial=1;
+      /*sb_full is unused.*/
     }
-    _fr->sb_full_last=_fr->sb_coded;
+    _fr->bits=bits;
+    _fr->b_coded_count=b_coded_count;
+    _fr->b_coded_count_prev=b_coded_count;
+    _fr->b_count=0;
+    _fr->b_coded=_b_coded;
+    _fr->b_coded_prev=_b_coded;
+    oc_fr_state_advance_sb(_fr,sb_partial,sb_full);
   }
-  _fr->b_pend=0;
-  _fr->sb_partial=0;
-  _fr->sb_coded=0;
+  else{
+    bits+=oc_block_run_bits(b_coded_count);
+    _fr->bits=bits;
+    _fr->b_coded_count=b_coded_count;
+    _fr->b_count=b_count;
+    _fr->b_coded=_b_coded;
+  }
 }
 
-static void oc_fr_flush(oc_fr_state *_fr){
-  /*Flush any pending partial run.*/
-  if(_fr->sb_partial_break)_fr->bits++;
-  if(_fr->sb_partial_count)_fr->bits+=oc_sb_run_bits(_fr->sb_partial_count);
-  /*Flush any pending full run.*/
-  if(_fr->sb_full_break)_fr->bits++;
-  if(_fr->sb_full_count)_fr->bits+=oc_sb_run_bits(_fr->sb_full_count);
-  /*Flush any pending block run.*/
-  if(_fr->b_count)_fr->bits+=oc_block_run_bits(_fr->b_count);
+static void oc_fr_skip_block(oc_fr_state *_fr){
+  oc_fr_state_advance_block(_fr,0);
 }
 
+static void oc_fr_code_block(oc_fr_state *_fr){
+  oc_fr_state_advance_block(_fr,1);
+}
+
 static int oc_fr_cost1(const oc_fr_state *_fr){
   oc_fr_state tmp;
-  int         bits;
+  ptrdiff_t   bits;
   *&tmp=*_fr;
   oc_fr_skip_block(&tmp);
   bits=tmp.bits;
   *&tmp=*_fr;
   oc_fr_code_block(&tmp);
-  return tmp.bits-bits;
+  return (int)(tmp.bits-bits);
 }
 
 static int oc_fr_cost4(const oc_fr_state *_pre,const oc_fr_state *_post){
@@ -383,34 +390,104 @@
   oc_fr_skip_block(&tmp);
   oc_fr_skip_block(&tmp);
   oc_fr_skip_block(&tmp);
-  return _post->bits-tmp.bits;
+  return (int)(_post->bits-tmp.bits);
 }
 
 
 
+struct oc_qii_state{
+  ptrdiff_t  bits;
+  unsigned   qi01_count:14;
+  signed int qi01:2;
+  unsigned   qi12_count:14;
+  signed int qi12:2;
+};
+
+
+
+static void oc_qii_state_init(oc_qii_state *_qs){
+  _qs->bits=0;
+  _qs->qi01_count=0;
+  _qs->qi01=-1;
+  _qs->qi12_count=0;
+  _qs->qi12=-1;
+}
+
+
+static void oc_qii_state_advance(oc_qii_state *_qd,
+ const oc_qii_state *_qs,int _qii){
+  ptrdiff_t bits;
+  int       qi01;
+  int       qi01_count;
+  int       qi12;
+  int       qi12_count;
+  bits=_qs->bits;
+  qi01=_qii+1>>1;
+  qi01_count=_qs->qi01_count;
+  if(qi01==_qs->qi01){
+    if(qi01_count>=4129){
+      bits++;
+      qi01_count=0;
+    }
+    else bits-=oc_sb_run_bits(qi01_count);
+  }
+  else qi01_count=0;
+  qi01_count++;
+  bits+=oc_sb_run_bits(qi01_count);
+  qi12_count=_qs->qi12_count;
+  if(_qii){
+    qi12=_qii>>1;
+    if(qi12==_qs->qi12){
+      if(qi12_count>=4129){
+        bits++;
+        qi12_count=0;
+      }
+      else bits-=oc_sb_run_bits(qi12_count);
+    }
+    else qi12_count=0;
+    qi12_count++;
+    bits+=oc_sb_run_bits(qi12_count);
+  }
+  else qi12=_qs->qi12;
+  _qd->bits=bits;
+  _qd->qi01=qi01;
+  _qd->qi01_count=qi01_count;
+  _qd->qi12=qi12;
+  _qd->qi12_count=qi12_count;
+}
+
+
+
 /*Temporary encoder state for the analysis pipeline.*/
 struct oc_enc_pipeline_state{
   int                 bounding_values[256];
   oc_fr_state         fr[3];
+  oc_qii_state        qs[3];
   /*Condensed dequantization tables.*/
   const ogg_uint16_t *dequant[3][3][2];
   /*Condensed quantization tables.*/
   const oc_iquant    *enquant[3][3][2];
+  /*Skip SSD storage for the current MCU in each plane.*/
+  unsigned           *skip_ssd[3];
   /*Coded/uncoded fragment lists for each plane for the current MCU.*/
   ptrdiff_t          *coded_fragis[3];
   ptrdiff_t          *uncoded_fragis[3];
   ptrdiff_t           ncoded_fragis[3];
   ptrdiff_t           nuncoded_fragis[3];
+  /*The starting fragment for the current MCU in each plane.*/
+  ptrdiff_t           froffset[3];
   /*The starting row for the current MCU in each plane.*/
   int                 fragy0[3];
   /*The ending row for the current MCU in each plane.*/
   int                 fragy_end[3];
+  /*The starting superblock for the current MCU in each plane.*/
+  unsigned            sbi0[3];
+  /*The ending superblock for the current MCU in each plane.*/
+  unsigned            sbi_end[3];
   /*The number of tokens for zzi=1 for each color plane.*/
   int                 ndct_tokens1[3];
   /*The outstanding eob_run count for zzi=1 for each color plane.*/
   int                 eob_run1[3];
-  /*The number of vertical super blocks in an MCU.*/
-  int                 mcu_nvsbs;
   /*Whether or not the loop filter is enabled.*/
   int                 loop_filter;
 };
@@ -418,6 +495,10 @@
 
 static void oc_enc_pipeline_init(oc_enc_ctx *_enc,oc_enc_pipeline_state *_pipe){
   ptrdiff_t *coded_fragis;
+  unsigned   mcu_nvsbs;
+  ptrdiff_t  mcu_nfrags;
+  int        hdec;
+  int        vdec;
   int        pli;
   int        qii;
   int        qti;
@@ -425,6 +506,15 @@
     These are used for bit-estimation purposes only; the real flag bits span
      all three planes, so we can't compute them in parallel.*/
   for(pli=0;pli<3;pli++)oc_fr_state_init(_pipe->fr+pli);
+  for(pli=0;pli<3;pli++)oc_qii_state_init(_pipe->qs+pli);
+  /*Set up the per-plane skip SSD storage pointers.*/
+  mcu_nvsbs=_enc->mcu_nvsbs;
+  mcu_nfrags=mcu_nvsbs*_enc->state.fplanes[0].nhsbs*16;
+  hdec=!(_enc->state.info.pixel_fmt&1);
+  vdec=!(_enc->state.info.pixel_fmt&2);
+  _pipe->skip_ssd[0]=_enc->mcu_skip_ssd;
+  _pipe->skip_ssd[1]=_pipe->skip_ssd[0]+mcu_nfrags;
+  _pipe->skip_ssd[2]=_pipe->skip_ssd[1]+(mcu_nfrags>>hdec+vdec);
   /*Set up per-plane pointers to the coded and uncoded fragments lists.
     Unlike the decoder, each planes' coded and uncoded fragment list is kept
      separate during the analysis stage; we only make the coded list for all
@@ -454,14 +544,45 @@
     _pipe->ndct_tokens1[pli]=0;
     _pipe->eob_run1[pli]=0;
   }
-  /*If chroma is sub-sampled in the vertical direction, we have to encode two
-     super block rows of Y' for each super block row of Cb and Cr.*/
-  _pipe->mcu_nvsbs=1<<!(_enc->state.info.pixel_fmt&2);
   /*Initialize the bounding value array for the loop filter.*/
   _pipe->loop_filter=!oc_state_loop_filter_init(&_enc->state,
    _pipe->bounding_values);
 }
 
+/*Sets the current MCU stripe to super block row _sby.
+  Return: A non-zero value if this was the last MCU.*/
+static int oc_enc_pipeline_set_stripe(oc_enc_ctx *_enc,
+ oc_enc_pipeline_state *_pipe,int _sby){
+  const oc_fragment_plane *fplane;
+  unsigned                 mcu_nvsbs;
+  int                      sby_end;
+  int                      notdone;
+  int                      vdec;
+  int                      pli;
+  mcu_nvsbs=_enc->mcu_nvsbs;
+  sby_end=_enc->state.fplanes[0].nvsbs;
+  notdone=_sby+mcu_nvsbs<sby_end;
+  if(notdone)sby_end=_sby+mcu_nvsbs;
+  vdec=0;
+  for(pli=0;pli<3;pli++){
+    fplane=_enc->state.fplanes+pli;
+    _pipe->sbi0[pli]=fplane->sboffset+(_sby>>vdec)*fplane->nhsbs;
+    _pipe->fragy0[pli]=_sby<<2-vdec;
+    _pipe->froffset[pli]=fplane->froffset
+     +_pipe->fragy0[pli]*(ptrdiff_t)fplane->nhfrags;
+    if(notdone){
+      _pipe->sbi_end[pli]=fplane->sboffset+(sby_end>>vdec)*fplane->nhsbs;
+      _pipe->fragy_end[pli]=sby_end<<2-vdec;
+    }
+    else{
+      _pipe->sbi_end[pli]=fplane->sboffset+fplane->nsbs;
+      _pipe->fragy_end[pli]=fplane->nvfrags;
+    }
+    vdec=!(_enc->state.info.pixel_fmt&2);
+  }
+  return notdone;
+}
+
 static void oc_enc_pipeline_finish_mcu_plane(oc_enc_ctx *_enc,
  oc_enc_pipeline_state *_pipe,int _pli,int _sdelay,int _edelay){
   int refi;
@@ -515,47 +636,58 @@
 static int oc_enc_block_transform_quantize(oc_enc_ctx *_enc,
  oc_enc_pipeline_state *_pipe,int _pli,ptrdiff_t _fragi,int _overhead_bits,
  oc_rd_metric *_mo,oc_token_checkpoint **_stack){
-  OC_ALIGN16(ogg_int16_t buffer[64]);
-  OC_ALIGN16(ogg_int16_t data[64]);
-  const ogg_uint16_t  *dequant;
-  const oc_iquant     *enquant;
-  ptrdiff_t            frag_offs;
-  int                  ystride;
-  const unsigned char *src;
-  const unsigned char *ref;
-  unsigned char       *dst;
-  int                  frame_type;
-  int                  nonzero;
-  int                  uncoded_ssd;
-  int                  coded_ssd;
-  int                  uncoded_dc;
-  int                  coded_dc;
-  int                  dc_flag;
-  oc_token_checkpoint *checkpoint;
-  oc_fragment         *frags;
-  int                  mb_mode;
-  int                  mv_offs[2];
-  int                  nmv_offs;
-  int                  ac_bits;
-  int                  borderi;
-  int                  pi;
-  int                  zzi;
+  OC_ALIGN16(ogg_int16_t  buffer[64]);
+  OC_ALIGN16(ogg_int16_t  data[64]);
+  ogg_uint16_t            dc_dequant;
+  const ogg_uint16_t     *dequant;
+  const oc_iquant        *enquant;
+  ptrdiff_t               frag_offs;
+  int                     ystride;
+  const unsigned char    *src;
+  const unsigned char    *ref;
+  unsigned char          *dst;
+  int                     frame_type;
+  int                     nonzero;
+  unsigned                uncoded_ssd;
+  unsigned                coded_ssd;
+  int                     coded_dc;
+  oc_token_checkpoint    *checkpoint;
+  oc_fragment            *frags;
+  int                     mb_mode;
+  int                     mv_offs[2];
+  int                     nmv_offs;
+  int                     ac_bits;
+  int                     borderi;
+  int                     qti;
+  int                     qii;
+  int                     pi;
+  int                     zzi;
+  int                     v;
+  int                     val;
+  int                     d;
+  int                     s;
   frags=_enc->state.frags;
   frag_offs=_enc->state.frag_buf_offs[_fragi];
   ystride=_enc->state.ref_ystride[_pli];
+  src=_enc->state.ref_frame_data[OC_FRAME_IO]+frag_offs;
+  borderi=frags[_fragi].borderi;
+  qii=frags[_fragi].qii;
+  if(qii&~3){
+#if 1
+    /*Enable early skip detection.*/
+    frags[_fragi].coded=0;
+    return 0;
+#else
+    /*Try and code the fragment anyway.*/
+    qii&=3;
+    frags[_fragi].qii=qii;
+#endif
+  }
   mb_mode=frags[_fragi].mb_mode;
-  src=_enc->state.ref_frame_data[OC_FRAME_IO]+frag_offs;
   ref=_enc->state.ref_frame_data[
    _enc->state.ref_frame_idx[OC_FRAME_FOR_MODE[mb_mode]]]+frag_offs;
   dst=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_SELF]]
    +frag_offs;
-  /*Although the fragment coding overhead determination is accurate, it is
-     greedy, using very coarse-grained local information.
-    Allowing it to mildly discourage coding turns out to be beneficial, but
-     it's not clear that allowing it to encourage coding through negative
-     coding overhead deltas is useful.
-    For that reason, we disallow negative coding_overheads.*/
-  if(_overhead_bits<0)_overhead_bits=0;
   /*Motion compensation:*/
   switch(mb_mode){
     case OC_MODE_INTRA:{
@@ -596,65 +728,28 @@
     _enc->frag_satd[_fragi]=satd;
   }
 #endif
-  frame_type=_enc->state.frame_type;
-  borderi=frags[_fragi].borderi;
-  uncoded_ssd=uncoded_dc=0;
-  if(frame_type!=OC_INTRA_FRAME){
-    if(mb_mode==OC_MODE_INTER_NOMV){
-      if(borderi<0){
-        for(pi=0;pi<64;pi++){
-          uncoded_ssd+=data[pi]*data[pi];
-          uncoded_dc+=data[pi];
-        }
-      }
-      else{
-        ogg_int64_t mask;
-        mask=_enc->state.borders[borderi].mask;
-        for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
-          uncoded_ssd+=data[pi]*data[pi];
-          uncoded_dc+=data[pi];
-        }
-      }
-    }
-    else{
-      oc_enc_frag_sub(_enc,buffer,src,
-       _enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_PREV]]
-       +frag_offs,ystride);
-      if(borderi<0){
-        for(pi=0;pi<64;pi++){
-          uncoded_ssd+=buffer[pi]*buffer[pi];
-          uncoded_dc+=buffer[pi];
-        }
-      }
-      else{
-        ogg_int64_t mask;
-        mask=_enc->state.borders[borderi].mask;
-        for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
-          uncoded_ssd+=buffer[pi]*buffer[pi];
-          uncoded_dc+=buffer[pi];
-        }
-      }
-    }
-    /*Scale to match DCT domain.*/
-    uncoded_ssd<<=4;
-  }
   /*Transform:*/
   oc_enc_fdct8x8(_enc,buffer,data);
-  /*Quantize:*/
-  /*TODO: Block-level quantizers.*/
-  dequant=_pipe->dequant[_pli][0][mb_mode!=OC_MODE_INTRA];
-  enquant=_pipe->enquant[_pli][0][mb_mode!=OC_MODE_INTRA];
+  /*Quantize the DC coefficient:*/
+  qti=mb_mode!=OC_MODE_INTRA;
+  enquant=_pipe->enquant[_pli][0][qti];
+  dc_dequant=_pipe->dequant[_pli][0][qti][0];
+  v=buffer[0];
+  val=v<<1;
+  s=OC_SIGNMASK(val);
+  val+=dc_dequant+s^s;
+  val=((enquant[0].m*(ogg_int32_t)val>>16)+val>>enquant[0].l)-s;
+  data[0]=OC_CLAMPI(-580,val,580);
   nonzero=0;
-  for(zzi=0;zzi<64;zzi++){
-    int v;
-    int val;
-    int d;
+  /*Quantize the AC coefficients:*/
+  dequant=_pipe->dequant[_pli][qii][qti];
+  enquant=_pipe->enquant[_pli][qii][qti];
+  for(zzi=1;zzi<64;zzi++){
     v=buffer[OC_FZIG_ZAG[zzi]];
     d=dequant[zzi];
     val=v<<1;
     v=abs(val);
     if(v>=d){
-      int s;
       s=OC_SIGNMASK(val);
       /*The bias added here rounds ties away from zero, since token
          optimization can only decrease the magnitude of the quantized
@@ -671,16 +766,17 @@
   /*Tokenize.*/
   checkpoint=*_stack;
   ac_bits=oc_enc_tokenize_ac(_enc,_pli,_fragi,data,dequant,buffer,nonzero+1,
-   _stack,mb_mode==OC_MODE_INTRA?3:0);
+   _stack,qti?0:3);
   /*Reconstruct.
     TODO: nonzero may need to be adjusted after tokenization.*/
   oc_dequant_idct8x8(&_enc->state,buffer,data,
-   nonzero+1,nonzero+1,dequant[0],(ogg_uint16_t *)dequant);
-  if(mb_mode==OC_MODE_INTRA)oc_enc_frag_recon_intra(_enc,dst,ystride,buffer);
+   nonzero+1,nonzero+1,dc_dequant,(ogg_uint16_t *)dequant);
+  if(!qti)oc_enc_frag_recon_intra(_enc,dst,ystride,buffer);
   else{
     oc_enc_frag_recon_inter(_enc,dst,
      nmv_offs==1?ref+mv_offs[0]:dst,ystride,buffer);
   }
+  frame_type=_enc->state.frame_type;
 #if !defined(OC_COLLECT_METRICS)
   if(frame_type!=OC_INTRA_FRAME)
 #endif
@@ -704,46 +800,46 @@
     }
     /*Scale to match DCT domain.*/
     coded_ssd<<=4;
-    /*We actually only want the AC contribution to the SSDs.*/
-    uncoded_ssd-=uncoded_dc*uncoded_dc>>2;
+    /*We actually only want the AC contribution to the SSD.*/
     coded_ssd-=coded_dc*coded_dc>>2;
 #if defined(OC_COLLECT_METRICS)
     _enc->frag_ssd[_fragi]=coded_ssd;
   }
   if(frame_type!=OC_INTRA_FRAME){
 #endif
+    uncoded_ssd=_pipe->skip_ssd[_pli][_fragi-_pipe->froffset[_pli]];
+    if(uncoded_ssd<UINT_MAX){
+      /*Although the fragment coding overhead determination is accurate, it is
+         greedy, using very coarse-grained local information.
+        Allowing it to mildly discourage coding turns out to be beneficial, but
+         it's not clear that allowing it to encourage coding through negative
+         coding overhead deltas is useful.
+        For that reason, we disallow negative coding_overheads.*/
+      if(_overhead_bits<0)_overhead_bits=0;
+      if(uncoded_ssd<=coded_ssd+(_overhead_bits+ac_bits)*_enc->lambda&&
+       /*Don't allow luma blocks to be skipped in 4MV mode when VP3
+          compatibility is enabled.*/
+       (!_enc->vp3_compatible||mb_mode!=OC_MODE_INTER_MV_FOUR||_pli)){
+        /*Hm, not worth it; roll back.*/
+        oc_enc_tokenlog_rollback(_enc,checkpoint,(*_stack)-checkpoint);
+        *_stack=checkpoint;
+        frags[_fragi].coded=0;
+        return 0;
+      }
+    }
+    else _mo->dc_flag=1;
     _mo->uncoded_ac_ssd+=uncoded_ssd;
-    /*DC is a special case; if there's more than a full-quantizer improvement
-       in the effective DC component, always force-code the block.
-      One might expect this to be abs(uncoded_dc-coded_dc), but this performs
-       slightly better, since coded_dc will always be near zero, but may be on
-       the opposite side of zero from uncoded_dc.*/
-    dc_flag=abs(uncoded_dc)-abs(coded_dc)>dequant[0]<<1;
-    if(!dc_flag&&uncoded_ssd<=coded_ssd+(_overhead_bits+ac_bits)*_enc->lambda&&
-     /*Don't allow luma blocks to be skipped in 4MV mode when VP3 compatibility
-        is enabled.*/
-     (!_enc->vp3_compatible||mb_mode!=OC_MODE_INTER_MV_FOUR)){
-      /*Hm, not worth it; roll back.*/
-      oc_enc_tokenlog_rollback(_enc,checkpoint,(*_stack)-checkpoint);
-      *_stack=checkpoint;
-      _mo->coded_ac_ssd+=uncoded_ssd;
-      frags[_fragi].coded=0;
-      return 0;
-    }
-    else{
-      _mo->dc_flag|=dc_flag;
-      _mo->coded_ac_ssd+=coded_ssd;
-      _mo->ac_bits+=ac_bits;
-    }
+    _mo->coded_ac_ssd+=coded_ssd;
+    _mo->ac_bits+=ac_bits;
   }
+  oc_qii_state_advance(_pipe->qs+_pli,_pipe->qs+_pli,qii);
   frags[_fragi].dc=data[0];
   frags[_fragi].coded=1;
   return 1;
 }
 
-/* mode_overhead is scaled by << OC_BIT_SCALE */
 static int oc_enc_mb_transform_quantize_luma(oc_enc_ctx *_enc,
- oc_enc_pipeline_state *_pipe,int _mbi,int _mode_overhead){
+ oc_enc_pipeline_state *_pipe,unsigned _mbi,int _mode_overhead){
   /*Worst case token stack usage for 4 fragments.*/
   oc_token_checkpoint  stack[64*4];
   oc_token_checkpoint *stackptr;
@@ -756,11 +852,13 @@
   ptrdiff_t            nuncoded_fragis;
   oc_rd_metric         mo;
   oc_fr_state          fr_checkpoint;
+  oc_qii_state         qs_checkpoint;
   int                  mb_mode;
   int                  ncoded;
   ptrdiff_t            fragi;
   int                  bi;
   *&fr_checkpoint=*(_pipe->fr+0);
+  *&qs_checkpoint=*(_pipe->qs+0);
   sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
   mb_modes=_enc->state.mb_modes;
   frags=_enc->state.frags;
@@ -792,12 +890,13 @@
       /*Some individual blocks were worth coding.
         See if that's still true when accounting for mode and MV overhead.*/
       cost=mo.coded_ac_ssd+_enc->lambda*(mo.ac_bits
-       +oc_fr_cost4(&fr_checkpoint,_pipe->fr+0)+(_mode_overhead>>OC_BIT_SCALE));
+       +oc_fr_cost4(&fr_checkpoint,_pipe->fr+0)+_mode_overhead);
       if(mo.uncoded_ac_ssd<=cost){
         /*Taking macroblock overhead into account, it is not worth coding this
            MB.*/
         oc_enc_tokenlog_rollback(_enc,stack,stackptr-stack);
         *(_pipe->fr+0)=*&fr_checkpoint;
+        *(_pipe->qs+0)=*&qs_checkpoint;
         for(bi=0;bi<4;bi++){
           fragi=sb_maps[_mbi>>2][_mbi&3][bi];
           if(frags[fragi].coded){
@@ -864,9 +963,9 @@
         }
       }
     }
-    oc_fr_finish_sb(_pipe->fr+_pli);
-    sb_flags[sbi].coded_fully=_pipe->fr[_pli].sb_full_last;
-    sb_flags[sbi].coded_partially=_pipe->fr[_pli].sb_partial_last;
+    oc_fr_state_flush_sb(_pipe->fr+_pli);
+    sb_flags[sbi].coded_fully=_pipe->fr[_pli].sb_full;
+    sb_flags[sbi].coded_partially=_pipe->fr[_pli].sb_partial;
   }
   _pipe->ncoded_fragis[_pli]=ncoded_fragis;
   _pipe->nuncoded_fragis[_pli]=nuncoded_fragis;
@@ -909,17 +1008,16 @@
     year=2003
   }*/
 
-/*Cost information about a MB mode.*/
-struct oc_mode_choice{
-  unsigned cost;
-  unsigned ssd;
-  unsigned rate;
-  unsigned overhead;
-};
+/*Computes (_ssd+_lambda*_rate)/(1<<OC_BIT_SCALE) with rounding, avoiding
+   overflow for large lambda values.*/
+#define OC_MODE_RD_COST(_ssd,_rate,_lambda) \
+ ((_ssd)>>OC_BIT_SCALE)+((_rate)>>OC_BIT_SCALE)*(_lambda) \
+ +(((_ssd)&(1<<OC_BIT_SCALE)-1)+((_rate)&(1<<OC_BIT_SCALE)-1)*(_lambda) \
+ +((1<<OC_BIT_SCALE)>>1)>>OC_BIT_SCALE)
 
-
-
-static void oc_mode_dct_cost_accum(oc_mode_choice *_modec,
+/*Estimate the R-D cost of the DCT coefficients given the SATD of a block after
+   prediction.*/
+static unsigned oc_dct_cost2(unsigned *_ssd,
  int _qi,int _pli,int _qti,int _satd){
   unsigned rmse;
   int      bin;
@@ -937,20 +1035,558 @@
   z0=OC_MODE_RD[_qi][_pli][_qti][bin].rmse;
   dy=OC_MODE_RD[_qi][_pli][_qti][bin+1].rate-y0;
   dz=OC_MODE_RD[_qi][_pli][_qti][bin+1].rmse-z0;
-  _modec->rate+=OC_MAXI(y0+(dy*dx>>OC_SAD_SHIFT),0);
   rmse=OC_MAXI(z0+(dz*dx>>OC_SAD_SHIFT),0);
-  _modec->ssd+=rmse*rmse>>2*OC_RMSE_SCALE-OC_BIT_SCALE;
+  *_ssd=rmse*rmse>>2*OC_RMSE_SCALE-OC_BIT_SCALE;
+  return OC_MAXI(y0+(dy*dx>>OC_SAD_SHIFT),0);
 }
 
+/*Select luma block-level quantizers for a MB in an INTRA frame.*/
+static unsigned oc_analyze_intra_mb_luma(oc_enc_ctx *_enc,
+ const oc_qii_state *_qs,unsigned _mbi){
+  const unsigned char *src;
+  const ptrdiff_t     *frag_buf_offs;
+  const oc_sb_map     *sb_maps;
+  oc_fragment         *frags;
+  ptrdiff_t            frag_offs;
+  ptrdiff_t            fragi;
+  oc_qii_state         qs[4][3];
+  unsigned             cost[4][3];
+  unsigned             ssd[4][3];
+  unsigned             rate[4][3];
+  int                  prev[3][3];
+  unsigned             satd;
+  unsigned             best_cost;
+  unsigned             best_ssd;
+  unsigned             best_rate;
+  int                  best_qii;
+  int                  qii;
+  int                  lambda;
+  int                  ystride;
+  int                  nqis;
+  int                  bi;
+  frag_buf_offs=_enc->state.frag_buf_offs;
+  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
+  src=_enc->state.ref_frame_data[OC_FRAME_IO];
+  ystride=_enc->state.ref_ystride[0];
+  fragi=sb_maps[_mbi>>2][_mbi&3][0];
+  frag_offs=frag_buf_offs[fragi];
+  satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
+  nqis=_enc->state.nqis;
+  lambda=_enc->lambda;
+  for(qii=0;qii<nqis;qii++){
+    oc_qii_state_advance(qs[0]+qii,_qs,qii);
+    rate[0][qii]=oc_dct_cost2(ssd[0]+qii,_enc->state.qis[qii],0,0,satd)
+     +(qs[0][qii].bits-_qs->bits<<OC_BIT_SCALE);
+    cost[0][qii]=OC_MODE_RD_COST(ssd[0][qii],rate[0][qii],lambda);
+  }
+  for(bi=1;bi<4;bi++){
+    fragi=sb_maps[_mbi>>2][_mbi&3][bi];
+    frag_offs=frag_buf_offs[fragi];
+    satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
+    for(qii=0;qii<nqis;qii++){
+      oc_qii_state qt[3];
+      unsigned     cur_ssd;
+      unsigned     cur_rate;
+      int          best_qij;
+      int          qij;
+      oc_qii_state_advance(qt+0,qs[bi-1]+0,qii);
+      cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,0,satd);
+      best_ssd=ssd[bi-1][0]+cur_ssd;
+      best_rate=rate[bi-1][0]+cur_rate
+       +(qt[0].bits-qs[bi-1][0].bits<<OC_BIT_SCALE);
+      best_cost=OC_MODE_RD_COST(best_ssd,best_rate,lambda);
+      best_qij=0;
+      for(qij=1;qij<nqis;qij++){
+        unsigned chain_ssd;
+        unsigned chain_rate;
+        unsigned chain_cost;
+        oc_qii_state_advance(qt+qij,qs[bi-1]+qij,qii);
+        chain_ssd=ssd[bi-1][qij]+cur_ssd;
+        chain_rate=rate[bi-1][qij]+cur_rate
+         +(qt[qij].bits-qs[bi-1][qij].bits<<OC_BIT_SCALE);
+        chain_cost=OC_MODE_RD_COST(chain_ssd,chain_rate,lambda);
+        if(chain_cost<best_cost){
+          best_cost=chain_cost;
+          best_ssd=chain_ssd;
+          best_rate=chain_rate;
+          best_qij=qij;
+        }
+      }
+      *(qs[bi]+qii)=*(qt+best_qij);
+      cost[bi][qii]=best_cost;
+      ssd[bi][qii]=best_ssd;
+      rate[bi][qii]=best_rate;
+      prev[bi-1][qii]=best_qij;
+    }
+  }
+  best_qii=0;
+  best_cost=cost[3][0];
+  for(qii=1;qii<nqis;qii++){
+    if(cost[3][qii]<best_cost){
+      best_cost=cost[3][qii];
+      best_qii=qii;
+    }
+  }
+  frags=_enc->state.frags;
+  for(bi=3;;){
+    fragi=sb_maps[_mbi>>2][_mbi&3][bi];
+    frags[fragi].qii=best_qii;
+    if(bi--<=0)break;
+    best_qii=prev[bi][best_qii];
+  }
+  return best_cost;
+}
+
+/*Select a block-level quantizer for a single chroma block in an INTRA frame.*/
+static unsigned oc_analyze_intra_chroma_block(oc_enc_ctx *_enc,
+ const oc_qii_state *_qs,int _pli,ptrdiff_t _fragi){
+  const unsigned char *src;
+  oc_fragment         *frags;
+  ptrdiff_t            frag_offs;
+  oc_qii_state         qt[3];
+  unsigned             cost[3];
+  unsigned             satd;
+  unsigned             best_cost;
+  int                  best_qii;
+  int                  qii;
+  int                  lambda;
+  int                  ystride;
+  int                  nqis;
+  src=_enc->state.ref_frame_data[OC_FRAME_IO];
+  ystride=_enc->state.ref_ystride[_pli];
+  frag_offs=_enc->state.frag_buf_offs[_fragi];
+  satd=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
+  nqis=_enc->state.nqis;
+  lambda=_enc->lambda;
+  best_qii=0;
+  for(qii=0;qii<nqis;qii++){
+    unsigned cur_rate;
+    unsigned cur_ssd;
+    oc_qii_state_advance(qt+qii,_qs,qii);
+    cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],_pli,0,satd)
+     +(qt[qii].bits-_qs->bits<<OC_BIT_SCALE);
+    cost[qii]=OC_MODE_RD_COST(cur_ssd,cur_rate,lambda);
+  }
+  best_cost=cost[0];
+  for(qii=1;qii<nqis;qii++){
+    if(cost[qii]<best_cost){
+      best_cost=cost[qii];
+      best_qii=qii;
+    }
+  }
+  frags=_enc->state.frags;
+  frags[_fragi].qii=best_qii;
+  return best_cost;
+}
+
+static void oc_enc_sb_transform_quantize_intra_chroma(oc_enc_ctx *_enc,
+ oc_enc_pipeline_state *_pipe,int _pli,int _sbi_start,int _sbi_end){
+  const oc_sb_map *sb_maps;
+  oc_sb_flags     *sb_flags;
+  ptrdiff_t       *coded_fragis;
+  ptrdiff_t        ncoded_fragis;
+  int              sbi;
+  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
+  sb_flags=_enc->state.sb_flags;
+  coded_fragis=_pipe->coded_fragis[_pli];
+  ncoded_fragis=_pipe->ncoded_fragis[_pli];
+  for(sbi=_sbi_start;sbi<_sbi_end;sbi++){
+    /*Worst case token stack usage for 1 fragment.*/
+    oc_token_checkpoint stack[64];
+    int                 quadi;
+    int                 bi;
+    for(quadi=0;quadi<4;quadi++)for(bi=0;bi<4;bi++){
+      ptrdiff_t fragi;
+      fragi=sb_maps[sbi][quadi][bi];
+      if(fragi>=0){
+        oc_token_checkpoint *stackptr;
+        oc_analyze_intra_chroma_block(_enc,_pipe->qs+_pli,_pli,fragi);
+        stackptr=stack;
+        oc_enc_block_transform_quantize(_enc,
+         _pipe,_pli,fragi,0,NULL,&stackptr);
+        coded_fragis[ncoded_fragis++]=fragi;
+      }
+    }
+  }
+  _pipe->ncoded_fragis[_pli]=ncoded_fragis;
+}
+
+/*Analysis stage for an INTRA frame.*/
+int oc_enc_analyze_intra(oc_enc_ctx *_enc,int _recode){
+  oc_enc_pipeline_state   pipe;
+  const unsigned char    *map_idxs;
+  int                     nmap_idxs;
+  oc_sb_flags            *sb_flags;
+  signed char            *mb_modes;
+  const oc_mb_map        *mb_maps;
+  oc_mb_enc_info         *embs;
+  oc_fragment            *frags;
+  unsigned                stripe_sby;
+  unsigned                mcu_nvsbs;
+  int                     notstart;
+  int                     notdone;
+  int                     refi;
+  int                     pli;
+  _enc->state.frame_type=OC_INTRA_FRAME;
+  oc_enc_tokenize_start(_enc);
+  oc_enc_pipeline_init(_enc,&pipe);
+  /*Choose MVs and MB modes and quantize and code luma.
+    Must be done in Hilbert order.*/
+  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
+  nmap_idxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
+  _enc->state.ncoded_fragis[0]=0;
+  _enc->state.ncoded_fragis[1]=0;
+  _enc->state.ncoded_fragis[2]=0;
+  sb_flags=_enc->state.sb_flags;
+  mb_modes=_enc->state.mb_modes;
+  mb_maps=(const oc_mb_map *)_enc->state.mb_maps;
+  embs=_enc->mb_info;
+  frags=_enc->state.frags;
+  notstart=0;
+  notdone=1;
+  mcu_nvsbs=_enc->mcu_nvsbs;
+  for(stripe_sby=0;notdone;stripe_sby+=mcu_nvsbs){
+    unsigned sbi;
+    unsigned sbi_end;
+    notdone=oc_enc_pipeline_set_stripe(_enc,&pipe,stripe_sby);
+    sbi_end=pipe.sbi_end[0];
+    for(sbi=pipe.sbi0[0];sbi<sbi_end;sbi++){
+      int quadi;
+      /*Mode addressing is through Y plane, always 4 MB per SB.*/
+      for(quadi=0;quadi<4;quadi++)if(sb_flags[sbi].quad_valid&1<<quadi){
+        unsigned  mbi;
+        int       mapii;
+        int       mapi;
+        int       bi;
+        ptrdiff_t fragi;
+        mbi=sbi<<2|quadi;
+        /*Motion estimation:
+          We always do a basic 1MV search for all macroblocks, coded or not,
+           keyframe or not.*/
+        if(!_recode&&_enc->state.curframe_num>0)oc_mcenc_search(_enc,mbi);
+        oc_analyze_intra_mb_luma(_enc,pipe.qs+0,mbi);
+        mb_modes[mbi]=OC_MODE_INTRA;
+        oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,0);
+        /*Propagate final MB mode and MVs to the chroma blocks.*/
+        for(mapii=4;mapii<nmap_idxs;mapii++){
+          mapi=map_idxs[mapii];
+          pli=mapi>>2;
+          bi=mapi&3;
+          fragi=mb_maps[mbi][pli][bi];
+          frags[fragi].mb_mode=OC_MODE_INTRA;
+        }
+      }
+    }
+    oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,0,notstart,notdone);
+    /*Code chroma planes.*/
+    for(pli=1;pli<3;pli++){
+      oc_enc_sb_transform_quantize_intra_chroma(_enc,&pipe,
+       pli,pipe.sbi0[pli],pipe.sbi_end[pli]);
+      oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,pli,notstart,notdone);
+    }
+    notstart=1;
+  }
+  /*Finish filling in the reference frame borders.*/
+  refi=_enc->state.ref_frame_idx[OC_FRAME_SELF];
+  for(pli=0;pli<3;pli++)oc_state_borders_fill_caps(&_enc->state,refi,pli);
+  _enc->state.ntotal_coded_fragis=_enc->state.nfrags;
+  return 0;
+}
+
+
+
+/*Cost information about a MB mode.*/
+struct oc_mode_choice{
+  unsigned      cost;
+  unsigned      ssd;
+  unsigned      rate;
+  unsigned      overhead;
+  unsigned char qii[12];
+};
+
+
+
 static void oc_mode_set_cost(oc_mode_choice *_modec,int _lambda){
-  _modec->cost=(_modec->ssd>>OC_BIT_SCALE)+
-    ((_modec->rate+_modec->overhead)>>OC_BIT_SCALE)*_lambda;
+  _modec->cost=OC_MODE_RD_COST(_modec->ssd,
+   _modec->rate+_modec->overhead,_lambda);
 }
 
-static void oc_cost_intra(oc_enc_ctx *_enc,oc_mode_choice *_modec,
- int _mbi,int _qi){
+/*A set of skip SSD's to use to disable early skipping.*/
+static const unsigned OC_NOSKIP[12]={
+  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX,
+  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX,
+  UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX
+};
+
+/*The estimated number of bits used by a coded chroma block to specify the AC
+   quantizer.
+  TODO: Currently this is just 0.5*log2(3) (estimating about 50% compression);
+   we should measure it.*/
+#define OC_CHROMA_QII_RATE ((0xCAE00D1DU>>31-OC_BIT_SCALE)+1>>1)
+
+static void oc_analyze_mb_mode_luma(oc_enc_ctx *_enc,
+ oc_mode_choice *_modec,const oc_fr_state *_fr,const oc_qii_state *_qs,
+ const unsigned _frag_satd[12],const unsigned _skip_ssd[12],int _qti){
+  oc_fr_state  fr;
+  oc_qii_state qs;
+  unsigned     ssd;
+  unsigned     rate;
+  int          overhead;
+  unsigned     satd;
+  unsigned     best_cost;
+  unsigned     best_ssd;
+  unsigned     best_rate;
+  int          best_overhead;
+  int          best_fri;
+  int          best_qii;
+  unsigned     cur_cost;
+  unsigned     cur_ssd;
+  unsigned     cur_rate;
+  int          cur_overhead;
+  int          lambda;
+  int          nqis;
+  int          nskipped;
+  int          bi;
+  int          qii;
+  lambda=_enc->lambda;
+  nqis=_enc->state.nqis;
+  /*We could do a trellis optimization here, but we don't make final skip
+     decisions until after transform+quantization, so the result wouldn't be
+     optimal anyway.
+    Instead we just use a greedy approach; for most SATD values, the
+     differences between the qiis are large enough to drown out the cost to
+     code the flags, anyway.*/
+  *&fr=*_fr;
+  *&qs=*_qs;
+  ssd=rate=overhead=nskipped=0;
+  for(bi=0;bi<4;bi++){
+    oc_fr_state  ft[2];
+    oc_qii_state qt[3];
+    satd=_frag_satd[bi];
+    *(ft+0)=*&fr;
+    oc_fr_code_block(ft+0);
+    oc_qii_state_advance(qt+0,&qs,0);
+    best_overhead=(ft[0].bits-fr.bits<<OC_BIT_SCALE);
+    best_rate=oc_dct_cost2(&best_ssd,_enc->state.qis[0],0,_qti,satd)
+     +(qt[0].bits-qs.bits<<OC_BIT_SCALE);
+    best_cost=OC_MODE_RD_COST(ssd+best_ssd,rate+best_rate+best_overhead,lambda);
+    best_fri=0;
+    best_qii=0;
+    for(qii=1;qii<nqis;qii++){
+      oc_qii_state_advance(qt+qii,&qs,qii);
+      cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,_qti,satd)
+       +(qt[qii].bits-qs.bits<<OC_BIT_SCALE);
+      cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_rate+best_overhead,lambda);
+      if(cur_cost<best_cost){
+        best_cost=cur_cost;
+        best_ssd=cur_ssd;
+        best_rate=cur_rate;
+        best_qii=qii;
+      }
+    }
+    if(_skip_ssd[bi]<UINT_MAX&&nskipped<3){
+      *(ft+1)=*&fr;
+      oc_fr_skip_block(ft+1);
+      cur_overhead=ft[1].bits-fr.bits<<OC_BIT_SCALE;
+      cur_ssd=_skip_ssd[bi]<<OC_BIT_SCALE;
+      cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_overhead,lambda);
+      if(cur_cost<=best_cost){
+        best_cost=cur_cost;
+        best_ssd=cur_ssd;
+        best_rate=0;
+        best_overhead=cur_overhead;
+        best_fri=1;
+        best_qii+=4;
+      }
+    }
+    rate+=best_rate;
+    ssd+=best_ssd;
+    overhead+=best_overhead;
+    *&fr=*(ft+best_fri);
+    if(best_fri==0)*&qs=*(qt+best_qii);
+    else nskipped++;
+    _modec->qii[bi]=best_qii;
+  }
+  _modec->ssd=ssd;
+  _modec->rate=rate;
+  _modec->overhead=OC_MAXI(overhead,0);
+}
+
+static void oc_analyze_mb_mode_chroma(oc_enc_ctx *_enc,
+ oc_mode_choice *_modec,const oc_fr_state *_fr,const oc_qii_state *_qs,
+ const unsigned _frag_satd[12],const unsigned _skip_ssd[12],int _qti){
+  unsigned ssd;
+  unsigned rate;
+  unsigned satd;
+  unsigned best_cost;
+  unsigned best_ssd;
+  unsigned best_rate;
+  int      best_qii;
+  unsigned cur_cost;
+  unsigned cur_ssd;
+  unsigned cur_rate;
+  int      lambda;
+  int      nblocks;
+  int      nqis;
+  int      pli;
+  int      bi;
+  int      qii;
+  lambda=_enc->lambda;
+  nqis=_enc->state.nqis;
+  ssd=_modec->ssd;
+  rate=_modec->rate;
+  /*Because (except in 4:4:4 mode) we aren't considering chroma blocks in coded
+     order, we assume a constant overhead for coded block and qii flags.*/
+  nblocks=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
+  nblocks=(nblocks-4>>1)+4;
+  bi=4;
+  for(pli=1;pli<3;pli++){
+    for(;bi<nblocks;bi++){
+      satd=_frag_satd[bi];
+      best_rate=oc_dct_cost2(&best_ssd,_enc->state.qis[0],pli,_qti,satd)
+       +OC_CHROMA_QII_RATE;
+      best_cost=OC_MODE_RD_COST(ssd+best_ssd,rate+best_rate,lambda);
+      best_qii=0;
+      for(qii=1;qii<nqis;qii++){
+        cur_rate=oc_dct_cost2(&cur_ssd,_enc->state.qis[qii],0,_qti,satd)
+         +OC_CHROMA_QII_RATE;
+        cur_cost=OC_MODE_RD_COST(ssd+cur_ssd,rate+cur_rate,lambda);
+        if(cur_cost<best_cost){
+          best_cost=cur_cost;
+          best_ssd=cur_ssd;
+          best_rate=cur_rate;
+          best_qii=qii;
+        }
+      }
+      if(_skip_ssd[bi]<UINT_MAX){
+        cur_cost=_skip_ssd[bi];
+        if(cur_cost<=best_cost){
+          best_cost=cur_cost;
+          best_ssd=cur_cost<<OC_BIT_SCALE;
+          best_rate=0;
+          best_qii+=4;
+        }
+      }
+      rate+=best_rate;
+      ssd+=best_ssd;
+      _modec->qii[bi]=best_qii;
+    }
+    nblocks=(nblocks-4<<1)+4;
+  }
+  _modec->ssd=ssd;
+  _modec->rate=rate;
+}
+
+static void oc_skip_cost(oc_enc_ctx *_enc,oc_enc_pipeline_state *_pipe,
+ unsigned _mbi,unsigned _ssd[12]){
+  OC_ALIGN16(ogg_int16_t  buffer[64]);
+  const unsigned char    *src;
+  const unsigned char    *ref;
+  int                     ystride;
+  const oc_fragment      *frags;
+  const ptrdiff_t        *frag_buf_offs;
+  const ptrdiff_t        *sb_map;
+  const oc_mb_map_plane  *mb_map;
+  const unsigned char    *map_idxs;
+  int                     map_nidxs;
+  ogg_int64_t             mask;
+  unsigned                uncoded_ssd;
+  int                     uncoded_dc;
+  unsigned                dc_dequant;
+  int                     dc_flag;
+  int                     mapii;
+  int                     mapi;
+  int                     pli;
+  int                     bi;
+  ptrdiff_t               fragi;
+  ptrdiff_t               frag_offs;
+  int                     borderi;
+  int                     pi;
+  src=_enc->state.ref_frame_data[OC_FRAME_IO];
+  ref=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_PREV]];
+  ystride=_enc->state.ref_ystride[0];
+  frags=_enc->state.frags;
+  frag_buf_offs=_enc->state.frag_buf_offs;
+  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
+  dc_dequant=_enc->state.dequant_tables[_enc->state.qis[0]][0][1][0];
+  for(bi=0;bi<4;bi++){
+    fragi=sb_map[bi];
+    frag_offs=frag_buf_offs[fragi];
+    oc_enc_frag_sub(_enc,buffer,src+frag_offs,ref+frag_offs,ystride);
+    borderi=frags[fragi].borderi;
+    uncoded_ssd=uncoded_dc=0;
+    if(borderi<0){
+      for(pi=0;pi<64;pi++){
+        uncoded_ssd+=buffer[pi]*buffer[pi];
+        uncoded_dc+=buffer[pi];
+      }
+    }
+    else{
+      ogg_int64_t mask;
+      mask=_enc->state.borders[borderi].mask;
+      for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
+        uncoded_ssd+=buffer[pi]*buffer[pi];
+        uncoded_dc+=buffer[pi];
+      }
+    }
+    /*Scale to match DCT domain.*/
+    uncoded_ssd<<=4;
+    /*We actually only want the AC contribution to the SSD.*/
+    uncoded_ssd-=uncoded_dc*uncoded_dc>>2;
+    /*DC is a special case; if there's more than a full-quantizer improvement
+       in the effective DC component, always force-code the block.*/
+    dc_flag=abs(uncoded_dc)>dc_dequant<<1;
+    uncoded_ssd|=-dc_flag;
+    _pipe->skip_ssd[0][fragi-_pipe->froffset[0]]=_ssd[bi]=uncoded_ssd;
+  }
+  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
+  map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
+  map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
+  map_nidxs=(map_nidxs-4>>1)+4;
+  mapii=4;
+  for(pli=1;pli<3;pli++){
+    ystride=_enc->state.ref_ystride[pli];
+    dc_dequant=_enc->state.dequant_tables[_enc->state.qis[0]][pli][1][0];
+    for(;mapii<map_nidxs;mapii++){
+      mapi=map_idxs[mapii];
+      bi=mapi&3;
+      fragi=mb_map[pli][bi];
+      frag_offs=frag_buf_offs[fragi];
+      oc_enc_frag_sub(_enc,buffer,src+frag_offs,ref+frag_offs,ystride);
+      borderi=frags[fragi].borderi;
+      uncoded_ssd=uncoded_dc=0;
+      if(borderi<0){
+        for(pi=0;pi<64;pi++){
+          uncoded_ssd+=buffer[pi]*buffer[pi];
+          uncoded_dc+=buffer[pi];
+        }
+      }
+      else{
+        mask=_enc->state.borders[borderi].mask;
+        for(pi=0;pi<64;pi++,mask>>=1)if(mask&1){
+          uncoded_ssd+=buffer[pi]*buffer[pi];
+          uncoded_dc+=buffer[pi];
+        }
+      }
+      /*Scale to match DCT domain.*/
+      uncoded_ssd<<=4;
+      /*We actually only want the AC contribution to the SSD.*/
+      uncoded_ssd-=uncoded_dc*uncoded_dc>>2;
+      /*DC is a special case; if there's more than a full-quantizer improvement
+         in the effective DC component, always force-code the block.*/
+      dc_flag=abs(uncoded_dc)>dc_dequant<<1;
+      uncoded_ssd|=-dc_flag;
+      _pipe->skip_ssd[pli][fragi-_pipe->froffset[pli]]=_ssd[mapii]=uncoded_ssd;
+    }
+    map_nidxs=(map_nidxs-4<<1)+4;
+  }
+}
+
+static void oc_mb_intra_satd(oc_enc_ctx *_enc,unsigned _mbi,
+ unsigned _frag_satd[12]){
   const unsigned char   *src;
   const ptrdiff_t       *frag_buf_offs;
+  const ptrdiff_t       *sb_map;
   const oc_mb_map_plane *mb_map;
   const unsigned char   *map_idxs;
   int                    map_nidxs;
@@ -962,16 +1598,15 @@
   ptrdiff_t              fragi;
   ptrdiff_t              frag_offs;
   frag_buf_offs=_enc->state.frag_buf_offs;
-  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
+  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
   src=_enc->state.ref_frame_data[OC_FRAME_IO];
-  _modec->rate=_modec->ssd=0;
   ystride=_enc->state.ref_ystride[0];
   for(bi=0;bi<4;bi++){
-    fragi=mb_map[0][bi];
+    fragi=sb_map[bi];
     frag_offs=frag_buf_offs[fragi];
-    oc_mode_dct_cost_accum(_modec,_qi,0,0,
-     oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride));
+    _frag_satd[bi]=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
   }
+  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
   map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
   map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
   /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
@@ -982,20 +1617,29 @@
     bi=mapi&3;
     fragi=mb_map[pli][bi];
     frag_offs=frag_buf_offs[fragi];
-    oc_mode_dct_cost_accum(_modec,_qi,pli,0,
-     oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride));
+    _frag_satd[mapii]=oc_enc_frag_intra_satd(_enc,src+frag_offs,ystride);
   }
-  _modec->overhead=
+}
+
+static void oc_cost_intra(oc_enc_ctx *_enc,oc_mode_choice *_modec,
+ unsigned _mbi,const oc_fr_state *_fr,const oc_qii_state *_qs,
+ const unsigned _frag_satd[12],const unsigned _skip_ssd[12]){
+  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,_frag_satd,_skip_ssd,0);
+  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,_frag_satd,_skip_ssd,0);
+  _modec->overhead+=
    oc_mode_scheme_chooser_cost(&_enc->chooser,OC_MODE_INTRA)<<OC_BIT_SCALE;
   oc_mode_set_cost(_modec,_enc->lambda);
 }
 
 static void oc_cost_inter(oc_enc_ctx *_enc,oc_mode_choice *_modec,
- int _mbi,int _mb_mode,const signed char *_mv,int _qi){
+ unsigned _mbi,int _mb_mode,const signed char *_mv,
+ const oc_fr_state *_fr,const oc_qii_state *_qs,const unsigned _skip_ssd[12]){
+  unsigned               frag_satd[12];
   const unsigned char   *src;
   const unsigned char   *ref;
   int                    ystride;
   const ptrdiff_t       *frag_buf_offs;
+  const ptrdiff_t       *sb_map;
   const oc_mb_map_plane *mb_map;
   const unsigned char   *map_idxs;
   int                    map_nidxs;
@@ -1013,28 +1657,27 @@
    _enc->state.ref_frame_idx[OC_FRAME_FOR_MODE[_mb_mode]]];
   ystride=_enc->state.ref_ystride[0];
   frag_buf_offs=_enc->state.frag_buf_offs;
-  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
+  sb_map=_enc->state.sb_maps[_mbi>>2][_mbi&3];
   dx=_mv[0];
   dy=_mv[1];
   _modec->rate=_modec->ssd=0;
   if(oc_state_get_mv_offsets(&_enc->state,mv_offs,0,dx,dy)>1){
     for(bi=0;bi<4;bi++){
-      fragi=mb_map[0][bi];
+      fragi=sb_map[bi];
       frag_offs=frag_buf_offs[fragi];
-      oc_mode_dct_cost_accum(_modec,_qi,0,1,oc_enc_frag_satd2_thresh(_enc,
-       src+frag_offs,ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,
-       UINT_MAX));
+      frag_satd[bi]=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
+       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
     }
   }
   else{
     for(bi=0;bi<4;bi++){
-      fragi=mb_map[0][bi];
+      fragi=sb_map[bi];
       frag_offs=frag_buf_offs[fragi];
-      oc_mode_dct_cost_accum(_modec,_qi,0,1,
-       oc_enc_frag_satd_thresh(_enc,src+frag_offs,
-       ref+frag_offs+mv_offs[0],ystride,UINT_MAX));
+      frag_satd[bi]=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
+       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
     }
   }
+  mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
   map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
   map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
   /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
@@ -1046,9 +1689,8 @@
       bi=mapi&3;
       fragi=mb_map[pli][bi];
       frag_offs=frag_buf_offs[fragi];
-      oc_mode_dct_cost_accum(_modec,_qi,pli,1,oc_enc_frag_satd2_thresh(_enc,
-       src+frag_offs,ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,
-       UINT_MAX));
+      frag_satd[mapii]=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
+       ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
     }
   }
   else{
@@ -1058,25 +1700,29 @@
       bi=mapi&3;
       fragi=mb_map[pli][bi];
       frag_offs=frag_buf_offs[fragi];
-      oc_mode_dct_cost_accum(_modec,_qi,pli,1,oc_enc_frag_satd_thresh(_enc,
-       src+frag_offs,ref+frag_offs+mv_offs[0],ystride,UINT_MAX));
+      frag_satd[mapii]=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
+       ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
     }
   }
-  _modec->overhead=
+  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
+  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
+  _modec->overhead+=
    oc_mode_scheme_chooser_cost(&_enc->chooser,_mb_mode)<<OC_BIT_SCALE;
   oc_mode_set_cost(_modec,_enc->lambda);
 }
 
 static void oc_cost_inter_nomv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
- int _mbi,int _mb_mode,int _qi){
+ unsigned _mbi,int _mb_mode,const oc_fr_state *_fr,const oc_qii_state *_qs,
+ const unsigned _skip_ssd[12]){
   static const oc_mv OC_MV_ZERO;
-  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,OC_MV_ZERO,_qi);
+  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,OC_MV_ZERO,_fr,_qs,_skip_ssd);
 }
 
 static int oc_cost_inter1mv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
- int _mbi,int _mb_mode,const signed char *_mv,int _qi){
+ unsigned _mbi,int _mb_mode,const signed char *_mv,
+ const oc_fr_state *_fr,const oc_qii_state *_qs,const unsigned _skip_ssd[12]){
   int bits0;
-  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,_mv,_qi);
+  oc_cost_inter(_enc,_modec,_mbi,_mb_mode,_mv,_fr,_qs,_skip_ssd);
   bits0=OC_MV_BITS[0][_mv[0]+31]+OC_MV_BITS[0][_mv[1]+31];
   _modec->overhead+=OC_MINI(_enc->mv_bits[0]+bits0,_enc->mv_bits[1]+12)
    -OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
@@ -1084,8 +1730,15 @@
   return bits0;
 }
 
-static int oc_cost_inter4mv(oc_enc_ctx *_enc,oc_mode_choice *_modec,int _mbi,
- oc_mv _mv[4],int _qi){
+/*A mapping from oc_mb_map (raster) ordering to oc_sb_map (Hilbert) ordering.*/
+static const unsigned char OC_MB_PHASE[4][4]={
+  {0,1,3,2},{0,3,1,2},{0,3,1,2},{2,3,1,0}
+};
+
+static void oc_cost_inter4mv(oc_enc_ctx *_enc,oc_mode_choice *_modec,
+ unsigned _mbi,oc_mv _mv[4],const oc_fr_state *_fr,const oc_qii_state *_qs,
+ const unsigned _skip_ssd[12]){
+  unsigned               frag_satd[12];
   oc_mv                  cbmvs[4];
   const unsigned char   *src;
   const unsigned char   *ref;
@@ -1095,6 +1748,7 @@
   const oc_mb_map_plane *mb_map;
   const unsigned char   *map_idxs;
   int                    map_nidxs;
+  int                    nqis;
   int                    mapii;
   int                    mapi;
   int                    mv_offs[2];
@@ -1105,6 +1759,7 @@
   ptrdiff_t              fragi;
   ptrdiff_t              frag_offs;
   int                    bits0;
+  int                    bits1;
   unsigned               satd;
   src=_enc->state.ref_frame_data[OC_FRAME_IO];
   ref=_enc->state.ref_frame_data[_enc->state.ref_frame_idx[OC_FRAME_PREV]];
@@ -1113,7 +1768,6 @@
   frag_mvs=_enc->state.frag_mvs;
   mb_map=(const oc_mb_map_plane *)_enc->state.mb_maps[_mbi];
   _modec->rate=_modec->ssd=0;
-  bits0=0;
   for(bi=0;bi<4;bi++){
     fragi=mb_map[0][bi];
     dx=_mv[bi][0];
@@ -1123,7 +1777,6 @@
     frag_mvs[fragi][0]=(signed char)dx;
     frag_mvs[fragi][1]=(signed char)dy;
     frag_offs=frag_buf_offs[fragi];
-    bits0+=OC_MV_BITS[0][dx+31]+OC_MV_BITS[0][dy+31];
     if(oc_state_get_mv_offsets(&_enc->state,mv_offs,0,dx,dy)>1){
       satd=oc_enc_frag_satd2_thresh(_enc,src+frag_offs,
        ref+frag_offs+mv_offs[0],ref+frag_offs+mv_offs[1],ystride,UINT_MAX);
@@ -1132,10 +1785,26 @@
       satd=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
        ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
     }
-    oc_mode_dct_cost_accum(_modec,_qi,0,1,satd);
+    frag_satd[OC_MB_PHASE[_mbi&3][bi]]=satd;
   }
+  oc_analyze_mb_mode_luma(_enc,_modec,_fr,_qs,frag_satd,
+   _enc->vp3_compatible?OC_NOSKIP:_skip_ssd,1);
+  /*Figure out which blocks are being skipped and give them (0,0) MVs.*/
+  bits0=0;
+  bits1=0;
+  nqis=_enc->state.nqis;
+  for(bi=0;bi<4;bi++){
+    if(_modec->qii[OC_MB_PHASE[_mbi&3][bi]]>=nqis){
+      memset(cbmvs+bi,0,sizeof(*cbmvs));
+    }
+    else{
+      memcpy(cbmvs+bi,_mv+bi,sizeof(*cbmvs));
+      bits0+=OC_MV_BITS[0][_mv[bi][0]+31]+OC_MV_BITS[0][_mv[bi][1]+31];
+      bits1+=12;
+    }
+  }
   (*OC_SET_CHROMA_MVS_TABLE[_enc->state.info.pixel_fmt])(cbmvs,
-   (const oc_mv *)_mv);
+   (const oc_mv *)cbmvs);
   map_idxs=OC_MB_MAP_IDXS[_enc->state.info.pixel_fmt];
   map_nidxs=OC_MB_MAP_NIDXS[_enc->state.info.pixel_fmt];
   /*Note: This assumes ref_ystride[1]==ref_ystride[2].*/
@@ -1158,19 +1827,20 @@
       satd=oc_enc_frag_satd_thresh(_enc,src+frag_offs,
        ref+frag_offs+mv_offs[0],ystride,UINT_MAX);
     }
-    oc_mode_dct_cost_accum(_modec,_qi,pli,1,satd);
+    frag_satd[mapii]=satd;
   }
-  _modec->overhead=oc_mode_scheme_chooser_cost(&_enc->chooser,
-   OC_MODE_INTER_MV_FOUR)+OC_MINI(_enc->mv_bits[0]+bits0,_enc->mv_bits[1]+48)
+  oc_analyze_mb_mode_chroma(_enc,_modec,_fr,_qs,frag_satd,_skip_ssd,1);
+  _modec->overhead+=
+   oc_mode_scheme_chooser_cost(&_enc->chooser,OC_MODE_INTER_MV_FOUR)
+   +OC_MINI(_enc->mv_bits[0]+bits0,_enc->mv_bits[1]+bits1)
    -OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
   oc_mode_set_cost(_modec,_enc->lambda);
-  return bits0;
 }
 
 int oc_enc_analyze(oc_enc_ctx *_enc,int _frame_type,int _recode){
   oc_set_chroma_mvs_func  set_chroma_mvs;
-  oc_mcenc_ctx            mcenc;
   oc_enc_pipeline_state   pipe;
+  oc_qii_state            intra_luma_qs;
   oc_mv                   last_mv;
   oc_mv                   prior_mv;
   ogg_int64_t             interbits;
@@ -1183,12 +1853,14 @@
   size_t                  nuncoded_mbis;
   oc_sb_flags            *sb_flags;
   signed char            *mb_modes;
+  const oc_sb_map        *sb_maps;
   const oc_mb_map        *mb_maps;
   oc_mb_enc_info         *embs;
   oc_fragment            *frags;
   oc_mv                  *frag_mvs;
   int                     qi;
   unsigned                stripe_sby;
+  unsigned                mcu_nvsbs;
   int                     notstart;
   int                     notdone;
   int                     vdec;
@@ -1196,11 +1868,13 @@
   unsigned                sbi_end;
   int                     refi;
   int                     pli;
+  if(_frame_type==OC_INTRA_FRAME)return oc_enc_analyze_intra(_enc,_recode);
   set_chroma_mvs=OC_SET_CHROMA_MVS_TABLE[_enc->state.info.pixel_fmt];
   _enc->state.frame_type=_frame_type;
   oc_mode_scheme_chooser_reset(&_enc->chooser);
   oc_enc_tokenize_start(_enc);
   oc_enc_pipeline_init(_enc,&pipe);
+  oc_qii_state_init(&intra_luma_qs);
   _enc->mv_bits[0]=_enc->mv_bits[1]=0;
   interbits=intrabits=0;
   last_mv[0]=last_mv[1]=prior_mv[0]=prior_mv[1]=0;
@@ -1218,272 +1892,237 @@
   _enc->state.ncoded_fragis[2]=0;
   sb_flags=_enc->state.sb_flags;
   mb_modes=_enc->state.mb_modes;
+  sb_maps=(const oc_sb_map *)_enc->state.sb_maps;
   mb_maps=(const oc_mb_map *)_enc->state.mb_maps;
   embs=_enc->mb_info;
   frags=_enc->state.frags;
   frag_mvs=_enc->state.frag_mvs;
-  sbi_end=_enc->state.fplanes[0].nsbs;
   vdec=!(_enc->state.info.pixel_fmt&2);
   notstart=0;
   notdone=1;
-  for(stripe_sby=0;notdone;stripe_sby+=pipe.mcu_nvsbs){
-    const oc_fragment_plane *fplane;
-    int                      sby_end;
-    fplane=_enc->state.fplanes+0;
-    pipe.fragy0[0]=stripe_sby<<2;
-    sby_end=fplane->nvsbs;
-    notdone=stripe_sby+pipe.mcu_nvsbs<sby_end;
-    if(notdone){
-      sby_end=stripe_sby+pipe.mcu_nvsbs;
-      pipe.fragy_end[0]=sby_end<<2;
-    }
-    else pipe.fragy_end[0]=fplane->nvfrags;
-    sbi=stripe_sby*fplane->nhsbs;
-    sbi_end=sby_end*fplane->nhsbs;
-    for(;sbi<sbi_end;sbi++){
+  mcu_nvsbs=_enc->mcu_nvsbs;
+  for(stripe_sby=0;notdone;stripe_sby+=mcu_nvsbs){
+    notdone=oc_enc_pipeline_set_stripe(_enc,&pipe,stripe_sby);
+    sbi_end=pipe.sbi_end[0];
+    for(sbi=pipe.sbi0[0];sbi<sbi_end;sbi++){
       int quadi;
       /*Mode addressing is through Y plane, always 4 MB per SB.*/
       for(quadi=0;quadi<4;quadi++)if(sb_flags[sbi].quad_valid&1<<quadi){
-        unsigned  mbi;
-        int       mb_mode;
-        int       dx;
-        int       dy;
-        int       mapii;
-        int       mapi;
-        int       bi;
-        ptrdiff_t fragi;
+        oc_mode_choice modes[8];
+        unsigned       skip_ssd[12];
+        unsigned       intra_satd[12];
+        int            mb_mv_bits_0;
+        int            mb_gmv_bits_0;
+        int            inter_mv_pref;
+        int            mb_mode;
+        int            dx;
+        int            dy;
+        unsigned       mbi;
+        int            mapii;
+        int            mapi;
+        int            bi;
+        ptrdiff_t      fragi;
         mbi=sbi<<2|quadi;
-        if(!_recode&&_enc->state.curframe_num>0){
-          /*Motion estimation:
-            We always do a basic 1MV search for all macroblocks, coded or not,
-             keyframe or not.*/
-          int accumP[2]={0,0};
-          int accumG[2]={0,0};
-          if(_enc->prevframe_dropped){
-            accumP[0] = embs[mbi].analysis_mv[0][OC_FRAME_PREV][0];
-            accumP[1] = embs[mbi].analysis_mv[0][OC_FRAME_PREV][1];
-          }
-          accumG[0]=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][0];
-          accumG[1]=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][1];
-
-          embs[mbi].analysis_mv[0][OC_FRAME_PREV][0] -= embs[mbi].analysis_mv[2][OC_FRAME_PREV][0];
-          embs[mbi].analysis_mv[0][OC_FRAME_PREV][1] -= embs[mbi].analysis_mv[2][OC_FRAME_PREV][1];
-
-          /*Move the motion vector predictors back a frame.*/
-          memmove(embs[mbi].analysis_mv+1,
-                  embs[mbi].analysis_mv,2*sizeof(embs[mbi].analysis_mv[0]));
-
-          /*Search the last frame.*/
-          oc_mcenc_search(_enc,&mcenc,accumP,mbi,OC_FRAME_PREV);
-          embs[mbi].analysis_mv[2][OC_FRAME_PREV][0]=accumP[0];
-          embs[mbi].analysis_mv[2][OC_FRAME_PREV][1]=accumP[1];
-
-          /* GOLDEN mvs are different from PREV mvs in that they're
-             each absolute offsets from some frame in the past rather
-             than relative offsets from the frame before.  For
-             predictor calculation to make sense, we need them to be
-             in the same form as PREV mvs */
-          embs[mbi].analysis_mv[1][OC_FRAME_GOLD][0]-=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][0];
-          embs[mbi].analysis_mv[1][OC_FRAME_GOLD][1]-=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][1];
-          embs[mbi].analysis_mv[2][OC_FRAME_GOLD][0]-=accumG[0];
-          embs[mbi].analysis_mv[2][OC_FRAME_GOLD][1]-=accumG[1];
-          /*Search the golden frame.*/
-          oc_mcenc_search(_enc,&mcenc,accumG,mbi,OC_FRAME_GOLD);
-          /*Put GOLDEN mvs back into absolute offset form.  Newest MV is already an absolute offset*/
-          embs[mbi].analysis_mv[2][OC_FRAME_GOLD][0]+=accumG[0];
-          embs[mbi].analysis_mv[2][OC_FRAME_GOLD][1]+=accumG[1];
-          embs[mbi].analysis_mv[1][OC_FRAME_GOLD][0]+=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][0];
-          embs[mbi].analysis_mv[1][OC_FRAME_GOLD][1]+=embs[mbi].analysis_mv[2][OC_FRAME_GOLD][1];
-
-        }
+        /*Motion estimation:
+          We always do a basic 1MV search for all macroblocks, coded or not,
+           keyframe or not.*/
+        if(!_recode)oc_mcenc_search(_enc,mbi);
         dx=dy=0;
-        if(_enc->state.frame_type==OC_INTRA_FRAME){
-          mb_modes[mbi]=mb_mode=OC_MODE_INTRA;
-          oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,0);
+        /*Find the block choice with the lowest estimated coding cost.
+          If a Cb or Cr block is coded but no Y' block from a macro block then
+           the mode MUST be OC_MODE_INTER_NOMV.
+          This is the default state to which the mode data structure is
+           initialised in encoder and decoder at the start of each frame.*/
+        /*Block coding cost is estimated from correlated SATD metrics.*/
+        /*At this point, all blocks that are in frame are still marked coded.*/
+        if(!_recode){
+          memcpy(embs[mbi].unref_mv,
+           embs[mbi].analysis_mv[0],sizeof(embs[mbi].unref_mv));
+          embs[mbi].refined=0;
         }
-        else{
-          oc_mode_choice modes[8];
-          int            mb_mv_bits_0;
-          int            mb_gmv_bits_0;
-          int            mb_4mv_bits_0;
-          int            mb_4mv_bits_1;
-          int            inter_mv_pref;
-          /*Find the block choice with the lowest estimated coding cost.
-            If a Cb or Cr block is coded but no Y' block from a macro block then
-             the mode MUST be OC_MODE_INTER_NOMV.
-            This is the default state to which the mode data structure is
-             initialised in encoder and decoder at the start of each frame.*/
-          /*Block coding cost is estimated from correlated SATD metrics.*/
-          /*At this point, all blocks that are in frame are still marked coded.*/
-          if(!_recode){
-            memcpy(embs[mbi].unref_mv,
-             embs[mbi].analysis_mv[0],sizeof(embs[mbi].unref_mv));
-            embs[mbi].refined=0;
+        oc_mb_intra_satd(_enc,mbi,intra_satd);
+        /*Estimate the cost of coding this MB in a keyframe.*/
+        oc_cost_intra(_enc,modes+OC_MODE_INTRA,mbi,
+         pipe.fr+0,&intra_luma_qs,intra_satd,OC_NOSKIP);
+        intrabits+=modes[OC_MODE_INTRA].rate;
+        for(bi=0;bi<4;bi++){
+          oc_qii_state_advance(&intra_luma_qs,&intra_luma_qs,
+           modes[OC_MODE_INTRA].qii[bi]);
+        }
+        /*Estimate the cost in a delta frame for various modes.*/
+        oc_skip_cost(_enc,&pipe,mbi,skip_ssd);
+        oc_cost_inter_nomv(_enc,modes+OC_MODE_INTER_NOMV,mbi,
+         OC_MODE_INTER_NOMV,pipe.fr+0,pipe.qs+0,skip_ssd);
+        oc_cost_intra(_enc,modes+OC_MODE_INTRA,mbi,
+         pipe.fr+0,pipe.qs+0,intra_satd,skip_ssd);
+        mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,
+         OC_MODE_INTER_MV,embs[mbi].unref_mv[OC_FRAME_PREV],
+         pipe.fr+0,pipe.qs+0,skip_ssd);
+        oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST,mbi,
+         OC_MODE_INTER_MV_LAST,last_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
+        oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST2,mbi,
+         OC_MODE_INTER_MV_LAST2,prior_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
+        oc_cost_inter_nomv(_enc,modes+OC_MODE_GOLDEN_NOMV,mbi,
+         OC_MODE_GOLDEN_NOMV,pipe.fr+0,pipe.qs+0,skip_ssd);
+        mb_gmv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_GOLDEN_MV,mbi,
+         OC_MODE_GOLDEN_MV,embs[mbi].unref_mv[OC_FRAME_GOLD],
+         pipe.fr+0,pipe.qs+0,skip_ssd);
+        oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
+         embs[mbi].block_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
+        /*The explicit MV modes (2,6,7) have not yet gone through halfpel
+           refinement.
+          We choose the explicit MV mode that's already furthest ahead on bits
+           and refine only that one.
+          We have to be careful to remember which ones we've refined so that
+           we don't refine it again if we re-encode this frame.*/
+        inter_mv_pref=_enc->lambda*3;
+        if(modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_INTER_MV].cost&&
+         modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_GOLDEN_MV].cost){
+          if(!(embs[mbi].refined&0x80)){
+            oc_mcenc_refine4mv(_enc,mbi);
+            embs[mbi].refined|=0x80;
           }
-          oc_cost_inter_nomv(_enc,modes+OC_MODE_INTER_NOMV,mbi,OC_MODE_INTER_NOMV,qi);
-          oc_cost_intra(_enc,modes+OC_MODE_INTRA,mbi,qi);
-          intrabits+=modes[OC_MODE_INTRA].rate;
-          mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,
-           OC_MODE_INTER_MV,embs[mbi].unref_mv[OC_FRAME_PREV],qi);
-          oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST,mbi,
-           OC_MODE_INTER_MV_LAST,last_mv,qi);
-          oc_cost_inter(_enc,modes+OC_MODE_INTER_MV_LAST2,mbi,
-           OC_MODE_INTER_MV_LAST2,prior_mv,qi);
-          oc_cost_inter_nomv(_enc,modes+OC_MODE_GOLDEN_NOMV,mbi,
-           OC_MODE_GOLDEN_NOMV,qi);
+          oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
+           embs[mbi].ref_mv,pipe.fr+0,pipe.qs+0,skip_ssd);
+        }
+        else if(modes[OC_MODE_GOLDEN_MV].cost+inter_mv_pref<
+         modes[OC_MODE_INTER_MV].cost){
+          if(!(embs[mbi].refined&0x40)){
+            oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_GOLD);
+            embs[mbi].refined|=0x40;
+          }
           mb_gmv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_GOLDEN_MV,mbi,
-           OC_MODE_GOLDEN_MV,embs[mbi].unref_mv[OC_FRAME_GOLD],qi);
-          mb_4mv_bits_0=oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
-           embs[mbi].block_mv,qi);
-          mb_4mv_bits_1=48;
-          /*The explicit MV modes (2,6,7) have not yet gone through halfpel
-             refinement.
-            We choose the explicit MV mode that's already furthest ahead on bits
-             and refine only that one.
-            We have to be careful to remember which ones we've refined so that
-             we don't refine it again if we re-encode this frame.*/
-          inter_mv_pref=_enc->lambda*3;
-          if(modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_INTER_MV].cost&&
-           modes[OC_MODE_INTER_MV_FOUR].cost<modes[OC_MODE_GOLDEN_MV].cost){
-            if(!(embs[mbi].refined&0x80)){
-              oc_mcenc_refine4mv(_enc,mbi);
-              embs[mbi].refined|=0x80;
-            }
-            mb_4mv_bits_0=oc_cost_inter4mv(_enc,modes+OC_MODE_INTER_MV_FOUR,mbi,
-             embs[mbi].ref_mv,qi);
+           OC_MODE_GOLDEN_MV,embs[mbi].analysis_mv[0][OC_FRAME_GOLD],
+           pipe.fr+0,pipe.qs+0,skip_ssd);
+        }
+        if(!(embs[mbi].refined&0x04)){
+          oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_PREV);
+          embs[mbi].refined|=0x04;
+        }
+        mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,
+         OC_MODE_INTER_MV,embs[mbi].analysis_mv[0][OC_FRAME_PREV],
+         pipe.fr+0,pipe.qs+0,skip_ssd);
+        /*Finally, pick the mode with the cheapest estimated R-D cost.*/
+        mb_mode=0;
+        if(modes[1].cost<modes[0].cost)mb_mode=1;
+        if(modes[3].cost<modes[mb_mode].cost)mb_mode=3;
+        if(modes[4].cost<modes[mb_mode].cost)mb_mode=4;
+        if(modes[5].cost<modes[mb_mode].cost)mb_mode=5;
+        if(modes[6].cost<modes[mb_mode].cost)mb_mode=6;
+        if(modes[7].cost<modes[mb_mode].cost)mb_mode=7;
+        /*We prefer OC_MODE_INTER_MV, but not over LAST and LAST2.*/
+        if(mb_mode==OC_MODE_INTER_MV_LAST||mb_mode==OC_MODE_INTER_MV_LAST2){
+          inter_mv_pref=0;
+        }
+        if(modes[2].cost<modes[mb_mode].cost+inter_mv_pref)mb_mode=2;
+        mb_modes[mbi]=mb_mode;
+        /*Propagate the MVs to the luma blocks.*/
+        if(mb_mode!=OC_MODE_INTER_MV_FOUR){
+          switch(mb_mode){
+            case OC_MODE_INTER_MV:{
+              dx=embs[mbi].analysis_mv[0][OC_FRAME_PREV][0];
+              dy=embs[mbi].analysis_mv[0][OC_FRAME_PREV][1];
+            }break;
+            case OC_MODE_INTER_MV_LAST:{
+              dx=last_mv[0];
+              dy=last_mv[1];
+            }break;
+            case OC_MODE_INTER_MV_LAST2:{
+              dx=prior_mv[0];
+              dy=prior_mv[1];
+            }break;
+            case OC_MODE_GOLDEN_MV:{
+              dx=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][0];
+              dy=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][1];
+            }break;
           }
-          else if(modes[OC_MODE_GOLDEN_MV].cost+inter_mv_pref<
-           modes[OC_MODE_INTER_MV].cost){
-            if(!(embs[mbi].refined&0x40)){
-              oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_GOLD);
-              embs[mbi].refined|=0x40;
-            }
-            mb_gmv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_GOLDEN_MV,mbi,
-             OC_MODE_GOLDEN_MV,embs[mbi].analysis_mv[0][OC_FRAME_GOLD],qi);
+          for(bi=0;bi<4;bi++){
+            fragi=mb_maps[mbi][0][bi];
+            frag_mvs[fragi][0]=(signed char)dx;
+            frag_mvs[fragi][1]=(signed char)dy;
           }
-          if(!(embs[mbi].refined&0x04)){
-            oc_mcenc_refine1mv(_enc,mbi,OC_FRAME_PREV);
-            embs[mbi].refined|=0x04;
-          }
-          mb_mv_bits_0=oc_cost_inter1mv(_enc,modes+OC_MODE_INTER_MV,mbi,
-           OC_MODE_INTER_MV,embs[mbi].analysis_mv[0][OC_FRAME_PREV],qi);
-          /*Finally, pick the mode with the cheapest estimated bit cost.*/
-          mb_mode=0;
-          if(modes[1].cost<modes[0].cost)mb_mode=1;
-          if(modes[3].cost<modes[mb_mode].cost)mb_mode=3;
-          if(modes[4].cost<modes[mb_mode].cost)mb_mode=4;
-          if(modes[5].cost<modes[mb_mode].cost)mb_mode=5;
-          if(modes[6].cost<modes[mb_mode].cost)mb_mode=6;
-          if(modes[7].cost<modes[mb_mode].cost)mb_mode=7;
-          /*We prefer OC_MODE_INTER_MV, but not over LAST and LAST2.*/
-          if(mb_mode==OC_MODE_INTER_MV_LAST||mb_mode==OC_MODE_INTER_MV_LAST2){
-            inter_mv_pref=0;
-          }
-          if(modes[2].cost<modes[mb_mode].cost+inter_mv_pref)mb_mode=2;
-          mb_modes[mbi]=mb_mode;
-          /*Propagate the MVs to the luma blocks.*/
-          if(mb_mode!=OC_MODE_INTER_MV_FOUR){
-            switch(mb_mode){
-              case OC_MODE_INTER_MV:{
-                dx=embs[mbi].analysis_mv[0][OC_FRAME_PREV][0];
-                dy=embs[mbi].analysis_mv[0][OC_FRAME_PREV][1];
-              }break;
-              case OC_MODE_INTER_MV_LAST:{
-                dx=last_mv[0];
-                dy=last_mv[1];
-              }break;
-              case OC_MODE_INTER_MV_LAST2:{
-                dx=prior_mv[0];
-                dy=prior_mv[1];
-              }break;
-              case OC_MODE_GOLDEN_MV:{
-                dx=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][0];
-                dy=embs[mbi].analysis_mv[0][OC_FRAME_GOLD][1];
-              }break;
-            }
-            for(bi=0;bi<4;bi++){
-              fragi=mb_maps[mbi][0][bi];
-              frag_mvs[fragi][0]=(signed char)dx;
-              frag_mvs[fragi][1]=(signed char)dy;
-            }
-          }
-          if(oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,
-           modes[mb_mode].overhead)>0){
-            int orig_mb_mode;
-            orig_mb_mode=mb_mode;
-            mb_mode=mb_modes[mbi];
-            switch(mb_mode){
-              case OC_MODE_INTER_MV:{
-                memcpy(prior_mv,last_mv,sizeof(prior_mv));
-                /*If we're backing out from 4MV, find the MV we're actually
-                   using.*/
-                if(orig_mb_mode==OC_MODE_INTER_MV_FOUR){
-                  for(bi=0;;bi++){
-                    fragi=mb_maps[mbi][0][bi];
-                    if(frags[fragi].coded){
-                      memcpy(last_mv,frag_mvs[fragi],sizeof(last_mv));
-                      dx=frag_mvs[fragi][0];
-                      dy=frag_mvs[fragi][1];
-                      break;
-                    }
-                  }
-                  mb_mv_bits_0=OC_MV_BITS[0][dx+31]+OC_MV_BITS[0][dy+31];
-                }
-                /*Otherwise we used the original analysis MV.*/
-                else{
-                  memcpy(last_mv,
-                   embs[mbi].analysis_mv[0][OC_FRAME_PREV],sizeof(last_mv));
-                }
-                _enc->mv_bits[0]+=mb_mv_bits_0;
-                _enc->mv_bits[1]+=12;
-              }break;
-              case OC_MODE_INTER_MV_LAST2:{
-                oc_mv tmp_mv;
-                memcpy(tmp_mv,prior_mv,sizeof(tmp_mv));
-                memcpy(prior_mv,last_mv,sizeof(prior_mv));
-                memcpy(last_mv,tmp_mv,sizeof(last_mv));
-              }break;
-              case OC_MODE_GOLDEN_MV:{
-                _enc->mv_bits[0]+=mb_gmv_bits_0;
-                _enc->mv_bits[1]+=12;
-              }break;
-              case OC_MODE_INTER_MV_FOUR:{
-                oc_mv lbmvs[4];
-                oc_mv cbmvs[4];
-                memcpy(prior_mv,last_mv,sizeof(prior_mv));
-                for(bi=0;bi<4;bi++){
+        }
+        for(bi=0;bi<4;bi++){
+          fragi=sb_maps[mbi>>2][mbi&3][bi];
+          frags[fragi].qii=modes[mb_mode].qii[bi];
+        }
+        if(oc_enc_mb_transform_quantize_luma(_enc,&pipe,mbi,
+         modes[mb_mode].overhead>>OC_BIT_SCALE)>0){
+          int orig_mb_mode;
+          orig_mb_mode=mb_mode;
+          mb_mode=mb_modes[mbi];
+          switch(mb_mode){
+            case OC_MODE_INTER_MV:{
+              memcpy(prior_mv,last_mv,sizeof(prior_mv));
+              /*If we're backing out from 4MV, find the MV we're actually
+                 using.*/
+              if(orig_mb_mode==OC_MODE_INTER_MV_FOUR){
+                for(bi=0;;bi++){
                   fragi=mb_maps[mbi][0][bi];
                   if(frags[fragi].coded){
                     memcpy(last_mv,frag_mvs[fragi],sizeof(last_mv));
-                    memcpy(lbmvs[bi],frag_mvs[fragi],sizeof(lbmvs[bi]));
-                    _enc->mv_bits[0]+=OC_MV_BITS[0][frag_mvs[fragi][0]+31]
-                     +OC_MV_BITS[0][frag_mvs[fragi][1]+31];
-                    _enc->mv_bits[1]+=12;
+                    dx=frag_mvs[fragi][0];
+                    dy=frag_mvs[fragi][1];
+                    break;
                   }
-                  /*Replace the block MVs for not-coded blocks with (0,0).*/
-                  else memset(lbmvs[bi],0,sizeof(lbmvs[bi]));
                 }
-                (*set_chroma_mvs)(cbmvs,(const oc_mv *)lbmvs);
-                for(mapii=4;mapii<nmap_idxs;mapii++){
-                  mapi=map_idxs[mapii];
-                  pli=mapi>>2;
-                  bi=mapi&3;
-                  fragi=mb_maps[mbi][pli][bi];
-                  frags[fragi].mb_mode=mb_mode;
-                  memcpy(frag_mvs[fragi],cbmvs[bi],sizeof(frag_mvs[fragi]));
+                mb_mv_bits_0=OC_MV_BITS[0][dx+31]+OC_MV_BITS[0][dy+31];
+              }
+              /*Otherwise we used the original analysis MV.*/
+              else{
+                memcpy(last_mv,
+                 embs[mbi].analysis_mv[0][OC_FRAME_PREV],sizeof(last_mv));
+              }
+              _enc->mv_bits[0]+=mb_mv_bits_0;
+              _enc->mv_bits[1]+=12;
+            }break;
+            case OC_MODE_INTER_MV_LAST2:{
+              oc_mv tmp_mv;
+              memcpy(tmp_mv,prior_mv,sizeof(tmp_mv));
+              memcpy(prior_mv,last_mv,sizeof(prior_mv));
+              memcpy(last_mv,tmp_mv,sizeof(last_mv));
+            }break;
+            case OC_MODE_GOLDEN_MV:{
+              _enc->mv_bits[0]+=mb_gmv_bits_0;
+              _enc->mv_bits[1]+=12;
+            }break;
+            case OC_MODE_INTER_MV_FOUR:{
+              oc_mv lbmvs[4];
+              oc_mv cbmvs[4];
+              memcpy(prior_mv,last_mv,sizeof(prior_mv));
+              for(bi=0;bi<4;bi++){
+                fragi=mb_maps[mbi][0][bi];
+                if(frags[fragi].coded){
+                  memcpy(last_mv,frag_mvs[fragi],sizeof(last_mv));
+                  memcpy(lbmvs[bi],frag_mvs[fragi],sizeof(lbmvs[bi]));
+                  _enc->mv_bits[0]+=OC_MV_BITS[0][frag_mvs[fragi][0]+31]
+                   +OC_MV_BITS[0][frag_mvs[fragi][1]+31];
+                  _enc->mv_bits[1]+=12;
                 }
-              }break;
-            }
-            coded_mbis[ncoded_mbis++]=mbi;
-            oc_mode_scheme_chooser_update(&_enc->chooser,mb_mode);
-            interbits+=modes[mb_mode].rate+modes[mb_mode].overhead;
+                /*Replace the block MVs for not-coded blocks with (0,0).*/
+                else memset(lbmvs[bi],0,sizeof(lbmvs[bi]));
+              }
+              (*set_chroma_mvs)(cbmvs,(const oc_mv *)lbmvs);
+              for(mapii=4;mapii<nmap_idxs;mapii++){
+                mapi=map_idxs[mapii];
+                pli=mapi>>2;
+                bi=mapi&3;
+                fragi=mb_maps[mbi][pli][bi];
+                frags[fragi].mb_mode=mb_mode;
+                frags[fragi].qii=modes[OC_MODE_INTER_MV_FOUR].qii[mapii];
+                memcpy(frag_mvs[fragi],cbmvs[bi],sizeof(frag_mvs[fragi]));
+              }
+            }break;
           }
-          else{
-            *(uncoded_mbis-++nuncoded_mbis)=mbi;
-            mb_mode=OC_MODE_INTER_NOMV;
-            dx=dy=0;
-          }
+          coded_mbis[ncoded_mbis++]=mbi;
+          oc_mode_scheme_chooser_update(&_enc->chooser,mb_mode);
+          interbits+=modes[mb_mode].rate+modes[mb_mode].overhead;
         }
+        else{
+          *(uncoded_mbis-++nuncoded_mbis)=mbi;
+          mb_mode=OC_MODE_INTER_NOMV;
+          dx=dy=0;
+        }
         /*Propagate final MB mode and MVs to the chroma blocks.
           This has already been done for 4MV mode, since it requires individual
            block motion vectors.*/
@@ -1494,30 +2133,24 @@
             bi=mapi&3;
             fragi=mb_maps[mbi][pli][bi];
             frags[fragi].mb_mode=mb_mode;
+            /*If we switched from 4MV mode to INTER_MV mode, then the qii
+               values won't have been chosen with the right MV, but it's
+               probaby not worth re-estimating them.*/
+            frags[fragi].qii=modes[mb_mode].qii[mapii];
             frag_mvs[fragi][0]=(signed char)dx;
             frag_mvs[fragi][1]=(signed char)dy;
           }
         }
       }
-      oc_fr_finish_sb(pipe.fr+0);
-      sb_flags[sbi].coded_fully=pipe.fr[0].sb_full_last;
-      sb_flags[sbi].coded_partially=pipe.fr[0].sb_partial_last;
+      oc_fr_state_flush_sb(pipe.fr+0);
+      sb_flags[sbi].coded_fully=pipe.fr[0].sb_full;
+      sb_flags[sbi].coded_partially=pipe.fr[0].sb_partial;
     }
     oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,0,notstart,notdone);
     /*Code chroma planes.*/
     for(pli=1;pli<3;pli++){
-      fplane=_enc->state.fplanes+pli;
-      sbi=fplane->sboffset+(stripe_sby>>vdec)*fplane->nhsbs;
-      pipe.fragy0[pli]=stripe_sby<<2-vdec;
-      if(notdone){
-        sbi_end=sbi+(sby_end-stripe_sby>>vdec)*fplane->nhsbs;
-        pipe.fragy_end[pli]=sby_end<<2-vdec;
-      }
-      else{
-        sbi_end=fplane->sboffset+fplane->nsbs;
-        pipe.fragy_end[pli]=fplane->nvfrags;
-      }
-      oc_enc_sb_transform_quantize_chroma(_enc,&pipe,pli,sbi,sbi_end);
+      oc_enc_sb_transform_quantize_chroma(_enc,&pipe,
+       pli,pipe.sbi0[pli],pipe.sbi_end[pli]);
       oc_enc_pipeline_finish_mcu_plane(_enc,&pipe,pli,notstart,notdone);
     }
     notstart=1;
@@ -1532,10 +2165,7 @@
     /*Technically the chroma plane counts are over-estimations, because they
        don't account for continuing runs from the luma planes, but the
        inaccuracy is small.*/
-    for(pli=0;pli<3;pli++){
-      oc_fr_flush(pipe.fr+pli);
-      interbits+=pipe.fr[pli].bits<<OC_BIT_SCALE;
-    }
+    for(pli=0;pli<3;pli++)interbits+=pipe.fr[pli].bits<<OC_BIT_SCALE;
     interbits+=OC_MINI(_enc->mv_bits[0],_enc->mv_bits[1])<<OC_BIT_SCALE;
     interbits+=
      _enc->chooser.scheme_bits[_enc->chooser.scheme_list[0]]<<OC_BIT_SCALE;
@@ -1561,6 +2191,9 @@
 # include <stdio.h>
 # include <math.h>
 
+/*TODO: It may be helpful (for block-level quantizers especially) to separate
+   out the contributions from AC and DC into separate tables.*/
+
 # define OC_ZWEIGHT   (0.25)
 # define OC_BIN(_satd) (OC_MINI((_satd)>>OC_SAD_SHIFT,OC_SAD_BINS-1))
 
@@ -1704,6 +2337,7 @@
   ptrdiff_t          fragii;
   double             fragw;
   int                qti;
+  int                qii;
   int                qi;
   int                pli;
   int                zzi;
@@ -1723,7 +2357,6 @@
     oc_has_mode_metrics=1;
   }
   qti=_enc->state.frame_type;
-  qi=_enc->state.qis[0];
   frags=_enc->state.frags;
   frag_satd=_enc->frag_satd;
   frag_ssd=_enc->frag_ssd;
@@ -1734,8 +2367,8 @@
   fragw=1.0/_enc->state.nfrags;
   for(pli=0;pli<3;pli++){
     ptrdiff_t ti[64];
-    int       eob_runs[64];
-    int       eob_rem[64];
+    int       eob_token[64];
+    int       eob_run[64];
     /*Set up token indices and eob run counts.
       We don't bother trying to figure out the real cost of the runs that span
        coefficients; instead we use the costs that were available when R-D
@@ -1745,11 +2378,14 @@
       if(ti[zzi]>0){
         token=_enc->dct_tokens[pli][zzi][0];
         eb=_enc->extra_bits[pli][zzi][0];
-        eob_runs[zzi]=-oc_dct_token_skip(token,eb);
+        eob_token[zzi]=token;
+        eob_run[zzi]=-oc_dct_token_skip(token,eb);
       }
-      else eob_runs[zzi]=0;
+      else{
+        eob_token[zzi]=OC_NDCT_EOB_TOKEN_MAX;
+        eob_run[zzi]=0;
+      }
     }
-    memcpy(eob_rem,eob_runs,sizeof(eob_rem));
     /*Scan the list of coded fragments for this plane.*/
     ncoded_fragis+=_enc->state.ncoded_fragis[pli];
     for(;fragii<ncoded_fragis;fragii++){
@@ -1763,25 +2399,28 @@
       fragi=coded_fragis[fragii];
       frag_bits=0;
       for(zzi=0;zzi<64;){
-        if(eob_rem[zzi]>0){
+        if(eob_run[zzi]>0){
           /*We've reached the end of the block.*/
-          eob_rem[zzi]--;
+          eob_run[zzi]--;
           break;
         }
         huffi=_enc->huff_idxs[qti][zzi>0][pli+1>>1]
          +OC_ZZI_HUFF_OFFSET[zzi];
-        if(eob_runs[zzi]>0){
+        if(eob_token[zzi]<OC_NDCT_EOB_TOKEN_MAX){
           /*This token caused an EOB run to be flushed.
             Therefore it gets the bits associated with it.*/
-          frag_bits+=_enc->huff_codes[huffi][token].nbits
-           +OC_DCT_TOKEN_EXTRA_BITS[token];
-          eob_runs[zzi]=0;
+          frag_bits+=_enc->huff_codes[huffi][eob_token[zzi]].nbits
+           +OC_DCT_TOKEN_EXTRA_BITS[eob_token[zzi]];
+          eob_token[zzi]=OC_NDCT_EOB_TOKEN_MAX;
         }
         token=_enc->dct_tokens[pli][zzi][ti[zzi]];
         eb=_enc->extra_bits[pli][zzi][ti[zzi]];
         ti[zzi]++;
         skip=oc_dct_token_skip(token,eb);
-        if(skip<0)eob_runs[zzi]=eob_rem[zzi]=-skip;
+        if(skip<0){
+          eob_token[zzi]=token;
+          eob_run[zzi]=-skip;
+        }
         else{
           /*A regular DCT value token; accumulate the bits for it.*/
           frag_bits+=_enc->huff_codes[huffi][token].nbits
@@ -1790,6 +2429,7 @@
         }
       }
       mb_mode=frags[fragi].mb_mode;
+      qi=_enc->state.qis[frags[fragi].qii];
       satd=frag_satd[fragi];
       bin=OC_MINI(satd>>OC_SAD_SHIFT,OC_SAD_BINS-1);
       oc_mode_metrics_add(OC_MODE_METRICS[qi][pli][mb_mode!=OC_MODE_INTRA]+bin,
@@ -1797,7 +2437,9 @@
     }
   }
   /*Update global SATD/rate/RMSE estimation matrix.*/
-  oc_enc_mode_metrics_update(_enc,qi);
+  for(qii=0;qii<_enc->state.nqis;qii++){
+    oc_enc_mode_metrics_update(_enc,_enc->state.qis[qii]);
+  }
 }
 
 void oc_enc_mode_metrics_dump(oc_enc_ctx *_enc){

Modified: branches/theora-thusnelda/lib/enc/encfrag.c
===================================================================
--- branches/theora-thusnelda/lib/enc/encfrag.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/encfrag.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -356,7 +356,7 @@
 unsigned oc_enc_frag_intra_satd_c(const unsigned char *_src,int _ystride){
   ogg_int16_t buf[64];
   oc_intra_hadamard(buf,_src,_ystride);
-  return oc_hadamard_sad_thresh(buf,0xFF000)
+  return oc_hadamard_sad_thresh(buf,UINT_MAX)
    -abs(buf[0]+buf[1]+buf[2]+buf[3]+buf[4]+buf[5]+buf[6]+buf[7]);
 }
 

Modified: branches/theora-thusnelda/lib/enc/encint.h
===================================================================
--- branches/theora-thusnelda/lib/enc/encint.h	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/encint.h	2009-07-22 01:56:26 UTC (rev 16314)
@@ -29,8 +29,9 @@
 
 
 
+typedef oc_mv                         oc_mv2[2];
+
 typedef struct oc_enc_opt_vtable      oc_enc_opt_vtable;
-typedef struct oc_mcenc_ctx           oc_mcenc_ctx;
 typedef struct oc_mb_enc_info         oc_mb_enc_info;
 typedef struct oc_mode_scheme_chooser oc_mode_scheme_chooser;
 typedef struct oc_rc_state            oc_rc_state;
@@ -116,7 +117,7 @@
      can be used to estimate constant velocity and constant acceleration
      predictors.
     Uninitialized MVs are (0,0).*/
-  oc_mv         analysis_mv[3][2]; /* [cur,prev,prev2][frame,golden] */
+  oc_mv2        analysis_mv[3];
   /*Current unrefined analysis MVs.*/
   oc_mv         unref_mv[2];
   /*Unrefined block MVs.*/
@@ -151,7 +152,7 @@
   /*The list of mode coding schemes, sorted in ascending order of bit cost.*/
   unsigned char        scheme_list[8];
   /*The number of bits used by each mode coding scheme.*/
-  int                  scheme_bits[8];
+  ptrdiff_t            scheme_bits[8];
 };
 
 
@@ -194,7 +195,7 @@
 void oc_enc_calc_lambda(oc_enc_ctx *_enc,int _frame_type);
 void oc_rc_state_init(oc_rc_state *_rc,const oc_enc_ctx *_enc);
 int oc_enc_update_rc_state(oc_enc_ctx *_enc,
-  long _bits,int _qti,int _qi,int _trial,int _droppable);
+ long _bits,int _qti,int _qi,int _trial,int _droppable);
 int oc_enc_select_qi(oc_enc_ctx *_enc,int _qti,int _clamp);
 
 
@@ -241,6 +242,10 @@
   size_t                   mv_bits[2];
   /*The mode scheme chooser for estimating mode coding costs.*/
   oc_mode_scheme_chooser   chooser;
+  /*The number of vertical super blocks in an MCU.*/
+  int                      mcu_nvsbs;
+  /*The SSD error for skipping each fragment in the current MCU.*/
+  unsigned                *mcu_skip_ssd;
   /*The DCT token lists for each coefficient and each plane.*/
   unsigned char          **dct_tokens[3];
   /*The extra bits associated with each DCT token.*/
@@ -289,18 +294,8 @@
 
 
 
-/*Temporary state used for motion estimation.*/
-struct oc_mcenc_ctx{
-  /*The candidate motion vectors.*/
-  int                candidates[12][2];
-  /*The start of the Set B candidates.*/
-  int                setb0;
-  /*The total number of candidates.*/
-  int                ncandidates;
-};
-
-/*Search for a single MB MV (and with OC_FRAME_PREV, block MVs) in one frame.*/
-void oc_mcenc_search(oc_enc_ctx *_enc,oc_mcenc_ctx *_mcenc,int acc[2],int _mbi,int _frame);
+/*Perform fullpel motion search for a single MB against both reference frames.*/
+void oc_mcenc_search(oc_enc_ctx *_enc,int _mbi);
 /*Refine a MB MV for one frame.*/
 void oc_mcenc_refine1mv(oc_enc_ctx *_enc,int _mbi,int _frame);
 /*Refine the block MVs.*/

Modified: branches/theora-thusnelda/lib/enc/encode.c
===================================================================
--- branches/theora-thusnelda/lib/enc/encode.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/encode.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -1035,9 +1035,13 @@
 }
 
 static int oc_enc_init(oc_enc_ctx *_enc,const th_info *_info){
-  th_info info;
-  int     ret;
-  int     pli;
+  th_info   info;
+  size_t    mcu_nmbs;
+  ptrdiff_t mcu_nfrags;
+  int       hdec;
+  int       vdec;
+  int       ret;
+  int       pli;
   /*Clean up the requested settings.*/
   memcpy(&info,_info,sizeof(info));
   info.version_major=TH_VERSION_MAJOR;
@@ -1053,6 +1057,15 @@
   _enc->frag_dc=_ogg_calloc(_enc->state.nfrags,sizeof(*_enc->frag_dc));
   _enc->coded_mbis=
    (unsigned *)_ogg_malloc(_enc->state.nmbs*sizeof(*_enc->coded_mbis));
+  hdec=!(_enc->state.info.pixel_fmt&1);
+  vdec=!(_enc->state.info.pixel_fmt&1);
+  /*If chroma is sub-sampled in the vertical direction, we have to encode two
+     super block rows of Y' for each super block row of Cb and Cr.*/
+  _enc->mcu_nvsbs=1<<vdec;
+  mcu_nmbs=_enc->mcu_nvsbs*_enc->state.fplanes[0].nhsbs*(size_t)4;
+  mcu_nfrags=4*mcu_nmbs+(8*mcu_nmbs>>hdec+vdec);
+  _enc->mcu_skip_ssd=(unsigned *)_ogg_malloc(
+   mcu_nfrags*sizeof(*_enc->mcu_skip_ssd));
   for(pli=0;pli<3;pli++){
     _enc->dct_tokens[pli]=(unsigned char **)oc_malloc_2d(64,
      _enc->state.fplanes[pli].nfrags,sizeof(**_enc->dct_tokens));
@@ -1104,6 +1117,7 @@
     oc_free_2d(_enc->extra_bits[pli]);
     oc_free_2d(_enc->dct_tokens[pli]);
   }
+  _ogg_free(_enc->mcu_skip_ssd);
   _ogg_free(_enc->coded_mbis);
   _ogg_free(_enc->frag_dc);
   _ogg_free(_enc->mb_info);
@@ -1111,12 +1125,12 @@
 }
 
 static void oc_enc_drop_frame(th_enc_ctx *_enc){
-  /* use the previous frame's reconstruction */
+  /*Use the previous frame's reconstruction.*/
   _enc->state.ref_frame_idx[OC_FRAME_SELF]=
-    _enc->state.ref_frame_idx[OC_FRAME_PREV];
-  /* flag motion vector analysis about the frame drop */
+   _enc->state.ref_frame_idx[OC_FRAME_PREV];
+  /*Flag motion vector analysis about the frame drop.*/
   _enc->prevframe_dropped=1;
-  /* zero the packet */
+  /*Zero the packet.*/
   oggpackB_reset(&_enc->opb);
 }
 
@@ -1157,9 +1171,9 @@
          prime feed-forward statistics.*/
       _enc->coded_inter_frame=1;
       if(_enc->state.info.target_bitrate>0){
-        /* rate control also needs to prime */
+        /*Rate control also needs to prime.*/
         oc_enc_update_rc_state(_enc,oggpackB_bytes(&_enc->opb)<<3,
-                               OC_INTER_FRAME,_enc->state.qis[0],1,0);
+         OC_INTER_FRAME,_enc->state.qis[0],1,0);
       }
       oc_enc_compress_frame(_enc,1);
     }
@@ -1403,7 +1417,7 @@
   int             vdec;
   int             pli;
   int             refi;
-  int             drop=0;
+  int             drop;
   /*Step 1: validate parameters.*/
   if(_enc==NULL||_img==NULL)return TH_EFAULT;
   if(_enc->packet_state==OC_PACKET_DONE)return TH_EINVAL;
@@ -1462,27 +1476,22 @@
    _enc->state.curframe_num-_enc->state.keyframe_num+_enc->dup_count>=
    _enc->keyframe_frequency_force){
     oc_enc_compress_keyframe(_enc,0);
-  }else{
+    drop=0;
+  }
+  else{
     oc_enc_compress_frame(_enc,0);
     drop=1;
   }
   oc_restore_fpu(&_enc->state);
-
-  /* drop is currently indicating if the frame is droppable.*/
-  if(_enc->state.info.target_bitrate>0)
+  /*drop currently indicates if the frame is droppable.*/
+  if(_enc->state.info.target_bitrate>0){
     drop=oc_enc_update_rc_state(_enc,oggpackB_bytes(&_enc->opb)<<3,
-                                _enc->state.frame_type,_enc->state.qis[0],0,drop);
-  else
-    drop=0;
-  /* drop now indicates if the frame was dropped */
-
-  if(drop){
-    oc_enc_drop_frame(_enc);
-    _enc->prevframe_dropped=1;
-  }else{
-    _enc->prevframe_dropped=0;
+     _enc->state.frame_type,_enc->state.qis[0],0,drop);
   }
-
+  else drop=0;
+  /*drop now indicates if the frame was dropped.*/
+  if(drop)oc_enc_drop_frame(_enc);
+  else _enc->prevframe_dropped=0;
   _enc->packet_state=OC_PACKET_READY;
   _enc->prev_dup_count=_enc->nqueued_dups=_enc->dup_count;
   _enc->dup_count=0;
@@ -1513,8 +1522,9 @@
     }
   }
   else return 0;
+  _last_p=_last_p&&_enc->nqueued_dups<=0;
   _op->b_o_s=0;
-  _op->e_o_s=_last_p=_last_p&&_enc->nqueued_dups<=0;
+  _op->e_o_s=_last_p;
   oc_enc_set_granpos(_enc);
   _op->packetno=th_granule_frame(_enc,_enc->state.granpos)+3;
   _op->granulepos=_enc->state.granpos;

Modified: branches/theora-thusnelda/lib/enc/enquant.c
===================================================================
--- branches/theora-thusnelda/lib/enc/enquant.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/enquant.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -170,17 +170,6 @@
       oc_iquant_init(_enquant[qi][pli][qti]+zzi,
        _dequant[qi][pli][qti][zzi]);
     }
-    /*Now compute an "average" quantizer for each qi level.
-      We do one for INTER and one for INTRA, since their behavior is very
-       different, but average across chroma channels.
-      The basic approach is to compute a harmonic average of the squared
-       quantizer, weighted by the expected squared magnitude of the DCT
-       coefficients.
-      Under the (not quite true) assumption that DCT coefficients are
-       Laplacian-distributed, this preserves the product Q*lambda, where
-       lambda=sqrt(2/sigma**2) is the Laplacian distribution parameter.
-      The value Q*lambda completely determines the entropy of the
-       coefficients.*/
   }
 }
 
@@ -210,7 +199,7 @@
    mode is significantly flatter) and b) the DPCM prediction of the DC
    coefficient gives a very minor improvement in the INTRA case and a quite
    significant one in the INTER case (over the expected variance).*/
-static ogg_uint16_t OC_RPSD[2][64]={
+static const ogg_uint16_t OC_RPSD[2][64]={
   {
     52725,17370,10399, 6867, 5115, 3798, 2942, 2076,
     17370, 9900, 6948, 4994, 3836, 2869, 2229, 1619,
@@ -239,7 +228,7 @@
    quantization, over a large set of test video encoded at all possible rates.
   TODO: These values are only from INTER frames; it should be re-measured for
    INTRA frames.*/
-static ogg_uint16_t OC_PCD[4][3]={
+static const ogg_uint16_t OC_PCD[4][3]={
   {59926, 3038, 2572},
   {55201, 5597, 4738},
   {55201, 5597, 4738},
@@ -247,6 +236,17 @@
 };
 
 
+/*Compute an "average" quantizer for each qi level.
+  We do one for INTER and one for INTRA, since their behavior is very
+   different, but average across chroma channels.
+  The basic approach is to compute a harmonic average of the squared quantizer,
+   weighted by the expected squared magnitude of the DCT coefficients.
+  Under the (not quite true) assumption that DCT coefficients are
+   Laplacian-distributed, this preserves the product Q*lambda, where
+   lambda=sqrt(2/sigma**2) is the Laplacian distribution parameter (not to be
+   confused with the lambda used in R-D optimization throughout most of the
+   rest of the code).
+  The value Q*lambda completely determines the entropy of the coefficients.*/
 void oc_enquant_qavg_init(ogg_int64_t _log_qavg[2][64],
  ogg_uint16_t *_dequant[64][3][2],int _pixel_fmt){
   int qi;

Modified: branches/theora-thusnelda/lib/enc/huffenc.c
===================================================================
--- branches/theora-thusnelda/lib/enc/huffenc.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/huffenc.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -862,7 +862,7 @@
     for(j=1;j<TH_NDCT_TOKENS;j++){
       maxlen=OC_MAXI(_codes[i][j].nbits,maxlen);
     }
-    mask=(1<<maxlen)-1;
+    mask=(1<<(maxlen>>1)<<(maxlen+1>>1))-1;
     /*Copy over the codes into our temporary workspace.
       The bit patterns are aligned, and the original entry each code is from
        is stored as well.*/

Modified: branches/theora-thusnelda/lib/enc/mcenc.c
===================================================================
--- branches/theora-thusnelda/lib/enc/mcenc.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/mcenc.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -19,6 +19,24 @@
 #include <string.h>
 #include "encint.h"
 
+
+
+typedef struct oc_mcenc_ctx           oc_mcenc_ctx;
+
+
+
+/*Temporary state used for motion estimation.*/
+struct oc_mcenc_ctx{
+  /*The candidate motion vectors.*/
+  int                candidates[12][2];
+  /*The start of the Set B candidates.*/
+  int                setb0;
+  /*The total number of candidates.*/
+  int                ncandidates;
+};
+
+
+
 /*The maximum Y plane SAD value for accepting the median predictor.*/
 #define OC_YSAD_THRESH1            (256)
 /*The amount to right shift the minimum error by when inflating it for
@@ -69,8 +87,9 @@
   {0,1,3}
 };
 
+
 static void oc_mcenc_find_candidates(oc_enc_ctx *_enc,oc_mcenc_ctx *_mcenc,
-                                     int _accum[2], int _mbi,int _frame){
+ int _accum[2],int _mbi,int _frame){
   oc_mb_enc_info *embs;
   int             a[3][2];
   int             ncandidates;
@@ -90,11 +109,13 @@
     }
     /*Add a few additional vectors to set A: the vector used in the
        previous frame and the (0,0) vector.*/
-    _mcenc->candidates[ncandidates][0]=OC_CLAMPI(-31,embs[_mbi].analysis_mv[1][_frame][0]+_accum[0],31);
-    _mcenc->candidates[ncandidates][1]=OC_CLAMPI(-31,embs[_mbi].analysis_mv[1][_frame][1]+_accum[1],31);
+    _mcenc->candidates[ncandidates][0]=OC_CLAMPI(-31,
+     embs[_mbi].analysis_mv[1][_frame][0]+_accum[0],31);
+    _mcenc->candidates[ncandidates][1]=OC_CLAMPI(-31,
+     embs[_mbi].analysis_mv[1][_frame][1]+_accum[1],31);
     ncandidates++;
-    _mcenc->candidates[ncandidates][0]=OC_CLAMPI(-31,_accum[0],31);
-    _mcenc->candidates[ncandidates][1]=OC_CLAMPI(-31,_accum[1],31);
+    _mcenc->candidates[ncandidates][0]=0;
+    _mcenc->candidates[ncandidates][1]=0;
     ncandidates++;
     /*Use the first three vectors of set A to find our best predictor: their
        median.*/
@@ -114,28 +135,28 @@
        for set A.*/
     _mcenc->candidates[0][0]=OC_CLAMPI(-31,_accum[0],31);
     _mcenc->candidates[0][1]=OC_CLAMPI(-31,_accum[1],31);
-    _mcenc->candidates[1][0]=OC_CLAMPI(-31,embs[_mbi].analysis_mv[1][_frame][0]+_accum[0],31);
-    _mcenc->candidates[1][1]=OC_CLAMPI(-31,embs[_mbi].analysis_mv[1][_frame][1]+_accum[1],31);
+    _mcenc->candidates[1][0]=OC_CLAMPI(-31,
+     embs[_mbi].analysis_mv[1][_frame][0]+_accum[0],31);
+    _mcenc->candidates[1][1]=OC_CLAMPI(-31,
+     embs[_mbi].analysis_mv[1][_frame][1]+_accum[1],31);
     ncandidates=2;
   }
-
   /*Fill in set B: accelerated predictors for this and adjacent macro
-    blocks.*/
+     blocks.*/
   _mcenc->setb0=ncandidates;
   /*The first time through the loop use the current macro block.*/
   nmbi=_mbi;
   for(i=0;;i++){
-    _mcenc->candidates[ncandidates][0]=
-      OC_CLAMPI(-31, 2*embs[_mbi].analysis_mv[1][_frame][0]-
-                embs[_mbi].analysis_mv[2][_frame][0]+_accum[0], 31);
-    _mcenc->candidates[ncandidates][1]=
-      OC_CLAMPI(-31, 2*embs[_mbi].analysis_mv[1][_frame][1]-
-                embs[_mbi].analysis_mv[2][_frame][1]+_accum[1], 31);
+    _mcenc->candidates[ncandidates][0]=OC_CLAMPI(-31,
+     2*embs[_mbi].analysis_mv[1][_frame][0]
+     -embs[_mbi].analysis_mv[2][_frame][0]+_accum[0],31);
+    _mcenc->candidates[ncandidates][1]=OC_CLAMPI(-31,
+     2*embs[_mbi].analysis_mv[1][_frame][1]
+     -embs[_mbi].analysis_mv[2][_frame][1]+_accum[1],31);
     ncandidates++;
     if(i>=embs[_mbi].npneighbors)break;
     nmbi=embs[_mbi].pneighbors[i];
   }
-
   /*Truncate to full-pel positions.*/
   for(i=0;i<ncandidates;i++){
     _mcenc->candidates[i][0]=OC_DIV2(_mcenc->candidates[i][0]);
@@ -230,10 +251,10 @@
   The actual motion vector is stored in the appropriate place in the
    oc_mb_enc_info structure.
   _mcenc:    The motion compensation context.
-  _accum:    drop frame/golden mv accumulators
+  _accum:    Drop frame/golden MV accumulators.
   _mbi:      The macro block index.
   _frame:    The frame to search, either OC_FRAME_PREV or OC_FRAME_GOLD.*/
-void oc_mcenc_search(oc_enc_ctx *_enc,oc_mcenc_ctx *_mcenc,int _accum[2],int _mbi,int _frame){
+void oc_mcenc_search_frame(oc_enc_ctx *_enc,int _accum[2],int _mbi,int _frame){
   /*Note: Traditionally this search is done using a rate-distortion objective
      function of the form D+lambda*R.
     However, xiphmont tested this and found it produced a small degredation,
@@ -249,6 +270,7 @@
      may cause increased degredation in many blocks to come.
     We could artificially reduce lambda to compensate, but it's faster to just
      disable it entirely, and use D (the distortion) as the sole criterion.*/
+  oc_mcenc_ctx         mcenc;
   const ptrdiff_t     *frag_buf_offs;
   const ptrdiff_t     *fragis;
   const unsigned char *src;
@@ -267,12 +289,12 @@
   int                  bi;
   embs=_enc->mb_info;
   /*Find some candidate motion vectors.*/
-  oc_mcenc_find_candidates(_enc,_mcenc,_accum,_mbi,_frame);
+  oc_mcenc_find_candidates(_enc,&mcenc,_accum,_mbi,_frame);
   /*Clear the cache of locations we've examined.*/
   memset(hit_cache,0,sizeof(hit_cache));
   /*Start with the median predictor.*/
-  candx=_mcenc->candidates[0][0];
-  candy=_mcenc->candidates[0][1];
+  candx=mcenc.candidates[0][0];
+  candy=mcenc.candidates[0][1];
   hit_cache[candy+15]|=(ogg_int32_t)1<<candx+15;
   frag_buf_offs=_enc->state.frag_buf_offs;
   fragis=_enc->state.mb_maps[_mbi][0];
@@ -305,9 +327,9 @@
     }
     t2+=(t2>>OC_YSAD_THRESH2_SCALE_BITS)+OC_YSAD_THRESH2_OFFSET;
     /*Examine the candidates in set A.*/
-    for(ci=1;ci<_mcenc->setb0;ci++){
-      candx=_mcenc->candidates[ci][0];
-      candy=_mcenc->candidates[ci][1];
+    for(ci=1;ci<mcenc.setb0;ci++){
+      candx=mcenc.candidates[ci][0];
+      candy=mcenc.candidates[ci][1];
       /*If we've already examined this vector, then we would be using it if it
          was better than what we are using.*/
       hitbit=(ogg_int32_t)1<<candx+15;
@@ -330,9 +352,9 @@
     }
     if(best_err>t2){
       /*Examine the candidates in set B.*/
-      for(;ci<_mcenc->ncandidates;ci++){
-        candx=_mcenc->candidates[ci][0];
-        candy=_mcenc->candidates[ci][1];
+      for(;ci<mcenc.ncandidates;ci++){
+        candx=mcenc.candidates[ci][0];
+        candy=mcenc.candidates[ci][1];
         hitbit=(ogg_int32_t)1<<candx+15;
         if(hit_cache[candy+15]&hitbit)continue;
         hit_cache[candy+15]|=hitbit;
@@ -479,6 +501,45 @@
   }
 }
 
+void oc_mcenc_search(oc_enc_ctx *_enc,int _mbi){
+  oc_mv2         *mvs;
+  int             accum_p[2];
+  int             accum_g[2];
+  mvs=_enc->mb_info[_mbi].analysis_mv;
+  if(_enc->prevframe_dropped){
+    accum_p[0]=mvs[0][OC_FRAME_PREV][0];
+    accum_p[1]=mvs[0][OC_FRAME_PREV][1];
+  }
+  else accum_p[1]=accum_p[0]=0;
+  accum_g[0]=mvs[2][OC_FRAME_GOLD][0];
+  accum_g[1]=mvs[2][OC_FRAME_GOLD][1];
+  mvs[0][OC_FRAME_PREV][0]-=mvs[2][OC_FRAME_PREV][0];
+  mvs[0][OC_FRAME_PREV][1]-=mvs[2][OC_FRAME_PREV][1];
+  /*Move the motion vector predictors back a frame.*/
+  memmove(mvs+1,mvs,2*sizeof(*mvs));
+  /*Search the last frame.*/
+  oc_mcenc_search_frame(_enc,accum_p,_mbi,OC_FRAME_PREV);
+  mvs[2][OC_FRAME_PREV][0]=accum_p[0];
+  mvs[2][OC_FRAME_PREV][1]=accum_p[1];
+  /*GOLDEN MVs are different from PREV MVs in that they're each absolute
+     offsets from some frame in the past rather than relative offsets from the
+     frame before.
+    For predictor calculation to make sense, we need them to be in the same
+     form as PREV MVs.*/
+  mvs[1][OC_FRAME_GOLD][0]-=mvs[2][OC_FRAME_GOLD][0];
+  mvs[1][OC_FRAME_GOLD][1]-=mvs[2][OC_FRAME_GOLD][1];
+  mvs[2][OC_FRAME_GOLD][0]-=accum_g[0];
+  mvs[2][OC_FRAME_GOLD][1]-=accum_g[1];
+  /*Search the golden frame.*/
+  oc_mcenc_search_frame(_enc,accum_g,_mbi,OC_FRAME_GOLD);
+  /*Put GOLDEN MVs back into absolute offset form.
+    The newest MV is already an absolute offset.*/
+  mvs[2][OC_FRAME_GOLD][0]+=accum_g[0];
+  mvs[2][OC_FRAME_GOLD][1]+=accum_g[1];
+  mvs[1][OC_FRAME_GOLD][0]+=mvs[2][OC_FRAME_GOLD][0];
+  mvs[1][OC_FRAME_GOLD][1]+=mvs[2][OC_FRAME_GOLD][1];
+}
+
 #if 0
 static int oc_mcenc_ysad_halfpel_mbrefine(const oc_enc_ctx *_enc,int _mbi,
  int _vec[2],int _best_err,int _frame){

Modified: branches/theora-thusnelda/lib/enc/rate.c
===================================================================
--- branches/theora-thusnelda/lib/enc/rate.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/rate.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -43,9 +43,11 @@
   return best_qi;
 }
 
-void oc_enc_calc_lambda(oc_enc_ctx *_enc,int _frame_type){
+void oc_enc_calc_lambda(oc_enc_ctx *_enc,int _qti){
   ogg_int64_t lq;
   int         qi;
+  int         qi1;
+  int         nqis;
   /*For now, lambda is fixed depending on the qi value and frame type:
       lambda=qscale*(qavg[qti][qi]**2),
      where qscale=0.2125.
@@ -61,9 +63,38 @@
      to reach, and give the rate control a semblance of "fractional qi"
      precision.*/
   if(_enc->state.info.target_bitrate>0)lq=_enc->rc.log_qtarget;
-  else lq=_enc->log_qavg[_frame_type][qi];
+  else lq=_enc->log_qavg[_qti][qi];
   /*The resulting lambda value is less than 0x500000.*/
   _enc->lambda=(int)oc_bexp64(2*lq-0x4780BD468D6B62BLL);
+  /*Select additional quantizers.
+    The R-D optimal block AC quantizer statistics suggest that the distribution
+     is roughly Gaussian-like with a slight positive skew.
+    K-means clustering on log_qavg to select 3 quantizers produces cluster
+     centers of {log_qavg-0.6,log_qavg,log_qavg+0.7}.
+    Experiments confirm these are relatively good choices.
+
+    Although we do greedy R-D optimization of the qii flags to avoid switching
+     too frequently, this becomes ineffective at low rates, either because we
+     do a poor job of predicting the actual R-D cost, or the greedy
+     optimization is not sufficient.
+    Therefore adaptive quantization is disabled above an (experimentally
+     suggested) threshold of log_qavg=7.00 (e.g., below INTRA qi=12 or
+     INTER qi=20 with current matrices).
+    This may need to be revised if the R-D cost estimation or qii flag
+     optimization strategies change.*/
+  nqis=1;
+  if(lq<(OC_Q57(56)>>3)&&!_enc->vp3_compatible){
+    qi1=oc_enc_find_qi_for_target(_enc,_qti,OC_MAXI(qi-1,0),0,
+     lq+(OC_Q57(7)+5)/10);
+    if(qi1!=qi)_enc->state.qis[nqis++]=qi1;
+    qi1=oc_enc_find_qi_for_target(_enc,_qti,OC_MINI(qi+1,63),0,
+     lq-(OC_Q57(6)+5)/10);
+    if(qi1!=qi&&qi1!=_enc->state.qis[nqis-1])_enc->state.qis[nqis++]=qi1;
+  }
+  /*printf("%i %.3f:",_qti,oc_bexp64(lq+OC_Q57(3))*0.125);
+  for(qi=0;qi<nqis;qi++)printf(" %2i",_enc->state.qis[qi]);
+  printf("\n");*/
+  _enc->state.nqis=nqis;
 }
 
 
@@ -130,25 +161,27 @@
 }
 
 int oc_enc_update_rc_state(oc_enc_ctx *_enc,
-                           long _bits,int _qti,int _qi,int _trial,int _droppable){
-
+ long _bits,int _qti,int _qi,int _trial,int _droppable){
   /*Note, setting OC_SCALE_SMOOTHING[1] to 0x80 (0.5), which one might expect
-    to be a reasonable value, actually causes a feedback loop with, e.g., 12
-    fps content encoded at 24 fps; use values near 0 or near 1 for now.
+     to be a reasonable value, actually causes a feedback loop with, e.g., 12
+     fps content encoded at 24 fps; use values near 0 or near 1 for now.
     TODO: Should probably revisit using an exponential moving average in the
-    first place at some point; dup tracking should help as well.*/
+     first place at some point; dup tracking should help as well.*/
   static const unsigned OC_SCALE_SMOOTHING[2]={0x13,0x00};
-  int dropped=0;
-
+  ogg_int64_t buf_delta;
+  int         dropped;
+  dropped=0;
+  buf_delta=_enc->rc.bits_per_frame*(1+_enc->dup_count);
   if(_bits<=0){
-     /*  Update the buffering stats as if this dropped frame was a dup
-         of the previous frame. */
+    /*We didn't code any blocks in this frame.
+      Add it to the previous frame's dup count.*/
     _enc->rc.prev_drop_count+=1+_enc->dup_count;
     /*If this was the first frame of this type, lower the expected scale, but
        don't set it to zero outright.*/
     if(_trial)_enc->rc.log_scale[_qti]>>=1;
     _bits=0;
-  }else{
+  }
+  else{
     ogg_int64_t log_scale;
     ogg_int64_t log_bits;
     ogg_int64_t log_qexp;
@@ -160,30 +193,30 @@
     /*Use it to set that factor directly if this was a trial.*/
     if(_trial)_enc->rc.log_scale[_qti]=log_scale;
     else{
-      /*Otherwise update an exponential moving average.*/
-      /*log scale is updated regardless of dropping*/
+      /*Otherwise update an exponential moving average for log_scale,
+         regardless of whether or not we dropped this frame.*/
       _enc->rc.log_scale[_qti]=log_scale
-        +(_enc->rc.log_scale[_qti]-log_scale+128>>8)*OC_SCALE_SMOOTHING[_qti];
-      /* If this frame busts our budget, it must be dropped.*/
-      if(_droppable && _enc->rc.fullness+_enc->rc.bits_per_frame*
-         (1+_enc->dup_count)<_bits){
+       +(_enc->rc.log_scale[_qti]-log_scale+128>>8)*OC_SCALE_SMOOTHING[_qti];
+      /*If this frame busts our budget, it must be dropped.*/
+      if(_droppable&&_enc->rc.fullness+buf_delta<_bits){
         _enc->rc.prev_drop_count+=1+_enc->dup_count;
         _bits=0;
         dropped=1;
-      }else{
-        /*log_drop_scale is only updated if the frame is coded as it
-          needs final previous counts*/
-        /*update a simple exponential moving average to estimate the "real"
-          frame rate taking drops and duplicates into account.*/
+      }
+      else{
+        /*Update a simple exponential moving average to estimate the "real"
+           frame rate taking drops and duplicates into account.
+          This is only done if the frame is coded, as it needs the final count
+           of dropped frames.*/
         _enc->rc.log_drop_scale=_enc->rc.log_drop_scale
-          +oc_blog64(_enc->rc.prev_drop_count+1)>>1;
+         +oc_blog64(_enc->rc.prev_drop_count+1)>>1;
         _enc->rc.prev_drop_count=_enc->dup_count;
       }
     }
   }
   if(!_trial){
     /*And update the buffer fullness level.*/
-    _enc->rc.fullness+=_enc->rc.bits_per_frame*(1+_enc->dup_count)-_bits;
+    _enc->rc.fullness+=buf_delta-_bits;
     /*If we're too quick filling the buffer, that rate is lost forever.*/
     if(_enc->rc.fullness>_enc->rc.max)_enc->rc.fullness=_enc->rc.max;
   }
@@ -207,8 +240,8 @@
   nframes[0]=(_enc->rc.buf_delay-OC_MINI(next_key_frame,_enc->rc.buf_delay)
    +_enc->keyframe_frequency_force-1)/_enc->keyframe_frequency_force;
   if(nframes[0]+_qti>1){
-    buf_delay=next_key_frame+(nframes[0]-1)*_enc->keyframe_frequency_force;
     nframes[0]--;
+    buf_delay=next_key_frame+nframes[0]*_enc->keyframe_frequency_force;
   }
   else buf_delay=_enc->rc.buf_delay;
   nframes[1]=buf_delay-nframes[0];
@@ -290,7 +323,7 @@
     ogg_int64_t log_qexp;
     int         exp0;
     /*Allow 50% of the rate for a single frame for prediction error.
-      This may not be enough for keyframes.*/
+      This may not be enough for keyframes or sudden changes in complexity.*/
     log_hard_limit=oc_blog64(_enc->rc.fullness+(_enc->rc.bits_per_frame>>1));
     exp0=_enc->rc.exp[_qti];
     log_qexp=log_qtarget-OC_Q57(2);

Modified: branches/theora-thusnelda/lib/enc/tokenize.c
===================================================================
--- branches/theora-thusnelda/lib/enc/tokenize.c	2009-07-22 00:56:19 UTC (rev 16313)
+++ branches/theora-thusnelda/lib/enc/tokenize.c	2009-07-22 01:56:26 UTC (rev 16314)
@@ -239,11 +239,11 @@
   for(zzi=OC_MINI(_zzi,63);zzi>0;zzi--){
     ogg_int32_t  lambda;
     ogg_uint32_t best_cost;
-    int          best_bits;
-    int          best_next;
-    int          best_token;
-    int          best_eb;
-    int          best_qc;
+    int          best_bits=best_bits;
+    int          best_next=best_next;
+    int          best_token=best_token;
+    int          best_eb=best_eb;
+    int          best_qc=best_qc;
     int          flush_bits;
     ogg_uint32_t d2;
     int          dq;
@@ -306,7 +306,7 @@
           bits=flush_bits+oc_token_bits(_enc,huffi,zzi,token);
           d2=sum_d2-d2_accum[zzj];
           cost=d2+lambda*bits+tokens[zzj][1].cost;
-          if(cost<best_cost){
+          if(cost<=best_cost){
             best_next=(zzj<<1)+1;
             best_token=token;
             best_eb=nzeros-1;
@@ -318,24 +318,6 @@
             val=_qdct[zzj];
             val_s=-(val<0);
             val=val+val_s^val_s;
-            if(nzeros<2+dc_reserve&&2<=val&&val<=4){
-              /*Try a +/- 2/3 combo token.*/
-              cat=nzeros>>1;
-              token=OC_DCT_RUN_CAT2A+cat;
-              bits=flush_bits+oc_token_bits(_enc,huffi,zzi,token);
-              val=2+((val+val_s^val_s)>2);
-              e=(_dct[OC_FZIG_ZAG[zzj]]+val_s^val_s)-_dequant[zzj]*val;
-              d2=e*(ogg_int32_t)e+sum_d2-d2_accum[zzj];
-              cost=d2+lambda*bits+tokens[zzk][tk].cost;
-              if(cost<=best_cost){
-                best_cost=cost;
-                best_bits=bits+tokens[zzk][tk].bits;
-                best_next=next;
-                best_token=token;
-                best_eb=(-val_s<<1+cat)+(val-2<<cat)+(nzeros-1>>1);
-                best_qc=val+val_s^val_s;
-              }
-            }
             if(val<=2){
               /*Try a +/- 1 combo token.*/
               if(nzeros<6){
@@ -360,6 +342,24 @@
                 best_qc=1+val_s^val_s;
               }
             }
+            if(nzeros<2+dc_reserve&&2<=val&&val<=4){
+              /*Try a +/- 2/3 combo token.*/
+              cat=nzeros>>1;
+              token=OC_DCT_RUN_CAT2A+cat;
+              bits=flush_bits+oc_token_bits(_enc,huffi,zzi,token);
+              val=2+((val+val_s^val_s)>2);
+              e=(_dct[OC_FZIG_ZAG[zzj]]+val_s^val_s)-_dequant[zzj]*val;
+              d2=e*(ogg_int32_t)e+sum_d2-d2_accum[zzj];
+              cost=d2+lambda*bits+tokens[zzk][tk].cost;
+              if(cost<=best_cost){
+                best_cost=cost;
+                best_bits=bits+tokens[zzk][tk].bits;
+                best_next=next;
+                best_token=token;
+                best_eb=(-val_s<<1+cat)+(val-2<<cat)+(nzeros-1>>1);
+                best_qc=val+val_s^val_s;
+              }
+            }
           }
           /*zzj can't be coded as a zero, so stop trying to extend the run.*/
           if(!(zflags>>zzj&1))break;
@@ -634,8 +634,7 @@
     eob=eob_run[zzi];
     if(tokens[zzi][ti].token<OC_NDCT_EOB_TOKEN_MAX){
       if(++eob>=4095){
-        token=oc_make_eob_token_full(eob,&eb);
-        oc_enc_token_log(_enc,_pli,zzi,token,eb);
+        oc_enc_eob_log(_enc,_pli,zzi,eob);
         eob=0;
       }
       eob_run[zzi]=eob;
@@ -672,7 +671,6 @@
   ptrdiff_t                fragi;
   int                     *pred_last;
   int                      nhfrags;
-  int                      nvfrags;
   int                      fragx;
   int                      fragy;
   fplane=_enc->state.fplanes+_pli;
@@ -680,7 +678,6 @@
   frag_dc=_enc->frag_dc;
   pred_last=_enc->dc_pred_last[_pli];
   nhfrags=fplane->nhfrags;
-  nvfrags=fplane->nvfrags;
   fragi=fplane->froffset+_fragy0*nhfrags;
   for(fragy=_fragy0;fragy<_frag_yend;fragy++){
     for(fragx=0;fragx<nhfrags;fragx++,fragi++){
@@ -710,10 +707,8 @@
   int                neobs1;
   int                token;
   int                eb;
-  /*eb1 and token1 are always initialized before use; if your compiler thinks
-     otherwise, it is dumb.*/
-  int                token1;
-  int                eb1;
+  int                token1=token1;
+  int                eb1=eb1;
   /*Return immediately if there are no coded fragments; otherwise we'd flush
      any trailing EOB run into the AC 1 list and never read it back out.*/
   if(_ncoded_fragis<=0)return;
@@ -952,9 +947,7 @@
     int       new_eb;
     int       zzj;
     int       plj;
-    /*ti is always initialized before use; if your compiler thinks otherwise,
-       it is dumb.*/
-    ptrdiff_t ti;
+    ptrdiff_t ti=ti;
     int       run_count;
     /*Make sure this coefficient has tokens at all.*/
     if(_enc->ndct_tokens[pli][zzi]<=0)continue;



More information about the commits mailing list