Merge "Prevent invaid memory access"
diff --git a/build/make/rtcd.sh b/build/make/rtcd.sh
index 2967b5a..ed03713 100755
--- a/build/make/rtcd.sh
+++ b/build/make/rtcd.sh
@@ -209,6 +209,10 @@
 #define RTCD_EXTERN extern
 #endif
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 $(process_forward_decls)
 
 $(declare_function_pointers c $ALL_ARCHS)
@@ -219,6 +223,11 @@
 
 common_bottom() {
   cat <<EOF
+
+#ifdef __cplusplus
+}  // extern "C"
+#endif
+
 #endif
 EOF
 }
diff --git a/test/codec_factory.h b/test/codec_factory.h
index 2ca6ff0..c060e86 100644
--- a/test/codec_factory.h
+++ b/test/codec_factory.h
@@ -10,7 +10,6 @@
 #ifndef TEST_CODEC_FACTORY_H_
 #define TEST_CODEC_FACTORY_H_
 
-extern "C" {
 #include "./vpx_config.h"
 #include "vpx/vpx_decoder.h"
 #include "vpx/vpx_encoder.h"
@@ -20,7 +19,6 @@
 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
 #include "vpx/vp8dx.h"
 #endif
-}
 
 #include "test/decode_test_driver.h"
 #include "test/encode_test_driver.h"
diff --git a/test/idct8x8_test.cc b/test/idct8x8_test.cc
index d8c61ff..5f4c33a 100644
--- a/test/idct8x8_test.cc
+++ b/test/idct8x8_test.cc
@@ -14,9 +14,7 @@
 
 #include "third_party/googletest/src/include/gtest/gtest.h"
 
-extern "C" {
 #include "./vp9_rtcd.h"
-}
 
 #include "test/acm_random.h"
 #include "vpx/vpx_integer.h"
diff --git a/test/idct_test.cc b/test/idct_test.cc
index 2c7fa0e..1bbf80a 100644
--- a/test/idct_test.cc
+++ b/test/idct_test.cc
@@ -8,10 +8,8 @@
  *  be found in the AUTHORS file in the root of the source tree.
  */
 
-extern "C" {
 #include "./vpx_config.h"
 #include "./vp8_rtcd.h"
-}
 #include "test/clear_system_state.h"
 #include "test/register_state_check.h"
 #include "third_party/googletest/src/include/gtest/gtest.h"
diff --git a/test/pp_filter_test.cc b/test/pp_filter_test.cc
index e5ac9db..ff7bb08 100644
--- a/test/pp_filter_test.cc
+++ b/test/pp_filter_test.cc
@@ -10,12 +10,10 @@
 #include "test/clear_system_state.h"
 #include "test/register_state_check.h"
 #include "third_party/googletest/src/include/gtest/gtest.h"
-extern "C" {
 #include "./vpx_config.h"
 #include "./vp8_rtcd.h"
 #include "vpx/vpx_integer.h"
 #include "vpx_mem/vpx_mem.h"
-}
 
 typedef void (*post_proc_func_t)(unsigned char *src_ptr,
                                  unsigned char *dst_ptr,
diff --git a/test/sad_test.cc b/test/sad_test.cc
index 453b3a8..4a91b0b 100644
--- a/test/sad_test.cc
+++ b/test/sad_test.cc
@@ -13,7 +13,6 @@
 #include <limits.h>
 #include <stdio.h>
 
-extern "C" {
 #include "./vpx_config.h"
 #if CONFIG_VP8_ENCODER
 #include "./vp8_rtcd.h"
@@ -22,7 +21,6 @@
 #include "./vp9_rtcd.h"
 #endif
 #include "vpx_mem/vpx_mem.h"
-}
 
 #include "test/acm_random.h"
 #include "test/clear_system_state.h"
diff --git a/test/sixtap_predict_test.cc b/test/sixtap_predict_test.cc
index 0f5c0a5..3434662 100644
--- a/test/sixtap_predict_test.cc
+++ b/test/sixtap_predict_test.cc
@@ -16,12 +16,10 @@
 #include "test/register_state_check.h"
 #include "test/util.h"
 #include "third_party/googletest/src/include/gtest/gtest.h"
-extern "C" {
 #include "./vpx_config.h"
 #include "./vp8_rtcd.h"
 #include "vpx/vpx_integer.h"
 #include "vpx_mem/vpx_mem.h"
-}
 
 namespace {
 
diff --git a/test/test_vector_test.cc b/test/test_vector_test.cc
index 6d93bb8..4adf9af 100644
--- a/test/test_vector_test.cc
+++ b/test/test_vector_test.cc
@@ -19,9 +19,7 @@
 #include "test/test_vectors.h"
 #include "test/util.h"
 #include "test/webm_video_source.h"
-extern "C" {
 #include "vpx_mem/vpx_mem.h"
-}
 
 namespace {
 
diff --git a/test/tile_independence_test.cc b/test/tile_independence_test.cc
index 863a366..d714452 100644
--- a/test/tile_independence_test.cc
+++ b/test/tile_independence_test.cc
@@ -17,9 +17,7 @@
 #include "test/i420_video_source.h"
 #include "test/util.h"
 #include "test/md5_helper.h"
-extern "C" {
 #include "vpx_mem/vpx_mem.h"
-}
 
 namespace {
 class TileIndependenceTest : public ::libvpx_test::EncoderTest,
diff --git a/test/vp8_fdct4x4_test.cc b/test/vp8_fdct4x4_test.cc
index 25465c5..e3c292e 100644
--- a/test/vp8_fdct4x4_test.cc
+++ b/test/vp8_fdct4x4_test.cc
@@ -15,9 +15,7 @@
 #include <string.h>
 #include <sys/types.h>
 
-extern "C" {
 #include "./vp8_rtcd.h"
-}
 
 #include "test/acm_random.h"
 #include "third_party/googletest/src/include/gtest/gtest.h"
diff --git a/vp8/encoder/arm/neon/denoising_neon.c b/vp8/encoder/arm/neon/denoising_neon.c
index d517dfa..3f85397 100644
--- a/vp8/encoder/arm/neon/denoising_neon.c
+++ b/vp8/encoder/arm/neon/denoising_neon.c
@@ -119,8 +119,10 @@
                                                      v_abs_adjustment);
         v_running_avg_y = vqaddq_u8(v_sig, v_pos_adjustment);
         v_running_avg_y = vqsubq_u8(v_running_avg_y, v_neg_adjustment);
-        v_sum_diff = vqaddq_s8(v_sum_diff, (int8x16_t)v_pos_adjustment);
-        v_sum_diff = vqsubq_s8(v_sum_diff, (int8x16_t)v_neg_adjustment);
+        v_sum_diff = vqaddq_s8(v_sum_diff,
+                               vreinterpretq_s8_u8(v_pos_adjustment));
+        v_sum_diff = vqsubq_s8(v_sum_diff,
+                               vreinterpretq_s8_u8(v_neg_adjustment));
 
         /* Store results. */
         vst1q_u8(running_avg_y, v_running_avg_y);
diff --git a/vp9/common/vp9_alloccommon.c b/vp9/common/vp9_alloccommon.c
index ff20553..ca42090 100644
--- a/vp9/common/vp9_alloccommon.c
+++ b/vp9/common/vp9_alloccommon.c
@@ -85,7 +85,7 @@
   int mi_size;
 
   if (vp9_realloc_frame_buffer(&cm->post_proc_buffer, width, height, ss_x, ss_y,
-                               VP9BORDERINPIXELS, NULL, NULL, NULL) < 0)
+                               VP9_DEC_BORDER_IN_PIXELS, NULL, NULL, NULL) < 0)
     goto fail;
 
   set_mb_mi(cm, aligned_width, aligned_height);
@@ -154,7 +154,7 @@
   for (i = 0; i < cm->fb_count; i++) {
     cm->fb_idx_ref_cnt[i] = 0;
     if (vp9_alloc_frame_buffer(&cm->yv12_fb[i], width, height, ss_x, ss_y,
-                               VP9BORDERINPIXELS) < 0)
+                               VP9_ENC_BORDER_IN_PIXELS) < 0)
       goto fail;
   }
 
@@ -167,7 +167,7 @@
   }
 
   if (vp9_alloc_frame_buffer(&cm->post_proc_buffer, width, height, ss_x, ss_y,
-                             VP9BORDERINPIXELS) < 0)
+                             VP9_ENC_BORDER_IN_PIXELS) < 0)
     goto fail;
 
   set_mb_mi(cm, aligned_width, aligned_height);
diff --git a/vp9/common/vp9_entropy.h b/vp9/common/vp9_entropy.h
index f43a85f..ba162fd 100644
--- a/vp9/common/vp9_entropy.h
+++ b/vp9/common/vp9_entropy.h
@@ -112,8 +112,8 @@
 // This macro is currently unused but may be used by certain implementations
 #define MAXBAND_INDEX 21
 
-extern const uint8_t vp9_coefband_trans_8x8plus[1024];
-extern const uint8_t vp9_coefband_trans_4x4[16];
+extern DECLARE_ALIGNED(16, const uint8_t, vp9_coefband_trans_8x8plus[1024]);
+extern DECLARE_ALIGNED(16, const uint8_t, vp9_coefband_trans_4x4[16]);
 
 static const uint8_t *get_band_translate(TX_SIZE tx_size) {
   return tx_size == TX_4X4 ? vp9_coefband_trans_4x4
diff --git a/vp9/common/vp9_mvref_common.h b/vp9/common/vp9_mvref_common.h
index 06adbab..cd89390 100644
--- a/vp9/common/vp9_mvref_common.h
+++ b/vp9/common/vp9_mvref_common.h
@@ -32,8 +32,10 @@
                        mv_ref_list, -1, mi_row, mi_col);
 }
 
-#define LEFT_TOP_MARGIN     ((VP9BORDERINPIXELS - VP9_INTERP_EXTEND) << 3)
-#define RIGHT_BOTTOM_MARGIN ((VP9BORDERINPIXELS - VP9_INTERP_EXTEND) << 3)
+#define LEFT_TOP_MARGIN     ((VP9_ENC_BORDER_IN_PIXELS  \
+                            - VP9_INTERP_EXTEND) << 3)
+#define RIGHT_BOTTOM_MARGIN ((VP9_ENC_BORDER_IN_PIXELS  \
+                            - VP9_INTERP_EXTEND) << 3)
 
 // check a list of motion vectors by sad score using a number rows of pixels
 // above and a number cols of pixels in the left to select the one with best
