Merge cherrypicks of [4195294, 4195296, 4195440, 4195441, 4186165, 4186166, 4186580, 4195442, 4195443, 4186193, 4186194, 4186195, 4186196, 4186607, 4195444, 4195297, 4186608, 4186609, 4186610, 4186611, 4186612, 4186613, 4186614, 4186649, 4186650, 4186651, 4186652, 4186653, 4186654, 4186655, 4186656, 4186657, 4195518, 4195519, 4195520, 4195521, 4195522, 4186406, 4186407, 4186408, 4195523, 4195558, 4195559, 4186197, 4195524, 4186615, 4195445, 4195446, 4186829, 4186830, 4186831, 4186832, 4186833, 4186834, 4186835, 4186836, 4186837, 4195578, 4195579, 4195580, 4195581, 4195447, 4186581, 4195448, 4195560] into sparse-4749909-L06000000176800346

Change-Id: I9e1dffeb44cde8ba74a1f339ecf255980c9c7512
diff --git a/libvpx/vp8/encoder/mcomp.c b/libvpx/vp8/encoder/mcomp.c
index 970120f..b4a49a3 100644
--- a/libvpx/vp8/encoder/mcomp.c
+++ b/libvpx/vp8/encoder/mcomp.c
@@ -34,19 +34,22 @@
    * NEAREST for subsequent blocks. The "Weight" parameter allows, to a
    * limited extent, for some account to be taken of these factors.
    */
-  return ((mvcost[0][(mv->as_mv.row - ref->as_mv.row) >> 1] +
-           mvcost[1][(mv->as_mv.col - ref->as_mv.col) >> 1]) *
-          Weight) >>
-         7;
+  const int mv_idx_row =
+      clamp((mv->as_mv.row - ref->as_mv.row) >> 1, 0, MVvals);
+  const int mv_idx_col =
+      clamp((mv->as_mv.col - ref->as_mv.col) >> 1, 0, MVvals);
+  return ((mvcost[0][mv_idx_row] + mvcost[1][mv_idx_col]) * Weight) >> 7;
 }
 
 static int mv_err_cost(int_mv *mv, int_mv *ref, int *mvcost[2],
                        int error_per_bit) {
   /* Ignore mv costing if mvcost is NULL */
   if (mvcost) {
-    return ((mvcost[0][(mv->as_mv.row - ref->as_mv.row) >> 1] +
-             mvcost[1][(mv->as_mv.col - ref->as_mv.col) >> 1]) *
-                error_per_bit +
+    const int mv_idx_row =
+        clamp((mv->as_mv.row - ref->as_mv.row) >> 1, 0, MVvals);
+    const int mv_idx_col =
+        clamp((mv->as_mv.col - ref->as_mv.col) >> 1, 0, MVvals);
+    return ((mvcost[0][mv_idx_row] + mvcost[1][mv_idx_col]) * error_per_bit +
             128) >>
            8;
   }