From 4bd00afcb3c6b45ac5849cd16b354a321e68eba6 Mon Sep 17 00:00:00 2001
From: yaswanthsastry <yaswanth.sastry@multicorewareinc.com>
Date: Thu, 20 Feb 2025 14:59:34 +0530
Subject: [PATCH] Fix inconsistent output with aq-motion and tune grain

---
 source/common/lowres.cpp   | 14 ++++++++++++++
 source/encoder/encoder.cpp |  2 --
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/source/common/lowres.cpp b/source/common/lowres.cpp
index 1596f79da..257259cde 100644
--- a/source/common/lowres.cpp
+++ b/source/common/lowres.cpp
@@ -415,4 +415,18 @@ void Lowres::init(PicYuv *origPic, int poc)
             quarterSampleLowResStrideY,
             widthFullRes / 4, heightFullRes / 4);
     }
+    int cuCount = maxBlocksInRow * maxBlocksInCol;
+    int cuCountFullRes = (origPic->m_param->rc.qgSize > 8) ? cuCount : cuCount << 2;
+    memset(intraCost, 0, sizeof(int32_t) * cuCount);
+    if (!!origPic->m_param->rc.aqMode || !!origPic->m_param->rc.hevcAq || !!origPic->m_param->bAQMotion || !!origPic->m_param->bEnableWeightedPred || !!origPic->m_param->bEnableWeightedBiPred)
+        {
+        memset(qpAqOffset, 0.0, sizeof(double) * cuCountFullRes);
+        memset(invQscaleFactor, 0, sizeof(int) * cuCountFullRes);
+        memset(qpCuTreeOffset, 0.0, sizeof(double) * cuCountFullRes);
+        if (origPic->m_param->rc.qgSize == 8)
+             memset(invQscaleFactor8x8, 0, sizeof(int) * cuCount);
+        memset(edgeInclined, 0, sizeof(int) * cuCountFullRes);
+        }
+     if (origPic->m_param->bAQMotion)
+        memset(qpAqMotionOffset, 0.0, sizeof(double) * cuCountFullRes);
 }
diff --git a/source/encoder/encoder.cpp b/source/encoder/encoder.cpp
index 5932d819f..cf2e95988 100644
--- a/source/encoder/encoder.cpp
+++ b/source/encoder/encoder.cpp
@@ -1599,8 +1599,6 @@ int Encoder::encode(const x265_picture* pic_in, x265_picture* pic_out)
                 inFrame[layer]->m_encodeStartTime = x265_mdate();
                 /* Set lowres scencut and satdCost here to aovid overwriting ANALYSIS_READ
                    decision by lowres init*/
-                int cuCount = inFrame[layer]->m_lowres.maxBlocksInRow * inFrame[layer]->m_lowres.maxBlocksInCol;
-                memset(inFrame[layer]->m_lowres.intraCost, 0, sizeof(int32_t) * cuCount);
                 inFrame[layer]->m_lowres.bScenecut = false;
                 inFrame[layer]->m_lowres.satdCost = (int64_t)-1;
                 inFrame[layer]->m_lowresInit = false;
-- 
2.37.3.windows.1

