Commit 2679698ef9 for aom

commit 2679698ef9444be38a839805b3137d2cf1e458db
Author: Alejandro Pacheco <alepacheco99@gmail.com>
Date:   Wed Oct 14 12:25:38 2026 +0200

    aom_scale: check reference copies against the caller's image

    AV1_SET_REFERENCE and AV1_COPY_REFERENCE copy between a reference
    frame and an aom_image_t from the application. Previously:
    - Encoder controls only asserted size/bit-depth matches, and the
      decoder checked dimensions but not bit depth, allowing OOB reads
      and writes on mismatched images.
    - Copying into an application's image extended borders using a border
      size guessed from y_stride in image2yuvconfig(), causing OOB writes
      for images with wide stride or a smaller allocated border
      (affecting both AV1_COPY_REFERENCE and AV1_COPY_NEW_FRAME_IMAGE /
      external AV1_SET_REFERENCE).

    Fixes:
    - Add aom_yv12_same_size_and_format() and
      aom_yv12_same_dimensions_and_border(), checking plane sizes, sample
      format, non-null plane buffers, and strides on encoder and decoder
      (gating chroma checks on num_planes > 1 for monochrome).
    - Add aom_yv12_copy_frame_planes() (no border extension) and use it
      for AV1_COPY_REFERENCE.
    - Validate chroma shifts, U/V stride equality, and high-bitdepth
      2-byte pointer/stride alignment in image2yuvconfig(), verify
      backing border space around active planes, and sync crop dimensions
      in AV1_COPY_NEW_FRAME_IMAGE.
    - Document the alignment and border requirements in aom/aom.h and add
      unit tests for AV1_COPY_REFERENCE, AV1_SET_REFERENCE, and
      AV1_COPY_NEW_FRAME_IMAGE.

    TAG=agy
    CONV=74ece8ab-3f39-4cda-9df8-8325c945d9d9

    Bug: 573427857
    Bug: 576072401
    Change-Id: I139d8ee6a2a5509c86ce290738ba58d8d31f9f0b

diff --git a/aom/aom.h b/aom/aom.h
index 0a7ae28187..42fd0194c6 100644
--- a/aom/aom.h
+++ b/aom/aom.h
@@ -51,13 +51,23 @@ enum aom_com_control_id {
   AV1_GET_REFERENCE = 230,

   /*!\brief Codec control function to write a frame into a reference buffer
+   *
+   * The input image must match the reference frame buffer's 8-aligned
+   * dimensions, chroma subsampling, and bit-depth format (for example,
+   * allocated with aom_img_alloc_with_border() using size_align = 8). When
+   * use_external_ref is set (decoder only), the image must also match the
+   * reference buffer's strides and allocated border size.
    *
    * av1_ref_frame_t* parameter
    */
   AV1_SET_REFERENCE = 231,

-  /*!\brief Codec control function to get a copy of reference frame from the
-   * decoder
+  /*!\brief Codec control function to get a copy of a reference frame
+   *
+   * The destination image must match the reference frame buffer's 8-aligned
+   * dimensions, chroma subsampling, and bit-depth format. Only the active
+   * planes are copied; any border area around the destination image is left
+   * untouched.
    *
    * av1_ref_frame_t* parameter
    */
@@ -70,6 +80,12 @@ enum aom_com_control_id {
   AV1_GET_NEW_FRAME_IMAGE = 233,

   /*!\brief Codec control function to copy the new frame to an external buffer
+   *
+   * The destination image must match the internal frame buffer's 8-aligned
+   * dimensions, chroma subsampling, bit-depth format, strides, and allocated
+   * border size (for example, allocated with aom_img_alloc_with_border()).
+   * Unlike AV1_COPY_REFERENCE, this control also extends the destination
+   * image's borders so it can be reused as an external reference buffer.
    *
    * aom_image_t* parameter
    */
diff --git a/aom_scale/aom_scale_rtcd.pl b/aom_scale/aom_scale_rtcd.pl
index 1f2df8dd3f..4fc7d95bc8 100644
--- a/aom_scale/aom_scale_rtcd.pl
+++ b/aom_scale/aom_scale_rtcd.pl
@@ -21,6 +21,8 @@ add_proto qw/int aom_yv12_realloc_with_new_border/, "struct yv12_buffer_config *

 add_proto qw/void aom_yv12_copy_frame/, "const struct yv12_buffer_config *src_bc, struct yv12_buffer_config *dst_bc, const int num_planes";

+add_proto qw/void aom_yv12_copy_frame_planes/, "const struct yv12_buffer_config *src_bc, struct yv12_buffer_config *dst_bc, const int num_planes";
+
 add_proto qw/void aom_yv12_copy_y/, "const struct yv12_buffer_config *src_ybc, struct yv12_buffer_config *dst_ybc, int use_crop";

 add_proto qw/void aom_yv12_copy_u/, "const struct yv12_buffer_config *src_bc, struct yv12_buffer_config *dst_bc, int use_crop";
diff --git a/aom_scale/generic/yv12extend.c b/aom_scale/generic/yv12extend.c
index 8bc01f7dcd..e7cb032504 100644
--- a/aom_scale/generic/yv12extend.c
+++ b/aom_scale/generic/yv12extend.c
@@ -194,11 +194,12 @@ static void memcpy_short_addr(uint8_t *dst8, const uint8_t *src8, int num) {
 }
 #endif

-// Copies the source image into the destination image and updates the
-// destination's UMV borders.
+// Copies the planes of the source image into the destination image, without
+// touching the destination's borders.
 // Note: The frames are assumed to be identical in size.
-void aom_yv12_copy_frame_c(const YV12_BUFFER_CONFIG *src_bc,
-                           YV12_BUFFER_CONFIG *dst_bc, const int num_planes) {
+void aom_yv12_copy_frame_planes_c(const YV12_BUFFER_CONFIG *src_bc,
+                                  YV12_BUFFER_CONFIG *dst_bc,
+                                  const int num_planes) {
   assert(src_bc->y_width == dst_bc->y_width);
   assert(src_bc->y_height == dst_bc->y_height);

@@ -218,7 +219,6 @@ void aom_yv12_copy_frame_c(const YV12_BUFFER_CONFIG *src_bc,
         plane_dst += dst_bc->strides[is_uv];
       }
     }
-    aom_extend_frame_borders_c(dst_bc, num_planes);
     return;
   }
 #endif
@@ -233,6 +233,15 @@ void aom_yv12_copy_frame_c(const YV12_BUFFER_CONFIG *src_bc,
       plane_dst += dst_bc->strides[is_uv];
     }
   }
+}
+
+// Copies the source image into the destination image and updates the
+// destination's UMV borders. The destination must be a frame buffer with a
+// border of dst_bc->border pixels around each plane.
+// Note: The frames are assumed to be identical in size.
+void aom_yv12_copy_frame_c(const YV12_BUFFER_CONFIG *src_bc,
+                           YV12_BUFFER_CONFIG *dst_bc, const int num_planes) {
+  aom_yv12_copy_frame_planes_c(src_bc, dst_bc, num_planes);
   aom_extend_frame_borders_c(dst_bc, num_planes);
 }

