From 62728cd0c696655f34972b47cff1e1e77d84e426 Mon Sep 17 00:00:00 2001 From: Mr-Z-2697 <74594146+Mr-Z-2697@users.noreply.github.com> Date: Sun, 13 Jul 2025 16:09:53 +0800 Subject: [PATCH] Ensuring the mvdLX is compliant The value of the mvdLX should be in the range of [-2^15, 2^15-1], as specified in H.265 7.4.9.9 Motion vector difference semantics. However there was no safety check in this area, the mvdLX have been observed to exceed the range, under some rare circumstances. This casting will cause overflow and underflow, should the mvd exceeds the int16_t range. But because of the decoding process Equation 8-94 to 8-97, and the MV itself having the range of [-2^15, 2^15-1], the decoded MV will still be correct, and mvdLX will be in the legal range. --- source/encoder/entropy.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/source/encoder/entropy.cpp b/source/encoder/entropy.cpp index d506fa441..625ec8ae5 100644 --- a/source/encoder/entropy.cpp +++ b/source/encoder/entropy.cpp @@ -2103,8 +2103,14 @@ void Entropy::codeRefFrmIdx(const CUData& cu, uint32_t absPartIdx, int list) void Entropy::codeMvd(const CUData& cu, uint32_t absPartIdx, int list) { const MV& mvd = cu.m_mvd[list][absPartIdx]; - const int hor = mvd.x; - const int ver = mvd.y; + + /* Cast to ensure the mvdLX is in the range of [-2^15, 2^15-1] as specified in + H.265 7.4.9.9 Motion vector difference semantics. + This casting will cause overflow and underflow, should the mvd exceeds the int16_t range. + But because of the decoding process Equation 8-94 to 8-97, and the MV itself having the range of [-2^15, 2^15-1], + the decoded MV will still be correct, and mvdLX will be in the legal range. */ + const int16_t hor = static_cast(mvd.x); + const int16_t ver = static_cast(mvd.y); encodeBin(hor != 0 ? 1 : 0, m_contextState[OFF_MV_RES_CTX]); encodeBin(ver != 0 ? 1 : 0, m_contextState[OFF_MV_RES_CTX]);