diff --git a/vp9/decoder/vp9_decodeframe.c b/vp9/decoder/vp9_decodeframe.c
index 59faccd..d66ee27 100644
--- a/vp9/decoder/vp9_decodeframe.c
+++ b/vp9/decoder/vp9_decodeframe.c
@@ -704,7 +704,7 @@
     if (vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
                                  cm->width, cm->height,
                                  cm->subsampling_x, cm->subsampling_y,
-                                 VP9BORDERINPIXELS, ext_fb,
+                                 VP9_DEC_BORDER_IN_PIXELS, ext_fb,
                                  cm->realloc_fb_cb, cm->user_priv)) {
       vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                          "Failed to allocate external frame buffer");
@@ -712,7 +712,7 @@
   } else {
     vp9_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
                              cm->subsampling_x, cm->subsampling_y,
-                             VP9BORDERINPIXELS, NULL, NULL, NULL);
+                             VP9_DEC_BORDER_IN_PIXELS, NULL, NULL, NULL);
   }
 }
 
@@ -1129,11 +1129,12 @@
 
   cm->show_existing_frame = vp9_rb_read_bit(rb);
   if (cm->show_existing_frame) {
-    // show an existing frame directly
+    // Show an existing frame directly.
     int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
     ref_cnt_fb(cm->fb_idx_ref_cnt, &cm->new_fb_idx, frame_to_show);
     pbi->refresh_frame_flags = 0;
     cm->lf.filter_level = 0;
+    cm->show_frame = 1;
     return 0;
   }
 
diff --git a/vp9/encoder/vp9_bitstream.c b/vp9/encoder/vp9_bitstream.c
index 2ab4c79..7188d76 100644
--- a/vp9/encoder/vp9_bitstream.c
+++ b/vp9/encoder/vp9_bitstream.c
@@ -746,7 +746,6 @@
   const TX_MODE tx_mode = cpi->common.tx_mode;
   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
   TX_SIZE tx_size;
-  vp9_clear_system_state();
 
   for (tx_size = TX_4X4; tx_size <= TX_32X32; ++tx_size)
     build_tree_distribution(cpi, tx_size);
@@ -1296,8 +1295,6 @@
     active_section = 7;
 #endif
 
-  vp9_clear_system_state();  // __asm emms;
-
   first_part_size = write_compressed_header(cpi, data);
   data += first_part_size;
   vp9_wb_write_literal(&saved_wb, first_part_size, 16);
diff --git a/vp9/encoder/vp9_encodemv.c b/vp9/encoder/vp9_encodemv.c
index af710a8..853094b 100644
--- a/vp9/encoder/vp9_encodemv.c
+++ b/vp9/encoder/vp9_encodemv.c
@@ -224,13 +224,9 @@
   }
 }
 
