aom: Add the saturate_cast_double_to_int() function

From 1e3f557d658c14b1923c160fcce64e7fe9b0ef6b Mon Sep 17 00:00:00 2001
From: Wan-Teh Chang <[EMAIL REDACTED]>
Date: Thu, 8 Aug 2024 11:08:00 -0700
Subject: [PATCH] Add the saturate_cast_double_to_int() function

This was originally added to libvpx in
https://chromium-review.googlesource.com/c/webm/libvpx/+/5673396.

Change-Id: I13f61f688fc4992f24bf6b08f8313261276154d0
---
 aom_dsp/aom_dsp_common.h | 8 ++++++++
 av1/encoder/ratectrl.c   | 5 ++---
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/aom_dsp/aom_dsp_common.h b/aom_dsp/aom_dsp_common.h
index ed82e56129..7667704df3 100644
--- a/aom_dsp/aom_dsp_common.h
+++ b/aom_dsp/aom_dsp_common.h
@@ -12,6 +12,8 @@
 #ifndef AOM_AOM_DSP_AOM_DSP_COMMON_H_
 #define AOM_AOM_DSP_AOM_DSP_COMMON_H_
 
+#include <limits.h>
+
 #include "config/aom_config.h"
 
 #include "aom/aom_integer.h"
@@ -92,6 +94,12 @@ static INLINE unsigned int negative_to_zero(int value) {
   return value & ~(value >> (sizeof(value) * 8 - 1));
 }
 
+// Returns the saturating cast of a double value to int.
+static INLINE int saturate_cast_double_to_int(double d) {
+  if (d > INT_MAX) return INT_MAX;
+  return (int)d;
+}
+
 #ifdef __cplusplus
 }  // extern "C"
 #endif
diff --git a/av1/encoder/ratectrl.c b/av1/encoder/ratectrl.c
index b9b7e28561..ea402201f1 100644
--- a/av1/encoder/ratectrl.c
+++ b/av1/encoder/ratectrl.c
@@ -2607,9 +2607,8 @@ void av1_rc_update_framerate(AV1_COMP *cpi, int width, int height) {
   RATE_CONTROL *const rc = &cpi->rc;
   const int MBs = av1_get_MBs(width, height);
 
-  const double avg_frame_bandwidth =
-      round(oxcf->rc_cfg.target_bandwidth / cpi->framerate);
-  rc->avg_frame_bandwidth = (int)AOMMIN(avg_frame_bandwidth, INT_MAX);
+  rc->avg_frame_bandwidth = saturate_cast_double_to_int(
+      round(oxcf->rc_cfg.target_bandwidth / cpi->framerate));
 
   int64_t vbr_min_bits =
       (int64_t)rc->avg_frame_bandwidth * oxcf->rc_cfg.vbrmin_section / 100;