diff --git a/src/context.rs b/src/context.rs
index c2ef119ede08675eb970dcc99e3e8e9aa53fc58b..33216a20d9db78f4b79058cd4ff6fd77bb165d28 100755
--- a/src/context.rs
+++ b/src/context.rs
@@ -2430,6 +2430,20 @@ impl ContextWriter {
 
     /* TODO: Handle single reference frame extension */
 
+    // clamp mvs
+    for mv in mv_stack {
+      let blk_w = bsize.width();
+      let blk_h = bsize.height();
+      let border_w = 128 + blk_w as isize * 8;
+      let border_h = 128 + blk_h as isize * 8;
+      let x_min = -(bo.x as isize) * (8 * MI_SIZE) as isize - border_w;
+      let x_max = (self.bc.cols - bo.x - blk_w / MI_SIZE) as isize * (8 * MI_SIZE) as isize + border_w;
+      let y_min = -(bo.y as isize) * (8 * MI_SIZE) as isize - border_h;
+      let y_max = (self.bc.rows - bo.y - blk_h / MI_SIZE) as isize * (8 * MI_SIZE) as isize + border_h;
+      mv.this_mv.row = (mv.this_mv.row as isize).max(y_min).min(y_max) as i16;
+      mv.this_mv.col = (mv.this_mv.col as isize).max(x_min).min(x_max) as i16;
+    }
+
     mode_context
   }