-void vp9_build_nmv_cost_table(int *mvjoint,
-                              int *mvcost[2],
+void vp9_build_nmv_cost_table(int *mvjoint, int *mvcost[2],
                               const nmv_context* const mvctx,
-                              int usehp,
-                              int mvc_flag_v,
-                              int mvc_flag_h) {
-  vp9_clear_system_state();
+                              int usehp, int mvc_flag_v, int mvc_flag_h) {
   vp9_cost_tokens(mvjoint, mvctx->joints, vp9_mv_joint_tree);
   if (mvc_flag_v)
     build_nmv_component_cost_table(mvcost[0], &mvctx->comps[0], usehp);
diff --git a/vp9/encoder/vp9_firstpass.c b/vp9/encoder/vp9_firstpass.c
index fe57af2..5cb8b53 100644
--- a/vp9/encoder/vp9_firstpass.c
+++ b/vp9/encoder/vp9_firstpass.c
@@ -394,42 +394,35 @@
 }
 
 static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
-                                     MV *ref_mv, MV *best_mv,
+                                     const MV *ref_mv, MV *best_mv,
                                      YV12_BUFFER_CONFIG *recon_buffer,
                                      int *best_motion_err, int recon_yoffset) {
   MACROBLOCKD *const xd = &x->e_mbd;
-  int num00;
-
   MV tmp_mv = {0, 0};
-  MV ref_mv_full;
-
-  int tmp_err;
+  MV ref_mv_full = {ref_mv->row >> 3, ref_mv->col >> 3};
+  int num00, tmp_err, n, sr = 0;
   int step_param = 3;
   int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
-  int n;
-  vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[xd->mi_8x8[0]->mbmi.sb_type];
+  const BLOCK_SIZE bsize = xd->mi_8x8[0]->mbmi.sb_type;
+  vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
   int new_mv_mode_penalty = 256;
-
-  int sr = 0;
-  int quart_frm = MIN(cpi->common.width, cpi->common.height);
+  const int quart_frm = MIN(cpi->common.width, cpi->common.height);
 
   // refine the motion search range accroding to the frame dimension
   // for first pass test
   while ((quart_frm << sr) < MAX_FULL_PEL_VAL)
     sr++;
 
-  step_param    += sr;
+  step_param += sr;
   further_steps -= sr;
 
   // override the default variance function to use MSE
-  v_fn_ptr.vf = get_block_variance_fn(xd->mi_8x8[0]->mbmi.sb_type);
+  v_fn_ptr.vf = get_block_variance_fn(bsize);
 
   // Set up pointers for this macro block recon buffer
   xd->plane[0].pre[0].buf = recon_buffer->y_buffer + recon_yoffset;
 
   // Initial step/diamond search centred on best mv
-  ref_mv_full.col = ref_mv->col >> 3;
-  ref_mv_full.row = ref_mv->row >> 3;
   tmp_err = cpi->diamond_search_sad(x, &ref_mv_full, &tmp_mv,
                                     step_param,
                                     x->sadperbit16, &num00, &v_fn_ptr,
@@ -504,6 +497,7 @@
   int new_mv_count = 0;
   int sum_in_vectors = 0;
   uint32_t lastmv_as_int = 0;
+  struct twopass_rc *const twopass = &cpi->twopass;
 
   int_mv zero_ref_mv;
 
@@ -830,23 +824,22 @@
     fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
 
     // don't want to do output stats with a stack variable!
-    cpi->twopass.this_frame_stats = fps;
-    output_stats(cpi, cpi->output_pkt_list, &cpi->twopass.this_frame_stats);
-    accumulate_stats(&cpi->twopass.total_stats, &fps);
+    twopass->this_frame_stats = fps;
+    output_stats(cpi, cpi->output_pkt_list, &twopass->this_frame_stats);
+    accumulate_stats(&twopass->total_stats, &fps);
   }
 
   // Copy the previous Last Frame back into gf and and arf buffers if
   // the prediction is good enough... but also dont allow it to lag too far
-  if ((cpi->twopass.sr_update_lag > 3) ||
+  if ((twopass->sr_update_lag > 3) ||
       ((cm->current_video_frame > 0) &&
-       (cpi->twopass.this_frame_stats.pcnt_inter > 0.20) &&
-       ((cpi->twopass.this_frame_stats.intra_error /
-         DOUBLE_DIVIDE_CHECK(cpi->twopass.this_frame_stats.coded_error)) >
-        2.0))) {
+       (twopass->this_frame_stats.pcnt_inter > 0.20) &&
+       ((twopass->this_frame_stats.intra_error /
+         DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
     vp8_yv12_copy_frame(lst_yv12, gld_yv12);
-    cpi->twopass.sr_update_lag = 1;
+    twopass->sr_update_lag = 1;
   } else {
-    cpi->twopass.sr_update_lag++;
+    twopass->sr_update_lag++;
   }
   // swap frame pointers so last frame refers to the frame we just compressed
   swap_yv12(lst_yv12, new_yv12);
@@ -1034,37 +1027,38 @@
 void vp9_init_second_pass(VP9_COMP *cpi) {
   FIRSTPASS_STATS this_frame;
   FIRSTPASS_STATS *start_pos;
+  struct twopass_rc *const twopass = &cpi->twopass;
 
-  zero_stats(&cpi->twopass.total_stats);
-  zero_stats(&cpi->twopass.total_left_stats);
+  zero_stats(&twopass->total_stats);
+  zero_stats(&twopass->total_left_stats);
 
-  if (!cpi->twopass.stats_in_end)
+  if (!twopass->stats_in_end)
     return;
 
-  cpi->twopass.total_stats = *cpi->twopass.stats_in_end;
-  cpi->twopass.total_left_stats = cpi->twopass.total_stats;
+  twopass->total_stats = *twopass->stats_in_end;
+  twopass->total_left_stats = twopass->total_stats;
 
   // each frame can have a different duration, as the frame rate in the source
   // isn't guaranteed to be constant.   The frame rate prior to the first frame
   // encoded in the second pass is a guess.  However the sum duration is not.
   // Its calculated based on the actual durations of all frames from the first
   // pass.
-  vp9_new_framerate(cpi, 10000000.0 * cpi->twopass.total_stats.count /
-                       cpi->twopass.total_stats.duration);
+  vp9_new_framerate(cpi, 10000000.0 * twopass->total_stats.count /
+                        twopass->total_stats.duration);
 
   cpi->output_framerate = cpi->oxcf.framerate;
-  cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats.duration *
-                                     cpi->oxcf.target_bandwidth / 10000000.0);
+  twopass->bits_left = (int64_t)(twopass->total_stats.duration *
+                                 cpi->oxcf.target_bandwidth / 10000000.0);
 
   // Calculate a minimum intra value to be used in determining the IIratio
   // scores used in the second pass. We have this minimum to make sure
   // that clips that are static but "low complexity" in the intra domain
   // are still boosted appropriately for KF/GF/ARF
-  cpi->twopass.kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
-  cpi->twopass.gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
+  twopass->kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
+  twopass->gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
 
   // This variable monitors how far behind the second ref update is lagging
-  cpi->twopass.sr_update_lag = 1;
+  twopass->sr_update_lag = 1;
 
   // Scan the first pass file and calculate an average Intra / Inter error score
   // ratio for the sequence.
@@ -1072,43 +1066,43 @@
     double sum_iiratio = 0.0;
     double IIRatio;
 
-    start_pos = cpi->twopass.stats_in;  // Note the starting "file" position.
+    start_pos = twopass->stats_in;  // Note the starting "file" position.
 
-    while (input_stats(&cpi->twopass, &this_frame) != EOF) {
+    while (input_stats(twopass, &this_frame) != EOF) {
       IIRatio = this_frame.intra_error
                 / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
       IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
       sum_iiratio += IIRatio;
     }
 
-    cpi->twopass.avg_iiratio = sum_iiratio /
-        DOUBLE_DIVIDE_CHECK((double)cpi->twopass.total_stats.count);
+    twopass->avg_iiratio = sum_iiratio /
+        DOUBLE_DIVIDE_CHECK((double)twopass->total_stats.count);
 
     // Reset file position
-    reset_fpf_position(&cpi->twopass, start_pos);
+    reset_fpf_position(twopass, start_pos);
   }
 
   // Scan the first pass file and calculate a modified total error based upon
   // the bias/power function used to allocate bits.
   {
-    double av_error = cpi->twopass.total_stats.ssim_weighted_pred_err /
-                      DOUBLE_DIVIDE_CHECK(cpi->twopass.total_stats.count);
+    double av_error = twopass->total_stats.ssim_weighted_pred_err /
+                      DOUBLE_DIVIDE_CHECK(twopass->total_stats.count);
 
-    start_pos = cpi->twopass.stats_in;  // Note starting "file" position
+    start_pos = twopass->stats_in;  // Note starting "file" position
 
-    cpi->twopass.modified_error_total = 0.0;
-    cpi->twopass.modified_error_min =
+    twopass->modified_error_total = 0.0;
+    twopass->modified_error_min =
       (av_error * cpi->oxcf.two_pass_vbrmin_section) / 100;
-    cpi->twopass.modified_error_max =
+    twopass->modified_error_max =
       (av_error * cpi->oxcf.two_pass_vbrmax_section) / 100;
 
-    while (input_stats(&cpi->twopass, &this_frame) != EOF) {
-      cpi->twopass.modified_error_total +=
+    while (input_stats(twopass, &this_frame) != EOF) {
+      twopass->modified_error_total +=
           calculate_modified_err(cpi, &this_frame);
     }
-    cpi->twopass.modified_error_left = cpi->twopass.modified_error_total;
+    twopass->modified_error_left = twopass->modified_error_total;
 
-    reset_fpf_position(&cpi->twopass, start_pos);  // Reset file position
+    reset_fpf_position(twopass, start_pos);
   }
 }
 
@@ -2232,12 +2226,13 @@
   double recent_loop_decay[8] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
 
   RATE_CONTROL *const rc = &cpi->rc;
+  struct twopass_rc *const twopass = &cpi->twopass;
 
   vp9_zero(next_frame);
 
   vp9_clear_system_state();  // __asm emms;
 
-  start_position = cpi->twopass.stats_in;
+  start_position = twopass->stats_in;
   cpi->common.frame_type = KEY_FRAME;
 
   // is this a forced key frame by interval
@@ -2254,14 +2249,14 @@
   // Take a copy of the initial frame details
   first_frame = *this_frame;
 
-  cpi->twopass.kf_group_bits = 0;        // Total bits available to kf group
-  cpi->twopass.kf_group_error_left = 0;  // Group modified error score.
+  twopass->kf_group_bits = 0;        // Total bits available to kf group
+  twopass->kf_group_error_left = 0;  // Group modified error score.
 
   kf_mod_err = calculate_modified_err(cpi, this_frame);
 
   // find the next keyframe
   i = 0;
-  while (cpi->twopass.stats_in < cpi->twopass.stats_in_end) {
+  while (twopass->stats_in < twopass->stats_in_end) {
     // Accumulate kf group error
     kf_group_err += calculate_modified_err(cpi, this_frame);
 
@@ -2273,11 +2268,11 @@
 
     // load a the next frame's stats
     last_frame = *this_frame;
-    input_stats(&cpi->twopass, this_frame);
+    input_stats(twopass, this_frame);
 
     // Provided that we are not at the end of the file...
     if (cpi->oxcf.auto_key &&
-        lookup_next_frame_stats(&cpi->twopass, &next_frame) != EOF) {
+        lookup_next_frame_stats(twopass, &next_frame) != EOF) {
       // Normal scene cut check
       if (test_candidate_kf(cpi, &last_frame, this_frame, &next_frame))
         break;
@@ -2327,7 +2322,7 @@
     tmp_frame = first_frame;
 
     // Reset to the start of the group
-    reset_fpf_position(&cpi->twopass, start_position);
+    reset_fpf_position(twopass, start_position);
 
     kf_group_err = 0;
     kf_group_intra_err = 0;
@@ -2341,17 +2336,17 @@
       kf_group_coded_err += tmp_frame.coded_error;
 
       // Load a the next frame's stats
-      input_stats(&cpi->twopass, &tmp_frame);
+      input_stats(twopass, &tmp_frame);
     }
     rc->next_key_frame_forced = 1;
-  } else if (cpi->twopass.stats_in == cpi->twopass.stats_in_end) {
+  } else if (twopass->stats_in == twopass->stats_in_end) {
     rc->next_key_frame_forced = 1;
   } else {
     rc->next_key_frame_forced = 0;
   }
 
   // Special case for the last key frame of the file
-  if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) {
+  if (twopass->stats_in >= twopass->stats_in_end) {
     // Accumulate kf group error
     kf_group_err += calculate_modified_err(cpi, this_frame);
 
@@ -2363,8 +2358,7 @@
   }
 
   // Calculate the number of bits that should be assigned to the kf group.
-  if ((cpi->twopass.bits_left > 0) &&
-      (cpi->twopass.modified_error_left > 0.0)) {
+  if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
     // Max for a single normal frame (not key frame)
     int max_bits = frame_max_bits(cpi);
 
@@ -2373,19 +2367,18 @@
 
     // Default allocation based on bits left and relative
     // complexity of the section
-    cpi->twopass.kf_group_bits = (int64_t)(cpi->twopass.bits_left *
-                                           (kf_group_err /
-                                            cpi->twopass.modified_error_left));
+    twopass->kf_group_bits = (int64_t)(twopass->bits_left *
+       (kf_group_err / twopass->modified_error_left));
 
     // Clip based on maximum per frame rate defined by the user.
     max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
-    if (cpi->twopass.kf_group_bits > max_grp_bits)
-      cpi->twopass.kf_group_bits = max_grp_bits;
+    if (twopass->kf_group_bits > max_grp_bits)
+      twopass->kf_group_bits = max_grp_bits;
   } else {
-    cpi->twopass.kf_group_bits = 0;
+    twopass->kf_group_bits = 0;
   }
   // Reset the first pass file position
-  reset_fpf_position(&cpi->twopass, start_position);
+  reset_fpf_position(twopass, start_position);
 
   // Determine how big to make this keyframe based on how well the subsequent
   // frames use inter blocks.
@@ -2397,7 +2390,7 @@
   for (i = 0; i < rc->frames_to_key; i++) {
     double r;
 
-    if (EOF == input_stats(&cpi->twopass, &next_frame))
+    if (EOF == input_stats(twopass, &next_frame))
       break;
 
     // Monitor for static sections.
@@ -2409,11 +2402,11 @@
 
     // For the first few frames collect data to decide kf boost.
     if (i <= (rc->max_gf_interval * 2)) {
-      if (next_frame.intra_error > cpi->twopass.kf_intra_err_min)
+      if (next_frame.intra_error > twopass->kf_intra_err_min)
         r = (IIKFACTOR2 * next_frame.intra_error /
              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
       else
-        r = (IIKFACTOR2 * cpi->twopass.kf_intra_err_min /
+        r = (IIKFACTOR2 * twopass->kf_intra_err_min /
              DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
 
       if (r > RMAX)
@@ -2435,21 +2428,21 @@
     FIRSTPASS_STATS sectionstats;
 
     zero_stats(&sectionstats);
-    reset_fpf_position(&cpi->twopass, start_position);
+    reset_fpf_position(twopass, start_position);
 
     for (i = 0; i < rc->frames_to_key; i++) {
-      input_stats(&cpi->twopass, &next_frame);
+      input_stats(twopass, &next_frame);
       accumulate_stats(&sectionstats, &next_frame);
     }
 
     avg_stats(&sectionstats);
 
-    cpi->twopass.section_intra_rating = (int) (sectionstats.intra_error /
+    twopass->section_intra_rating = (int) (sectionstats.intra_error /
         DOUBLE_DIVIDE_CHECK(sectionstats.coded_error));
   }
 
   // Reset the first pass file position
-  reset_fpf_position(&cpi->twopass, start_position);
+  reset_fpf_position(twopass, start_position);
 
   // Work out how many bits to allocate for the key frame itself
   if (1) {
@@ -2466,7 +2459,7 @@
     // Make a note of baseline boost and the zero motion
     // accumulator value for use elsewhere.
     rc->kf_boost = kf_boost;
-    cpi->twopass.kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
+    twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
 
     // We do three calculations for kf size.
     // The first is based on the error score for the whole kf group.
@@ -2481,11 +2474,9 @@
     // cpi->rc.frames_to_key-1 because key frame itself is taken
     // care of by kf_boost.
     if (zero_motion_accumulator >= 0.99) {
-      allocation_chunks =
-        ((rc->frames_to_key - 1) * 10) + kf_boost;
+      allocation_chunks = ((rc->frames_to_key - 1) * 10) + kf_boost;
     } else {
-      allocation_chunks =
-        ((rc->frames_to_key - 1) * 100) + kf_boost;
+      allocation_chunks = ((rc->frames_to_key - 1) * 100) + kf_boost;
     }
 
     // Prevent overflow
@@ -2495,58 +2486,54 @@
       allocation_chunks /= divisor;
     }
 
-    cpi->twopass.kf_group_bits = (cpi->twopass.kf_group_bits < 0) ? 0
-           : cpi->twopass.kf_group_bits;
+    twopass->kf_group_bits = (twopass->kf_group_bits < 0) ? 0
+           : twopass->kf_group_bits;
 
     // Calculate the number of bits to be spent on the key frame
-    cpi->twopass.kf_bits = (int)((double)kf_boost *
-              ((double)cpi->twopass.kf_group_bits / (double)allocation_chunks));
+    twopass->kf_bits = (int)((double)kf_boost *
+        ((double)twopass->kf_group_bits / allocation_chunks));
 
     // If the key frame is actually easier than the average for the
     // kf group (which does sometimes happen... eg a blank intro frame)
     // Then use an alternate calculation based on the kf error score
     // which should give a smaller key frame.
     if (kf_mod_err < kf_group_err / rc->frames_to_key) {
-      double  alt_kf_grp_bits =
-        ((double)cpi->twopass.bits_left *
+      double  alt_kf_grp_bits = ((double)twopass->bits_left *
          (kf_mod_err * (double)rc->frames_to_key) /
-         DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left));
+         DOUBLE_DIVIDE_CHECK(twopass->modified_error_left));
 
       alt_kf_bits = (int)((double)kf_boost *
                           (alt_kf_grp_bits / (double)allocation_chunks));
 
-      if (cpi->twopass.kf_bits > alt_kf_bits) {
-        cpi->twopass.kf_bits = alt_kf_bits;
-      }
+      if (twopass->kf_bits > alt_kf_bits)
+        twopass->kf_bits = alt_kf_bits;
     } else {
     // Else if it is much harder than other frames in the group make sure
     // it at least receives an allocation in keeping with its relative
     // error score
-      alt_kf_bits = (int)((double)cpi->twopass.bits_left *
-              (kf_mod_err /
-               DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left)));
+      alt_kf_bits = (int)((double)twopass->bits_left * (kf_mod_err /
+               DOUBLE_DIVIDE_CHECK(twopass->modified_error_left)));
 
-      if (alt_kf_bits > cpi->twopass.kf_bits) {
-        cpi->twopass.kf_bits = alt_kf_bits;
+      if (alt_kf_bits > twopass->kf_bits) {
+        twopass->kf_bits = alt_kf_bits;
       }
     }
 
-    cpi->twopass.kf_group_bits -= cpi->twopass.kf_bits;
+    twopass->kf_group_bits -= twopass->kf_bits;
 
     // Peer frame bit target for this frame
-    rc->per_frame_bandwidth = cpi->twopass.kf_bits;
+    rc->per_frame_bandwidth = twopass->kf_bits;
     // Convert to a per second bitrate
-    cpi->target_bandwidth = (int)(cpi->twopass.kf_bits *
-                                  cpi->output_framerate);
+    cpi->target_bandwidth = (int)(twopass->kf_bits * cpi->output_framerate);
   }
 
   // Note the total error score of the kf group minus the key frame itself
-  cpi->twopass.kf_group_error_left = (int)(kf_group_err - kf_mod_err);
+  twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
 
   // Adjust the count of total modified error left.
   // The count of bits left is adjusted elsewhere based on real coded frame
   // sizes.
-  cpi->twopass.modified_error_left -= kf_group_err;
+  twopass->modified_error_left -= kf_group_err;
 }
 
 void vp9_twopass_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
diff --git a/vp9/encoder/vp9_lookahead.c b/vp9/encoder/vp9_lookahead.c
index 277bd7d..ee73ff1 100644
--- a/vp9/encoder/vp9_lookahead.c
+++ b/vp9/encoder/vp9_lookahead.c
@@ -73,7 +73,7 @@
     for (i = 0; i < depth; i++)
       if (vp9_alloc_frame_buffer(&ctx->buf[i].img,
                                  width, height, subsampling_x, subsampling_y,
-                                 VP9BORDERINPIXELS))
+                                 VP9_ENC_BORDER_IN_PIXELS))
         goto bail;
   }
   return ctx;
diff --git a/vp9/encoder/vp9_onyx_if.c b/vp9/encoder/vp9_onyx_if.c
index 59d36ee..9d24b09 100644
--- a/vp9/encoder/vp9_onyx_if.c
+++ b/vp9/encoder/vp9_onyx_if.c
@@ -968,7 +968,7 @@
   if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
                                cpi->oxcf.width, cpi->oxcf.height,
                                cm->subsampling_x, cm->subsampling_y,
-                               VP9BORDERINPIXELS, NULL, NULL, NULL))
+                               VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                        "Failed to allocate altref buffer");
 }