diff --git a/aom_scale/yv12config.h b/aom_scale/yv12config.h
index a29125db2f..ade06176ec 100644
--- a/aom_scale/yv12config.h
+++ b/aom_scale/yv12config.h
@@ -17,6 +17,7 @@ extern "C" {
 #endif

 #include <stdbool.h>
+#include <stddef.h>

 #include "config/aom_config.h"

@@ -216,6 +217,48 @@ static inline int aom_calc_y_stride(int aligned_width, int border) {
   return ((aligned_width + 2 * border) + 31) & ~31;
 }

+/*!\brief Checks that two frames can be copied into each other.
+ *
+ * Returns 1 if the frames have the same plane sizes and sample format, and
+ * valid non-null plane buffers and strides for \p num_planes planes, so that
+ * aom_yv12_copy_frame() or aom_yv12_copy_frame_planes() can copy one into the
+ * other.
+ */
+static inline int aom_yv12_same_size_and_format(const YV12_BUFFER_CONFIG *a,
+                                                const YV12_BUFFER_CONFIG *b,
+                                                int num_planes) {
+  if (a->y_width != b->y_width || a->y_height != b->y_height ||
+      (a->flags & YV12_FLAG_HIGHBITDEPTH) !=
+          (b->flags & YV12_FLAG_HIGHBITDEPTH)) {
+    return 0;
+  }
+  if (a->y_buffer == NULL || b->y_buffer == NULL || a->y_stride < a->y_width ||
+      b->y_stride < b->y_width) {
+    return 0;
+  }
+  if (num_planes > 1 &&
+      (a->uv_width != b->uv_width || a->uv_height != b->uv_height ||
+       a->u_buffer == NULL || a->v_buffer == NULL || b->u_buffer == NULL ||
+       b->v_buffer == NULL || a->uv_stride < a->uv_width ||
+       b->uv_stride < b->uv_width)) {
+    return 0;
+  }
+  return 1;
+}
+
+/*!\brief Checks that two frames match in size, format, strides, and border.
+ *
+ * Returns 1 if aom_yv12_same_size_and_format() holds and both frames have the
+ * same strides and border size.
+ */
+static inline int aom_yv12_same_dimensions_and_border(
+    const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b, int num_planes) {
+  return aom_yv12_same_size_and_format(a, b, num_planes) &&
+         a->y_stride == b->y_stride &&
+         (num_planes <= 1 || a->uv_stride == b->uv_stride) &&
+         a->border == b->border;
+}
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/av1/av1_cx_iface.c b/av1/av1_cx_iface.c
index c48added74..8f88441a9f 100644
--- a/av1/av1_cx_iface.c
+++ b/av1/av1_cx_iface.c
@@ -3532,6 +3532,9 @@ static aom_codec_err_t encoder_encode(aom_codec_alg_priv_t *ctx,

       YV12_BUFFER_CONFIG sd;
       res = image2yuvconfig(img, &sd);
+      if (res != AOM_CODEC_OK) {
+        aom_internal_error(&ppi->error, res, "Invalid chroma subsampling");
+      }
       // When generating a monochrome stream, make |sd| a monochrome image.
       if (ctx->cfg.monochrome) {
         sd.u_buffer = sd.v_buffer = NULL;
@@ -3934,7 +3937,8 @@ static aom_codec_err_t ctrl_set_reference(aom_codec_alg_priv_t *ctx,
     YV12_BUFFER_CONFIG sd;

     image2yuvconfig(&frame->img, &sd);
-    av1_set_reference_enc(ctx->ppi->cpi, frame->idx, &sd);
+    if (av1_set_reference_enc(ctx->ppi->cpi, frame->idx, &sd) != 0)
+      return AOM_CODEC_ERROR;
     return AOM_CODEC_OK;
   } else {
     return AOM_CODEC_INVALID_PARAM;
@@ -3951,7 +3955,8 @@ static aom_codec_err_t ctrl_copy_reference(aom_codec_alg_priv_t *ctx,
     YV12_BUFFER_CONFIG sd;

     image2yuvconfig(&frame->img, &sd);
-    av1_copy_reference_enc(ctx->ppi->cpi, frame->idx, &sd);
+    if (av1_copy_reference_enc(ctx->ppi->cpi, frame->idx, &sd) != 0)
+      return AOM_CODEC_ERROR;
     return AOM_CODEC_OK;
   } else {
     return AOM_CODEC_INVALID_PARAM;
diff --git a/av1/av1_iface_common.h b/av1/av1_iface_common.h
index e47f8b07f8..666bbc18f0 100644
--- a/av1/av1_iface_common.h
+++ b/av1/av1_iface_common.h
@@ -12,6 +12,10 @@
 #define AOM_AV1_AV1_IFACE_COMMON_H_

 #include <assert.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>

 #include "aom_ports/mem.h"
 #include "aom_scale/yv12config.h"
@@ -83,8 +87,99 @@ static inline void yuvconfig2image(aom_image_t *img,
   img->metadata = NULL;
 }

+static inline int image_plane_in_bounds(
+    const uint8_t *buf_start, size_t buf_size, const uint8_t *plane_ptr,
+    int stride_bytes, size_t width, size_t height, size_t border_x,
+    size_t border_y, size_t bps, uintptr_t *out_start, uintptr_t *out_end) {
+  if (plane_ptr == NULL || stride_bytes <= 0 || width == 0 || height == 0) {
+    return 0;
+  }
+  const size_t stride = (size_t)stride_bytes;
+  if ((uintptr_t)plane_ptr % bps != 0 || stride % bps != 0) return 0;
+  if (width > SIZE_MAX / 2 || border_x > SIZE_MAX / 4) return 0;
+  if (width + 2 * border_x > stride / bps) return 0;
+  if (border_y > (SIZE_MAX - height) / 2) return 0;
+  const size_t total_rows = height + 2 * border_y;
+  if (total_rows > SIZE_MAX / stride) return 0;
+
+  // Extending borders accesses [plane_ptr - before, plane_ptr + after).
+  const size_t before = border_y * stride + border_x * bps;
+  const size_t after =
+      (height + border_y - 1) * stride + (width + border_x) * bps;
+
+  const uintptr_t base = (uintptr_t)buf_start;
+  const uintptr_t limit = base + buf_size;
+  if (limit < base) return 0;
+  const uintptr_t ptr = (uintptr_t)plane_ptr;
+  if (ptr < base || ptr > limit) return 0;
+  if ((size_t)(ptr - base) < before) return 0;
+  if ((size_t)(limit - ptr) < after) return 0;
+
+  *out_start = ptr - before;
+  *out_end = ptr + after;
+  return 1;
+}
+
+// Verifies that |img|'s backing allocation [img->img_data, img->img_data +
+// img->sz) contains non-overlapping space for |border| pixels around every
+// active plane.
+static inline int image_has_border_space(const aom_image_t *img,
+                                         const YV12_BUFFER_CONFIG *yv12,
+                                         int border) {
+  if (border <= 0 || img->img_data == NULL || img->sz == 0) return 0;
+  if (!(img->fmt & AOM_IMG_FMT_PLANAR) || img->fmt == AOM_IMG_FMT_NV12) {
+    return 0;
+  }
+  if (img->x_chroma_shift > 1 || img->y_chroma_shift > 1) return 0;
+  const size_t bps = (img->fmt & AOM_IMG_FMT_HIGHBITDEPTH) ? 2 : 1;
+
+  uintptr_t starts[3];
+  uintptr_t ends[3];
+  if (!image_plane_in_bounds(img->img_data, img->sz, img->planes[AOM_PLANE_Y],
+                             img->stride[AOM_PLANE_Y], img->w, img->h,
+                             (size_t)border, (size_t)border, bps, &starts[0],
+                             &ends[0])) {
+    return 0;
+  }
+
+  if (img->monochrome && img->planes[AOM_PLANE_U] == NULL &&
+      img->planes[AOM_PLANE_V] == NULL) {
+    return 1;
+  }
+
+  if (img->stride[AOM_PLANE_U] != img->stride[AOM_PLANE_V]) return 0;
+
+  const size_t uv_border_x = (size_t)border >> img->x_chroma_shift;
+  const size_t uv_border_y = (size_t)border >> img->y_chroma_shift;
+  if (yv12->uv_width <= 0 || yv12->uv_height <= 0) return 0;
+  if (!image_plane_in_bounds(img->img_data, img->sz, img->planes[AOM_PLANE_U],
+                             img->stride[AOM_PLANE_U], (size_t)yv12->uv_width,
+                             (size_t)yv12->uv_height, uv_border_x, uv_border_y,
+                             bps, &starts[1], &ends[1])) {
+    return 0;
+  }
+  if (!image_plane_in_bounds(img->img_data, img->sz, img->planes[AOM_PLANE_V],
+                             img->stride[AOM_PLANE_V], (size_t)yv12->uv_width,
+                             (size_t)yv12->uv_height, uv_border_x, uv_border_y,
+                             bps, &starts[2], &ends[2])) {
+    return 0;
+  }
+
+  for (int i = 0; i < 3; ++i) {
+    for (int j = i + 1; j < 3; ++j) {
+      if (starts[i] < ends[j] && starts[j] < ends[i]) return 0;
+    }
+  }
+  return 1;
+}
+
 static inline aom_codec_err_t image2yuvconfig(const aom_image_t *img,
                                               YV12_BUFFER_CONFIG *yv12) {
+  if (img->x_chroma_shift > 1 || img->y_chroma_shift > 1) {
+    memset(yv12, 0, sizeof(*yv12));
+    return AOM_CODEC_INVALID_PARAM;
+  }
+
   yv12->y_buffer = img->planes[AOM_PLANE_Y];
   yv12->u_buffer = img->planes[AOM_PLANE_U];
   yv12->v_buffer = img->planes[AOM_PLANE_V];
@@ -106,6 +201,13 @@ static inline aom_codec_err_t image2yuvconfig(const aom_image_t *img,

   yv12->y_stride = img->stride[AOM_PLANE_Y];
   yv12->uv_stride = img->stride[AOM_PLANE_U];
+  if (img->fmt == AOM_IMG_FMT_NV12) {
+    yv12->v_buffer = NULL;
+  } else if (img->stride[AOM_PLANE_U] != img->stride[AOM_PLANE_V]) {
+    yv12->u_buffer = NULL;
+    yv12->v_buffer = NULL;
+    yv12->uv_stride = 0;
+  }
   yv12->color_primaries = img->cp;
   yv12->transfer_characteristics = img->tc;
   yv12->matrix_coefficients = img->mc;
@@ -124,21 +226,36 @@ static inline aom_codec_err_t image2yuvconfig(const aom_image_t *img,
     // should work correctly.
     // However, before we do any pixel operations we need to cast the address
     // to a uint16 ponter and double its value.
-    yv12->y_buffer = CONVERT_TO_BYTEPTR(yv12->y_buffer);
-    yv12->u_buffer = CONVERT_TO_BYTEPTR(yv12->u_buffer);
-    yv12->v_buffer = CONVERT_TO_BYTEPTR(yv12->v_buffer);
-    yv12->y_stride >>= 1;
-    yv12->uv_stride >>= 1;
+    if ((((uintptr_t)yv12->y_buffer) & 1) || (yv12->y_stride & 1)) {
+      yv12->y_buffer = NULL;
+      yv12->y_stride = 0;
+    } else {
+      yv12->y_buffer = CONVERT_TO_BYTEPTR(yv12->y_buffer);
+      yv12->y_stride >>= 1;
+    }
+    if ((((uintptr_t)yv12->u_buffer) & 1) ||
+        (((uintptr_t)yv12->v_buffer) & 1) || (yv12->uv_stride & 1)) {
+      yv12->u_buffer = NULL;
+      yv12->v_buffer = NULL;
+      yv12->uv_stride = 0;
+    } else {
+      yv12->u_buffer = CONVERT_TO_BYTEPTR(yv12->u_buffer);
+      yv12->v_buffer = CONVERT_TO_BYTEPTR(yv12->v_buffer);
+      yv12->uv_stride >>= 1;
+    }
     yv12->flags = YV12_FLAG_HIGHBITDEPTH;
   } else {
     yv12->flags = 0;
   }

   // Note(yunqing): if img is allocated the same as the frame buffer, y_stride
-  // is 32-byte aligned. Also, handle the cases while allocating img without a
-  // border or stride_align is less than 32.
-  int border = (yv12->y_stride - (int)((img->w + 31) & ~31u)) / 2;
-  yv12->border = (border < 0) ? 0 : border;
+  // is 32-byte aligned. Also verify that the backing buffer actually has space
+  // for this border around every plane so stride padding alone is not mistaken
+  // for an allocated border.
+  const int64_t aligned_w = ((int64_t)img->w + 31) & ~(int64_t)31;
+  const int64_t border64 = ((int64_t)yv12->y_stride - aligned_w) / 2;
+  const int border = (border64 > 0 && border64 <= INT_MAX) ? (int)border64 : 0;
+  yv12->border = image_has_border_space(img, yv12, border) ? border : 0;
   yv12->subsampling_x = img->x_chroma_shift;
   yv12->subsampling_y = img->y_chroma_shift;
   yv12->metadata = img->metadata;
diff --git a/av1/decoder/decoder.c b/av1/decoder/decoder.c
index 91a356a838..96a858b4d9 100644
--- a/av1/decoder/decoder.c
+++ b/av1/decoder/decoder.c
@@ -256,12 +256,6 @@ void av1_visit_palette(AV1Decoder *const pbi, MACROBLOCKD *const xd,
   }
 }

-static int equal_dimensions(const YV12_BUFFER_CONFIG *a,
-                            const YV12_BUFFER_CONFIG *b) {
-  return a->y_height == b->y_height && a->y_width == b->y_width &&
-         a->uv_height == b->uv_height && a->uv_width == b->uv_width;
-}
-
 aom_codec_err_t av1_copy_reference_dec(AV1Decoder *pbi, int idx,
                                        YV12_BUFFER_CONFIG *sd) {
   AV1_COMMON *cm = &pbi->common;
@@ -272,26 +266,18 @@ aom_codec_err_t av1_copy_reference_dec(AV1Decoder *pbi, int idx,
     aom_set_error(&pbi->error, AOM_CODEC_ERROR, "No reference frame");
     return pbi->error.error_code;
   }
-  if (!equal_dimensions(cfg, sd)) {
-    aom_set_error(&pbi->error, AOM_CODEC_ERROR, "Incorrect buffer dimensions");
+  if (!aom_yv12_same_size_and_format(cfg, sd, num_planes)) {
+    aom_set_error(&pbi->error, AOM_CODEC_ERROR,
+                  "Incorrect buffer dimensions or format");
     return pbi->error.error_code;
   }

-  aom_yv12_copy_frame(cfg, sd, num_planes);
+  // sd is the caller's image, which has no border to extend.
+  aom_yv12_copy_frame_planes(cfg, sd, num_planes);

   return AOM_CODEC_OK;
 }

-static int equal_dimensions_and_border(const YV12_BUFFER_CONFIG *a,
-                                       const YV12_BUFFER_CONFIG *b) {
-  return a->y_height == b->y_height && a->y_width == b->y_width &&
-         a->uv_height == b->uv_height && a->uv_width == b->uv_width &&
-         a->y_stride == b->y_stride && a->uv_stride == b->uv_stride &&
-         a->border == b->border &&
-         (a->flags & YV12_FLAG_HIGHBITDEPTH) ==
-             (b->flags & YV12_FLAG_HIGHBITDEPTH);
-}
-
 aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx,
                                       int use_external_ref,
                                       YV12_BUFFER_CONFIG *sd) {
@@ -306,26 +292,36 @@ aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx,
   }

   if (!use_external_ref) {
-    if (!equal_dimensions(ref_buf, sd)) {
+    if (!aom_yv12_same_size_and_format(ref_buf, sd, num_planes)) {
       aom_internal_error(cm->error, AOM_CODEC_ERROR,
-                         "Incorrect buffer dimensions");
+                         "Incorrect buffer dimensions or format");
+    }
+    if (ref_buf->use_external_reference_buffers) {
+      ref_buf->y_buffer = ref_buf->store_buf_adr[0];
+      ref_buf->u_buffer = ref_buf->store_buf_adr[1];
+      ref_buf->v_buffer = ref_buf->store_buf_adr[2];
+      ref_buf->use_external_reference_buffers = 0;
     }
     // Overwrite the reference frame buffer.
     aom_yv12_copy_frame(sd, ref_buf, num_planes);
   } else {
-    if (!equal_dimensions_and_border(ref_buf, sd)) {
+    if (!aom_yv12_same_dimensions_and_border(ref_buf, sd, num_planes)) {
       aom_internal_error(cm->error, AOM_CODEC_ERROR,
-                         "Incorrect buffer dimensions");
+                         "Incorrect buffer dimensions or format");
     }
     // Overwrite the reference frame buffer pointers.
     // Once we no longer need the external reference buffer, these pointers
     // are restored.
-    ref_buf->store_buf_adr[0] = ref_buf->y_buffer;
-    ref_buf->store_buf_adr[1] = ref_buf->u_buffer;
-    ref_buf->store_buf_adr[2] = ref_buf->v_buffer;
+    if (!ref_buf->use_external_reference_buffers) {
+      ref_buf->store_buf_adr[0] = ref_buf->y_buffer;
+      ref_buf->store_buf_adr[1] = ref_buf->u_buffer;
+      ref_buf->store_buf_adr[2] = ref_buf->v_buffer;
+    }
     ref_buf->y_buffer = sd->y_buffer;
-    ref_buf->u_buffer = sd->u_buffer;
-    ref_buf->v_buffer = sd->v_buffer;
+    if (num_planes > 1) {
+      ref_buf->u_buffer = sd->u_buffer;
+      ref_buf->v_buffer = sd->v_buffer;
+    }
     ref_buf->use_external_reference_buffers = 1;
   }

@@ -337,11 +333,16 @@ aom_codec_err_t av1_copy_new_frame_dec(AV1_COMMON *cm,
                                        YV12_BUFFER_CONFIG *sd) {
   const int num_planes = av1_num_planes(cm);

-  if (!equal_dimensions_and_border(new_frame, sd)) {
-    aom_set_error(cm->error, AOM_CODEC_ERROR, "Incorrect buffer dimensions");
+  if (!aom_yv12_same_dimensions_and_border(new_frame, sd, num_planes)) {
+    aom_set_error(cm->error, AOM_CODEC_ERROR,
+                  "Incorrect buffer dimensions or format");
     return cm->error->error_code;
   }

+  sd->y_crop_width = new_frame->y_crop_width;
+  sd->y_crop_height = new_frame->y_crop_height;
+  sd->uv_crop_width = new_frame->uv_crop_width;
+  sd->uv_crop_height = new_frame->uv_crop_height;
   aom_yv12_copy_frame(new_frame, sd, num_planes);

   return AOM_CODEC_OK;
diff --git a/av1/encoder/encoder.c b/av1/encoder/encoder.c
index 50381a213f..2913303d95 100644
--- a/av1/encoder/encoder.c
+++ b/av1/encoder/encoder.c
@@ -1947,24 +1947,23 @@ int av1_copy_reference_enc(AV1_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd) {
   AV1_COMMON *const cm = &cpi->common;
   const int num_planes = av1_num_planes(cm);
   YV12_BUFFER_CONFIG *cfg = get_ref_frame(cm, idx);
-  if (cfg) {
-    aom_yv12_copy_frame(cfg, sd, num_planes);
-    return 0;
-  } else {
+  if (cfg == NULL || !aom_yv12_same_size_and_format(cfg, sd, num_planes)) {
     return -1;
   }
+  // sd is the caller's image, which has no border to extend.
+  aom_yv12_copy_frame_planes(cfg, sd, num_planes);
+  return 0;
 }

 int av1_set_reference_enc(AV1_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd) {
   AV1_COMMON *const cm = &cpi->common;
   const int num_planes = av1_num_planes(cm);
   YV12_BUFFER_CONFIG *cfg = get_ref_frame(cm, idx);
-  if (cfg) {
-    aom_yv12_copy_frame(sd, cfg, num_planes);
-    return 0;
-  } else {
+  if (cfg == NULL || !aom_yv12_same_size_and_format(cfg, sd, num_planes)) {
     return -1;
   }
+  aom_yv12_copy_frame(sd, cfg, num_planes);
+  return 0;
 }

 #ifdef OUTPUT_YUV_REC
@@ -6022,13 +6021,19 @@ aom_codec_err_t av1_copy_new_frame_enc(AV1_COMMON *cm,
                                        YV12_BUFFER_CONFIG *new_frame,
                                        YV12_BUFFER_CONFIG *sd) {
   const int num_planes = av1_num_planes(cm);
-  if (!equal_dimensions_and_border(new_frame, sd))
-    aom_internal_error(cm->error, AOM_CODEC_ERROR,
-                       "Incorrect buffer dimensions");
-  else
-    aom_yv12_copy_frame(new_frame, sd, num_planes);
+  if (!aom_yv12_same_dimensions_and_border(new_frame, sd, num_planes)) {
+    aom_set_error(cm->error, AOM_CODEC_ERROR,
+                  "Incorrect buffer dimensions or format");
+    return cm->error->error_code;
+  }

-  return cm->error->error_code;
+  sd->y_crop_width = new_frame->y_crop_width;
+  sd->y_crop_height = new_frame->y_crop_height;
+  sd->uv_crop_width = new_frame->uv_crop_width;
+  sd->uv_crop_height = new_frame->uv_crop_height;
+  aom_yv12_copy_frame(new_frame, sd, num_planes);
+
+  return AOM_CODEC_OK;
 }

 int av1_set_internal_size(AV1EncoderConfig *const oxcf,
diff --git a/av1/encoder/encoder_utils.h b/av1/encoder/encoder_utils.h
index 8691e48436..9b5823b6aa 100644
--- a/av1/encoder/encoder_utils.h
+++ b/av1/encoder/encoder_utils.h
@@ -893,16 +893,6 @@ static inline void restore_extra_coding_context(AV1_COMP *cpi) {
   cpi->frame_index_set = cc->frame_index_set;
 }

-static inline int equal_dimensions_and_border(const YV12_BUFFER_CONFIG *a,
-                                              const YV12_BUFFER_CONFIG *b) {
-  return a->y_height == b->y_height && a->y_width == b->y_width &&
-         a->uv_height == b->uv_height && a->uv_width == b->uv_width &&
-         a->y_stride == b->y_stride && a->uv_stride == b->uv_stride &&
-         a->border == b->border &&
-         (a->flags & YV12_FLAG_HIGHBITDEPTH) ==
-             (b->flags & YV12_FLAG_HIGHBITDEPTH);
-}
-
 static inline int update_entropy(bool *ext_refresh_frame_context,
                                  bool *ext_refresh_frame_context_pending,
                                  bool update) {
diff --git a/test/encode_api_test.cc b/test/encode_api_test.cc
index d7eead9e64..c9c3afd0c5 100644
--- a/test/encode_api_test.cc
+++ b/test/encode_api_test.cc
@@ -3708,6 +3708,682 @@ TEST(EncodeAPI, Buganizer504317456) {
 }
 #endif  // !CONFIG_REALTIME_ONLY

+// With internal resizing the reference frames are smaller than the configured
+// frame size, so a configured-size image does not match them and must be
+// rejected by AV1_SET_REFERENCE and AV1_COPY_REFERENCE.
+TEST(EncodeAPI, SetReferenceRejectsMismatchedSize) {
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = 1280;
+  cfg.g_h = 720;
+  cfg.g_lag_in_frames = 0;
+  cfg.rc_resize_mode = 1;  // RESIZE_FIXED
+  cfg.rc_resize_denominator = 16;
+  cfg.rc_resize_kf_denominator = 16;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, cfg.g_w, cfg.g_h, 1);
+  ASSERT_NE(img, nullptr);
+  FillImage(img, 128);
+  ASSERT_EQ(aom_codec_encode(&enc, img, 0, 1, 0), AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (aom_codec_get_cx_data(&enc, &iter) != nullptr) {
+  }
+
+  av1_ref_frame_t ref;
+  ref.idx = 0;
+  ref.use_external_ref = 0;
+  ref.img = *img;
+  EXPECT_EQ(aom_codec_control(&enc, AV1_SET_REFERENCE, &ref), AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&enc, AV1_COPY_REFERENCE, &ref), AOM_CODEC_ERROR);
+
+  aom_img_free(img);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
+// AV1_COPY_REFERENCE copies into the caller's image, which has no border
+// around its planes even when its stride is larger than its width.
+TEST(EncodeAPI, CopyReferenceToImageWithWideStride) {
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = 1288;
+  cfg.g_h = 720;
+  cfg.g_lag_in_frames = 0;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  // A stride alignment of 64 gives a stride of 1344 for a width of 1288.
+  aom_image_t *img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, cfg.g_w, cfg.g_h, 64);
+  ASSERT_NE(img, nullptr);
+  FillImage(img, 128);
+  ASSERT_EQ(aom_codec_encode(&enc, img, 0, 1, 0), AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (aom_codec_get_cx_data(&enc, &iter) != nullptr) {
+  }
+
+  av1_ref_frame_t ref;
+  ref.idx = 0;
+  ref.use_external_ref = 0;
+  ref.img = *img;
+  EXPECT_EQ(aom_codec_control(&enc, AV1_COPY_REFERENCE, &ref), AOM_CODEC_OK);
+
+  aom_img_free(img);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
+#if CONFIG_AV1_DECODER
+// Decoder AV1_COPY_REFERENCE must not extend borders past a small allocated
+// border, must copy the active pixels accurately, and must reject non-planar
+// formats such as NV12.
+TEST(EncodeAPI, DecoderCopyReferenceBorderAndPixels) {
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *src =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32);
+  ASSERT_NE(src, nullptr);
+  for (int p = 0; p < 3; ++p) {
+    const int h = p == 0 ? kHeight : kHeight / 2;
+    const int w = p == 0 ? kWidth : kWidth / 2;
+    for (int r = 0; r < h; ++r) {
+      uint8_t *row = src->planes[p] + r * src->stride[p];
+      for (int c = 0; c < w; ++c) {
+        row[c] = static_cast<uint8_t>((r * 7 + c * 13 + p * 41) & 0xff);
+      }
+    }
+  }
+  ASSERT_EQ(aom_codec_encode(&enc, src, 0, 1, 0), AOM_CODEC_OK);
+
+  // Decode to 8-bit buffers even when FORCE_HIGHBITDEPTH_DECODING is on.
+  aom_codec_dec_cfg_t dec_cfg = {};
+  dec_cfg.allow_lowbitdepth = 1;
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  // Stride alignment 32 with border 1 produces stride 96, which would trick
+  // stride-only border estimation into extending 16 pixels past the 1-pixel
+  // border.
+  aom_image_t *dst = aom_img_alloc_with_border(nullptr, AOM_IMG_FMT_I420,
+                                               kWidth, kHeight, 32, 1, 1);
+  ASSERT_NE(dst, nullptr);
+  av1_ref_frame_t ref = {};
+  ref.idx = 0;
+  ref.img = *dst;
+  ASSERT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &ref), AOM_CODEC_OK);
+
+  av1_ref_frame_t expected_ref = {};
+  expected_ref.idx = 0;
+  ASSERT_EQ(aom_codec_control(&dec, AV1_GET_REFERENCE, &expected_ref),
+            AOM_CODEC_OK);
+  for (int p = 0; p < 3; ++p) {
+    const int h = p == 0 ? kHeight : kHeight / 2;
+    const int w = p == 0 ? kWidth : kWidth / 2;
+    for (int r = 0; r < h; ++r) {
+      EXPECT_EQ(
+          memcmp(dst->planes[p] + r * dst->stride[p],
+                 expected_ref.img.planes[p] + r * expected_ref.img.stride[p],
+                 w),
+          0)
+          << "Mismatch on plane " << p << " row " << r;
+    }
+  }
+
+  // Non-planar NV12 has NULL V plane and must be rejected.
+  aom_image_t *nv12 =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_NV12, kWidth, kHeight, 32);
+  ASSERT_NE(nv12, nullptr);
+  av1_ref_frame_t nv12_ref = {};
+  nv12_ref.idx = 0;
+  nv12_ref.img = *nv12;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &nv12_ref),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &nv12_ref),
+            AOM_CODEC_ERROR);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(nv12);
+  aom_img_free(dst);
+  aom_img_free(src);
+}
+
+TEST(EncodeAPI, CopyReferenceRejectsMismatchedUVStrides) {
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *src =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 128);
+  ASSERT_NE(src, nullptr);
+  FillImage(src, 128);
+  ASSERT_EQ(aom_codec_encode(&enc, src, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_dec_cfg_t dec_cfg = {};
+  dec_cfg.allow_lowbitdepth = 1;
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  // Plane U has stride 64, while plane V only has space for stride 32.
+  std::vector<uint8_t> small_v((kHeight / 2) * (kWidth / 2), 96);
+  av1_ref_frame_t bad_uv = {};
+  bad_uv.idx = 0;
+  bad_uv.img = *src;
+  bad_uv.img.planes[AOM_PLANE_V] = small_v.data();
+  bad_uv.img.stride[AOM_PLANE_V] = kWidth / 2;
+  ASSERT_LT(bad_uv.img.stride[AOM_PLANE_V], bad_uv.img.stride[AOM_PLANE_U]);
+
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &bad_uv),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &bad_uv),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&enc, AV1_COPY_REFERENCE, &bad_uv),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&enc, AV1_SET_REFERENCE, &bad_uv),
+            AOM_CODEC_ERROR);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(src);
+}
+
+TEST(EncodeAPI, ReferenceControlsRejectInvalidChromaShift) {
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *src =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32);
+  ASSERT_NE(src, nullptr);
+  FillImage(src, 128);
+  ASSERT_EQ(aom_codec_encode(&enc, src, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_dec_cfg_t dec_cfg = {};
+  dec_cfg.allow_lowbitdepth = 1;
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  av1_ref_frame_t bad_shift = {};
+  bad_shift.idx = 0;
+  bad_shift.img = *src;
+  bad_shift.img.x_chroma_shift = 32;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &bad_shift),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &bad_shift),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, &bad_shift.img),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_encode(&enc, &bad_shift.img, 1, 1, 0),
+            AOM_CODEC_INVALID_PARAM);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(src);
+}
+
+TEST(EncodeAPI, MonochromeYOnlyReferenceAndCopyNewFrame) {
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  constexpr int kBorder = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  cfg.monochrome = 1;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *src =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32);
+  ASSERT_NE(src, nullptr);
+  FillImage(src, 111);
+  ASSERT_EQ(aom_codec_encode(&enc, src, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_dec_cfg_t dec_cfg = {};
+  dec_cfg.allow_lowbitdepth = 1;
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  constexpr int kStride = kWidth + 2 * kBorder;
+  std::vector<uint8_t> y_buf((kHeight + 2 * kBorder) * kStride, 0);
+  aom_image_t y_only = {};
+  y_only.fmt = AOM_IMG_FMT_I420;
+  y_only.bit_depth = 8;
+  y_only.monochrome = 1;
+  y_only.w = kWidth;
+  y_only.h = kHeight;
+  y_only.d_w = kWidth;
+  y_only.d_h = kHeight;
+  y_only.x_chroma_shift = 1;
+  y_only.y_chroma_shift = 1;
+  y_only.img_data = y_buf.data();
+  y_only.sz = y_buf.size();
+  y_only.planes[AOM_PLANE_Y] = y_buf.data() + kBorder * kStride + kBorder;
+  y_only.stride[AOM_PLANE_Y] = kStride;
+
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, &y_only),
+            AOM_CODEC_OK);
+
+  av1_ref_frame_t ref = {};
+  ref.idx = 0;
+  ref.img = y_only;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &ref), AOM_CODEC_OK);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &ref), AOM_CODEC_OK);
+  ref.use_external_ref = 1;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &ref), AOM_CODEC_OK);
+
+  av1_ref_frame_t got_ref = {};
+  got_ref.idx = 0;
+  ASSERT_EQ(aom_codec_control(&dec, AV1_GET_REFERENCE, &got_ref), AOM_CODEC_OK);
+  EXPECT_EQ(got_ref.img.planes[AOM_PLANE_Y], y_only.planes[AOM_PLANE_Y]);
+  EXPECT_NE(got_ref.img.planes[AOM_PLANE_U], nullptr);
+  EXPECT_NE(got_ref.img.planes[AOM_PLANE_V], nullptr);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(src);
+}
+
+// AV1_COPY_NEW_FRAME_IMAGE and external AV1_SET_REFERENCE must verify that the
+// destination image actually has enough allocated border memory, rather than
+// inferring the border from stride alone.
+TEST(EncodeAPI, CopyNewFrameImageRejectsInsufficientBorder) {
+  auto check_planes_equal = [](const aom_image_t &a, const aom_image_t &b,
+                               int width, int height) {
+    for (int p = 0; p < 3; ++p) {
+      const int h = p == 0 ? height : height / 2;
+      const int w = p == 0 ? width : width / 2;
+      for (int r = 0; r < h; ++r) {
+        EXPECT_EQ(memcmp(a.planes[p] + r * a.stride[p],
+                         b.planes[p] + r * b.stride[p], w),
+                  0)
+            << "Mismatch on plane " << p << " row " << r;
+      }
+    }
+  };
+
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *src =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32);
+  ASSERT_NE(src, nullptr);
+  for (int p = 0; p < 3; ++p) {
+    const int h = p == 0 ? kHeight : kHeight / 2;
+    const int w = p == 0 ? kWidth : kWidth / 2;
+    for (int r = 0; r < h; ++r) {
+      uint8_t *row = src->planes[p] + r * src->stride[p];
+      for (int c = 0; c < w; ++c) {
+        row[c] = static_cast<uint8_t>((r * 5 + c * 11 + p * 29) & 0xff);
+      }
+    }
+  }
+  ASSERT_EQ(aom_codec_encode(&enc, src, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_dec_cfg_t dec_cfg = {};
+  dec_cfg.allow_lowbitdepth = 1;
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  // Border 49 with stride align 32 gives stride 192 (matching border 64), but
+  // only 49 pixels of actual border.
+  aom_image_t *short_dec_img = aom_img_alloc_with_border(
+      nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32, 8, 49);
+  ASSERT_NE(short_dec_img, nullptr);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, short_dec_img),
+            AOM_CODEC_ERROR);
+  av1_ref_frame_t short_ext_ref = {};
+  short_ext_ref.idx = 0;
+  short_ext_ref.use_external_ref = 1;
+  short_ext_ref.img = *short_dec_img;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &short_ext_ref),
+            AOM_CODEC_ERROR);
+
+  // Matching decoder border (64) must succeed and copy pixels accurately.
+  aom_image_t *valid_dec_img = aom_img_alloc_with_border(
+      nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32, 8, 64);
+  ASSERT_NE(valid_dec_img, nullptr);
+  ASSERT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, valid_dec_img),
+            AOM_CODEC_OK);
+  aom_image_t dec_new = {};
+  ASSERT_EQ(aom_codec_control(&dec, AV1_GET_NEW_FRAME_IMAGE, &dec_new),
+            AOM_CODEC_OK);
+  check_planes_equal(*valid_dec_img, dec_new, kWidth, kHeight);
+  av1_ref_frame_t valid_ext_ref = {};
+  valid_ext_ref.idx = 0;
+  valid_ext_ref.use_external_ref = 1;
+  valid_ext_ref.img = *valid_dec_img;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &valid_ext_ref),
+            AOM_CODEC_OK);
+
+  // Encoder AV1_COPY_NEW_FRAME_IMAGE: border (enc_border - 15) has the same
+  // 32-byte-aligned stride as enc_border, so it must be rejected.
+  aom_image_t enc_new = {};
+  ASSERT_EQ(aom_codec_control(&enc, AV1_GET_NEW_FRAME_IMAGE, &enc_new),
+            AOM_CODEC_OK);
+  const int enc_border = (enc_new.stride[AOM_PLANE_Y] - kWidth) / 2;
+  ASSERT_GE(enc_border, 32);
+  aom_image_t *short_enc_img = aom_img_alloc_with_border(
+      nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32, 8, enc_border - 15);
+  ASSERT_NE(short_enc_img, nullptr);
+  EXPECT_EQ(aom_codec_control(&enc, AV1_COPY_NEW_FRAME_IMAGE, short_enc_img),
+            AOM_CODEC_ERROR);
+
+  aom_image_t *valid_enc_img = aom_img_alloc_with_border(
+      nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32, 8, enc_border);
+  ASSERT_NE(valid_enc_img, nullptr);
+  ASSERT_EQ(aom_codec_control(&enc, AV1_COPY_NEW_FRAME_IMAGE, valid_enc_img),
+            AOM_CODEC_OK);
+  check_planes_equal(*valid_enc_img, enc_new, kWidth, kHeight);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(valid_enc_img);
+  aom_img_free(short_enc_img);
+  aom_img_free(valid_dec_img);
+  aom_img_free(short_dec_img);
+  aom_img_free(src);
+
+  // An image with border 0 whose stride alignment matches the bordered frame
+  // stride (128 + 2*64 = 256) must also be rejected.
+  constexpr int kWideW = 128;
+  constexpr int kWideH = 128;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWideW;
+  cfg.g_h = kWideH;
+  cfg.g_lag_in_frames = 0;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *wide_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWideW, kWideH, 256);
+  ASSERT_NE(wide_img, nullptr);
+  FillImage(wide_img, 128);
+  ASSERT_EQ(aom_codec_encode(&enc, wide_img, 0, 1, 0), AOM_CODEC_OK);
+
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), &dec_cfg, 0),
+            AOM_CODEC_OK);
+  iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, wide_img),
+            AOM_CODEC_ERROR);
+
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  aom_img_free(wide_img);
+}
+#endif  // CONFIG_AV1_DECODER
+
+#if CONFIG_AV1_DECODER && CONFIG_AV1_HIGHBITDEPTH
+// The bit depth of the decoder's reference frames comes from the stream, so
+// AV1_COPY_REFERENCE and AV1_SET_REFERENCE must reject an 8-bit image when the
+// stream is 10-bit.
+TEST(EncodeAPI, DecoderCopyReferenceRejectsBitDepthMismatch) {
+  constexpr int kWidth = 320;
+  constexpr int kHeight = 192;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  cfg.g_bit_depth = AOM_BITS_10;
+  cfg.g_input_bit_depth = 10;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, AOM_CODEC_USE_HIGHBITDEPTH),
+            AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *img16 =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I42016, kWidth, kHeight, 32);
+  ASSERT_NE(img16, nullptr);
+  for (int p = 0; p < 3; ++p) {
+    const int h = p == 0 ? kHeight : kHeight / 2;
+    const int w = p == 0 ? kWidth : kWidth / 2;
+    for (int r = 0; r < h; ++r) {
+      uint16_t *row =
+          reinterpret_cast<uint16_t *>(img16->planes[p] + r * img16->stride[p]);
+      for (int c = 0; c < w; ++c) row[c] = 512;
+    }
+  }
+  ASSERT_EQ(aom_codec_encode(&enc, img16, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), nullptr, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  aom_image_t *img8 =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kWidth, kHeight, 32);
+  ASSERT_NE(img8, nullptr);
+  av1_ref_frame_t ref;
+  ref.idx = 0;
+  ref.use_external_ref = 0;
+  ref.img = *img8;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &ref), AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &ref), AOM_CODEC_ERROR);
+
+  aom_img_free(img8);
+  aom_img_free(img16);
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
+TEST(EncodeAPI, ReferenceControlsRejectMisalignedHbd) {
+  constexpr int kWidth = 64;
+  constexpr int kHeight = 64;
+  constexpr int kBorder = 64;
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg.g_w = kWidth;
+  cfg.g_h = kHeight;
+  cfg.g_lag_in_frames = 0;
+  cfg.g_bit_depth = AOM_BITS_10;
+  cfg.g_input_bit_depth = 10;
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, AOM_CODEC_USE_HIGHBITDEPTH),
+            AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+
+  aom_image_t *valid_hbd = aom_img_alloc_with_border(
+      nullptr, AOM_IMG_FMT_I42016, kWidth, kHeight, 32, 8, kBorder);
+  ASSERT_NE(valid_hbd, nullptr);
+  valid_hbd->bit_depth = 10;
+  for (int p = 0; p < 3; ++p) {
+    const int h = p == 0 ? kHeight : kHeight / 2;
+    const int w = p == 0 ? kWidth : kWidth / 2;
+    for (int r = 0; r < h; ++r) {
+      uint16_t *row = reinterpret_cast<uint16_t *>(valid_hbd->planes[p] +
+                                                   r * valid_hbd->stride[p]);
+      for (int c = 0; c < w; ++c) row[c] = 512;
+    }
+  }
+  ASSERT_EQ(aom_codec_encode(&enc, valid_hbd, 0, 1, 0), AOM_CODEC_OK);
+
+  aom_codec_ctx_t dec;
+  ASSERT_EQ(aom_codec_dec_init(&dec, aom_codec_av1_dx(), nullptr, 0),
+            AOM_CODEC_OK);
+  aom_codec_iter_t iter = nullptr;
+  while (const aom_codec_cx_pkt_t *pkt = aom_codec_get_cx_data(&enc, &iter)) {
+    if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) continue;
+    ASSERT_EQ(aom_codec_decode(
+                  &dec, static_cast<const uint8_t *>(pkt->data.frame.buf),
+                  pkt->data.frame.sz, nullptr),
+              AOM_CODEC_OK);
+  }
+  aom_codec_iter_t dec_iter = nullptr;
+  ASSERT_NE(aom_codec_get_frame(&dec, &dec_iter), nullptr);
+
+  // Relocate the bordered HBD image to an odd base address preceded by a canary
+  // byte (0xab); truncating bit 0 would write into odd_base[-1].
+  std::vector<uint8_t> odd_storage(valid_hbd->sz + 3, 0xab);
+  uint8_t *odd_base =
+      odd_storage.data() +
+      ((reinterpret_cast<uintptr_t>(odd_storage.data()) & 1) ? 2 : 1);
+  ASSERT_EQ(reinterpret_cast<uintptr_t>(odd_base) & 1u, 1u);
+  aom_image_t misaligned = *valid_hbd;
+  misaligned.img_data = odd_base;
+  for (int p = 0; p < 3; ++p) {
+    misaligned.planes[p] =
+        odd_base + (valid_hbd->planes[p] - valid_hbd->img_data);
+  }
+
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_NEW_FRAME_IMAGE, &misaligned),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(odd_base[-1], 0xab);
+
+  std::fill(odd_storage.begin(), odd_storage.end(), 0xab);
+  av1_ref_frame_t ref = {};
+  ref.idx = 0;
+  ref.img = misaligned;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &ref), AOM_CODEC_ERROR);
+  EXPECT_EQ(misaligned.planes[AOM_PLANE_Y][-1], 0xab);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &ref), AOM_CODEC_ERROR);
+  ref.use_external_ref = 1;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &ref), AOM_CODEC_ERROR);
+
+  // Also reject odd byte strides on HBD images.
+  av1_ref_frame_t odd_stride = {};
+  odd_stride.idx = 0;
+  odd_stride.img = *valid_hbd;
+  odd_stride.img.stride[AOM_PLANE_Y] += 1;
+  EXPECT_EQ(aom_codec_control(&dec, AV1_COPY_REFERENCE, &odd_stride),
+            AOM_CODEC_ERROR);
+  EXPECT_EQ(aom_codec_control(&dec, AV1_SET_REFERENCE, &odd_stride),
+            AOM_CODEC_ERROR);
+
+  aom_img_free(valid_hbd);
+  ASSERT_EQ(aom_codec_destroy(&dec), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+#endif  // CONFIG_AV1_DECODER && CONFIG_AV1_HIGHBITDEPTH
+
 // Test for issue: 505976409.
 TEST(EncodeAPI, SvcSourceLastTL0Uninitialized) {
   aom_codec_iface_t *iface = aom_codec_av1_cx();