aom: rtc: Fix source_sad setting near boundary

From c08b9808c3c91d21c9c06320db832ecf0f5a7b4c Mon Sep 17 00:00:00 2001
From: Marco Paniconi <[EMAIL REDACTED]>
Date: Tue, 11 Jun 2024 23:30:03 -0700
Subject: [PATCH] rtc: Fix source_sad setting near boundary

Avoid using the src_sad_blk_64x64[] near the boundary
as this may not be set in the scene_detection under
certain conditions (like dropped frame or temporal layers).
So return curr_sb_sad = UINT64_MAX which triggers source_sad
calculation for that boundary block.

This prevents incorrectly setting the value
x->content_state_sb.source_sad_rd near the boundary,
which was causing the psnr regression for scroll clips,
where new text was coming in from the bottom boundary.

Bug: b/343429036
Change-Id: I0611b8f3e87fd05f6115570ab22bad8963f93d64
---
 av1/encoder/encodeframe.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/av1/encoder/encodeframe.c b/av1/encoder/encodeframe.c
index 46e92f8ed..10fc61114 100644
--- a/av1/encoder/encodeframe.c
+++ b/av1/encoder/encodeframe.c
@@ -1008,12 +1008,16 @@ static AOM_INLINE uint64_t get_sb_source_sad(const AV1_COMP *cpi, int mi_row,
   const int blk_64x64_col_index = mi_col / blk_64x64_in_mis;
   const int blk_64x64_row_index = mi_row / blk_64x64_in_mis;
   uint64_t curr_sb_sad = UINT64_MAX;
+  // Avoid the border as sad_blk_64x64 may not be set for the border
+  // in the scene detection.
+  if ((blk_64x64_row_index >= num_blk_64x64_rows - 1) ||
+      (blk_64x64_col_index >= num_blk_64x64_cols - 1)) {
+    return curr_sb_sad;
+  }
   const uint64_t *const src_sad_blk_64x64_data =
       &cpi->src_sad_blk_64x64[blk_64x64_col_index +
                               blk_64x64_row_index * num_blk_64x64_cols];
-  if (cm->seq_params->sb_size == BLOCK_128X128 &&
-      blk_64x64_col_index + 1 < num_blk_64x64_cols &&
-      blk_64x64_row_index + 1 < num_blk_64x64_rows) {
+  if (cm->seq_params->sb_size == BLOCK_128X128) {
     // Calculate SB source SAD by accumulating source SAD of 64x64 blocks in the
     // superblock
     curr_sb_sad = src_sad_blk_64x64_data[0] + src_sad_blk_64x64_data[1] +