@@ -983,14 +983,14 @@
   if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
                              cm->width, cm->height,
                              cm->subsampling_x, cm->subsampling_y,
-                             VP9BORDERINPIXELS))
+                             VP9_ENC_BORDER_IN_PIXELS))
     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                        "Failed to allocate last frame buffer");
 
   if (vp9_alloc_frame_buffer(&cpi->scaled_source,
                              cm->width, cm->height,
                              cm->subsampling_x, cm->subsampling_y,
-                             VP9BORDERINPIXELS))
+                             VP9_ENC_BORDER_IN_PIXELS))
     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                        "Failed to allocate scaled source buffer");
 
@@ -1036,14 +1036,14 @@
   if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
                                cm->width, cm->height,
                                cm->subsampling_x, cm->subsampling_y,
-                               VP9BORDERINPIXELS, NULL, NULL, NULL))
+                               VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                        "Failed to reallocate last frame buffer");
 
   if (vp9_realloc_frame_buffer(&cpi->scaled_source,
                                cm->width, cm->height,
                                cm->subsampling_x, cm->subsampling_y,
-                               VP9BORDERINPIXELS, NULL, NULL, NULL))
+                               VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
                        "Failed to reallocate scaled source buffer");
 
@@ -2552,7 +2552,7 @@
       vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
                                cm->width, cm->height,
                                cm->subsampling_x, cm->subsampling_y,
-                               VP9BORDERINPIXELS, NULL, NULL, NULL);
+                               VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
       scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
       cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
     } else {
@@ -3279,12 +3279,12 @@
   vp9_twopass_postencode_update(cpi, *size);
 }
 
-static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
+static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
+                                int subsampling_y) {
   VP9_COMMON *const cm = &cpi->common;
   if (!cpi->initial_width) {
-    // TODO(agrange) Subsampling defaults to assuming sampled chroma.
-    cm->subsampling_x = sd != NULL ? (sd->uv_width < sd->y_width) : 1;
-    cm->subsampling_y = sd != NULL ? (sd->uv_height < sd->y_height) : 1;
+    cm->subsampling_x = subsampling_x;
+    cm->subsampling_y = subsampling_y;
     alloc_raw_frame_buffers(cpi);
     cpi->initial_width = cm->width;
     cpi->initial_height = cm->height;
@@ -3298,8 +3298,10 @@
   VP9_COMP              *cpi = (VP9_COMP *) ptr;
   struct vpx_usec_timer  timer;
   int                    res = 0;
+  const int    subsampling_x = sd->uv_width  < sd->y_width;
+  const int    subsampling_y = sd->uv_height < sd->y_height;
 
-  check_initial_width(cpi, sd);
+  check_initial_width(cpi, subsampling_x, subsampling_y);
   vpx_usec_timer_start(&timer);
   if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
                          cpi->active_map_enabled ? cpi->active_map : NULL))
@@ -3377,7 +3379,6 @@
   struct vpx_usec_timer  cmptimer;
   YV12_BUFFER_CONFIG *force_src_buffer = NULL;
   MV_REFERENCE_FRAME ref_frame;
-  // FILE *fp_out = fopen("enc_frame_type.txt", "a");
 
   if (!cpi)
     return -1;
@@ -3499,8 +3500,6 @@
       vp9_end_first_pass(cpi);    /* get last stats packet */
       cpi->twopass.first_pass_done = 1;
     }
-
-    // fclose(fp_out);
     return -1;
   }
 
@@ -3543,7 +3542,7 @@
   vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
                            cm->width, cm->height,
                            cm->subsampling_x, cm->subsampling_y,
-                           VP9BORDERINPIXELS, NULL, NULL, NULL);
+                           VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
 
 
   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
@@ -3669,7 +3668,6 @@
   }
 
 #endif
-  // fclose(fp_out);
   return 0;
 }
 
@@ -3798,7 +3796,7 @@
   VP9_COMP *cpi = (VP9_COMP *)comp;
   VP9_COMMON *cm = &cpi->common;
 
-  check_initial_width(cpi, NULL);
+  check_initial_width(cpi, 1, 1);
 
   if (width) {
     cm->width = width;
diff --git a/vp9/encoder/vp9_pickmode.c b/vp9/encoder/vp9_pickmode.c
index 17d1f59..f317f2a 100644
--- a/vp9/encoder/vp9_pickmode.c
+++ b/vp9/encoder/vp9_pickmode.c
@@ -174,7 +174,7 @@
   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
     x->pred_mv_sad[ref_frame] = INT_MAX;
     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
-      vp9_setup_buffer_inter(cpi, x, tile, get_ref_frame_idx(cpi, ref_frame),
+      vp9_setup_buffer_inter(cpi, x, tile,
                              ref_frame, block_size, mi_row, mi_col,
                              frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
     }
diff --git a/vp9/encoder/vp9_ratectrl.c b/vp9/encoder/vp9_ratectrl.c
index 4d2d43a..3ebf98c 100644
--- a/vp9/encoder/vp9_ratectrl.c
+++ b/vp9/encoder/vp9_ratectrl.c
@@ -211,19 +211,16 @@
 
 
 static void calc_iframe_target_size(VP9_COMP *cpi) {
-  // boost defaults to half second
+  const VP9_CONFIG *oxcf = &cpi->oxcf;
+  RATE_CONTROL *const rc = &cpi->rc;
   int target;
 
-  // Clear down mmx registers to allow floating point in what follows
   vp9_clear_system_state();  // __asm emms;
 
-  // New Two pass RC
-  target = cpi->rc.per_frame_bandwidth;
-
   // For 1-pass.
   if (cpi->pass == 0) {
     if (cpi->common.current_video_frame == 0) {
-      target = cpi->oxcf.starting_buffer_level / 2;
+      target = oxcf->starting_buffer_level / 2;
     } else {
       // TODO(marpan): Add in adjustment based on Q.
       // If this keyframe was forced, use a more recent Q estimate.
@@ -235,47 +232,49 @@
       // Adjustment up based on q: need to fix.
       // kf_boost = kf_boost * kfboost_qadjust(Q) / 100;
       // Frame separation adjustment (down).
-      if (cpi->rc.frames_since_key  < cpi->output_framerate / 2) {
-        kf_boost = (int)(kf_boost * cpi->rc.frames_since_key /
-            (cpi->output_framerate / 2));
+      if (rc->frames_since_key  < cpi->output_framerate / 2) {
+        kf_boost = (int)(kf_boost * rc->frames_since_key /
+                       (cpi->output_framerate / 2));
       }
       kf_boost = (kf_boost < 16) ? 16 : kf_boost;
-      target = ((16 + kf_boost) * cpi->rc.per_frame_bandwidth) >> 4;
+      target = ((16 + kf_boost) * rc->per_frame_bandwidth) >> 4;
     }
-    cpi->rc.active_worst_quality = cpi->rc.worst_quality;
+    rc->active_worst_quality = rc->worst_quality;
+  } else {
+    target = rc->per_frame_bandwidth;
   }
 
-  if (cpi->oxcf.rc_max_intra_bitrate_pct) {
-    int max_rate = cpi->rc.per_frame_bandwidth
-                 * cpi->oxcf.rc_max_intra_bitrate_pct / 100;
-
-    if (target > max_rate)
-      target = max_rate;
+  if (oxcf->rc_max_intra_bitrate_pct) {
+    const int max_rate = rc->per_frame_bandwidth *
+                             oxcf->rc_max_intra_bitrate_pct / 100;
+    target = MIN(target, max_rate);
   }
-  cpi->rc.this_frame_target = target;
+  rc->this_frame_target = target;
 }
 
 // Update the buffer level: leaky bucket model.
 void vp9_update_buffer_level(VP9_COMP *const cpi, int encoded_frame_size) {
-  VP9_COMMON *const cm = &cpi->common;
+  const VP9_COMMON *const cm = &cpi->common;
+  const VP9_CONFIG *oxcf = &cpi->oxcf;
   RATE_CONTROL *const rc = &cpi->rc;
+
   // Non-viewable frames are a special case and are treated as pure overhead.
   if (!cm->show_frame) {
     rc->bits_off_target -= encoded_frame_size;
   } else {
     rc->bits_off_target += rc->av_per_frame_bandwidth - encoded_frame_size;
   }
+
   // Clip the buffer level to the maximum specified buffer size.
-  if (rc->bits_off_target > cpi->oxcf.maximum_buffer_size) {
-    rc->bits_off_target = cpi->oxcf.maximum_buffer_size;
-  }
-  rc->buffer_level = rc->bits_off_target;
+  rc->buffer_level = MIN(rc->bits_off_target, oxcf->maximum_buffer_size);
 }
 
 int vp9_drop_frame(VP9_COMP *const cpi) {
+  const VP9_CONFIG *oxcf = &cpi->oxcf;
   RATE_CONTROL *const rc = &cpi->rc;
 
-  if (!cpi->oxcf.drop_frames_water_mark) {
+
+  if (!oxcf->drop_frames_water_mark) {
     return 0;
   } else {
     if (rc->buffer_level < 0) {
@@ -284,8 +283,8 @@
     } else {
       // If buffer is below drop_mark, for now just drop every other frame
       // (starting with the next frame) until it increases back over drop_mark.
-      int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
-          cpi->oxcf.optimal_buffer_level / 100);
+      int drop_mark = (int)(oxcf->drop_frames_water_mark *
+                                oxcf->optimal_buffer_level / 100);
       if ((rc->buffer_level > drop_mark) &&
           (rc->decimation_factor > 0)) {
         --rc->decimation_factor;
@@ -310,14 +309,14 @@
 }
 
 // Adjust active_worst_quality level based on buffer level.
-static int adjust_active_worst_quality_from_buffer_level(const VP9_COMP *cpi) {
+static int adjust_active_worst_quality_from_buffer_level(const VP9_CONFIG *oxcf,
+    const RATE_CONTROL *rc) {
   // Adjust active_worst_quality: If buffer is above the optimal/target level,
   // bring active_worst_quality down depending on fullness over buffer.
   // If buffer is below the optimal level, let the active_worst_quality go from
   // ambient Q (at buffer = optimal level) to worst_quality level
   // (at buffer = critical level).
-  const RATE_CONTROL *const rc = &cpi->rc;
-  const VP9_CONFIG *const oxcf = &cpi->oxcf;
+
   int active_worst_quality = rc->active_worst_quality;
   // Maximum limit for down adjustment, ~20%.
   int max_adjustment_down = active_worst_quality / 5;
@@ -354,31 +353,23 @@
 }
 
 // Adjust target frame size with respect to the buffering constraints:
-static int target_size_from_buffer_level(const VP9_COMP *cpi) {
-  const RATE_CONTROL *const rc = &cpi->rc;
-  const VP9_CONFIG *const oxcf = &cpi->oxcf;
-  int this_frame_target = cpi->rc.this_frame_target;
-  int percent_low = 0;
-  int percent_high = 0;
-  int one_percent_bits = (int)(1 + oxcf->optimal_buffer_level / 100);
-  if (rc->buffer_level < oxcf->optimal_buffer_level) {
-    percent_low = (int)((oxcf->optimal_buffer_level - rc->buffer_level) /
-                      one_percent_bits);
-    if (percent_low > oxcf->under_shoot_pct)
-      percent_low = oxcf->under_shoot_pct;
+static int target_size_from_buffer_level(const VP9_CONFIG *oxcf,
+                                         const RATE_CONTROL *rc) {
+  int target = rc->this_frame_target;
+  const int64_t diff = oxcf->optimal_buffer_level - rc->buffer_level;
+  const int one_pct_bits = 1 + oxcf->optimal_buffer_level / 100;
 
+  if (diff > 0) {
     // Lower the target bandwidth for this frame.
-    this_frame_target -= (this_frame_target * percent_low) / 200;
-  } else  if (rc->buffer_level > oxcf->optimal_buffer_level) {
-    percent_high = (int)((rc->buffer_level - oxcf->optimal_buffer_level) /
-                     one_percent_bits);
-    if (percent_high > oxcf->over_shoot_pct)
-      percent_high = oxcf->over_shoot_pct;
-
+    const int pct_low = MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
+    target -= (target * pct_low) / 200;
+  } else  if (diff < 0) {
     // Increase the target bandwidth for this frame.
-    this_frame_target += (this_frame_target * percent_high) / 200;
+    const int pct_high = MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
+    target += (target * pct_high) / 200;
   }
-  return this_frame_target;
+
+  return target;
 }
 
 static void calc_pframe_target_size(VP9_COMP *const cpi) {
@@ -400,10 +391,10 @@
       // For now, use: cpi->rc.av_per_frame_bandwidth / 16:
       min_frame_target = MAX(rc->av_per_frame_bandwidth >> 4,
                              FRAME_OVERHEAD_BITS);
-      rc->this_frame_target = target_size_from_buffer_level(cpi);
+      rc->this_frame_target = target_size_from_buffer_level(oxcf, rc);
       // Adjust qp-max based on buffer level.
       rc->active_worst_quality =
-          adjust_active_worst_quality_from_buffer_level(cpi);
+          adjust_active_worst_quality_from_buffer_level(oxcf, rc);
     }
   }
 
diff --git a/vp9/encoder/vp9_rdopt.c b/vp9/encoder/vp9_rdopt.c
index fa6b362..242aa87 100644
--- a/vp9/encoder/vp9_rdopt.c
+++ b/vp9/encoder/vp9_rdopt.c
@@ -233,8 +233,8 @@
     const int q = compute_rd_thresh_factor(qindex);
 
     for (bsize = 0; bsize < BLOCK_SIZES; ++bsize) {
-      // Threshold here seem unecessarily harsh but fine given actual
-      // range of values used for cpi->sf.thresh_mult[]
+      // Threshold here seems unnecessarily harsh but fine given actual
+      // range of values used for cpi->sf.thresh_mult[].
       const int t = q * rd_thresh_block_size_factor[bsize];
       const int thresh_max = INT_MAX / t;
 
@@ -419,18 +419,12 @@
     struct macroblock_plane *const p = &x->plane[i];
     struct macroblockd_plane *const pd = &xd->plane[i];
     const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
-    int rate;
-    int64_t dist;
     (void) cpi->fn_ptr[bs].vf(p->src.buf, p->src.stride,
                               pd->dst.buf, pd->dst.stride, &sse);
     if (i == 0)
       x->pred_sse[ref] = sse;
-    // sse works better than var, since there is no dc prediction used
-    model_rd_from_var_lapndz(sse, 1 << num_pels_log2_lookup[bs],
-                             pd->dequant[1] >> 3, &rate, &dist);
 
-    rate_sum += rate;
-    dist_sum += (int)dist;
+    dist_sum += (int)sse;
   }
 
   *out_rate_sum = rate_sum;
@@ -2276,41 +2270,38 @@
 
 void vp9_setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
                             const TileInfo *const tile,
-                            int idx, MV_REFERENCE_FRAME frame_type,
+                            MV_REFERENCE_FRAME ref_frame,
                             BLOCK_SIZE block_size,
                             int mi_row, int mi_col,
                             int_mv frame_nearest_mv[MAX_REF_FRAMES],
                             int_mv frame_near_mv[MAX_REF_FRAMES],
                             struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
-  VP9_COMMON *cm = &cpi->common;
-  YV12_BUFFER_CONFIG *yv12 = &cm->yv12_fb[cpi->common.ref_frame_map[idx]];
+  const VP9_COMMON *cm = &cpi->common;
+  const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
   MACROBLOCKD *const xd = &x->e_mbd;
-  MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
-  const struct scale_factors *const sf = &cm->frame_refs[frame_type - 1].sf;
-
+  MODE_INFO *const mi = xd->mi_8x8[0];
+  int_mv *const candidates = mi->mbmi.ref_mvs[ref_frame];
+  const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
 
   // TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
   // use the UV scaling factors.
-  setup_pred_block(xd, yv12_mb[frame_type], yv12, mi_row, mi_col, sf, sf);
+  setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
 
   // Gets an initial list of candidate vectors from neighbours and orders them
-  vp9_find_mv_refs(cm, xd, tile, xd->mi_8x8[0],
-                   xd->last_mi,
-                   frame_type,
-                   mbmi->ref_mvs[frame_type], mi_row, mi_col);
+  vp9_find_mv_refs(cm, xd, tile, mi, xd->last_mi, ref_frame, candidates,
+                   mi_row, mi_col);
 
   // Candidate refinement carried out at encoder and decoder
-  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv,
-                        mbmi->ref_mvs[frame_type],
-                        &frame_nearest_mv[frame_type],
-                        &frame_near_mv[frame_type]);
+  vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
+                        &frame_nearest_mv[ref_frame],
+                        &frame_near_mv[ref_frame]);
 
   // Further refinement that is encode side only to test the top few candidates
   // in full and choose the best as the centre point for subsequent searches.
   // The current implementation doesn't support scaling.
   if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
-    mv_pred(cpi, x, yv12_mb[frame_type][0].buf, yv12->y_stride,
-            frame_type, block_size);
+    mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride,
+            ref_frame, block_size);
 }
 
 YV12_BUFFER_CONFIG *vp9_get_scaled_ref_frame(VP9_COMP *cpi, int ref_frame) {
@@ -3173,7 +3164,7 @@
   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
     x->pred_mv_sad[ref_frame] = INT_MAX;
     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
-      vp9_setup_buffer_inter(cpi, x, tile, get_ref_frame_idx(cpi, ref_frame),
+      vp9_setup_buffer_inter(cpi, x, tile,
                              ref_frame, block_size, mi_row, mi_col,
                              frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
     }
@@ -3798,7 +3789,7 @@
 
   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
     if (cpi->ref_frame_flags & flag_list[ref_frame]) {
-      vp9_setup_buffer_inter(cpi, x, tile, get_ref_frame_idx(cpi, ref_frame),
+      vp9_setup_buffer_inter(cpi, x, tile,
                              ref_frame, block_size, mi_row, mi_col,
                              frame_mv[NEARESTMV], frame_mv[NEARMV],
                              yv12_mb);
diff --git a/vp9/encoder/vp9_rdopt.h b/vp9/encoder/vp9_rdopt.h
index 696cf6b..9ac1f54 100644
--- a/vp9/encoder/vp9_rdopt.h
+++ b/vp9/encoder/vp9_rdopt.h
@@ -39,7 +39,7 @@
 
 void vp9_setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
                             const TileInfo *const tile,
-                            int idx, MV_REFERENCE_FRAME frame_type,
+                            MV_REFERENCE_FRAME ref_frame,
                             BLOCK_SIZE block_size,
                             int mi_row, int mi_col,
                             int_mv frame_nearest_mv[MAX_REF_FRAMES],
diff --git a/vp9/encoder/vp9_sad_c.c b/vp9/encoder/vp9_sad_c.c
index 55d595b..58c5df4 100644
--- a/vp9/encoder/vp9_sad_c.c
+++ b/vp9/encoder/vp9_sad_c.c
@@ -8,31 +8,44 @@
  *  be found in the AUTHORS file in the root of the source tree.
  */
 
-
 #include <stdlib.h>
+
 #include "./vp9_rtcd.h"
 #include "./vpx_config.h"
-#include "vp9/encoder/vp9_sadmxn.h"
-#include "vp9/encoder/vp9_variance.h"
+
 #include "vpx/vpx_integer.h"
+#include "vp9/encoder/vp9_variance.h"
+
+static INLINE unsigned int sad(const uint8_t *a, int a_stride,
+                               const uint8_t *b, int b_stride,
+                               int width, int height) {
+  int y, x;
+  unsigned int sad = 0;
+
+  for (y = 0; y < height; y++) {
+    for (x = 0; x < width; x++)
+      sad += abs(a[x] - b[x]);
+
+    a += a_stride;
+    b += b_stride;
+  }
+
+  return sad;
+}
 
 #define sad_mxn_func(m, n) \
-unsigned int vp9_sad##m##x##n##_c(const uint8_t *src_ptr, \
-                                  int  src_stride, \
-                                  const uint8_t *ref_ptr, \
-                                  int  ref_stride, \
+unsigned int vp9_sad##m##x##n##_c(const uint8_t *src_ptr, int src_stride, \
+                                  const uint8_t *ref_ptr, int ref_stride, \
                                   unsigned int max_sad) { \
-  return sad_mx_n_c(src_ptr, src_stride, ref_ptr, ref_stride, m, n); \
+  return sad(src_ptr, src_stride, ref_ptr, ref_stride, m, n); \
 } \
-unsigned int vp9_sad##m##x##n##_avg_c(const uint8_t *src_ptr, \
-                                      int  src_stride, \
-                                      const uint8_t *ref_ptr, \
-                                      int  ref_stride, \
+unsigned int vp9_sad##m##x##n##_avg_c(const uint8_t *src_ptr, int src_stride, \
+                                      const uint8_t *ref_ptr, int ref_stride, \
                                       const uint8_t *second_pred, \
                                       unsigned int max_sad) { \
   uint8_t comp_pred[m * n]; \
   comp_avg_pred(comp_pred, second_pred, m, n, ref_ptr, ref_stride); \
-  return sad_mx_n_c(src_ptr, src_stride, comp_pred, m, m, n); \
+  return sad(src_ptr, src_stride, comp_pred, m, m, n); \
 }
 
 sad_mxn_func(64, 64)
@@ -49,567 +62,263 @@
 sad_mxn_func(4, 8)
 sad_mxn_func(4, 4)
 
-void vp9_sad64x32x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad64x32x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad64x32(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad64x32(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad64x32(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad64x32(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad64x32(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad32x64x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad32x64x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad32x64(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad32x64(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad32x64(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad32x64(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad32x64(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad32x16x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad32x16x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad32x16(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad32x16(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad32x16(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad32x16(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad32x16(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x32x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad16x32x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad16x32(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad16x32(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad16x32(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad16x32(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad16x32(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad64x64x3_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad64x64x3_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad64x64(src_ptr, src_stride, ref_ptr, ref_stride,
-                              0x7fffffff);
-  sad_array[1] = vp9_sad64x64(src_ptr, src_stride, ref_ptr + 1, ref_stride,
-                              0x7fffffff);
-  sad_array[2] = vp9_sad64x64(src_ptr, src_stride, ref_ptr + 2, ref_stride,
-                              0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad64x64(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad32x32x3_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad32x32x3_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad32x32(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad64x64x8_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad64x64x8_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr, ref_stride,
-                              0x7fffffff);
-  sad_array[1] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 1, ref_stride,
-                              0x7fffffff);
-  sad_array[2] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 2, ref_stride,
-                              0x7fffffff);
-  sad_array[3] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 3, ref_stride,
-                              0x7fffffff);
-  sad_array[4] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 4, ref_stride,
-                              0x7fffffff);
-  sad_array[5] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 5, ref_stride,
-                              0x7fffffff);
-  sad_array[6] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 6, ref_stride,
-                              0x7fffffff);
-  sad_array[7] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr + 7, ref_stride,
-                              0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad64x64(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad32x32x8_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad32x32x8_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr, ref_stride,
-                              0x7fffffff);
-  sad_array[1] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 1, ref_stride,
-                              0x7fffffff);
-  sad_array[2] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 2, ref_stride,
-                              0x7fffffff);
-  sad_array[3] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 3, ref_stride,
-                              0x7fffffff);
-  sad_array[4] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 4, ref_stride,
-                              0x7fffffff);
-  sad_array[5] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 5, ref_stride,
-                              0x7fffffff);
-  sad_array[6] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 6, ref_stride,
-                              0x7fffffff);
-  sad_array[7] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr + 7, ref_stride,
-                              0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad32x32(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x16x3_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad16x16x3_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad16x16(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x16x8_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t *ref_ptr,
-                      int  ref_stride,
+void vp9_sad16x16x8_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t *ref_ptr, int ref_stride,
                       uint32_t *sad_array) {
-  sad_array[0] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr, ref_stride,
-                              0x7fffffff);
-  sad_array[1] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 1, ref_stride,
-                              0x7fffffff);
-  sad_array[2] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 2, ref_stride,
-                              0x7fffffff);
-  sad_array[3] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 3, ref_stride,
-                              0x7fffffff);
-  sad_array[4] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 4, ref_stride,
-                              0x7fffffff);
-  sad_array[5] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 5, ref_stride,
-                              0x7fffffff);
-  sad_array[6] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 6, ref_stride,
-                              0x7fffffff);
-  sad_array[7] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr + 7, ref_stride,
-                              0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad16x16(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x8x3_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
+void vp9_sad16x8x3_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t *ref_ptr, int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad16x8(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad16x8x8_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
+void vp9_sad16x8x8_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t *ref_ptr, int ref_stride,
                      uint32_t *sad_array) {
-  sad_array[0] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr, ref_stride,
-                             0x7fffffff);
-  sad_array[1] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride,
-                             0x7fffffff);
-  sad_array[2] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride,
-                             0x7fffffff);
-  sad_array[3] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 3, ref_stride,
-                             0x7fffffff);
-  sad_array[4] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 4, ref_stride,
-                             0x7fffffff);
-  sad_array[5] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 5, ref_stride,
-                             0x7fffffff);
-  sad_array[6] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 6, ref_stride,
-                             0x7fffffff);
-  sad_array[7] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr + 7, ref_stride,
-                             0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad16x8(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad8x8x3_c(const uint8_t *src_ptr,
-                    int  src_stride,
-                    const uint8_t *ref_ptr,
-                    int  ref_stride,
+void vp9_sad8x8x3_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
                     unsigned int *sad_array) {
-  sad_array[0] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad8x8(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad8x8x8_c(const uint8_t *src_ptr,
-                    int  src_stride,
-                    const uint8_t *ref_ptr,
-                    int  ref_stride,
+void vp9_sad8x8x8_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
                     uint32_t *sad_array) {
-  sad_array[0] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr, ref_stride,
-                            0x7fffffff);
-  sad_array[1] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 1, ref_stride,
-                            0x7fffffff);
-  sad_array[2] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 2, ref_stride,
-                            0x7fffffff);
-  sad_array[3] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 3, ref_stride,
-                            0x7fffffff);
-  sad_array[4] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 4, ref_stride,
-                            0x7fffffff);
-  sad_array[5] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 5, ref_stride,
-                            0x7fffffff);
-  sad_array[6] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 6, ref_stride,
-                            0x7fffffff);
-  sad_array[7] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr + 7, ref_stride,
-                            0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad8x8(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad8x16x3_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
+void vp9_sad8x16x3_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t *ref_ptr, int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad8x16(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad8x16x8_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
+void vp9_sad8x16x8_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t *ref_ptr, int ref_stride,
                      uint32_t *sad_array) {
-  sad_array[0] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr, ref_stride,
-                             0x7fffffff);
-  sad_array[1] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride,
-                             0x7fffffff);
-  sad_array[2] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride,
-                             0x7fffffff);
-  sad_array[3] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 3, ref_stride,
-                             0x7fffffff);
-  sad_array[4] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 4, ref_stride,
-                             0x7fffffff);
-  sad_array[5] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 5, ref_stride,
-                             0x7fffffff);
-  sad_array[6] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 6, ref_stride,
-                             0x7fffffff);
-  sad_array[7] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr + 7, ref_stride,
-                             0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad8x16(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad4x4x3_c(const uint8_t *src_ptr,
-                    int  src_stride,
-                    const uint8_t *ref_ptr,
-                    int  ref_stride,
+void vp9_sad4x4x3_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
                     unsigned int *sad_array) {
-  sad_array[0] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr, ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 1, ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 2, ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 3; ++i)
+    sad_array[i] = vp9_sad4x4(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad4x4x8_c(const uint8_t *src_ptr,
-                    int  src_stride,
-                    const uint8_t *ref_ptr,
-                    int  ref_stride,
+void vp9_sad4x4x8_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
                     uint32_t *sad_array) {
-  sad_array[0] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr, ref_stride,
-                            0x7fffffff);
-  sad_array[1] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 1, ref_stride,
-                            0x7fffffff);
-  sad_array[2] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 2, ref_stride,
-                            0x7fffffff);
-  sad_array[3] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 3, ref_stride,
-                            0x7fffffff);
-  sad_array[4] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 4, ref_stride,
-                            0x7fffffff);
-  sad_array[5] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 5, ref_stride,
-                            0x7fffffff);
-  sad_array[6] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 6, ref_stride,
-                            0x7fffffff);
-  sad_array[7] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr + 7, ref_stride,
-                            0x7fffffff);
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad4x4(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad64x64x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad64x64x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad64x64(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad64x64(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad32x32x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad32x32x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad32x32(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad32x32(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x16x4d_c(const uint8_t *src_ptr,
-                       int  src_stride,
-                       const uint8_t* const ref_ptr[],
-                       int  ref_stride,
+void vp9_sad16x16x4d_c(const uint8_t *src_ptr, int src_stride,
+                       const uint8_t* const ref_ptr[], int ref_stride,
                        unsigned int *sad_array) {
-  sad_array[0] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad16x16(src_ptr, src_stride,
-                              ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad16x16(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                                0x7fffffff);
 }
 
-void vp9_sad16x8x4d_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t* const ref_ptr[],
-                      int  ref_stride,
+void vp9_sad16x8x4d_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t* const ref_ptr[], int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad16x8(src_ptr, src_stride,
-                             ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad16x8(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad8x8x4d_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t* const ref_ptr[],
-                     int  ref_stride,
+void vp9_sad8x8x4d_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t* const ref_ptr[], int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad8x8(src_ptr, src_stride,
-                            ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad8x8(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad8x16x4d_c(const uint8_t *src_ptr,
-                      int  src_stride,
-                      const uint8_t* const ref_ptr[],
-                      int  ref_stride,
+void vp9_sad8x16x4d_c(const uint8_t *src_ptr, int src_stride,
+                      const uint8_t* const ref_ptr[], int ref_stride,
                       unsigned int *sad_array) {
-  sad_array[0] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad8x16(src_ptr, src_stride,
-                             ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad8x16(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                               0x7fffffff);
 }
 
-void vp9_sad8x4x4d_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t* const ref_ptr[],
-                     int  ref_stride,
+void vp9_sad8x4x4d_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t* const ref_ptr[], int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad8x4(src_ptr, src_stride,
-                            ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad8x4(src_ptr, src_stride,
-                            ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad8x4(src_ptr, src_stride,
-                            ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad8x4(src_ptr, src_stride,
-                            ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad8x4(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad8x4x8_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
-                     uint32_t *sad_array) {
-  sad_array[0] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr, ref_stride,
-                             0x7fffffff);
-  sad_array[1] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride,
-                             0x7fffffff);
-  sad_array[2] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride,
-                             0x7fffffff);
-  sad_array[3] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 3, ref_stride,
-                             0x7fffffff);
-  sad_array[4] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 4, ref_stride,
-                             0x7fffffff);
-  sad_array[5] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 5, ref_stride,
-                             0x7fffffff);
-  sad_array[6] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 6, ref_stride,
-                             0x7fffffff);
-  sad_array[7] = vp9_sad8x4(src_ptr, src_stride,
-                             ref_ptr + 7, ref_stride,
-                             0x7fffffff);
+void vp9_sad8x4x8_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
+                    uint32_t *sad_array) {
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad8x4(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad4x8x4d_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t* const ref_ptr[],
-                     int  ref_stride,
+void vp9_sad4x8x4d_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t* const ref_ptr[], int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad4x8(src_ptr, src_stride,
-                            ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad4x8(src_ptr, src_stride,
-                            ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad4x8(src_ptr, src_stride,
-                            ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad4x8(src_ptr, src_stride,
-                            ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad4x8(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad4x8x8_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t *ref_ptr,
-                     int  ref_stride,
-                     uint32_t *sad_array) {
-  sad_array[0] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr, ref_stride,
-                             0x7fffffff);
-  sad_array[1] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 1, ref_stride,
-                             0x7fffffff);
-  sad_array[2] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 2, ref_stride,
-                             0x7fffffff);
-  sad_array[3] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 3, ref_stride,
-                             0x7fffffff);
-  sad_array[4] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 4, ref_stride,
-                             0x7fffffff);
-  sad_array[5] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 5, ref_stride,
-                             0x7fffffff);
-  sad_array[6] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 6, ref_stride,
-                             0x7fffffff);
-  sad_array[7] = vp9_sad4x8(src_ptr, src_stride,
-                             ref_ptr + 7, ref_stride,
-                             0x7fffffff);
+void vp9_sad4x8x8_c(const uint8_t *src_ptr, int src_stride,
+                    const uint8_t *ref_ptr, int ref_stride,
+                    uint32_t *sad_array) {
+  int i;
+  for (i = 0; i < 8; ++i)
+    sad_array[i] = vp9_sad4x8(src_ptr, src_stride, ref_ptr + i, ref_stride,
+                              0x7fffffff);
 }
 
-void vp9_sad4x4x4d_c(const uint8_t *src_ptr,
-                     int  src_stride,
-                     const uint8_t* const ref_ptr[],
-                     int  ref_stride,
+void vp9_sad4x4x4d_c(const uint8_t *src_ptr, int src_stride,
+                     const uint8_t* const ref_ptr[], int ref_stride,
                      unsigned int *sad_array) {
-  sad_array[0] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr[0], ref_stride, 0x7fffffff);
-  sad_array[1] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr[1], ref_stride, 0x7fffffff);
-  sad_array[2] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr[2], ref_stride, 0x7fffffff);
-  sad_array[3] = vp9_sad4x4(src_ptr, src_stride,
-                            ref_ptr[3], ref_stride, 0x7fffffff);
+  int i;
+  for (i = 0; i < 4; ++i)
+    sad_array[i] = vp9_sad4x4(src_ptr, src_stride, ref_ptr[i], ref_stride,
+                              0x7fffffff);
 }
diff --git a/vp9/encoder/vp9_sadmxn.h b/vp9/encoder/vp9_sadmxn.h
deleted file mode 100644
index 1bae4dd..0000000
--- a/vp9/encoder/vp9_sadmxn.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
- *
- *  Use of this source code is governed by a BSD-style license
- *  that can be found in the LICENSE file in the root of the source
- *  tree. An additional intellectual property rights grant can be found
- *  in the file PATENTS.  All contributing project authors may
- *  be found in the AUTHORS file in the root of the source tree.
- */
-
-#ifndef VP9_ENCODER_VP9_SADMXN_H_
-#define VP9_ENCODER_VP9_SADMXN_H_
-
-#include "./vpx_config.h"
-#include "vpx/vpx_integer.h"
-
-static INLINE unsigned int sad_mx_n_c(const uint8_t *src_ptr,
-                                      int src_stride,
-                                      const uint8_t *ref_ptr,
-                                      int ref_stride,
-                                      int m,
-                                      int n) {
-  int r, c;
-  unsigned int sad = 0;
-
-  for (r = 0; r < n; r++) {
-    for (c = 0; c < m; c++) {
-      sad += abs(src_ptr[c] - ref_ptr[c]);
-    }
-
-    src_ptr += src_stride;
-    ref_ptr += ref_stride;
-  }
-
-  return sad;
-}
-
-#endif  // VP9_ENCODER_VP9_SADMXN_H_
diff --git a/vp9/encoder/vp9_temporal_filter.c b/vp9/encoder/vp9_temporal_filter.c
index 8762192..c2eea0a 100644
--- a/vp9/encoder/vp9_temporal_filter.c
+++ b/vp9/encoder/vp9_temporal_filter.c
@@ -227,7 +227,7 @@
   for (mb_row = 0; mb_row < mb_rows; mb_row++) {
 #if ALT_REF_MC_ENABLED
     // Source frames are extended to 16 pixels.  This is different than
-    //  L/A/G reference frames that have a border of 32 (VP9BORDERINPIXELS)
+    //  L/A/G reference frames that have a border of 32 (VP9ENCBORDERINPIXELS)
     // A 6/8 tap filter is used for motion search.  This requires 2 pixels
     //  before and 3 pixels after.  So the largest Y mv on a border would
     //  then be 16 - VP9_INTERP_EXTEND. The UV blocks are half the size of the
diff --git a/vp9/vp9_cx_iface.c b/vp9/vp9_cx_iface.c
index 5c14b2e..897ecd7 100644
--- a/vp9/vp9_cx_iface.c
+++ b/vp9/vp9_cx_iface.c
@@ -513,10 +513,8 @@
     priv->vp8_cfg = extracfg_map[i].cfg;
     priv->vp8_cfg.pkt_list = &priv->pkt_list.head;
 
-    // TODO(agrange) Check the limits set on this buffer, or the check that is
-    // applied in vp9e_encode.
+    // Maximum buffer size approximated based on having multiple ARF.
     priv->cx_data_sz = priv->cfg.g_w * priv->cfg.g_h * 3 / 2 * 8;
-//    priv->cx_data_sz = priv->cfg.g_w * priv->cfg.g_h * 3 / 2 * 2;
 
     if (priv->cx_data_sz < 4096) priv->cx_data_sz = 4096;
 
@@ -692,7 +690,7 @@
     }
   }
 
-  /* Initialize the encoder instance on the first frame*/
+  /* Initialize the encoder instance on the first frame. */
   if (!res && ctx->cpi) {
     unsigned int lib_flags;
     YV12_BUFFER_CONFIG sd;
@@ -704,9 +702,6 @@
     if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
       ((VP9_COMP *)ctx->cpi)->b_calculate_psnr = 1;
 
-    // if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
-    //    ((VP9_COMP *)ctx->cpi)->output_partition = 1;
-
     /* Convert API flags to internal codec lib flags */
     lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
 
diff --git a/vp9/vp9_iface_common.h b/vp9/vp9_iface_common.h
index ed0122c..58256b2 100644
--- a/vp9/vp9_iface_common.h
+++ b/vp9/vp9_iface_common.h
@@ -29,7 +29,7 @@
     img->fmt = VPX_IMG_FMT_I420;
   }
   img->w = yv12->y_stride;
-  img->h = ALIGN_POWER_OF_TWO(yv12->y_height + 2 * VP9BORDERINPIXELS, 3);
+  img->h = ALIGN_POWER_OF_TWO(yv12->y_height + 2 * VP9_ENC_BORDER_IN_PIXELS, 3);
   img->d_w = yv12->y_crop_width;
   img->d_h = yv12->y_crop_height;
   img->x_chroma_shift = yv12->uv_width < yv12->y_width;
@@ -75,7 +75,7 @@
 
   yv12->border  = (img->stride[VPX_PLANE_Y] - img->w) / 2;
 #if CONFIG_ALPHA
-  // For development purposes, force alpha to hold the same data a Y for now.
+  // For development purposes, force alpha to hold the same data as Y for now.
   yv12->alpha_buffer = yv12->y_buffer;
   yv12->alpha_width = yv12->y_width;
   yv12->alpha_height = yv12->y_height;
diff --git a/vp9/vp9cx.mk b/vp9/vp9cx.mk
index 9ea0f54..dd33099 100644
--- a/vp9/vp9cx.mk
+++ b/vp9/vp9cx.mk
@@ -44,7 +44,6 @@
 VP9_CX_SRCS-yes += encoder/vp9_ratectrl.h
 VP9_CX_SRCS-yes += encoder/vp9_rdopt.h
 VP9_CX_SRCS-yes += encoder/vp9_pickmode.h
-VP9_CX_SRCS-yes += encoder/vp9_sadmxn.h
 VP9_CX_SRCS-yes += encoder/vp9_tokenize.h
 VP9_CX_SRCS-yes += encoder/vp9_treewriter.h
 VP9_CX_SRCS-yes += encoder/vp9_variance.h
diff --git a/vpx_scale/yv12config.h b/vpx_scale/yv12config.h
index bf5fc07..610e7d2 100644
--- a/vpx_scale/yv12config.h
+++ b/vpx_scale/yv12config.h
@@ -18,10 +18,11 @@
 #include "vpx/vpx_external_frame_buffer.h"
 #include "vpx/vpx_integer.h"
 
-#define VP8BORDERINPIXELS       32
-#define VP9INNERBORDERINPIXELS  96
-#define VP9BORDERINPIXELS      160
-#define VP9_INTERP_EXTEND        4
+#define VP8BORDERINPIXELS           32
+#define VP9INNERBORDERINPIXELS      96
+#define VP9_INTERP_EXTEND           4
+#define VP9_ENC_BORDER_IN_PIXELS    160
+#define VP9_DEC_BORDER_IN_PIXELS    32
 
   typedef struct yv12_buffer_config {
     int   y_width;
diff --git a/vpxdec.c b/vpxdec.c
index c067609..deb307e 100644
--- a/vpxdec.c
+++ b/vpxdec.c
@@ -245,25 +245,6 @@
   }
 }
 
-void *out_open(const char *out_fn, int do_md5) {
-  void *out = NULL;
-
-  if (do_md5) {
-    MD5Context *md5_ctx = out = malloc(sizeof(MD5Context));
-    (void)out_fn;
-    MD5Init(md5_ctx);
-  } else {
-    FILE *outfile = out = strcmp("-", out_fn) ? fopen(out_fn, "wb")
-                          : set_binary_mode(stdout);
-
-    if (!outfile) {
-      fatal("Failed to output file");
-    }
-  }
-
-  return out;
-}
-
 static int get_image_plane_width(int plane, const vpx_image_t *img) {
   return (plane > 0 && img->x_chroma_shift > 0) ?
              (img->d_w + 1) >> img->x_chroma_shift :
@@ -312,23 +293,6 @@
   }
 }
 
-void out_close(void *out, const char *out_fn, int do_md5) {
-  if (do_md5) {
-    uint8_t md5[16];
-    int i;
-
-    MD5Final(md5, out);
-    free(out);
-
-    for (i = 0; i < 16; i++)
-      printf("%02x", md5[i]);
-
-    printf("  %s\n", out_fn);
-  } else {
-    fclose(out);
-  }
-}
-
 int file_is_raw(struct VpxInputContext *input) {
   uint8_t buf[32];
   int is_raw = 0;
@@ -469,6 +433,40 @@
   } while (*p);
 }
 
+static int is_single_file(const char *outfile_pattern) {
+  const char *p = outfile_pattern;
+
+  do {
+    p = strchr(p, '%');
+    if (p && p[1] >= '1' && p[1] <= '9')
+      return 0;  // pattern contains sequence number, so it's not unique
+    if (p)
+      p++;
+  } while (p);
+
+  return 1;
+}
+
+static void print_md5(unsigned char digest[16], const char *filename) {
+  int i;
+
+  for (i = 0; i < 16; ++i)
+    printf("%02x", digest[i]);
+  printf("  %s\n", filename);
+}
+
+static FILE *open_outfile(const char *name) {
+  if (strcmp("-", name) == 0) {
+    set_binary_mode(stdout);
+    return stdout;
+  } else {
+    FILE *file = fopen(name, "wb");
+    if (!file)
+      fatal("Failed to output file %s", name);
+    return file;
+  }
+}
+
 int main_loop(int argc, const char **argv_) {
   vpx_codec_ctx_t       decoder;
   char                  *fn = NULL;
@@ -485,11 +483,9 @@
   unsigned long          dx_time = 0;
   struct arg               arg;
   char                   **argv, **argi, **argj;
-  const char             *outfile_pattern = 0;
-  char                    outfile[PATH_MAX];
+
   int                     single_file;
   int                     use_y4m = 1;
-  void                   *out = NULL;
   vpx_codec_dec_cfg_t     cfg = {0};
 #if CONFIG_VP8_DECODER
   vp8_postproc_cfg_t      vp8_pp_cfg = {0};
@@ -507,6 +503,13 @@
   int                     fb_lru_cache = 0;
   vpx_codec_frame_buffer_t *frame_buffers = NULL;
 
+  const char *outfile_pattern = NULL;
+  char outfile_name[PATH_MAX] = {0};
+  FILE *outfile = NULL;
+
+  MD5Context md5_ctx;
+  unsigned char md5_digest[16];
+
   struct VpxDecInputContext input = {0};
   struct VpxInputContext vpx_input_ctx = {0};
   struct WebmInputContext webm_ctx = {0};
@@ -641,8 +644,7 @@
   infile = strcmp(fn, "-") ? fopen(fn, "rb") : set_binary_mode(stdin);
 
   if (!infile) {
-    fprintf(stderr, "Failed to open file '%s'",
-            strcmp(fn, "-") ? fn : "stdin");
+    fprintf(stderr, "Failed to open file '%s'", strcmp(fn, "-") ? fn : "stdin");
     return EXIT_FAILURE;
   }
 #if CONFIG_OS_SUPPORT
@@ -666,29 +668,16 @@
     return EXIT_FAILURE;
   }
 
-  /* If the output file is not set or doesn't have a sequence number in
-   * it, then we only open it once.
-   */
   outfile_pattern = outfile_pattern ? outfile_pattern : "-";
-  single_file = 1;
-  {
-    const char *p = outfile_pattern;
-    do {
-      p = strchr(p, '%');
-      if (p && p[1] >= '1' && p[1] <= '9') {
-        /* pattern contains sequence number, so it's not unique. */
-        single_file = 0;
-        break;
-      }
-      if (p)
-        p++;
-    } while (p);
-  }
+  single_file = is_single_file(outfile_pattern);
 
-  if (single_file && !noblit) {
-    generate_filename(outfile_pattern, outfile, sizeof(outfile) - 1,
+  if (!noblit && single_file) {
+    generate_filename(outfile_pattern, outfile_name, PATH_MAX,
                       vpx_input_ctx.width, vpx_input_ctx.height, 0);
-    out = out_open(outfile, do_md5);
+    if (do_md5)
+      MD5Init(&md5_ctx);
+    else
+      outfile = open_outfile(outfile_name);
   }
 
   if (use_y4m && !noblit) {
@@ -851,17 +840,18 @@
       show_progress(frame_in, frame_out, dx_time);
 
     if (!noblit) {
-      if (frame_out == 1 && img && use_y4m) {
-        y4m_write_file_header(out, vpx_input_ctx.width, vpx_input_ctx.height,
+      if (frame_out == 1 && img && use_y4m && single_file)
+        y4m_write_file_header(outfile,
+                              vpx_input_ctx.width, vpx_input_ctx.height,
                               &vpx_input_ctx.framerate, img->fmt);
-      }
 
       if (img && do_scale) {
         if (frame_out == 1) {
           // If the output frames are to be scaled to a fixed display size then
           // use the width and height specified in the container. If either of
           // these is set to 0, use the display size set in the first frame
-          // header.
+          // header. If that is unavailable, use the raw decoded size of the
+          // first decoded frame.
           int display_width = vpx_input_ctx.width;
           int display_height = vpx_input_ctx.height;
           if (!display_width || !display_height) {
@@ -891,24 +881,29 @@
         const int PLANES_YVU[] = {VPX_PLANE_Y, VPX_PLANE_V, VPX_PLANE_U};
 
         const int *planes = flipuv ? PLANES_YVU : PLANES_YUV;
-        char out_fn[PATH_MAX];
 
         if (!single_file) {
-          generate_filename(outfile_pattern, out_fn, PATH_MAX,
+          generate_filename(outfile_pattern, outfile_name, PATH_MAX,
                             img->d_w, img->d_h, frame_in);
-          out = out_open(out_fn, do_md5);
+          if (do_md5) {
+            MD5Init(&md5_ctx);
+            update_image_md5(img, planes, &md5_ctx);
+            MD5Final(md5_digest, &md5_ctx);
+            print_md5(md5_digest, outfile_name);
+          } else {
+            outfile = open_outfile(outfile_name);
+            write_image_file(img, planes, outfile);
+            fclose(outfile);
+          }
         } else {
-          if (use_y4m)
-            y4m_write_frame_header(out);
+          if (do_md5) {
+            update_image_md5(img, planes, &md5_ctx);
+          } else {
+            if (use_y4m)
+              y4m_write_frame_header(outfile);
+            write_image_file(img, planes, outfile);
+          }
         }
-
-        if (do_md5)
-          update_image_md5(img, planes, out);
-        else
-          write_image_file(img, planes, out);
-
-        if (!single_file)
-          out_close(out, out_fn, do_md5);
       }
     }
 
@@ -932,8 +927,14 @@
     return EXIT_FAILURE;
   }
 
-  if (single_file && !noblit)
-    out_close(out, outfile, do_md5);
+  if (!noblit && single_file) {
+    if (do_md5) {
+      MD5Final(md5_digest, &md5_ctx);
+      print_md5(md5_digest, outfile_name);
+    } else {
+      fclose(outfile);
+    }
+  }
 
   if (input.vpx_input_ctx->file_type == FILE_TYPE_WEBM)
     webm_free(input.webm_ctx);