From 57d92ff1488101faef01e6428d9a705b8bf692d1 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:22:04 +0200 Subject: [PATCH 01/20] Video: public API additions for defect fixes - TextureUsageBits::VIDEO_OUTPUT_ONLY for decode outputs / encode inputs that never act as DPB pictures (drivers requiring separate DPB images) - H.264 SPS frame cropping (FRAME_CROPPING + crop offsets) - VideoH265EncodePictureDesc to select VPS/SPS/PPS ids on encode - VideoAV1DecodePictureDesc::skipModeFrames - VideoAV1EncodeDecodeInfoDesc::pictureDesc/av1PictureDesc for the metadata-only (no payload header) reconstruction path - documented H.265 generalLevelIdc units and H.264 frame reference flags - documented AV1 encode txMode 0 (backend default), AV1 decode orderHints indexing and the decode setup slot contract Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 30 +++++++++++++++++++++++------- Include/NRIDescs.h | 3 ++- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index a9b39ebf..9b2e1e14 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -85,7 +85,8 @@ NriBits(VideoH264SequenceParameterSetBits, uint16_t, DELTA_PIC_ORDER_ALWAYS_ZERO = NriBit(9), SEPARATE_COLOUR_PLANE = NriBit(10), GAPS_IN_FRAME_NUM_ALLOWED = NriBit(11), - QPPRIME_Y_ZERO_TRANSFORM_BYPASS = NriBit(12) + QPPRIME_Y_ZERO_TRANSFORM_BYPASS = NriBit(12), + FRAME_CROPPING = NriBit(13) ); NriBits(VideoH264PictureParameterSetBits, uint8_t, @@ -109,7 +110,7 @@ NriBits(VideoH264DecodePictureBits, uint8_t, COMPLEMENTARY_FIELD_PAIR = NriBit(5) ); -NriBits(VideoH264DecodeReferenceBits, uint8_t, +NriBits(VideoH264DecodeReferenceBits, uint8_t, // a frame reference sets neither or both of "TOP_FIELD" and "BOTTOM_FIELD" NONE = 0, TOP_FIELD = NriBit(0), BOTTOM_FIELD = NriBit(1), @@ -381,6 +382,10 @@ NriStruct(VideoH264SequenceParameterSetDesc) { uint8_t referenceFrameNum; uint16_t pictureWidthInMbsMinus1; uint16_t pictureHeightInMapUnitsMinus1; + uint16_t frameCropLeftOffset; // used with "FRAME_CROPPING", in "CropUnitX" units (2 luma samples for 4:2:0) + uint16_t frameCropRightOffset; + uint16_t frameCropTopOffset; // used with "FRAME_CROPPING", in "CropUnitY" units (2 luma samples for 4:2:0 progressive) + uint16_t frameCropBottomOffset; }; NriStruct(VideoH264PictureParameterSetDesc) { @@ -408,7 +413,7 @@ NriStruct(VideoH264SessionParametersDesc) { NriStruct(VideoH265ProfileTierLevelDesc) { Nri(VideoH265ProfileTierLevelBits) flags; uint8_t generalProfileIdc; - uint8_t generalLevelIdc; + uint8_t generalLevelIdc; // "general_level_idc" as coded in the bitstream: 30 times the level number (e.g. 120 = level 4) }; NriStruct(VideoH265DecPicBufMgrDesc) { @@ -682,6 +687,12 @@ NriStruct(VideoH264EncodePictureDesc) { NriOptional uint32_t referenceNum; }; +NriStruct(VideoH265EncodePictureDesc) { + uint8_t videoParameterSetId; + uint8_t sequenceParameterSetId; + uint8_t pictureParameterSetId; +}; + NriStruct(VideoAV1ReferenceDesc) { Nri(VideoAV1ReferenceName) name; // NONE describes an AV1 DPB slot that is not mapped to a current-frame reference name uint8_t refFrameIndex; @@ -793,7 +804,7 @@ NriStruct(VideoAV1EncodePictureDesc) { uint16_t renderHeightMinus1; uint8_t codedDenom; uint8_t interpolationFilter; - uint8_t txMode; + uint8_t txMode; // 0 selects the backend default; ONLY_4X4 is implied for lossless frames uint8_t baseQIndex; uint8_t cdefDampingMinus3; uint8_t cdefBits; @@ -846,7 +857,8 @@ NriStruct(VideoAV1DecodePictureDesc) { NriOptional const NriPtr(VideoAV1LoopRestorationDesc) loopRestoration; NriOptional const NriPtr(VideoAV1GlobalMotionDesc) globalMotion; NriOptional const NriPtr(VideoAV1FilmGrainDesc) filmGrain; // used with "APPLY_GRAIN"; TODO: currently unsupported for decode - NriOptional const uint8_t* orderHints; // if provided, must include 8 entries + NriOptional const uint8_t* orderHints; // 8 entries indexed like AV1 "OrderHints[]" by reference frame name: 0 = INTRA_FRAME, 1..7 = LAST..ALTREF; named reference entries are overridden by "references[].orderHint" + Nri(VideoAV1ReferenceName) skipModeFrames[2]; // "SkipModeFrame[0..1]" used with "SKIP_MODE_PRESENT" const NriPtr(VideoAV1DecodeTileDesc) tiles; uint32_t tileNum; NriOptional const NriPtr(VideoAV1ReferenceDesc) references; @@ -861,7 +873,8 @@ NriStruct(VideoDecodeDesc) { NriOptional NriPtr(VideoPicture) setupPicture; // reconstructed/DPB setup picture; required for distinct mode, may alias "dstPicture" in coincide mode NriOptional const NriPtr(VideoReference) references; NriOptional uint32_t referenceNum; - uint32_t dstSlot; // default reconstructed picture slot; neutral H.264 may override it with "referenceSlot"; native DXVA "CurrPic" must use "dstSlot" and reference "PicEntry" indices must match "VideoReference::slot" + uint32_t dstSlot; // default setup slot, always written; neutral H.264 may override it with "referenceSlot"; native DXVA "CurrPic" must use "dstSlot" and reference "PicEntry" indices must match "VideoReference::slot" + // for non-reference pictures, use a slot whose picture is no longer needed, never one referenced by this or a later decode NriOptional const NriPtr(VideoDecodeArgument) arguments; // native DXVA frame arguments; if omitted, the neutral codec picture description is used NriOptional uint32_t argumentNum; NriOptional const NriPtr(VideoH264DecodePictureDesc) h264PictureDesc; // neutral H.264 picture description; required if "argumentNum" is 0 @@ -889,6 +902,8 @@ NriStruct(VideoAV1EncodeDecodeInfoDesc) { uint64_t encodedPayloadHeaderSize; NriOptional const NriPtr(VideoAV1ReferenceDesc) references; // previous AV1 DPB snapshot; required for inter frames NriOptional uint32_t referenceNum; + NriOptional const NriPtr(VideoEncodePictureDesc) pictureDesc; // submitted picture description; required if "encodedPayloadHeader" is not provided + NriOptional const NriPtr(VideoAV1EncodePictureDesc) av1PictureDesc; // submitted AV1 picture description; required if "encodedPayloadHeader" is not provided }; NriStruct(VideoAV1EncodeDecodeInfo) { @@ -929,6 +944,7 @@ NriStruct(VideoEncodeDesc) { NriOptional uint32_t referenceNum; uint32_t reconstructedSlot; NriOptional const NriPtr(VideoH264EncodePictureDesc) h264PictureDesc; + NriOptional const NriPtr(VideoH265EncodePictureDesc) h265PictureDesc; // parameter set selection; all ids default to 0 NriOptional const NriPtr(VideoAV1EncodePictureDesc) av1PictureDesc; NriOptional const NriPtr(VideoH265ReferenceDesc) h265ReferenceDescs; }; @@ -964,7 +980,7 @@ NriStruct(VideoInterface) { // Command buffer // { // Video decode/encode command buffers must be created from "QueueType::VIDEO_DECODE" or "QueueType::VIDEO_ENCODE" queues. - // VK: video session initialization is implicit on first recorded use, so commands for the same session must be recorded in submit order + // VK: video session initialization and rate control changes are applied on recorded use, so commands for the same session must be recorded in submit order void (NRI_CALL *CmdDecodeVideo) (NriRef(CommandBuffer) commandBuffer, const NriRef(VideoDecodeDesc) videoDecodeDesc); void (NRI_CALL *CmdEncodeVideo) (NriRef(CommandBuffer) commandBuffer, const NriRef(VideoEncodeDesc) videoEncodeDesc); diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index 5009d4ac..e8543b36 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -734,7 +734,8 @@ NriBits(TextureUsageBits, uint16_t, // Min compatible access: HOST_TRANSFER = NriBit(6), // HOST_READ/HOST_WRITE Synchronous copy between texture and host memory VIDEO_DECODE = NriBit(7), // VIDEO_DECODE Video decode output / DPB picture VIDEO_ENCODE = NriBit(8), // VIDEO_ENCODE Video encode input / DPB picture - VIDEO_REFERENCE_ONLY = NriBit(9) // VIDEO_* Video DPB/reference-only allocation + VIDEO_REFERENCE_ONLY = NriBit(9), // VIDEO_* Video DPB/reference-only allocation + VIDEO_OUTPUT_ONLY = NriBit(10) // VIDEO_* Video decode output / encode input never used as a DPB picture (required if "decodeDpbAndOutputCoincide" is false) ); // https://docs.vulkan.org/refpages/latest/refpages/source/VkBufferUsageFlagBits.html From 218dad8c9180192e269ddef94fc55075a82f5984 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:25:59 +0200 Subject: [PATCH 02/20] Validation: video checks for defect fixes - reject encode feedback readback buffers that are not CPU-visible (track MemoryLocation on BufferVal for bound, committed and placed buffers) - VIDEO_OUTPUT_ONLY textures: require a video usage, forbid combining with VIDEO_REFERENCE_ONLY, forbid reference pictures and coincident DPB setup - H.264 SPS frame cropping range checks (session parameters, Annex-B writer) - H.265 encode VPS/SPS/PPS selection must exist in the session parameters - AV1 decode SKIP_MODE_PRESENT requires valid, referenced skipModeFrames - AV1 encode decode-info: require pictureDesc/av1PictureDesc and a CPU-visible readback buffer when no payload header is provided - decode setup slot / encode reconstructed slot must not be a current reference - AV1: bound distinct reference slots (names may share a slot); require all 7 reference names for inter frame decode Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 10 +- Source/Validation/BufferVal.h | 9 ++ Source/Validation/CommandBufferVal.hpp | 51 +++++++++- Source/Validation/DeviceVal.hpp | 12 +++ Source/Validation/ImplVal.cpp | 97 ++++++++++++++----- Source/Validation/MemoryVal.hpp | 1 + Source/Validation/VideoPictureVal.h | 2 + Source/Validation/VideoPictureVal.hpp | 7 +- Source/Validation/VideoSessionParametersVal.h | 2 + .../Validation/VideoSessionParametersVal.hpp | 6 ++ 10 files changed, 165 insertions(+), 32 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 9b2e1e14..d7cd4b1d 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -413,7 +413,7 @@ NriStruct(VideoH264SessionParametersDesc) { NriStruct(VideoH265ProfileTierLevelDesc) { Nri(VideoH265ProfileTierLevelBits) flags; uint8_t generalProfileIdc; - uint8_t generalLevelIdc; // "general_level_idc" as coded in the bitstream: 30 times the level number (e.g. 120 = level 4) + uint8_t generalLevelIdc; // "general_level_idc" as coded in the bitstream: 30 times the level number (e.g. 120 = level 4), or 0 (unspecified) }; NriStruct(VideoH265DecPicBufMgrDesc) { @@ -803,8 +803,8 @@ NriStruct(VideoAV1EncodePictureDesc) { uint16_t renderWidthMinus1; uint16_t renderHeightMinus1; uint8_t codedDenom; - uint8_t interpolationFilter; - uint8_t txMode; // 0 selects the backend default; ONLY_4X4 is implied for lossless frames + uint8_t interpolationFilter; // AV1 "interpolation_filter": 0..4 (4 = SWITCHABLE) + uint8_t txMode; // 0 selects the backend default, else AV1 "TxMode" 1..2 (LARGEST, SELECT); ONLY_4X4 is implied for lossless frames uint8_t baseQIndex; uint8_t cdefDampingMinus3; uint8_t cdefBits; @@ -843,8 +843,8 @@ NriStruct(VideoAV1DecodePictureDesc) { uint8_t baseQIndex; uint8_t superresDenom; uint8_t codedDenom; - uint8_t interpolationFilter; - uint8_t txMode; + uint8_t interpolationFilter; // AV1 "interpolation_filter": 0..4 (4 = SWITCHABLE) + uint8_t txMode; // AV1 "TxMode": 0..2 (ONLY_4X4, LARGEST, SELECT) uint8_t cdefDampingMinus3; uint8_t cdefBits; uint8_t deltaQRes; diff --git a/Source/Validation/BufferVal.h b/Source/Validation/BufferVal.h index 4fb10583..5ba35401 100644 --- a/Source/Validation/BufferVal.h +++ b/Source/Validation/BufferVal.h @@ -34,6 +34,14 @@ struct BufferVal final : public ObjectVal { m_IsBoundToMemory = true; } + inline void SetMemoryLocation(MemoryLocation memoryLocation) { + m_MemoryLocation = memoryLocation; + } + + inline bool IsHostVisible() const { + return m_IsBoundToMemory && m_MemoryLocation != MemoryLocation::DEVICE; // "MAX_NUM" = unknown (wrapped) + } + //================================================================================================================ // NRI //================================================================================================================ @@ -45,6 +53,7 @@ struct BufferVal final : public ObjectVal { private: BufferDesc m_Desc = {}; // .natvis MemoryVal* m_Memory = nullptr; + MemoryLocation m_MemoryLocation = MemoryLocation::MAX_NUM; bool m_IsBoundToMemory = false; bool m_IsMapped = false; }; diff --git a/Source/Validation/CommandBufferVal.hpp b/Source/Validation/CommandBufferVal.hpp index d2c2a839..a4e9a58e 100644 --- a/Source/Validation/CommandBufferVal.hpp +++ b/Source/Validation/CommandBufferVal.hpp @@ -324,7 +324,7 @@ static inline bool IsVideoPictureUsageValid(const VideoPictureVal& picture, Vide if (picture.GetUsage() == usage) return true; - return usage == VideoPictureUsage::DECODE_REFERENCE && picture.GetUsage() == VideoPictureUsage::DECODE_OUTPUT; + return usage == VideoPictureUsage::DECODE_REFERENCE && picture.GetUsage() == VideoPictureUsage::DECODE_OUTPUT && !picture.IsOutputOnly(); } static inline bool IsVideoPictureValidForSession(const VideoPictureVal& picture, VideoPictureUsage usage, const VideoSessionDesc& sessionDesc) { @@ -416,6 +416,20 @@ static inline bool IsVideoAV1LoopRestorationDescValid(const VideoAV1LoopRestorat return desc.lrUvShift <= desc.lrUnitShift; } +static inline bool IsVideoAV1CdefDescValid(const VideoAV1CdefDesc& desc) { + for (uint32_t i = 0; i < 8; i++) { + if (desc.yPrimaryStrength[i] > 15 || desc.ySecondaryStrength[i] > 3 || desc.uvPrimaryStrength[i] > 15 || desc.uvSecondaryStrength[i] > 3) + return false; + } + + return true; +} + +// AV1 "interpolation_filter" (4 = SWITCHABLE) and "TxMode" +static inline bool AreVideoAV1PictureModesValid(uint8_t interpolationFilter, uint8_t txMode) { + return interpolationFilter <= video::av1::INTERPOLATION_FILTER_SWITCHABLE && txMode <= video::av1::TX_MODE_SELECT; +} + static inline bool IsVideoAV1InterFrameWithoutReferences(VideoFrameType frameType, uint32_t referenceNum) { return (frameType == VideoFrameType::P || frameType == VideoFrameType::B) && referenceNum == 0; } @@ -456,6 +470,14 @@ static bool IsVideoAV1DecodePictureDescValid(const VideoDecodeDesc& videoDecodeD if (IsVideoAV1InterFrameWithoutReferences(desc.frameType, videoDecodeDesc.referenceNum)) return false; + // Inter frames code "ref_frame_idx" for every reference name (AV1 "uncompressed_header") + if (desc.frameType == VideoFrameType::P || desc.frameType == VideoFrameType::B) { + for (uint8_t name = (uint8_t)VideoAV1ReferenceName::LAST; name <= (uint8_t)VideoAV1ReferenceName::ALTREF; name++) { + if (!HasVideoAV1ReferenceName(desc.references, desc.referenceNum, (VideoAV1ReferenceName)name)) + return false; + } + } + for (uint32_t i = 0; i < desc.tileNum; i++) { const VideoAV1DecodeTileDesc& tile = desc.tiles[i]; if (tile.offset >= videoDecodeDesc.bitstream.size || tile.size > videoDecodeDesc.bitstream.size - tile.offset) @@ -465,12 +487,22 @@ static bool IsVideoAV1DecodePictureDescValid(const VideoDecodeDesc& videoDecodeD if (!IsVideoAV1ReferenceNameValid(desc.primaryReferenceName)) return false; + if (desc.flags & VideoAV1PictureBits::SKIP_MODE_PRESENT) { + for (VideoAV1ReferenceName skipModeFrame : desc.skipModeFrames) { + if (skipModeFrame == VideoAV1ReferenceName::NONE || !IsVideoAV1ReferenceNameValid(skipModeFrame) || !HasVideoAV1ReferenceName(desc.references, desc.referenceNum, skipModeFrame)) + return false; + } + } + if (desc.tileLayout && !IsVideoAV1TileLayoutValid(*desc.tileLayout)) return false; if (desc.loopRestoration && !IsVideoAV1LoopRestorationDescValid(*desc.loopRestoration)) return false; + if ((desc.cdef && !IsVideoAV1CdefDescValid(*desc.cdef)) || !AreVideoAV1PictureModesValid(desc.interpolationFilter, desc.txMode)) + return false; + for (uint32_t i = 0; i < desc.referenceNum; i++) { const VideoAV1ReferenceDesc& reference = desc.references[i]; if (!IsVideoAV1ReferenceNameValid(reference.name) || !IsVideoFrameTypeValid(reference.frameType) || reference.refFrameIndex >= 8) @@ -506,6 +538,9 @@ static bool IsVideoAV1EncodePictureDescValid(const VideoEncodeDesc& videoEncodeD if (desc.loopRestoration && !IsVideoAV1LoopRestorationDescValid(*desc.loopRestoration)) return false; + if ((desc.cdef && !IsVideoAV1CdefDescValid(*desc.cdef)) || !AreVideoAV1PictureModesValid(desc.interpolationFilter, desc.txMode)) + return false; + if (desc.refreshFrameFlags && !videoEncodeDesc.reconstructedPicture) return false; @@ -1620,6 +1655,7 @@ NRI_INLINE void CommandBufferVal::DecodeVideo(const VideoDecodeDesc& videoDecode } NRI_RETURN_ON_FAILURE(&m_Device, isDpbAndOutputDistinct ? capabilities.decodeDpbAndOutputDistinct : capabilities.decodeDpbAndOutputCoincide, ReturnVoid(), "the video session does not support the requested decode output and DPB setup mode"); + NRI_RETURN_ON_FAILURE(&m_Device, videoDecodeDesc.setupPicture || !sessionVal.GetDesc().maxReferenceNum || !dstPictureVal.IsOutputOnly(), ReturnVoid(), "'dstPicture' uses a 'VIDEO_OUTPUT_ONLY' texture and can't be the DPB setup picture; provide a distinct 'setupPicture'"); if (videoDecodeDesc.argumentNum > 10) { NRI_REPORT_ERROR(&m_Device, "'argumentNum' must be <= 10"); @@ -1633,7 +1669,10 @@ NRI_INLINE void CommandBufferVal::DecodeVideo(const VideoDecodeDesc& videoDecode NRI_RETURN_ON_FAILURE(&m_Device, IsVideoDecodeDpbLayoutValid(videoDecodeDesc, sessionVal.GetDesc().maxReferenceNum), ReturnVoid(), "'references' exceed the session capacity or contain duplicate slots"); + const uint32_t setupSlot = video::GetDecodeSetupSlot(videoDecodeDesc); + for (uint32_t i = 0; i < videoDecodeDesc.referenceNum; i++) { + NRI_RETURN_ON_FAILURE(&m_Device, setupSlot != videoDecodeDesc.references[i].slot, ReturnVoid(), "the decode setup slot must not match 'references[%u].slot'", i); NRI_RETURN_ON_FAILURE(&m_Device, videoDecodeDesc.references[i].picture, ReturnVoid(), "'references[%u].picture' is NULL", i); VideoPictureVal& pictureVal = *(VideoPictureVal*)videoDecodeDesc.references[i].picture; @@ -1789,6 +1828,15 @@ NRI_INLINE void CommandBufferVal::EncodeVideo(const VideoEncodeDesc& videoEncode NRI_RETURN_ON_FAILURE(&m_Device, ¶metersVal.GetSession() == &sessionVal, ReturnVoid(), "'parameters' must belong to 'session'"); NRI_RETURN_ON_FAILURE(&m_Device, !videoEncodeDesc.h264PictureDesc || sessionVal.GetDesc().codec == VideoCodec::H264, ReturnVoid(), "'h264PictureDesc' requires an H.264 session"); NRI_RETURN_ON_FAILURE(&m_Device, !videoEncodeDesc.h265ReferenceDescs || sessionVal.GetDesc().codec == VideoCodec::H265, ReturnVoid(), "'h265ReferenceDescs' require an H.265 session"); + NRI_RETURN_ON_FAILURE(&m_Device, !videoEncodeDesc.h265PictureDesc || sessionVal.GetDesc().codec == VideoCodec::H265, ReturnVoid(), "'h265PictureDesc' requires an H.265 session"); + + if (sessionVal.GetDesc().codec == VideoCodec::H265) { + const VideoH265EncodePictureDesc h265PictureDesc = videoEncodeDesc.h265PictureDesc ? *videoEncodeDesc.h265PictureDesc : VideoH265EncodePictureDesc{}; + const bool isParameterSetValid = parametersVal.HasH265Parameters() + ? parametersVal.IsH265ParameterSetValid(h265PictureDesc.videoParameterSetId, h265PictureDesc.sequenceParameterSetId, h265PictureDesc.pictureParameterSetId) + : (h265PictureDesc.videoParameterSetId == 0 && h265PictureDesc.sequenceParameterSetId == 0 && h265PictureDesc.pictureParameterSetId == 0); + NRI_RETURN_ON_FAILURE(&m_Device, isParameterSetValid, ReturnVoid(), "'h265PictureDesc' must select a matching VPS/SPS/PPS chain from 'parameters' (all ids must be 0 for internal default parameters)"); + } NRI_RETURN_ON_FAILURE(&m_Device, !videoEncodeDesc.av1PictureDesc || sessionVal.GetDesc().codec == VideoCodec::AV1, ReturnVoid(), "'av1PictureDesc' requires an AV1 session"); const uint8_t h264SequenceParameterSetId = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->sequenceParameterSetId : 0; const uint8_t h264PictureParameterSetId = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->pictureParameterSetId : 0; @@ -1820,6 +1868,7 @@ NRI_INLINE void CommandBufferVal::EncodeVideo(const VideoEncodeDesc& videoEncode NRI_RETURN_ON_FAILURE(&m_Device, IsVideoEncodeDpbLayoutValid(videoEncodeDesc, sessionVal.GetDesc().maxReferenceNum), ReturnVoid(), "'references' exceed the session capacity or contain duplicate slots"); for (uint32_t i = 0; i < videoEncodeDesc.referenceNum; i++) { + NRI_RETURN_ON_FAILURE(&m_Device, !videoEncodeDesc.reconstructedPicture || videoEncodeDesc.reconstructedSlot != videoEncodeDesc.references[i].slot, ReturnVoid(), "'reconstructedSlot' must not match 'references[%u].slot'", i); NRI_RETURN_ON_FAILURE(&m_Device, videoEncodeDesc.references[i].picture, ReturnVoid(), "'references[%u].picture' is NULL", i); VideoPictureVal& pictureVal = *(VideoPictureVal*)videoEncodeDesc.references[i].picture; diff --git a/Source/Validation/DeviceVal.hpp b/Source/Validation/DeviceVal.hpp index e63df577..079d877b 100644 --- a/Source/Validation/DeviceVal.hpp +++ b/Source/Validation/DeviceVal.hpp @@ -353,6 +353,8 @@ NRI_INLINE Result DeviceVal::CreateTexture(const TextureDesc& textureDesc, Textu NRI_RETURN_ON_FAILURE(this, textureDesc.videoCodec < VideoCodec::MAX_NUM, Result::INVALID_ARGUMENT, "'videoCodec' is invalid"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) || textureDesc.videoCodec != VideoCodec::NONE, Result::INVALID_ARGUMENT, "'videoCodec' must not be 'NONE' for video textures"); + NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY) || ((textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) && !(textureDesc.usage & TextureUsageBits::VIDEO_REFERENCE_ONLY)), Result::INVALID_ARGUMENT, + "'VIDEO_OUTPUT_ONLY' requires 'VIDEO_DECODE' or 'VIDEO_ENCODE' and is incompatible with 'VIDEO_REFERENCE_ONLY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || (GetFormatSupport(textureDesc.format) & FormatSupportBits::HOST_COPY), Result::UNSUPPORTED, "'format' does not support 'FormatSupportBits::HOST_COPY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || textureDesc.sampleNum == 1, Result::INVALID_ARGUMENT, @@ -970,6 +972,9 @@ NRI_INLINE Result DeviceVal::CreateCommittedBuffer(MemoryLocation memoryLocation if (result == Result::SUCCESS) buffer = (Buffer*)Allocate(GetAllocationCallbacks(), *this, bufferImpl, true); + if (buffer) + ((BufferVal*)buffer)->SetMemoryLocation(memoryLocation); + return result; } @@ -982,6 +987,8 @@ NRI_INLINE Result DeviceVal::CreateCommittedTexture(MemoryLocation memoryLocatio NRI_RETURN_ON_FAILURE(this, textureDesc.videoCodec < VideoCodec::MAX_NUM, Result::INVALID_ARGUMENT, "'videoCodec' is invalid"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) || textureDesc.videoCodec != VideoCodec::NONE, Result::INVALID_ARGUMENT, "'videoCodec' must not be 'NONE' for video textures"); + NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY) || ((textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) && !(textureDesc.usage & TextureUsageBits::VIDEO_REFERENCE_ONLY)), Result::INVALID_ARGUMENT, + "'VIDEO_OUTPUT_ONLY' requires 'VIDEO_DECODE' or 'VIDEO_ENCODE' and is incompatible with 'VIDEO_REFERENCE_ONLY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || (GetFormatSupport(textureDesc.format) & FormatSupportBits::HOST_COPY), Result::UNSUPPORTED, "'format' does not support 'FormatSupportBits::HOST_COPY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || textureDesc.sampleNum == 1, Result::INVALID_ARGUMENT, @@ -1110,6 +1117,9 @@ NRI_INLINE Result DeviceVal::CreatePlacedBuffer(Memory* memory, uint64_t offset, if (result == Result::SUCCESS) buffer = (Buffer*)Allocate(GetAllocationCallbacks(), *this, bufferImpl, !memory); + if (buffer && !memory) + ((BufferVal*)buffer)->SetMemoryLocation((MemoryLocation)offset); + // Update if (buffer && memory) { MemoryVal& memoryVal = *(MemoryVal*)memory; @@ -1127,6 +1137,8 @@ NRI_INLINE Result DeviceVal::CreatePlacedTexture(Memory* memory, uint64_t offset NRI_RETURN_ON_FAILURE(this, textureDesc.videoCodec < VideoCodec::MAX_NUM, Result::INVALID_ARGUMENT, "'videoCodec' is invalid"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) || textureDesc.videoCodec != VideoCodec::NONE, Result::INVALID_ARGUMENT, "'videoCodec' must not be 'NONE' for video textures"); + NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY) || ((textureDesc.usage & (TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_ENCODE)) && !(textureDesc.usage & TextureUsageBits::VIDEO_REFERENCE_ONLY)), Result::INVALID_ARGUMENT, + "'VIDEO_OUTPUT_ONLY' requires 'VIDEO_DECODE' or 'VIDEO_ENCODE' and is incompatible with 'VIDEO_REFERENCE_ONLY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || (GetFormatSupport(textureDesc.format) & FormatSupportBits::HOST_COPY), Result::UNSUPPORTED, "'format' does not support 'FormatSupportBits::HOST_COPY'"); NRI_RETURN_ON_FAILURE(this, !(textureDesc.usage & TextureUsageBits::HOST_TRANSFER) || textureDesc.sampleNum == 1, Result::INVALID_ARGUMENT, diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index 62ce094a..9805779f 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -60,6 +60,42 @@ static inline uint8_t GetVideoSessionBitDepth(Format format) { return format == Format::NV12_UNORM ? 8 : 10; } +static inline bool IsVideoH264CroppingValid(const VideoH264SequenceParameterSetDesc& sequence) { + if (!(sequence.flags & VideoH264SequenceParameterSetBits::FRAME_CROPPING)) + return true; + + // 4:2:0 progressive: "CropUnitX = CropUnitY = 2" + const uint32_t width = (sequence.pictureWidthInMbsMinus1 + 1u) * 16u; + const uint32_t height = (sequence.pictureHeightInMapUnitsMinus1 + 1u) * 16u; + + return (sequence.frameCropLeftOffset + sequence.frameCropRightOffset) * 2u < width && (sequence.frameCropTopOffset + sequence.frameCropBottomOffset) * 2u < height; +} + +// "general_level_idc" (H.265 Table A.8, 30 times the level number) or 0 +static inline bool IsVideoH265LevelIdcValid(uint8_t generalLevelIdc) { + constexpr std::array levels = {0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183, 186}; + + return std::find(levels.begin(), levels.end(), generalLevelIdc) != levels.end(); +} + +static inline bool AreVideoH265LevelsValid(const VideoSessionParametersDesc& desc) { + if (!desc.h265Parameters) + return true; + + const VideoH265SessionParametersDesc& parameters = *desc.h265Parameters; + for (uint32_t i = 0; i < parameters.videoParameterSetNum; i++) { + if (!IsVideoH265LevelIdcValid(parameters.videoParameterSets[i].profileTierLevel.generalLevelIdc)) + return false; + } + + for (uint32_t i = 0; i < parameters.sequenceParameterSetNum; i++) { + if (!IsVideoH265LevelIdcValid(parameters.sequenceParameterSets[i].profileTierLevel.generalLevelIdc)) + return false; + } + + return true; +} + static inline bool IsVideoSessionParametersDescValid(const VideoSessionDesc& sessionDesc, const VideoCapabilities& capabilities, const VideoSessionParametersDesc& desc) { constexpr uint8_t h264HighProfileIdc = 100; constexpr uint8_t h265MainProfileIdc = 1; @@ -90,7 +126,7 @@ static inline bool IsVideoSessionParametersDescValid(const VideoSessionDesc& ses for (uint32_t i = 0; i < parameters.sequenceParameterSetNum; i++) { const VideoH264SequenceParameterSetDesc& sequence = parameters.sequenceParameterSets[i]; const bool isProgressive = (sequence.flags & VideoH264SequenceParameterSetBits::FRAME_MBS_ONLY) && !(sequence.flags & VideoH264SequenceParameterSetBits::MB_ADAPTIVE_FRAME_FIELD); - if (sequence.sequenceParameterSetId >= 32 || (sequenceParameterSetMask & (1u << sequence.sequenceParameterSetId)) != 0 || sequence.profileIdc != h264HighProfileIdc || sequence.chromaFormatIdc != 1 || sequence.bitDepthLumaMinus8 != 0 || sequence.bitDepthChromaMinus8 != 0 || !isProgressive) + if (sequence.sequenceParameterSetId >= 32 || (sequenceParameterSetMask & (1u << sequence.sequenceParameterSetId)) != 0 || sequence.profileIdc != h264HighProfileIdc || sequence.chromaFormatIdc != 1 || sequence.bitDepthLumaMinus8 != 0 || sequence.bitDepthChromaMinus8 != 0 || !isProgressive || !IsVideoH264CroppingValid(sequence)) return false; sequenceParameterSetMask |= 1u << sequence.sequenceParameterSetId; @@ -169,9 +205,10 @@ static inline bool IsVideoPictureDescValid(const VideoPictureDesc& desc, const T const TextureUsageBits requiredUsage = desc.usage == VideoPictureUsage::DECODE_OUTPUT || desc.usage == VideoPictureUsage::DECODE_REFERENCE ? TextureUsageBits::VIDEO_DECODE : TextureUsageBits::VIDEO_ENCODE; const bool requiresOperationUsage = desc.usage == VideoPictureUsage::DECODE_OUTPUT || desc.usage == VideoPictureUsage::ENCODE_INPUT; const bool isReferenceOnly = (textureDesc.usage & TextureUsageBits::VIDEO_REFERENCE_ONLY) != 0; + const bool isOutputOnly = (textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY) != 0; const uint32_t layerNum = textureDesc.layerNum ? textureDesc.layerNum : 1; - return (textureDesc.usage & requiredUsage) != 0 && (!requiresOperationUsage || !isReferenceOnly) && desc.layer < layerNum && (!desc.width || desc.width <= textureDesc.width) && (!desc.height || desc.height <= textureDesc.height); + return (textureDesc.usage & requiredUsage) != 0 && (!requiresOperationUsage || !isReferenceOnly) && (requiresOperationUsage || !isOutputOnly) && desc.layer < layerNum && (!desc.width || desc.width <= textureDesc.width) && (!desc.height || desc.height <= textureDesc.height); } static inline bool IsVideoPictureRoleCompatible(VideoPictureUsage usage, VideoPictureRole role) { @@ -203,6 +240,27 @@ static inline bool HasUniqueVideoReferenceSlots(const VideoReference* references return true; } +// Several AV1 reference names may share one "ref_frame_idx" and DPB slot, so the session capacity bounds distinct slots, not entries +static inline bool IsVideoAV1ReferenceLayoutValid(const VideoAV1ReferenceDesc* references, uint32_t referenceNum, uint32_t maxReferenceNum) { + if (referenceNum > video::av1::REFERENCE_FRAME_NUM || (referenceNum && !references)) + return false; + + uint32_t slotNum = 0; + for (uint32_t i = 0; i < referenceNum; i++) { + if (references[i].slot > maxReferenceNum) + return false; + + uint32_t j = 0; + while (j < i && references[j].slot != references[i].slot) + j++; + + if (j == i) + slotNum++; + } + + return slotNum <= maxReferenceNum; +} + static inline bool IsVideoDecodeDpbLayoutValid(const VideoDecodeDesc& desc, uint32_t maxReferenceNum) { if (desc.referenceNum > maxReferenceNum || (desc.referenceNum && !desc.references) || video::GetDecodeSetupSlot(desc) > maxReferenceNum || (desc.references && !HasUniqueVideoReferenceSlots(desc.references, desc.referenceNum))) return false; @@ -236,17 +294,8 @@ static inline bool IsVideoDecodeDpbLayoutValid(const VideoDecodeDesc& desc, uint } } - if (desc.av1PictureDesc) { - const VideoAV1DecodePictureDesc& picture = *desc.av1PictureDesc; - - if (picture.referenceNum > maxReferenceNum || (picture.referenceNum && !picture.references)) - return false; - - for (uint32_t i = 0; i < picture.referenceNum; i++) { - if (picture.references[i].slot > maxReferenceNum) - return false; - } - } + if (desc.av1PictureDesc && !IsVideoAV1ReferenceLayoutValid(desc.av1PictureDesc->references, desc.av1PictureDesc->referenceNum, maxReferenceNum)) + return false; return true; } @@ -279,17 +328,8 @@ static inline bool IsVideoEncodeDpbLayoutValid(const VideoEncodeDesc& desc, uint } } - if (desc.av1PictureDesc) { - const VideoAV1EncodePictureDesc& picture = *desc.av1PictureDesc; - - if (picture.referenceNum > maxReferenceNum || (picture.referenceNum && !picture.references)) - return false; - - for (uint32_t i = 0; i < picture.referenceNum; i++) { - if (picture.references[i].slot > maxReferenceNum) - return false; - } - } + if (desc.av1PictureDesc && !IsVideoAV1ReferenceLayoutValid(desc.av1PictureDesc->references, desc.av1PictureDesc->referenceNum, maxReferenceNum)) + return false; return true; } @@ -1796,6 +1836,8 @@ static Result NRI_CALL CreateVideoSessionParameters(Device& device, const VideoS VideoSessionVal& sessionVal = *(VideoSessionVal*)videoSessionParametersDesc.session; NRI_RETURN_ON_FAILURE(&deviceVal, IsVideoSessionParametersDescValid(sessionVal.GetDesc(), sessionVal.GetCapabilities(), videoSessionParametersDesc), Result::INVALID_ARGUMENT, "'videoSessionParametersDesc' is invalid for the fixed session profile, format or picture layout"); + NRI_RETURN_ON_FAILURE(&deviceVal, AreVideoH265LevelsValid(videoSessionParametersDesc), Result::INVALID_ARGUMENT, + "H.265 'generalLevelIdc' must be 0 or 30 times a level of H.265 Table A.8 (30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183 or 186)"); VideoSessionParametersDesc descImpl = videoSessionParametersDesc; descImpl.session = sessionVal.GetImpl(); @@ -1869,7 +1911,7 @@ static Result NRI_CALL GetVideoPictureState(const VideoPicture& videoPicture, Vi static Result NRI_CALL WriteVideoAnnexBParameterSets(VideoAnnexBParameterSetsDesc& annexBParameterSetsDesc) { if (annexBParameterSetsDesc.codec == VideoCodec::H264) { - if (!annexBParameterSetsDesc.h264Sps || !annexBParameterSetsDesc.h264Pps) + if (!annexBParameterSetsDesc.h264Sps || !annexBParameterSetsDesc.h264Pps || !IsVideoH264CroppingValid(*annexBParameterSetsDesc.h264Sps)) return Result::INVALID_ARGUMENT; } else if (annexBParameterSetsDesc.codec == VideoCodec::H265) { if (!annexBParameterSetsDesc.h265Vps || !annexBParameterSetsDesc.h265Sps || !annexBParameterSetsDesc.h265Pps) @@ -1907,6 +1949,7 @@ static Result NRI_CALL GetVideoEncodeFeedback(VideoSession& videoSession, Buffer VideoSessionVal& videoSessionVal = (VideoSessionVal&)videoSession; BufferVal& resolvedMetadataReadbackVal = (BufferVal&)resolvedMetadataReadback; NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), videoSessionVal.GetDesc().type == VideoSessionType::ENCODE && videoSessionVal.GetCapabilities().encodeFeedbackSupported && videoSessionVal.IsResolvedMetadataRangeValid(resolvedMetadataReadbackVal, resolvedMetadataOffset), Result::INVALID_ARGUMENT, "encode feedback must be supported and 'resolvedMetadataReadback' must be a valid buffer range"); + NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), resolvedMetadataReadbackVal.IsHostVisible(), Result::INVALID_ARGUMENT, "'resolvedMetadataReadback' must be bound to CPU-visible memory"); return videoSessionVal.GetDevice().GetVideoInterfaceImpl().GetVideoEncodeFeedback(*videoSessionVal.GetImpl(), *resolvedMetadataReadbackVal.GetImpl(), resolvedMetadataOffset, feedback); } @@ -1916,6 +1959,10 @@ static Result NRI_CALL GetVideoAV1EncodeDecodeInfo(VideoSession& videoSession, B VideoSessionVal& videoSessionVal = (VideoSessionVal&)videoSession; BufferVal& resolvedMetadataReadbackVal = (BufferVal&)resolvedMetadataReadback; NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), desc.feedback && desc.sequence, Result::INVALID_ARGUMENT, "'feedback' and 'sequence' must be valid"); + + const bool hasPayloadHeader = desc.encodedPayloadHeader && desc.encodedPayloadHeaderSize; + NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), hasPayloadHeader || (desc.pictureDesc && desc.av1PictureDesc), Result::INVALID_ARGUMENT, "'pictureDesc' and 'av1PictureDesc' are required if 'encodedPayloadHeader' is not provided"); + NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), hasPayloadHeader || resolvedMetadataReadbackVal.IsHostVisible(), Result::INVALID_ARGUMENT, "'resolvedMetadataReadback' must be bound to CPU-visible memory"); NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), (desc.references == nullptr) == (desc.referenceNum == 0) && desc.referenceNum <= 8, Result::INVALID_ARGUMENT, "'references' and 'referenceNum' are inconsistent"); NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), !desc.references || HasValidVideoAV1ReferenceKeys(desc.references, desc.referenceNum), Result::INVALID_ARGUMENT, "'references' contain inconsistent AV1 identities"); NRI_RETURN_ON_FAILURE(&videoSessionVal.GetDevice(), videoSessionVal.GetDesc().type == VideoSessionType::ENCODE && videoSessionVal.GetDesc().codec == VideoCodec::AV1 && videoSessionVal.GetCapabilities().encodeFeedbackSupported && videoSessionVal.IsResolvedMetadataRangeValid(resolvedMetadataReadbackVal, resolvedMetadataOffset), Result::INVALID_ARGUMENT, "encode feedback must be supported and 'resolvedMetadataReadback' must be a valid buffer range"); diff --git a/Source/Validation/MemoryVal.hpp b/Source/Validation/MemoryVal.hpp index 9d65b3af..e30b7a86 100644 --- a/Source/Validation/MemoryVal.hpp +++ b/Source/Validation/MemoryVal.hpp @@ -37,6 +37,7 @@ void MemoryVal::Bind(BufferVal& buffer) { m_Buffers.push_back(&buffer); buffer.SetBoundToMemory(this); + buffer.SetMemoryLocation(m_MemoryLocation); } void MemoryVal::Bind(TextureVal& texture) { diff --git a/Source/Validation/VideoPictureVal.h b/Source/Validation/VideoPictureVal.h index 6566a908..99ef01d5 100644 --- a/Source/Validation/VideoPictureVal.h +++ b/Source/Validation/VideoPictureVal.h @@ -13,6 +13,7 @@ struct VideoPictureVal final : public ObjectVal { bool IsSameSubresource(const VideoPictureVal& videoPicture) const; bool IsSameTexture(const VideoPictureVal& videoPicture) const; uint32_t GetTextureLayerNum() const; + bool IsOutputOnly() const; private: const TextureVal* m_Texture = nullptr; @@ -23,5 +24,6 @@ struct VideoPictureVal final : public ObjectVal { uint32_t m_TextureLayerNum = 0; VideoCodec m_Codec = VideoCodec::NONE; VideoPictureUsage m_Usage = VideoPictureUsage::MAX_NUM; + bool m_IsOutputOnly = false; }; } // namespace nri diff --git a/Source/Validation/VideoPictureVal.hpp b/Source/Validation/VideoPictureVal.hpp index 641b11e0..10d98259 100644 --- a/Source/Validation/VideoPictureVal.hpp +++ b/Source/Validation/VideoPictureVal.hpp @@ -9,7 +9,8 @@ NRI_INLINE VideoPictureVal::VideoPictureVal(DeviceVal& device, VideoPicture* imp , m_Layer(desc.layer) , m_TextureLayerNum(textureDesc.layerNum ? textureDesc.layerNum : 1) , m_Codec(textureDesc.videoCodec) - , m_Usage(desc.usage) { + , m_Usage(desc.usage) + , m_IsOutputOnly((textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY) != 0) { } NRI_INLINE VideoPicture* VideoPictureVal::GetImpl() const { @@ -35,3 +36,7 @@ NRI_INLINE bool VideoPictureVal::IsSameTexture(const VideoPictureVal& videoPictu NRI_INLINE uint32_t VideoPictureVal::GetTextureLayerNum() const { return m_TextureLayerNum; } + +NRI_INLINE bool VideoPictureVal::IsOutputOnly() const { + return m_IsOutputOnly; +} diff --git a/Source/Validation/VideoSessionParametersVal.h b/Source/Validation/VideoSessionParametersVal.h index c12e3bef..79f2ed47 100644 --- a/Source/Validation/VideoSessionParametersVal.h +++ b/Source/Validation/VideoSessionParametersVal.h @@ -11,11 +11,13 @@ struct VideoSessionParametersVal final : public ObjectVal { VideoSessionVal& GetSession() const; bool IsH264ParameterSetValid(uint8_t sequenceParameterSetId, uint8_t pictureParameterSetId) const; bool IsH265ParameterSetValid(uint8_t videoParameterSetId, uint8_t sequenceParameterSetId, uint8_t pictureParameterSetId) const; + bool HasH265Parameters() const; private: VideoSessionVal& m_Session; std::array m_H264PpsToSpsPlusOne = {}; std::array m_H265PpsToSpsPlusOne = {}; std::array m_H265PpsToVpsPlusOne = {}; + bool m_HasH265Parameters = false; }; } // namespace nri diff --git a/Source/Validation/VideoSessionParametersVal.hpp b/Source/Validation/VideoSessionParametersVal.hpp index 3464a7a1..6d91c3af 100644 --- a/Source/Validation/VideoSessionParametersVal.hpp +++ b/Source/Validation/VideoSessionParametersVal.hpp @@ -11,6 +11,8 @@ NRI_INLINE VideoSessionParametersVal::VideoSessionParametersVal(DeviceVal& devic } if (desc.h265Parameters) { + m_HasH265Parameters = true; + for (uint32_t i = 0; i < desc.h265Parameters->pictureParameterSetNum; i++) { const VideoH265PictureParameterSetDesc& pictureParameterSet = desc.h265Parameters->pictureParameterSets[i]; m_H265PpsToSpsPlusOne[pictureParameterSet.pictureParameterSetId] = (uint8_t)(pictureParameterSet.sequenceParameterSetId + 1); @@ -34,6 +36,10 @@ NRI_INLINE bool VideoSessionParametersVal::IsH264ParameterSetValid(uint8_t seque return m_H264PpsToSpsPlusOne[pictureParameterSetId] == sequenceParameterSetId + 1; } +NRI_INLINE bool VideoSessionParametersVal::HasH265Parameters() const { + return m_HasH265Parameters; +} + NRI_INLINE bool VideoSessionParametersVal::IsH265ParameterSetValid(uint8_t videoParameterSetId, uint8_t sequenceParameterSetId, uint8_t pictureParameterSetId) const { if (videoParameterSetId >= 16 || sequenceParameterSetId >= 16 || pictureParameterSetId >= 64) return false; From 2d447a317a5b28a7492b63699de461c5bd2129e4 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:36:19 +0200 Subject: [PATCH 03/20] Shared: fix AV1 header reconstruction and H.264 SPS cropping AV1 GetEncodeDecodeInfoFromHeader (single spec-ordered frame header parser replacing the separate key/inter parsers): - read delta_frame_id_minus_1 per reference; allow_high_precision_mv gated on force_integer_mv - quantization: NumPlanes (mono_chrome), diff_uv_delta and V deltas; NumPlanes gating for loop filter, CDEF and loop restoration - 128x128 superblocks in tile info and single-tile layouts - loop restoration: Remap_Lr_Type, lr_unit_shift/lr_uv_shift, USES_LR flags - byte_alignment before the tile group of an OBU_FRAME - inter tail order: reference mode, skip mode (fills skipModeFrames), allow_warped_motion, reduced_tx_set, global motion - superres MiCols from the downscaled width; intrabc only without superres - honor key-frame frame size override; parse delta_lf params - reject film grain with apply_grain, reduced still picture headers and nonzero byte-alignment padding - keep enable_ref_frame_mvs/enable_jnt_comp consistent without order hints Annex-B writer: H.264 SPS frame cropping; reject invalid frame id lengths. Co-Authored-By: Claude Opus 5.5 --- Source/Shared/SharedVideo.h | 941 ++++++++++++++++------------------ Source/Validation/ImplVal.cpp | 15 +- 2 files changed, 451 insertions(+), 505 deletions(-) diff --git a/Source/Shared/SharedVideo.h b/Source/Shared/SharedVideo.h index b1c4154e..63d00be6 100644 --- a/Source/Shared/SharedVideo.h +++ b/Source/Shared/SharedVideo.h @@ -176,6 +176,21 @@ static inline void AppendNalHeader(bitstream::ByteWriter& bytes, uint8_t nalHead bytes.WriteByte(nalHeader); } +// The cropped frame must not be empty: "CropUnitX * (left + right) < PicWidthInSamplesL", "CropUnitY * (top + bottom) < 16 * FrameHeightInMbs" +static inline bool IsFrameCroppingValid(const VideoH264SequenceParameterSetDesc& sps) { + if (!(sps.flags & VideoH264SequenceParameterSetBits::FRAME_CROPPING)) + return true; + + const bool frameMbsOnly = !!(sps.flags & VideoH264SequenceParameterSetBits::FRAME_MBS_ONLY); + const bool hasChroma = sps.chromaFormatIdc != 0 && !(sps.flags & VideoH264SequenceParameterSetBits::SEPARATE_COLOUR_PLANE); + const uint32_t cropUnitX = (hasChroma && sps.chromaFormatIdc != 3) ? 2 : 1; + const uint32_t cropUnitY = ((hasChroma && sps.chromaFormatIdc == 1) ? 2 : 1) * (frameMbsOnly ? 1 : 2); + const uint32_t frameWidth = (sps.pictureWidthInMbsMinus1 + 1u) * 16; + const uint32_t frameHeight = (sps.pictureHeightInMapUnitsMinus1 + 1u) * 16 * (frameMbsOnly ? 1 : 2); + + return (cropUnitX * (sps.frameCropLeftOffset + sps.frameCropRightOffset)) < frameWidth && (cropUnitY * (sps.frameCropTopOffset + sps.frameCropBottomOffset)) < frameHeight; +} + static inline Result WriteAnnexBParameterSets(const VideoAnnexBParameterSetsDesc& desc, bitstream::ByteWriter& bytes) { const bool hasParameterSets = desc.h264Sps && desc.h264Pps; @@ -189,6 +204,9 @@ static inline Result WriteAnnexBParameterSets(const VideoAnnexBParameterSetsDesc if (!highProfileSps || sps.chromaFormatIdc > 3 || sps.pictureOrderCountType > 2 || (pps.flags & VideoH264PictureParameterSetBits::TRANSFORM_8X8_MODE) != 0) return Result::UNSUPPORTED; + if (!IsFrameCroppingValid(sps)) + return Result::INVALID_ARGUMENT; + AppendNalHeader(bytes, 0x67); bitstream::RbspBitWriter spsWriter{bytes}; spsWriter.WriteBits(sps.profileIdc, 8); @@ -233,8 +251,17 @@ static inline Result WriteAnnexBParameterSets(const VideoAnnexBParameterSetsDesc spsWriter.WriteBit(!!(sps.flags & VideoH264SequenceParameterSetBits::MB_ADAPTIVE_FRAME_FIELD)); spsWriter.WriteBit(!!(sps.flags & VideoH264SequenceParameterSetBits::DIRECT_8X8_INFERENCE)); - spsWriter.WriteBit(0); - spsWriter.WriteBit(0); + const bool frameCropping = !!(sps.flags & VideoH264SequenceParameterSetBits::FRAME_CROPPING); + spsWriter.WriteBit(frameCropping); + + if (frameCropping) { + spsWriter.WriteUe(sps.frameCropLeftOffset); + spsWriter.WriteUe(sps.frameCropRightOffset); + spsWriter.WriteUe(sps.frameCropTopOffset); + spsWriter.WriteUe(sps.frameCropBottomOffset); + } + + spsWriter.WriteBit(0); // vui_parameters_present_flag spsWriter.FinishRbsp(); AppendNalHeader(bytes, 0x68); @@ -735,7 +762,8 @@ struct BitReader { bool ByteAlign() { while (bitOffset % 8) { uint32_t bit = 0; - if (!ReadBits(1, bit)) + + if (!ReadBits(1, bit) || bit) return false; } return true; @@ -837,21 +865,6 @@ static inline bool FindFramePayload(const uint8_t* data, size_t size, FramePaylo return false; } -static inline bool PeekGeneratedFrameType(const uint8_t* payload, size_t availablePayloadSize, uint32_t& frameType, uint8_t& showFrame) { - BitReader reader{payload, availablePayloadSize, 0}; - uint8_t showExistingFrame = 0; - if (!reader.ReadFlag(showExistingFrame) || showExistingFrame || !reader.ReadBits(2, frameType) || !reader.ReadFlag(showFrame)) - return false; - - return true; -} - -static inline uint32_t TileLog2(uint32_t blockSize, uint32_t target); -static inline bool ReadDeltaQ(BitReader& reader, int8_t& value); -static inline void BindPointers(VideoAV1EncodeDecodeInfo& info); -static inline void FillIdentityGlobalMotion(VideoAV1GlobalMotionDesc& globalMotion); -static inline void FillSingleTileLayout(VideoAV1EncodeDecodeInfo& info, uint32_t width, uint32_t height); - static inline VideoAV1ReferenceName GetReferenceNameFromReferenceIndex(uint32_t referenceIndex) { switch (referenceIndex) { case 0: @@ -903,344 +916,6 @@ static inline bool BuildInterFrameReferences(const VideoAV1EncodeDecodeInfoDesc& return true; } -static inline bool ParseGeneratedInterFrameHeader(const uint8_t* payload, size_t availablePayloadSize, size_t fullPayloadSize, bool requireTilePayload, - const VideoAV1SequenceDesc& sequence, - std::array& refFrameIndices, VideoAV1EncodeDecodeInfo& info) { - BitReader reader{payload, availablePayloadSize, 0}; - VideoAV1PictureBits flags = VideoAV1PictureBits::SHOW_FRAME | VideoAV1PictureBits::SHOWABLE_FRAME; - - uint8_t showExistingFrame = 0; - uint32_t frameType = 0; - uint8_t showFrame = 0; - uint8_t errorResilient = 0; - uint8_t disableCdfUpdate = 0; - uint8_t allowScreenContentTools = 0; - uint8_t forceIntegerMv = 0; - uint8_t frameSizeOverride = 0; - uint32_t orderHint = 0; - uint32_t primaryRefFrame = 0; - uint32_t refreshFrameFlags = 0; - uint32_t ignored = 0; - if (!reader.ReadFlag(showExistingFrame) || showExistingFrame || !reader.ReadBits(2, frameType) || !reader.ReadFlag(showFrame) || frameType != 1 || !showFrame) - return false; - if (!reader.ReadFlag(errorResilient) || errorResilient || !reader.ReadFlag(disableCdfUpdate)) - return false; - if (disableCdfUpdate) - flags |= VideoAV1PictureBits::DISABLE_CDF_UPDATE | VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF; - if (sequence.seqForceScreenContentTools == SELECT_SCREEN_CONTENT_TOOLS) { - if (!reader.ReadFlag(allowScreenContentTools)) - return false; - } else - allowScreenContentTools = sequence.seqForceScreenContentTools; - if (allowScreenContentTools) { - flags |= VideoAV1PictureBits::ALLOW_SCREEN_CONTENT_TOOLS; - if (sequence.seqForceIntegerMv == SELECT_SCREEN_CONTENT_TOOLS) { - if (!reader.ReadFlag(forceIntegerMv)) - return false; - } else - forceIntegerMv = sequence.seqForceIntegerMv; - if (forceIntegerMv) - flags |= VideoAV1PictureBits::FORCE_INTEGER_MV; - } - - if (sequence.flags & VideoAV1SequenceBits::FRAME_ID_NUMBERS_PRESENT) { - uint32_t currentFrameId = 0; - const uint32_t frameIdBits = sequence.additionalFrameIdLengthMinus1 + sequence.deltaFrameIdLengthMinus2 + 3; - - if (!reader.ReadBits(frameIdBits, currentFrameId)) - - return false; - - info.picture.currentFrameId = currentFrameId; - } - - if (!reader.ReadFlag(frameSizeOverride)) - return false; - - if (sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT) { - if (!reader.ReadBits(sequence.orderHintBitsMinus1 + 1, orderHint)) - return false; - } - if (!reader.ReadBits(3, primaryRefFrame) || !reader.ReadBits(8, refreshFrameFlags)) - return false; - - if (sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT) { - uint8_t frameRefsShortSignaling = 0; - if (!reader.ReadFlag(frameRefsShortSignaling) || frameRefsShortSignaling) - return false; - } - for (uint32_t i = 0; i < 7; i++) { - if (!reader.ReadBits(3, ignored)) - return false; - refFrameIndices[i] = (uint8_t)ignored; - } - if (frameSizeOverride) - return false; - - const uint32_t width = sequence.maxFrameWidthMinus1 + 1; - const uint32_t height = sequence.maxFrameHeightMinus1 + 1; - if (sequence.flags & VideoAV1SequenceBits::ENABLE_SUPERRES) { - uint8_t useSuperres = 0; - if (!reader.ReadFlag(useSuperres)) - return false; - if (useSuperres) { - uint32_t codedDenom = 0; - if (!reader.ReadBits(3, codedDenom)) - return false; - info.picture.codedDenom = (uint8_t)codedDenom; - info.picture.superresDenom = (uint8_t)(codedDenom + 9); - flags |= VideoAV1PictureBits::USE_SUPERRES; - } - } - uint32_t renderWidthMinus1 = width - 1; - uint32_t renderHeightMinus1 = height - 1; - uint8_t renderAndFrameSizeDifferent = 0; - if (!reader.ReadFlag(renderAndFrameSizeDifferent)) - return false; - if (renderAndFrameSizeDifferent) { - if (!reader.ReadBits(16, renderWidthMinus1) || !reader.ReadBits(16, renderHeightMinus1)) - return false; - flags |= VideoAV1PictureBits::RENDER_AND_FRAME_SIZE_DIFFERENT; - } - - uint8_t allowHighPrecisionMv = 0; - if (!allowScreenContentTools && !reader.ReadFlag(allowHighPrecisionMv)) - return false; - if (allowHighPrecisionMv) - flags |= VideoAV1PictureBits::ALLOW_HIGH_PRECISION_MV; - uint8_t isFilterSwitchable = 0; - if (!reader.ReadFlag(isFilterSwitchable)) - return false; - if (isFilterSwitchable) - flags |= VideoAV1PictureBits::IS_FILTER_SWITCHABLE; - uint32_t interpolationFilter = INTERPOLATION_FILTER_EIGHTTAP; - if (isFilterSwitchable) - interpolationFilter = INTERPOLATION_FILTER_SWITCHABLE; - else if (!reader.ReadBits(2, interpolationFilter)) - return false; - uint8_t isMotionModeSwitchable = 0; - if (!reader.ReadFlag(isMotionModeSwitchable)) - return false; - if (isMotionModeSwitchable) - flags |= VideoAV1PictureBits::IS_MOTION_MODE_SWITCHABLE; - if (sequence.flags & VideoAV1SequenceBits::ENABLE_REF_FRAME_MVS) { - uint8_t useRefFrameMvs = 0; - if (!reader.ReadFlag(useRefFrameMvs)) - return false; - if (useRefFrameMvs) - flags |= VideoAV1PictureBits::USE_REF_FRAME_MVS; - } - if (!disableCdfUpdate) { - uint8_t disableFrameEndUpdateCdf = 0; - if (!reader.ReadFlag(disableFrameEndUpdateCdf)) - return false; - if (disableFrameEndUpdateCdf) - flags |= VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF; - } - - const uint32_t miCols = 2 * ((width + 7) >> 3); - const uint32_t miRows = 2 * ((height + 7) >> 3); - const uint32_t sbShift = 4; - const uint32_t sbSize = sbShift + 2; - const uint32_t sbCols = (miCols + 15) >> 4; - const uint32_t sbRows = (miRows + 15) >> 4; - const uint32_t minLog2TileCols = TileLog2(4096 >> sbSize, sbCols); - const uint32_t maxLog2TileCols = TileLog2(1, std::min(sbCols, 64u)); - const uint32_t maxLog2TileRows = TileLog2(1, std::min(sbRows, 64u)); - const uint32_t minLog2Tiles = std::max(minLog2TileCols, TileLog2((4096 * 2304) >> (2 * sbSize), sbRows * sbCols)); - uint8_t uniformTileSpacing = 0; - if (!reader.ReadFlag(uniformTileSpacing) || !uniformTileSpacing) - return false; - uint32_t tileColsLog2 = 0; - uint32_t tileRowsLog2 = 0; - if (!reader.ReadIncrement(minLog2TileCols, maxLog2TileCols, tileColsLog2)) - return false; - const uint32_t minLog2TileRows = std::max((int32_t)minLog2Tiles - (int32_t)tileColsLog2, 0); - if (!reader.ReadIncrement(minLog2TileRows, maxLog2TileRows, tileRowsLog2)) - return false; - if (tileColsLog2 || tileRowsLog2) - return false; - - uint32_t baseQIndex = 0; - uint8_t usingQmatrix = 0; - int8_t deltaQYDc = 0; - int8_t deltaQUDc = 0; - int8_t deltaQUAc = 0; - - if (!reader.ReadBits(8, baseQIndex) || !ReadDeltaQ(reader, deltaQYDc) || !ReadDeltaQ(reader, deltaQUDc) || !ReadDeltaQ(reader, deltaQUAc) || !reader.ReadFlag(usingQmatrix)) - return false; - - uint32_t qmY = 0; - uint32_t qmU = 0; - uint32_t qmV = 0; - - if (usingQmatrix) { - if (!reader.ReadBits(4, qmY) || !reader.ReadBits(4, qmU)) - - return false; - - if (sequence.flags & VideoAV1SequenceBits::SEPARATE_UV_DELTA_Q) { - if (!reader.ReadBits(4, qmV)) - - return false; - } else { - qmV = qmU; - } - } - - uint8_t segmentationEnabled = 0; - - if (!reader.ReadFlag(segmentationEnabled) || segmentationEnabled) - return false; - uint32_t deltaQRes = 0; - if (baseQIndex) { - uint8_t deltaQPresent = 0; - if (!reader.ReadFlag(deltaQPresent)) - return false; - if (deltaQPresent) { - if (!reader.ReadBits(2, deltaQRes)) - return false; - flags |= VideoAV1PictureBits::DELTA_Q_PRESENT; - uint8_t deltaLfPresent = 0; - if (!reader.ReadFlag(deltaLfPresent) || deltaLfPresent) - return false; - } - } - - const bool codedLossless = baseQIndex == 0 && deltaQYDc == 0 && deltaQUDc == 0 && deltaQUAc == 0; - uint32_t loopFilterLevel0 = 0; - uint32_t loopFilterLevel1 = 0; - uint32_t loopFilterLevelU = 0; - uint32_t loopFilterLevelV = 0; - uint32_t loopFilterSharpness = 0; - uint32_t value = 0; - if (!codedLossless) { - if (!reader.ReadBits(6, loopFilterLevel0) || !reader.ReadBits(6, loopFilterLevel1)) - return false; - if (loopFilterLevel0 || loopFilterLevel1) { - if (!reader.ReadBits(6, loopFilterLevelU) || !reader.ReadBits(6, loopFilterLevelV)) - return false; - } - uint8_t loopFilterDeltaEnabled = 0; - if (!reader.ReadBits(3, loopFilterSharpness) || !reader.ReadFlag(loopFilterDeltaEnabled) || loopFilterDeltaEnabled) - return false; - } - uint32_t cdefDampingMinus3 = 0; - uint32_t cdefBits = 0; - std::array cdefYPrimaryStrength = {}; - std::array cdefYSecondaryStrength = {}; - std::array cdefUvPrimaryStrength = {}; - std::array cdefUvSecondaryStrength = {}; - if ((sequence.flags & VideoAV1SequenceBits::ENABLE_CDEF) && !codedLossless) { - if (!reader.ReadBits(2, cdefDampingMinus3) || !reader.ReadBits(2, cdefBits)) - return false; - for (uint32_t i = 0; i < (1u << cdefBits); i++) { - if (!reader.ReadBits(4, value)) - return false; - cdefYPrimaryStrength[i] = (uint8_t)value; - if (!reader.ReadBits(2, value)) - return false; - cdefYSecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); - if (!reader.ReadBits(4, value)) - return false; - cdefUvPrimaryStrength[i] = (uint8_t)value; - if (!reader.ReadBits(2, value)) - return false; - cdefUvSecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); - } - } - std::array restorationTypes = {}; - if ((sequence.flags & VideoAV1SequenceBits::ENABLE_RESTORATION) && !codedLossless) { - for (uint32_t i = 0; i < 3; i++) { - if (!reader.ReadBits(2, value) || value) - return false; - restorationTypes[i] = (uint8_t)value; - } - } - uint32_t txMode = TX_MODE_ONLY_4X4; - if (!codedLossless) { - if (!reader.ReadIncrement(TX_MODE_LARGEST, TX_MODE_SELECT, txMode)) - return false; - } - uint8_t referenceSelect = 0; - if (!reader.ReadFlag(referenceSelect)) - return false; - if (referenceSelect) - flags |= VideoAV1PictureBits::REFERENCE_SELECT; - for (uint32_t i = 0; i < 7; i++) { - uint8_t isGlobal = 0; - if (!reader.ReadFlag(isGlobal) || isGlobal) - return false; - } - uint8_t reducedTxSet = 0; - if (!reader.ReadFlag(reducedTxSet) || !reader.ByteAlign()) - return false; - if (reducedTxSet) - flags |= VideoAV1PictureBits::REDUCED_TX_SET; - - const size_t tileDataOffset = reader.ByteOffset(); - - if (requireTilePayload && tileDataOffset >= fullPayloadSize) - return false; - - if (requireTilePayload) { - if (tileDataOffset > std::numeric_limits::max() || fullPayloadSize - tileDataOffset > std::numeric_limits::max()) - - return false; - } - - info.sequence = sequence; - FillSingleTileLayout(info, width, height); - info.picture.tileNum = 1; - - if (requireTilePayload) - info.tiles[0] = {(uint32_t)tileDataOffset, (uint32_t)(fullPayloadSize - tileDataOffset), 0, 0, 0xFF}; - - info.picture.frameType = VideoFrameType::P; - info.picture.orderHint = (uint8_t)orderHint; - info.picture.refreshFrameFlags = (uint8_t)refreshFrameFlags; - info.picture.primaryReferenceName = GetReferenceNameFromReferenceIndex(primaryRefFrame); - info.picture.flags = flags; - info.picture.renderWidthMinus1 = (uint16_t)renderWidthMinus1; - info.picture.renderHeightMinus1 = (uint16_t)renderHeightMinus1; - info.picture.baseQIndex = (uint8_t)baseQIndex; - info.picture.interpolationFilter = (uint8_t)interpolationFilter; - info.picture.txMode = (uint8_t)txMode; - info.picture.cdefDampingMinus3 = (uint8_t)cdefDampingMinus3; - info.picture.cdefBits = (uint8_t)cdefBits; - info.picture.deltaQRes = (uint8_t)deltaQRes; - info.tileLayout.contextUpdateTileId = 0; - info.quantization.deltaQYDc = deltaQYDc; - info.quantization.deltaQUDc = deltaQUDc; - info.quantization.deltaQUAc = deltaQUAc; - info.quantization.deltaQVDc = deltaQUDc; - info.quantization.deltaQVAc = deltaQUAc; - info.quantization.usingQmatrix = usingQmatrix; - info.quantization.qmY = (uint8_t)qmY; - info.quantization.qmU = (uint8_t)qmU; - info.quantization.qmV = (uint8_t)qmV; - info.loopFilter.level[0] = (uint8_t)loopFilterLevel0; - info.loopFilter.level[1] = (uint8_t)loopFilterLevel1; - info.loopFilter.level[2] = (uint8_t)loopFilterLevelU; - info.loopFilter.level[3] = (uint8_t)loopFilterLevelV; - info.loopFilter.sharpness = (uint8_t)loopFilterSharpness; - info.loopFilter.refDeltas[0] = 1; - info.loopFilter.refDeltas[4] = -1; - info.loopFilter.refDeltas[6] = -1; - info.loopFilter.refDeltas[7] = -1; - for (uint32_t i = 0; i < 8; i++) { - info.cdef.yPrimaryStrength[i] = cdefYPrimaryStrength[i]; - info.cdef.ySecondaryStrength[i] = cdefYSecondaryStrength[i]; - info.cdef.uvPrimaryStrength[i] = cdefUvPrimaryStrength[i]; - info.cdef.uvSecondaryStrength[i] = cdefUvSecondaryStrength[i]; - } - for (uint32_t i = 0; i < 3; i++) - info.loopRestoration.frameRestorationType[i] = restorationTypes[i]; - FillIdentityGlobalMotion(info.globalMotion); - BindPointers(info); - return true; -} - static inline uint32_t TileLog2(uint32_t blockSize, uint32_t target) { uint32_t value = 0; while ((blockSize << value) < target) @@ -1306,11 +981,13 @@ static inline void FillIdentityGlobalMotion(VideoAV1GlobalMotionDesc& globalMoti } } +// The superblock size is taken from "info.sequence" static inline void FillSingleTileLayout(VideoAV1EncodeDecodeInfo& info, uint32_t width, uint32_t height) { + const uint32_t sbShift = (info.sequence.flags & VideoAV1SequenceBits::USE_128X128_SUPERBLOCK) ? 5 : 4; const uint32_t miCols = 2 * ((width + 7) >> 3); const uint32_t miRows = 2 * ((height + 7) >> 3); - const uint32_t sbCols = (miCols + 15) >> 4; - const uint32_t sbRows = (miRows + 15) >> 4; + const uint32_t sbCols = (miCols + (1u << sbShift) - 1) >> sbShift; + const uint32_t sbRows = (miRows + (1u << sbShift) - 1) >> sbShift; info.tileLayout.columnNum = 1; info.tileLayout.rowNum = 1; @@ -1324,16 +1001,91 @@ static inline void FillSingleTileLayout(VideoAV1EncodeDecodeInfo& info, uint32_t info.heightInSuperblocksMinus1[0] = (uint16_t)(sbRows - 1); } -static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t availablePayloadSize, const uint8_t* tilePayload, size_t availableTilePayloadSize, - size_t fullTilePayloadSize, bool combinedFrameObu, const VideoAV1SequenceDesc& sequence, VideoAV1EncodeDecodeInfo& info) { +// "get_relative_dist" +static inline int32_t GetRelativeDistance(const VideoAV1SequenceDesc& sequence, uint32_t a, uint32_t b) { + if (!(sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT)) + return 0; + + const int32_t m = 1 << sequence.orderHintBitsMinus1; + const int32_t diff = (int32_t)a - (int32_t)b; + + return (diff & (m - 1)) - (diff & m); +} + +// "skip_mode_params": returns "skipModeAllowed" and fills "SkipModeFrame" from the references of the current frame, ordered by reference name +static inline bool GetSkipModeFrames(const VideoAV1SequenceDesc& sequence, uint32_t orderHint, const VideoAV1ReferenceDesc* references, VideoAV1ReferenceName* skipModeFrames) { + int32_t forwardIndex = -1; + int32_t backwardIndex = -1; + uint32_t forwardHint = 0; + uint32_t backwardHint = 0; + + for (int32_t i = 0; i < (int32_t)REFERENCE_NAME_NUM; i++) { + const uint32_t referenceHint = references[i].orderHint; + + if (GetRelativeDistance(sequence, referenceHint, orderHint) < 0) { + if (forwardIndex < 0 || GetRelativeDistance(sequence, referenceHint, forwardHint) > 0) { + forwardIndex = i; + forwardHint = referenceHint; + } + } else if (GetRelativeDistance(sequence, referenceHint, orderHint) > 0) { + if (backwardIndex < 0 || GetRelativeDistance(sequence, referenceHint, backwardHint) < 0) { + backwardIndex = i; + backwardHint = referenceHint; + } + } + } + + if (forwardIndex < 0) + return false; + + int32_t secondIndex = backwardIndex; + + if (secondIndex < 0) { + uint32_t secondForwardHint = 0; + + for (int32_t i = 0; i < (int32_t)REFERENCE_NAME_NUM; i++) { + const uint32_t referenceHint = references[i].orderHint; + + if (GetRelativeDistance(sequence, referenceHint, forwardHint) < 0 && (secondIndex < 0 || GetRelativeDistance(sequence, referenceHint, secondForwardHint) > 0)) { + secondIndex = i; + secondForwardHint = referenceHint; + } + } + + if (secondIndex < 0) + return false; + } + + skipModeFrames[0] = GetReferenceNameFromReferenceIndex((uint32_t)std::min(forwardIndex, secondIndex)); + skipModeFrames[1] = GetReferenceNameFromReferenceIndex((uint32_t)std::max(forwardIndex, secondIndex)); + + return true; +} + +// Parses "uncompressed_header" and the following tile group header of a shown KEY or INTER frame. Syntax that would need state not +// available here ("frame_refs_short_signaling", "frame_size_with_refs", segmentation, global motion, film grain, error resilient +// INTER frames, loop filter deltas inherited from "primary_ref_frame") is rejected +static inline bool ParseGeneratedFrameHeader(const VideoAV1EncodeDecodeInfoDesc& desc, const uint8_t* payload, size_t availablePayloadSize, const uint8_t* tilePayload, size_t availableTilePayloadSize, + size_t fullTilePayloadSize, bool combinedFrameObu, VideoAV1EncodeDecodeInfo& info) { constexpr uint32_t MAX_TILE_WIDTH = 4096; constexpr uint32_t MAX_TILE_AREA = 4096 * 2304; constexpr uint32_t MAX_TILE_COLS = 64; constexpr uint32_t MAX_TILE_ROWS = 64; + constexpr uint32_t PRIMARY_REF_NONE = 7; + constexpr uint32_t SUPERRES_NUM = 8; + constexpr uint8_t REMAP_LR_TYPE[4] = {0, 3, 1, 2}; + + const VideoAV1SequenceDesc& sequence = *desc.sequence; + const bool enableOrderHint = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT); + const bool frameIdNumbersPresent = !!(sequence.flags & VideoAV1SequenceBits::FRAME_ID_NUMBERS_PRESENT); + const bool use128x128Superblock = !!(sequence.flags & VideoAV1SequenceBits::USE_128X128_SUPERBLOCK); + const bool separateUvDeltaQ = !!(sequence.flags & VideoAV1SequenceBits::SEPARATE_UV_DELTA_Q); + const uint32_t planeNum = (sequence.flags & VideoAV1SequenceBits::MONO_CHROME) ? 1 : 3; + + if (sequence.flags & VideoAV1SequenceBits::REDUCED_STILL_PICTURE_HEADER) + return false; BitReader reader{payload, availablePayloadSize, 0}; - VideoAV1PictureBits flags = VideoAV1PictureBits::NONE; - uint8_t showExistingFrame = 0; uint32_t frameType = 0; uint8_t showFrame = 0; @@ -1341,40 +1093,59 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a if (!reader.ReadFlag(showExistingFrame) || showExistingFrame || !reader.ReadBits(2, frameType) || !reader.ReadFlag(showFrame)) return false; - if (frameType != 0 || !showFrame) + if (frameType > 1 || !showFrame) return false; - flags |= VideoAV1PictureBits::ERROR_RESILIENT_MODE | VideoAV1PictureBits::SHOW_FRAME; + const bool isKeyFrame = frameType == 0; + VideoAV1PictureBits flags = VideoAV1PictureBits::SHOW_FRAME; + + if (isKeyFrame) + flags |= VideoAV1PictureBits::ERROR_RESILIENT_MODE; + else { + uint8_t errorResilient = 0; + + if (!reader.ReadFlag(errorResilient) || errorResilient) + return false; + + flags |= VideoAV1PictureBits::SHOWABLE_FRAME; + } uint8_t disableCdfUpdate = 0; uint8_t allowScreenContentTools = 0; uint8_t forceIntegerMv = 0; + if (!reader.ReadFlag(disableCdfUpdate)) return false; + + if (disableCdfUpdate) + flags |= VideoAV1PictureBits::DISABLE_CDF_UPDATE | VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF; + if (sequence.seqForceScreenContentTools == SELECT_SCREEN_CONTENT_TOOLS) { if (!reader.ReadFlag(allowScreenContentTools)) return false; } else allowScreenContentTools = sequence.seqForceScreenContentTools; - if (disableCdfUpdate) - flags |= VideoAV1PictureBits::DISABLE_CDF_UPDATE | VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF; + if (allowScreenContentTools) { flags |= VideoAV1PictureBits::ALLOW_SCREEN_CONTENT_TOOLS; + if (sequence.seqForceIntegerMv == SELECT_SCREEN_CONTENT_TOOLS) { if (!reader.ReadFlag(forceIntegerMv)) return false; } else forceIntegerMv = sequence.seqForceIntegerMv; - if (forceIntegerMv) - flags |= VideoAV1PictureBits::FORCE_INTEGER_MV; } - if (sequence.flags & VideoAV1SequenceBits::FRAME_ID_NUMBERS_PRESENT) { - uint32_t currentFrameId = 0; - const uint32_t frameIdBits = sequence.additionalFrameIdLengthMinus1 + sequence.deltaFrameIdLengthMinus2 + 3; + if (isKeyFrame) + forceIntegerMv = 1; - if (!reader.ReadBits(frameIdBits, currentFrameId)) + if (forceIntegerMv) + flags |= VideoAV1PictureBits::FORCE_INTEGER_MV; + + if (frameIdNumbersPresent) { + uint32_t currentFrameId = 0; + if (!reader.ReadBits(sequence.additionalFrameIdLengthMinus1 + sequence.deltaFrameIdLengthMinus2 + 3, currentFrameId)) return false; info.picture.currentFrameId = currentFrameId; @@ -1382,66 +1153,167 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint8_t frameSizeOverride = 0; uint32_t orderHint = 0; + uint32_t primaryRefFrame = PRIMARY_REF_NONE; + uint32_t refreshFrameFlags = 0xFF; + if (!reader.ReadFlag(frameSizeOverride)) return false; - if (sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT) { - if (!reader.ReadBits(sequence.orderHintBitsMinus1 + 1, orderHint)) + + if (enableOrderHint && !reader.ReadBits(sequence.orderHintBitsMinus1 + 1, orderHint)) + return false; + + if (!isKeyFrame) { + if (!reader.ReadBits(3, primaryRefFrame) || !reader.ReadBits(8, refreshFrameFlags)) + return false; + + uint8_t frameRefsShortSignaling = 0; + + if (enableOrderHint && (!reader.ReadFlag(frameRefsShortSignaling) || frameRefsShortSignaling)) + return false; + + std::array refFrameIndices = {}; + + for (uint32_t i = 0; i < REFERENCE_NAME_NUM; i++) { + uint32_t value = 0; + + if (!reader.ReadBits(3, value)) + return false; + + refFrameIndices[i] = (uint8_t)value; + + // "delta_frame_id_minus_1" + if (frameIdNumbersPresent && !reader.ReadBits(sequence.deltaFrameIdLengthMinus2 + 2, value)) + return false; + } + + // "frame_size_with_refs" needs the reference frame sizes + if (frameSizeOverride || !BuildInterFrameReferences(desc, refFrameIndices, info)) return false; } + + // "frame_size" and "superres_params" + uint32_t upscaledWidth = sequence.maxFrameWidthMinus1 + 1u; + uint32_t frameHeight = sequence.maxFrameHeightMinus1 + 1u; + if (frameSizeOverride) { - flags |= VideoAV1PictureBits::FRAME_SIZE_OVERRIDE; - uint32_t ignored = 0; - if (!reader.ReadBits(sequence.frameWidthBitsMinus1 + 1, ignored) || !reader.ReadBits(sequence.frameHeightBitsMinus1 + 1, ignored)) + uint32_t frameWidthMinus1 = 0; + uint32_t frameHeightMinus1 = 0; + + if (!reader.ReadBits(sequence.frameWidthBitsMinus1 + 1, frameWidthMinus1) || !reader.ReadBits(sequence.frameHeightBitsMinus1 + 1, frameHeightMinus1)) + return false; + + if (frameWidthMinus1 > sequence.maxFrameWidthMinus1 || frameHeightMinus1 > sequence.maxFrameHeightMinus1) return false; + + upscaledWidth = frameWidthMinus1 + 1; + frameHeight = frameHeightMinus1 + 1; + flags |= VideoAV1PictureBits::FRAME_SIZE_OVERRIDE; } - const uint32_t width = sequence.maxFrameWidthMinus1 + 1; - const uint32_t height = sequence.maxFrameHeightMinus1 + 1; + uint32_t superresDenom = SUPERRES_NUM; + if (sequence.flags & VideoAV1SequenceBits::ENABLE_SUPERRES) { uint8_t useSuperres = 0; + if (!reader.ReadFlag(useSuperres)) return false; + if (useSuperres) { uint32_t codedDenom = 0; + if (!reader.ReadBits(3, codedDenom)) return false; + + superresDenom = codedDenom + 9; info.picture.codedDenom = (uint8_t)codedDenom; - info.picture.superresDenom = (uint8_t)(codedDenom + 9); + info.picture.superresDenom = (uint8_t)superresDenom; flags |= VideoAV1PictureBits::USE_SUPERRES; } } - uint32_t renderWidthMinus1 = width - 1; - uint32_t renderHeightMinus1 = height - 1; + const uint32_t frameWidth = (upscaledWidth * SUPERRES_NUM + superresDenom / 2) / superresDenom; + + // "render_size" + uint32_t renderWidthMinus1 = upscaledWidth - 1; + uint32_t renderHeightMinus1 = frameHeight - 1; uint8_t renderAndFrameSizeDifferent = 0; + if (!reader.ReadFlag(renderAndFrameSizeDifferent)) return false; + if (renderAndFrameSizeDifferent) { if (!reader.ReadBits(16, renderWidthMinus1) || !reader.ReadBits(16, renderHeightMinus1)) return false; + flags |= VideoAV1PictureBits::RENDER_AND_FRAME_SIZE_DIFFERENT; } uint8_t allowIntrabc = 0; - if (allowScreenContentTools && !reader.ReadFlag(allowIntrabc)) - return false; - if (allowIntrabc) - flags |= VideoAV1PictureBits::ALLOW_INTRABC; + uint32_t interpolationFilter = INTERPOLATION_FILTER_EIGHTTAP; + + if (isKeyFrame) { + if (allowScreenContentTools && upscaledWidth == frameWidth && !reader.ReadFlag(allowIntrabc)) + return false; + + if (allowIntrabc) + flags |= VideoAV1PictureBits::ALLOW_INTRABC; + } else { + uint8_t allowHighPrecisionMv = 0; + + if (!forceIntegerMv && !reader.ReadFlag(allowHighPrecisionMv)) + return false; + + if (allowHighPrecisionMv) + flags |= VideoAV1PictureBits::ALLOW_HIGH_PRECISION_MV; + + uint8_t isFilterSwitchable = 0; + + if (!reader.ReadFlag(isFilterSwitchable)) + return false; + + if (isFilterSwitchable) { + interpolationFilter = INTERPOLATION_FILTER_SWITCHABLE; + flags |= VideoAV1PictureBits::IS_FILTER_SWITCHABLE; + } else if (!reader.ReadBits(2, interpolationFilter)) + return false; + + uint8_t isMotionModeSwitchable = 0; + + if (!reader.ReadFlag(isMotionModeSwitchable)) + return false; + + if (isMotionModeSwitchable) + flags |= VideoAV1PictureBits::IS_MOTION_MODE_SWITCHABLE; + + // "enable_ref_frame_mvs" is only coded (and the writer only emits it) with "enable_order_hint" + if (enableOrderHint && (sequence.flags & VideoAV1SequenceBits::ENABLE_REF_FRAME_MVS)) { + uint8_t useRefFrameMvs = 0; + + if (!reader.ReadFlag(useRefFrameMvs)) + return false; + + if (useRefFrameMvs) + flags |= VideoAV1PictureBits::USE_REF_FRAME_MVS; + } + } if (!disableCdfUpdate) { uint8_t disableFrameEndUpdateCdf = 0; + if (!reader.ReadFlag(disableFrameEndUpdateCdf)) return false; + if (disableFrameEndUpdateCdf) flags |= VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF; } - const uint32_t miCols = 2 * ((width + 7) >> 3); - const uint32_t miRows = 2 * ((height + 7) >> 3); - const uint32_t sbShift = 4; + // "tile_info" + const uint32_t miCols = 2 * ((frameWidth + 7) >> 3); + const uint32_t miRows = 2 * ((frameHeight + 7) >> 3); + const uint32_t sbShift = use128x128Superblock ? 5 : 4; const uint32_t sbSize = sbShift + 2; - const uint32_t sbCols = (miCols + 15) >> 4; - const uint32_t sbRows = (miRows + 15) >> 4; + const uint32_t sbCols = (miCols + (1u << sbShift) - 1) >> sbShift; + const uint32_t sbRows = (miRows + (1u << sbShift) - 1) >> sbShift; const uint32_t minLog2TileCols = TileLog2(MAX_TILE_WIDTH >> sbSize, sbCols); const uint32_t maxLog2TileCols = TileLog2(1, std::min(sbCols, MAX_TILE_COLS)); const uint32_t maxLog2TileRows = TileLog2(1, std::min(sbRows, MAX_TILE_ROWS)); @@ -1499,7 +1371,6 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint32_t tileWidthMinus1 = 0; if (!ReadNs(reader, maxWidth, tileWidthMinus1)) - return false; const uint32_t tileWidthSb = tileWidthMinus1 + 1; @@ -1511,7 +1382,6 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a tileColsLog2 = TileLog2(1, tileCols); if (startSb != sbCols || !tileCols) - return false; startSb = 0; @@ -1530,7 +1400,6 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint32_t tileHeightMinus1 = 0; if (!ReadNs(reader, maxHeight, tileHeightMinus1)) - return false; info.heightInSuperblocksMinus1[i] = (uint16_t)tileHeightMinus1; @@ -1541,7 +1410,6 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a tileRowsLog2 = TileLog2(1, tileRows); if (startSb != sbRows || !tileRows) - return false; } @@ -1558,46 +1426,57 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a info.miRowStarts[i] = (uint16_t)(tileStartRowSb[i] << sbShift); info.miRowStarts[tileRows] = (uint16_t)miRows; + // "quantization_params" + VideoAV1QuantizationDesc& quantization = info.quantization; uint32_t baseQIndex = 0; - uint8_t usingQmatrix = 0; - if (!reader.ReadBits(8, baseQIndex) || !ReadDeltaQ(reader, info.quantization.deltaQYDc) || !ReadDeltaQ(reader, info.quantization.deltaQUDc) || !ReadDeltaQ(reader, info.quantization.deltaQUAc) || !reader.ReadFlag(usingQmatrix)) + if (!reader.ReadBits(8, baseQIndex) || !ReadDeltaQ(reader, quantization.deltaQYDc)) return false; - info.quantization.deltaQVDc = info.quantization.deltaQUDc; - info.quantization.deltaQVAc = info.quantization.deltaQUAc; - info.quantization.usingQmatrix = usingQmatrix; + if (planeNum > 1) { + if (separateUvDeltaQ && !reader.ReadFlag(quantization.diffUvDelta)) + return false; + + if (!ReadDeltaQ(reader, quantization.deltaQUDc) || !ReadDeltaQ(reader, quantization.deltaQUAc)) + return false; + + if (quantization.diffUvDelta) { + if (!ReadDeltaQ(reader, quantization.deltaQVDc) || !ReadDeltaQ(reader, quantization.deltaQVAc)) + return false; + } else { + quantization.deltaQVDc = quantization.deltaQUDc; + quantization.deltaQVAc = quantization.deltaQUAc; + } + } + + if (!reader.ReadFlag(quantization.usingQmatrix)) + return false; - if (usingQmatrix) { + if (quantization.usingQmatrix) { uint32_t qmY = 0; uint32_t qmU = 0; uint32_t qmV = 0; if (!reader.ReadBits(4, qmY) || !reader.ReadBits(4, qmU)) - return false; - if (sequence.flags & VideoAV1SequenceBits::SEPARATE_UV_DELTA_Q) { - if (!reader.ReadBits(4, qmV)) - - return false; - } else { + if (!separateUvDeltaQ) qmV = qmU; - } + else if (!reader.ReadBits(4, qmV)) + return false; - info.quantization.qmY = (uint8_t)qmY; - info.quantization.qmU = (uint8_t)qmU; - info.quantization.qmV = (uint8_t)qmV; + quantization.qmY = (uint8_t)qmY; + quantization.qmU = (uint8_t)qmU; + quantization.qmV = (uint8_t)qmV; } + // "segmentation_params" uint8_t segmentationEnabled = 0; - if (!reader.ReadFlag(segmentationEnabled)) - return false; - - if (segmentationEnabled) + if (!reader.ReadFlag(segmentationEnabled) || segmentationEnabled) return false; + // "delta_q_params" and "delta_lf_params" if (baseQIndex > 0) { uint8_t deltaQPresent = 0; @@ -1612,20 +1491,32 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a info.picture.deltaQRes = (uint8_t)deltaQRes; flags |= VideoAV1PictureBits::DELTA_Q_PRESENT; - } - } - if (flags & VideoAV1PictureBits::DELTA_Q_PRESENT) { - uint8_t deltaLfPresent = 0; + uint8_t deltaLfPresent = 0; - if (!allowIntrabc && !reader.ReadFlag(deltaLfPresent)) - return false; + if (!allowIntrabc && !reader.ReadFlag(deltaLfPresent)) + return false; - if (deltaLfPresent) - return false; + if (deltaLfPresent) { + uint32_t deltaLfRes = 0; + uint8_t deltaLfMulti = 0; + + if (!reader.ReadBits(2, deltaLfRes) || !reader.ReadFlag(deltaLfMulti)) + return false; + + info.picture.deltaLfRes = (uint8_t)deltaLfRes; + flags |= VideoAV1PictureBits::DELTA_LF_PRESENT; + + if (deltaLfMulti) + flags |= VideoAV1PictureBits::DELTA_LF_MULTI; + } + } } - const bool codedLossless = baseQIndex == 0 && info.quantization.deltaQYDc == 0 && info.quantization.deltaQUDc == 0 && info.quantization.deltaQUAc == 0; + const bool codedLossless = baseQIndex == 0 && quantization.deltaQYDc == 0 && quantization.deltaQUDc == 0 && quantization.deltaQUAc == 0 && quantization.deltaQVDc == 0 && quantization.deltaQVAc == 0; + const bool allLossless = codedLossless && frameWidth == upscaledWidth; + + // "loop_filter_params" info.loopFilter.refDeltas[0] = 1; info.loopFilter.refDeltas[4] = -1; info.loopFilter.refDeltas[6] = -1; @@ -1642,7 +1533,7 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a return false; info.loopFilter.level[1] = (uint8_t)value; - if (info.loopFilter.level[0] || info.loopFilter.level[1]) { + if (planeNum > 1 && (info.loopFilter.level[0] || info.loopFilter.level[1])) { if (!reader.ReadBits(6, value)) return false; info.loopFilter.level[2] = (uint8_t)value; @@ -1659,20 +1550,21 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a if (!reader.ReadFlag(info.loopFilter.deltaEnabled)) return false; + // Deltas inherited from "primary_ref_frame" are unknown + if (info.loopFilter.deltaEnabled && primaryRefFrame != PRIMARY_REF_NONE) + return false; + if (info.loopFilter.deltaEnabled) { if (!reader.ReadFlag(info.loopFilter.deltaUpdate)) - return false; for (uint32_t i = 0; i < 8; i++) { uint8_t updateRefDelta = 0; if (info.loopFilter.deltaUpdate && !reader.ReadFlag(updateRefDelta)) - return false; if (updateRefDelta && !reader.ReadSigned(7, info.loopFilter.refDeltas[i])) - return false; } @@ -1680,65 +1572,130 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint8_t updateModeDelta = 0; if (info.loopFilter.deltaUpdate && !reader.ReadFlag(updateModeDelta)) - return false; - if (updateModeDelta) { - int8_t modeDelta = 0; - - if (!reader.ReadSigned(7, modeDelta)) - - return false; - - info.loopFilter.modeDeltas[i] = modeDelta; - } + if (updateModeDelta && !reader.ReadSigned(7, info.loopFilter.modeDeltas[i])) + return false; } } } + // "cdef_params" if ((sequence.flags & VideoAV1SequenceBits::ENABLE_CDEF) && !codedLossless && !allowIntrabc) { uint32_t value = 0; + if (!reader.ReadBits(2, value)) return false; info.picture.cdefDampingMinus3 = (uint8_t)value; + if (!reader.ReadBits(2, value)) return false; info.picture.cdefBits = (uint8_t)value; + const uint32_t cdefStrengthNum = 1u << info.picture.cdefBits; for (uint32_t i = 0; i < cdefStrengthNum; i++) { if (!reader.ReadBits(4, value)) return false; info.cdef.yPrimaryStrength[i] = (uint8_t)value; + if (!reader.ReadBits(2, value)) return false; info.cdef.ySecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); - if (!reader.ReadBits(4, value)) - return false; - info.cdef.uvPrimaryStrength[i] = (uint8_t)value; - if (!reader.ReadBits(2, value)) - return false; - info.cdef.uvSecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); + + if (planeNum > 1) { + if (!reader.ReadBits(4, value)) + return false; + info.cdef.uvPrimaryStrength[i] = (uint8_t)value; + + if (!reader.ReadBits(2, value)) + return false; + info.cdef.uvSecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); + } } } - if ((sequence.flags & VideoAV1SequenceBits::ENABLE_RESTORATION) && !codedLossless && !allowIntrabc) { - uint32_t restorationType = 0; + // "lr_params" + if ((sequence.flags & VideoAV1SequenceBits::ENABLE_RESTORATION) && !allLossless && !allowIntrabc) { + for (uint32_t plane = 0; plane < planeNum; plane++) { + uint32_t lrType = 0; + + if (!reader.ReadBits(2, lrType)) + return false; + + info.loopRestoration.frameRestorationType[plane] = REMAP_LR_TYPE[lrType]; + + if (lrType) { + flags |= VideoAV1PictureBits::USES_LR; + + if (plane) + flags |= VideoAV1PictureBits::USES_CHROMA_LR; + } + } + + if (flags & VideoAV1PictureBits::USES_LR) { + uint32_t lrUnitShift = 0; + + if (!reader.ReadBits(1, lrUnitShift)) + return false; + + if (use128x128Superblock) + lrUnitShift++; + else if (lrUnitShift) { + uint32_t lrUnitExtraShift = 0; + + if (!reader.ReadBits(1, lrUnitExtraShift)) + return false; + + lrUnitShift += lrUnitExtraShift; + } + + info.loopRestoration.lrUnitShift = (uint8_t)lrUnitShift; - for (uint32_t plane = 0; plane < 3; plane++) { - if (!reader.ReadBits(2, restorationType)) + uint32_t lrUvShift = 0; + + if (sequence.subsamplingX && sequence.subsamplingY && (flags & VideoAV1PictureBits::USES_CHROMA_LR) && !reader.ReadBits(1, lrUvShift)) return false; - info.loopRestoration.frameRestorationType[plane] = (uint8_t)restorationType; + + info.loopRestoration.lrUvShift = (uint8_t)lrUvShift; } } - if (!codedLossless) { - uint32_t txMode = TX_MODE_ONLY_4X4; + // "read_tx_mode" + uint32_t txMode = TX_MODE_ONLY_4X4; + + if (!codedLossless && !reader.ReadIncrement(TX_MODE_LARGEST, TX_MODE_SELECT, txMode)) + return false; + + // "frame_reference_mode" and "skip_mode_params" + info.picture.skipModeFrames[0] = VideoAV1ReferenceName::NONE; + info.picture.skipModeFrames[1] = VideoAV1ReferenceName::NONE; + + if (!isKeyFrame) { + uint8_t referenceSelect = 0; + + if (!reader.ReadFlag(referenceSelect)) + return false; + + if (referenceSelect) + flags |= VideoAV1PictureBits::REFERENCE_SELECT; + + uint8_t skipModePresent = 0; + + if (referenceSelect && enableOrderHint && GetSkipModeFrames(sequence, orderHint, info.references, info.picture.skipModeFrames) && !reader.ReadFlag(skipModePresent)) + return false; + + if (skipModePresent) + flags |= VideoAV1PictureBits::SKIP_MODE_PRESENT; + + uint8_t allowWarpedMotion = 0; - if (!reader.ReadIncrement(TX_MODE_LARGEST, TX_MODE_SELECT, txMode)) + if ((sequence.flags & VideoAV1SequenceBits::ENABLE_WARPED_MOTION) && !reader.ReadFlag(allowWarpedMotion)) return false; - info.picture.txMode = (uint8_t)txMode; + if (allowWarpedMotion) + flags |= VideoAV1PictureBits::ALLOW_WARPED_MOTION; } + uint8_t reducedTxSet = 0; if (!reader.ReadFlag(reducedTxSet)) @@ -1747,6 +1704,29 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a if (reducedTxSet) flags |= VideoAV1PictureBits::REDUCED_TX_SET; + // "global_motion_params" + if (!isKeyFrame) { + for (uint32_t i = 0; i < REFERENCE_NAME_NUM; i++) { + uint8_t isGlobal = 0; + + if (!reader.ReadFlag(isGlobal) || isGlobal) + return false; + } + } + + // "film_grain_params" + if (sequence.flags & VideoAV1SequenceBits::FILM_GRAIN_PARAMS_PRESENT) { + uint8_t applyGrain = 0; + + if (!reader.ReadFlag(applyGrain) || applyGrain) + return false; + } + + // "frame_obu": "byte_alignment" between "frame_header_obu" and "tile_group_obu" + if (combinedFrameObu && !reader.ByteAlign()) + return false; + + // "tile_group_obu" const uint32_t tileNum = tileCols * tileRows; BitReader tileReader{tilePayload, availableTilePayloadSize, 0}; BitReader& tileGroupReader = combinedFrameObu ? reader : tileReader; @@ -1758,18 +1738,15 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint8_t tileStartAndEndPresent = 0; if (!tileGroupReader.ReadFlag(tileStartAndEndPresent)) - return false; if (tileStartAndEndPresent) { const uint32_t tileBits = tileColsLog2 + tileRowsLog2; if (!tileGroupReader.ReadBits(tileBits, tileGroupStart) || !tileGroupReader.ReadBits(tileBits, tileGroupEnd)) - return false; if (tileGroupStart > tileGroupEnd || tileGroupEnd >= tileNum) - return false; } } @@ -1785,11 +1762,9 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a uint32_t tileGroupTileNum = tileGroupEnd - tileGroupStart + 1; if (!tileGroupTileNum || tileGroupTileNum > std::size(info.tiles)) - return false; if (tileGroupStart != 0 || tileGroupEnd != tileNum - 1) - return false; const uint32_t tileSizeByteNum = tileSizeBytesMinus1 + 1; @@ -1802,7 +1777,6 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a if (groupTileIndex + 1 < tileGroupTileNum) { if (tilePayloadCursor + tileSizeByteNum > availableTilePayloadSize) - return false; uint32_t tileSizeMinus1 = 0; @@ -1813,14 +1787,12 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a tileSize = tileSizeMinus1 + 1; } else { if (tilePayloadCursor > fullTilePayloadSize || fullTilePayloadSize - tilePayloadCursor > std::numeric_limits::max()) - return false; tileSize = (uint32_t)(fullTilePayloadSize - tilePayloadCursor); } if (tilePayloadCursor + tileSize > fullTilePayloadSize) - return false; VideoAV1DecodeTileDesc& tile = info.tiles[groupTileIndex]; @@ -1838,25 +1810,29 @@ static inline bool ParseGeneratedKeyFrameHeader(const uint8_t* payload, size_t a if (!parseTilePayload()) return false; - info.sequence = sequence; - if (fullTilePayloadSize > std::numeric_limits::max()) return false; + info.sequence = sequence; + + if (!enableOrderHint) + info.sequence.flags &= ~(VideoAV1SequenceBits::ENABLE_JNT_COMP | VideoAV1SequenceBits::ENABLE_REF_FRAME_MVS); + info.tileLayout.columnNum = (uint8_t)tileCols; info.tileLayout.rowNum = (uint8_t)tileRows; info.tileLayout.tileSizeBytesMinus1 = (uint8_t)tileSizeBytesMinus1; info.tileLayout.uniformSpacing = uniformTileSpacing; info.tileLayout.contextUpdateTileId = (uint16_t)contextUpdateTileId; - info.picture.frameType = VideoFrameType::IDR; + info.picture.frameType = isKeyFrame ? VideoFrameType::IDR : VideoFrameType::P; info.picture.orderHint = (uint8_t)orderHint; - info.picture.refreshFrameFlags = 0xFF; - info.picture.primaryReferenceName = VideoAV1ReferenceName::NONE; + info.picture.refreshFrameFlags = (uint8_t)refreshFrameFlags; + info.picture.primaryReferenceName = GetReferenceNameFromReferenceIndex(primaryRefFrame); info.picture.flags = flags; info.picture.renderWidthMinus1 = (uint16_t)renderWidthMinus1; info.picture.renderHeightMinus1 = (uint16_t)renderHeightMinus1; info.picture.baseQIndex = (uint8_t)baseQIndex; - info.picture.interpolationFilter = INTERPOLATION_FILTER_EIGHTTAP; + info.picture.interpolationFilter = (uint8_t)interpolationFilter; + info.picture.txMode = (uint8_t)txMode; info.picture.tileNum = tileGroupTileNum; FillIdentityGlobalMotion(info.globalMotion); BindPointers(info); @@ -1883,32 +1859,9 @@ static inline Result GetEncodeDecodeInfoFromHeader(const VideoAV1EncodeDecodeInf const uint8_t* tilePayload = desc.encodedPayloadHeader + (frame.combinedFrameObu ? frame.headerPayloadOffset : frame.tilePayloadOffset); const size_t availableTilePayload = frame.combinedFrameObu ? availablePayload : (size_t)desc.encodedPayloadHeaderSize - frame.tilePayloadOffset; const size_t fullTilePayloadSize = frame.combinedFrameObu ? frame.headerPayloadSize : frame.tilePayloadSize; - const size_t fullHeaderPayloadSize = frame.headerPayloadSize; - - if (!ParseGeneratedKeyFrameHeader(desc.encodedPayloadHeader + frame.headerPayloadOffset, availablePayload, tilePayload, availableTilePayload, fullTilePayloadSize, frame.combinedFrameObu, *desc.sequence, parsedInfo)) { - uint32_t frameType = 0; - uint8_t showFrame = 0; - - if (!PeekGeneratedFrameType(desc.encodedPayloadHeader + frame.headerPayloadOffset, availablePayload, frameType, showFrame) || frameType != 1 || !showFrame) - return Result::FAILURE; - - std::array refFrameIndices = {}; - - if (!ParseGeneratedInterFrameHeader(desc.encodedPayloadHeader + frame.headerPayloadOffset, availablePayload, fullHeaderPayloadSize, frame.combinedFrameObu, *desc.sequence, refFrameIndices, parsedInfo)) - return Result::FAILURE; - - if (!BuildInterFrameReferences(desc, refFrameIndices, parsedInfo)) - return Result::FAILURE; - if (!frame.combinedFrameObu) { - if (frame.tilePayloadSize > std::numeric_limits::max()) - - return Result::FAILURE; - - parsedInfo.picture.tileNum = 1; - parsedInfo.tiles[0] = {0, (uint32_t)frame.tilePayloadSize, 0, 0, 0xFF}; - } - } + if (!ParseGeneratedFrameHeader(desc, desc.encodedPayloadHeader + frame.headerPayloadOffset, availablePayload, tilePayload, availableTilePayload, fullTilePayloadSize, frame.combinedFrameObu, parsedInfo)) + return Result::FAILURE; if (frame.combinedFrameObu) { parsedInfo.bitstreamOffset = frame.headerPayloadOffset; @@ -2086,6 +2039,10 @@ static inline Result WriteSequenceHeaderPayload(const VideoAV1SequenceDesc& desc if (reducedStillPictureHeader && (!stillPicture || timingInfoPresent || initialDisplayDelayPresent || frameIdNumbersPresent || enableOrderHint)) return Result::INVALID_ARGUMENT; + // "frame_id_length" (additional_frame_id_length_minus_1 + delta_frame_id_length_minus_2 + 3) must not exceed 16 + if (frameIdNumbersPresent && (desc.additionalFrameIdLengthMinus1 > 7 || (desc.additionalFrameIdLengthMinus1 + desc.deltaFrameIdLengthMinus2 + 3) > 16)) + return Result::INVALID_ARGUMENT; + if (timingInfoPresent && (!desc.numUnitsInDisplayTick || !desc.timeScale || desc.numTicksPerPictureMinus1 == UINT32_MAX)) return Result::INVALID_ARGUMENT; diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index 9805779f..014328a4 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -60,17 +60,6 @@ static inline uint8_t GetVideoSessionBitDepth(Format format) { return format == Format::NV12_UNORM ? 8 : 10; } -static inline bool IsVideoH264CroppingValid(const VideoH264SequenceParameterSetDesc& sequence) { - if (!(sequence.flags & VideoH264SequenceParameterSetBits::FRAME_CROPPING)) - return true; - - // 4:2:0 progressive: "CropUnitX = CropUnitY = 2" - const uint32_t width = (sequence.pictureWidthInMbsMinus1 + 1u) * 16u; - const uint32_t height = (sequence.pictureHeightInMapUnitsMinus1 + 1u) * 16u; - - return (sequence.frameCropLeftOffset + sequence.frameCropRightOffset) * 2u < width && (sequence.frameCropTopOffset + sequence.frameCropBottomOffset) * 2u < height; -} - // "general_level_idc" (H.265 Table A.8, 30 times the level number) or 0 static inline bool IsVideoH265LevelIdcValid(uint8_t generalLevelIdc) { constexpr std::array levels = {0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183, 186}; @@ -126,7 +115,7 @@ static inline bool IsVideoSessionParametersDescValid(const VideoSessionDesc& ses for (uint32_t i = 0; i < parameters.sequenceParameterSetNum; i++) { const VideoH264SequenceParameterSetDesc& sequence = parameters.sequenceParameterSets[i]; const bool isProgressive = (sequence.flags & VideoH264SequenceParameterSetBits::FRAME_MBS_ONLY) && !(sequence.flags & VideoH264SequenceParameterSetBits::MB_ADAPTIVE_FRAME_FIELD); - if (sequence.sequenceParameterSetId >= 32 || (sequenceParameterSetMask & (1u << sequence.sequenceParameterSetId)) != 0 || sequence.profileIdc != h264HighProfileIdc || sequence.chromaFormatIdc != 1 || sequence.bitDepthLumaMinus8 != 0 || sequence.bitDepthChromaMinus8 != 0 || !isProgressive || !IsVideoH264CroppingValid(sequence)) + if (sequence.sequenceParameterSetId >= 32 || (sequenceParameterSetMask & (1u << sequence.sequenceParameterSetId)) != 0 || sequence.profileIdc != h264HighProfileIdc || sequence.chromaFormatIdc != 1 || sequence.bitDepthLumaMinus8 != 0 || sequence.bitDepthChromaMinus8 != 0 || !isProgressive || !video::h264::IsFrameCroppingValid(sequence)) return false; sequenceParameterSetMask |= 1u << sequence.sequenceParameterSetId; @@ -1911,7 +1900,7 @@ static Result NRI_CALL GetVideoPictureState(const VideoPicture& videoPicture, Vi static Result NRI_CALL WriteVideoAnnexBParameterSets(VideoAnnexBParameterSetsDesc& annexBParameterSetsDesc) { if (annexBParameterSetsDesc.codec == VideoCodec::H264) { - if (!annexBParameterSetsDesc.h264Sps || !annexBParameterSetsDesc.h264Pps || !IsVideoH264CroppingValid(*annexBParameterSetsDesc.h264Sps)) + if (!annexBParameterSetsDesc.h264Sps || !annexBParameterSetsDesc.h264Pps || !video::h264::IsFrameCroppingValid(*annexBParameterSetsDesc.h264Sps)) return Result::INVALID_ARGUMENT; } else if (annexBParameterSetsDesc.codec == VideoCodec::H265) { if (!annexBParameterSetsDesc.h265Vps || !annexBParameterSetsDesc.h265Sps || !annexBParameterSetsDesc.h265Pps) From 8641aaf4b6f8f67e1d2ca8ddc850cf25566fd954 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:39:11 +0200 Subject: [PATCH 04/20] VK: fix video decode/encode defects - decode: always pass the validated setup slot when the session has DPB slots (VUID-VkVideoDecodeInfoKHR-pSetupReferenceSlot-07168) - decode H.265: slice segment offsets point at the 3-byte start code (+1 instead of +4); sort StCurrBefore/StCurrAfter by POC - encode: track rate control state and apply changes with vkCmdControlVideoCodingKHR (VUID-...-08254); constantQp only for CQP (08269/08272) - encode H.265: select VPS/SPS/PPS ids from h265PictureDesc (08231-08233); convert generalLevelIdc from bitstream units to StdVideoH265LevelIdc and pick spec-correct default levels - encode H.264: num_ref_idx_active_override_flag; SPS frame cropping - AV1 decode: pass interpolation filter and tx mode through, OrderHints and expectedFrameId by reference name, SkipModeFrame, setup SavedOrderHints from the current frame's OrderHints - AV1 encode: signal loop filter ref/mode delta updates - GetTextureMemoryDesc2: chain the video profile list like texture creation (RADV crashed without it) - VIDEO_OUTPUT_ONLY usage (DST/SRC only); query DST and DPB usage separately and report coincide/distinct decode modes from the driver (fixes decode being reported unsupported on RADV) - encode feedback: fail instead of dereferencing an unmapped buffer - H.264 decode: a frame reference with both field flags has no std field flags - AV1 encode: txMode 0 keeps the default; keep the app's seq_force_screen_content_tools and fail with UNSUPPORTED if driver overrides change the sequence header that WriteVideoAV1ObuHeaders writes Co-Authored-By: Claude Opus 5.5 --- Include/NRIDescs.h | 2 +- Source/VK/CommandBufferVK.hpp | 158 +++++++---- Source/VK/DeviceVK.h | 1 + Source/VK/DeviceVK.hpp | 22 ++ Source/VK/TextureVK.hpp | 18 +- Source/VK/VideoHelpersVK.h | 168 +++++++++-- Source/VK/VideoPictureVK.hpp | 5 +- Source/VK/VideoSessionParametersVK.h | 13 +- Source/VK/VideoSessionParametersVK.hpp | 375 ++++++++++++++++++------- Source/VK/VideoSessionVK.h | 9 + Source/VK/VideoSessionVK.hpp | 47 +++- 11 files changed, 615 insertions(+), 203 deletions(-) diff --git a/Include/NRIDescs.h b/Include/NRIDescs.h index e8543b36..08321d63 100644 --- a/Include/NRIDescs.h +++ b/Include/NRIDescs.h @@ -735,7 +735,7 @@ NriBits(TextureUsageBits, uint16_t, // Min compatible access: VIDEO_DECODE = NriBit(7), // VIDEO_DECODE Video decode output / DPB picture VIDEO_ENCODE = NriBit(8), // VIDEO_ENCODE Video encode input / DPB picture VIDEO_REFERENCE_ONLY = NriBit(9), // VIDEO_* Video DPB/reference-only allocation - VIDEO_OUTPUT_ONLY = NriBit(10) // VIDEO_* Video decode output / encode input never used as a DPB picture (required if "decodeDpbAndOutputCoincide" is false) + VIDEO_OUTPUT_ONLY = NriBit(10) // VIDEO_* Video decode output / encode input never used as a DPB picture (required if "decodeDpbAndOutputCoincide" is false; encode: pair with "VIDEO_REFERENCE_ONLY" DPB textures, VK may not support the combined usage) ); // https://docs.vulkan.org/refpages/latest/refpages/source/VkBufferUsageFlagBits.html diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index 6770763f..d6b0f6b2 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -506,8 +506,8 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD NRI_CHECK(referenceDesc, "H.264 reference is missing after NRI validation"); h264StdReferences[i] = {}; - h264StdReferences[i].flags.top_field_flag = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::TOP_FIELD); - h264StdReferences[i].flags.bottom_field_flag = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::BOTTOM_FIELD); + h264StdReferences[i].flags.top_field_flag = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::TOP_FIELD) && !(referenceDesc->flags & VideoH264DecodeReferenceBits::BOTTOM_FIELD); + h264StdReferences[i].flags.bottom_field_flag = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::BOTTOM_FIELD) && !(referenceDesc->flags & VideoH264DecodeReferenceBits::TOP_FIELD); h264StdReferences[i].flags.used_for_long_term_reference = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::LONG_TERM); h264StdReferences[i].flags.is_non_existing = !!(referenceDesc->flags & VideoH264DecodeReferenceBits::NON_EXISTING); h264StdReferences[i].FrameNum = (uint16_t)referenceDesc->frameNum; @@ -570,7 +570,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD Scratch av1HeightInSbsMinus1 = NRI_ALLOCATE_SCRATCH(m_Device, uint16_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); void* codecPictureInfo = nullptr; const void* setupReferenceInfo = nullptr; - bool activatesSetupReferenceSlot = false; if (session.GetDesc().codec == VideoCodec::H264) { const VideoH264DecodePictureDesc& desc = *videoDecodeDesc.h264PictureDesc; h264StdPicture.flags.field_pic_flag = !!(desc.flags & VideoH264DecodePictureBits::FIELD_PICTURE); @@ -600,7 +599,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD h264StdReference.PicOrderCnt[1] = desc.bottomFieldOrderCount; h264DpbSlot.pStdReferenceInfo = &h264StdReference; setupReferenceInfo = &h264DpbSlot; - activatesSetupReferenceSlot = (desc.flags & VideoH264DecodePictureBits::REFERENCE) != 0; } else if (session.GetDesc().codec == VideoCodec::H265) { const VideoH265DecodePictureDesc& desc = *videoDecodeDesc.h265PictureDesc; h265StdPicture.flags.IrapPicFlag = !!(desc.flags & VideoH265DecodePictureBits::IRAP); @@ -620,26 +618,37 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD for (uint8_t& entry : h265StdPicture.RefPicSetLtCurr) entry = STD_VIDEO_H265_NO_REFERENCE_PICTURE; + // RefPicSetStCurrBefore is ordered by descending and RefPicSetStCurrAfter by ascending POC (H.265 8.3.2) + std::array before = {}; + std::array after = {}; uint32_t beforeNum = 0; uint32_t afterNum = 0; uint32_t longTermNum = 0; for (uint32_t i = 0; i < desc.referenceNum; i++) { const VideoH265ReferenceDesc& reference = desc.references[i]; - const uint8_t slot = (uint8_t)reference.slot; if (reference.longTerm) - h265StdPicture.RefPicSetLtCurr[longTermNum++] = slot; + h265StdPicture.RefPicSetLtCurr[longTermNum++] = (uint8_t)reference.slot; else if (reference.pictureOrderCount < desc.pictureOrderCount) - h265StdPicture.RefPicSetStCurrBefore[beforeNum++] = slot; + before[beforeNum++] = &reference; else if (reference.pictureOrderCount > desc.pictureOrderCount) - h265StdPicture.RefPicSetStCurrAfter[afterNum++] = slot; + after[afterNum++] = &reference; else { NRI_CHECK(false, "Unexpected equal H.265 short-term reference picture order count"); return; } } + std::sort(before.begin(), before.begin() + beforeNum, [](const VideoH265ReferenceDesc* a, const VideoH265ReferenceDesc* b) { return a->pictureOrderCount > b->pictureOrderCount; }); + std::sort(after.begin(), after.begin() + afterNum, [](const VideoH265ReferenceDesc* a, const VideoH265ReferenceDesc* b) { return a->pictureOrderCount < b->pictureOrderCount; }); + + for (uint32_t i = 0; i < beforeNum; i++) + h265StdPicture.RefPicSetStCurrBefore[i] = (uint8_t)before[i]->slot; + + for (uint32_t i = 0; i < afterNum; i++) + h265StdPicture.RefPicSetStCurrAfter[i] = (uint8_t)after[i]->slot; + for (uint32_t i = 0; i < desc.sliceSegmentOffsetNum; i++) - h265SliceSegmentOffsets[i] = desc.sliceSegmentOffsets[i] + 4; + h265SliceSegmentOffsets[i] = desc.sliceSegmentOffsets[i] + 1; // skip the leading zero byte of the documented 4-byte start code, pointing at "00 00 01" h265Picture.pStdPictureInfo = &h265StdPicture; h265Picture.sliceSegmentCount = desc.sliceSegmentOffsetNum; @@ -649,7 +658,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD h265StdReference.PicOrderCntVal = desc.pictureOrderCount; h265DpbSlot.pStdReferenceInfo = &h265StdReference; setupReferenceInfo = &h265DpbSlot; - activatesSetupReferenceSlot = (desc.flags & VideoH265DecodePictureBits::REFERENCE) != 0; } else if (session.GetDesc().codec == VideoCodec::AV1) { const VideoAV1DecodePictureDesc& desc = *videoDecodeDesc.av1PictureDesc; for (int32_t& slotIndex : av1Picture.referenceNameSlotIndices) @@ -711,7 +719,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD FillVideoDecodeAV1SetupReferenceInfo(av1StdReference, desc, pictureFlags); av1DpbSlot.pStdReferenceInfo = &av1StdReference; setupReferenceInfo = &av1DpbSlot; - activatesSetupReferenceSlot = desc.refreshFrameFlags != 0; } VideoPictureVK& dstPicture = *(VideoPictureVK*)videoDecodeDesc.dstPicture; @@ -721,7 +728,7 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD VkVideoReferenceSlotInfoKHR setupReferenceSlot = {VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR}; setupReferenceSlot.pNext = setupReferenceInfo; const uint32_t setupReferenceSlotIndex = video::GetDecodeSetupSlot(videoDecodeDesc); - setupReferenceSlot.slotIndex = (hasDpbSlots && activatesSetupReferenceSlot) ? (int32_t)setupReferenceSlotIndex : -1; + setupReferenceSlot.slotIndex = hasDpbSlots ? (int32_t)setupReferenceSlotIndex : -1; setupReferenceSlot.pPictureResource = &setupPicture.GetResource(); VkVideoBeginCodingInfoKHR beginInfo = {VK_STRUCTURE_TYPE_VIDEO_BEGIN_CODING_INFO_KHR}; @@ -864,6 +871,16 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD h264StdPicture.flags.no_output_of_prior_pics_flag = pictureDesc.frameType == VideoFrameType::IDR; h264StdPicture.seq_parameter_set_id = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->sequenceParameterSetId : 0; h264StdPicture.pic_parameter_set_id = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->pictureParameterSetId : 0; + + if (h264StdPicture.pRefLists) { + uint8_t l0DefaultActiveMinus1 = 0; + uint8_t l1DefaultActiveMinus1 = 0; + parameters.GetH264ReferenceIndexDefaults(h264StdPicture.pic_parameter_set_id, l0DefaultActiveMinus1, l1DefaultActiveMinus1); + + const bool isL1Active = pictureDesc.frameType == VideoFrameType::B; + h264SliceHeader.flags.num_ref_idx_active_override_flag = h264ReferenceLists.num_ref_idx_l0_active_minus1 != l0DefaultActiveMinus1 + || (isL1Active && h264ReferenceLists.num_ref_idx_l1_active_minus1 != l1DefaultActiveMinus1); + } h264StdPicture.idr_pic_id = pictureDesc.idrPictureId; h264StdPicture.primary_pic_type = GetVideoEncodeH264PictureType(pictureDesc.frameType); h264StdPicture.frame_num = pictureDesc.frameIndex; @@ -871,7 +888,7 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD h264StdPicture.temporal_id = pictureDesc.temporalLayer; h264SliceHeader.slice_type = pictureDesc.frameType == VideoFrameType::B ? STD_VIDEO_H264_SLICE_TYPE_B : (pictureDesc.frameType == VideoFrameType::P ? STD_VIDEO_H264_SLICE_TYPE_P : STD_VIDEO_H264_SLICE_TYPE_I); h264SliceHeader.disable_deblocking_filter_idc = STD_VIDEO_H264_DISABLE_DEBLOCKING_FILTER_IDC_DISABLED; - h264SliceInfo.constantQp = video::GetEncodeQPByFrameType(rateControlDesc, pictureDesc.frameType); + h264SliceInfo.constantQp = rateControlDesc.mode == VideoEncodeRateControlMode::CQP ? video::GetEncodeQPByFrameType(rateControlDesc, pictureDesc.frameType) : 0; h264SliceInfo.pStdSliceHeader = &h264SliceHeader; h264Picture.naluSliceEntryCount = 1; h264Picture.pNaluSliceEntries = &h264SliceInfo; @@ -888,9 +905,9 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD } case VideoCodec::H265: h265StdPicture.pic_type = GetVideoEncodeH265PictureType(pictureDesc.frameType); - h265StdPicture.sps_video_parameter_set_id = 0; - h265StdPicture.pps_seq_parameter_set_id = 0; - h265StdPicture.pps_pic_parameter_set_id = 0; + h265StdPicture.sps_video_parameter_set_id = videoEncodeDesc.h265PictureDesc ? videoEncodeDesc.h265PictureDesc->videoParameterSetId : 0; + h265StdPicture.pps_seq_parameter_set_id = videoEncodeDesc.h265PictureDesc ? videoEncodeDesc.h265PictureDesc->sequenceParameterSetId : 0; + h265StdPicture.pps_pic_parameter_set_id = videoEncodeDesc.h265PictureDesc ? videoEncodeDesc.h265PictureDesc->pictureParameterSetId : 0; h265StdPicture.PicOrderCntVal = pictureDesc.pictureOrderCount; h265StdPicture.TemporalId = pictureDesc.temporalLayer; h265StdPicture.flags.IrapPicFlag = pictureDesc.frameType == VideoFrameType::IDR || pictureDesc.frameType == VideoFrameType::I; @@ -969,12 +986,20 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD h265SliceHeader.flags.first_slice_segment_in_pic_flag = true; h265SliceHeader.flags.slice_sao_luma_flag = true; h265SliceHeader.flags.slice_sao_chroma_flag = true; - h265SliceHeader.flags.num_ref_idx_active_override_flag = h265ReferenceLists.num_ref_idx_l0_active_minus1 != 0 || h265ReferenceLists.num_ref_idx_l1_active_minus1 != 0; + if (h265StdPicture.pRefLists) { + uint8_t l0DefaultActiveMinus1 = 0; + uint8_t l1DefaultActiveMinus1 = 0; + parameters.GetH265ReferenceIndexDefaults(h265StdPicture.pps_seq_parameter_set_id, h265StdPicture.pps_pic_parameter_set_id, l0DefaultActiveMinus1, l1DefaultActiveMinus1); + + const bool isL1Active = pictureDesc.frameType == VideoFrameType::B; + h265SliceHeader.flags.num_ref_idx_active_override_flag = h265ReferenceLists.num_ref_idx_l0_active_minus1 != l0DefaultActiveMinus1 + || (isL1Active && h265ReferenceLists.num_ref_idx_l1_active_minus1 != l1DefaultActiveMinus1); + } h265SliceHeader.flags.mvd_l1_zero_flag = false; h265SliceHeader.flags.collocated_from_l0_flag = false; h265SliceHeader.slice_type = pictureDesc.frameType == VideoFrameType::B ? STD_VIDEO_H265_SLICE_TYPE_B : (pictureDesc.frameType == VideoFrameType::P ? STD_VIDEO_H265_SLICE_TYPE_P : STD_VIDEO_H265_SLICE_TYPE_I); h265SliceHeader.MaxNumMergeCand = 5; - h265SliceInfo.constantQp = video::GetEncodeQPByFrameType(rateControlDesc, pictureDesc.frameType); + h265SliceInfo.constantQp = rateControlDesc.mode == VideoEncodeRateControlMode::CQP ? video::GetEncodeQPByFrameType(rateControlDesc, pictureDesc.frameType) : 0; h265SliceInfo.pStdSliceSegmentHeader = &h265SliceHeader; h265Picture.naluSliceSegmentEntryCount = 1; h265Picture.pNaluSliceSegmentEntries = &h265SliceInfo; @@ -1019,11 +1044,14 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD av1StdPicture.render_width_minus_1 = av1PictureDesc->renderWidthMinus1 ? av1PictureDesc->renderWidthMinus1 : av1StdPicture.render_width_minus_1; av1StdPicture.render_height_minus_1 = av1PictureDesc->renderHeightMinus1 ? av1PictureDesc->renderHeightMinus1 : av1StdPicture.render_height_minus_1; av1StdPicture.interpolation_filter = (StdVideoAV1InterpolationFilter)av1PictureDesc->interpolationFilter; - av1StdPicture.TxMode = av1PictureDesc->txMode ? (StdVideoAV1TxMode)av1PictureDesc->txMode : STD_VIDEO_AV1_TX_MODE_SELECT; av1StdPicture.coded_denom = av1StdPicture.flags.use_superres ? av1PictureDesc->codedDenom : 0; av1StdPicture.delta_q_res = av1PictureDesc->deltaQRes; av1StdPicture.delta_lf_res = av1PictureDesc->deltaLfRes; } + + if (av1PictureDesc && av1PictureDesc->txMode) + av1StdPicture.TxMode = (StdVideoAV1TxMode)av1PictureDesc->txMode; + if (av1StdPicture.flags.frame_size_override_flag && (session.GetAV1CapabilityFlags() & VK_VIDEO_ENCODE_AV1_CAPABILITY_FRAME_SIZE_OVERRIDE_BIT_KHR) == 0) { NRI_REPORT_ERROR(&m_Device, "Vulkan AV1 encode does not support frame size override"); return; @@ -1288,43 +1316,39 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD referenceSlots[videoEncodeDesc.referenceNum] = GetVideoSetupReferenceSlotForBegin(setupReferenceSlot); } - VkVideoEncodeRateControlInfoKHR rateControlInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_INFO_KHR}; - VkVideoEncodeRateControlLayerInfoKHR rateControlLayer = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_LAYER_INFO_KHR}; - VkVideoEncodeH264RateControlInfoKHR h264RateControlInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H264_RATE_CONTROL_INFO_KHR}; - VkVideoEncodeH265RateControlInfoKHR h265RateControlInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H265_RATE_CONTROL_INFO_KHR}; - VkVideoEncodeAV1RateControlInfoKHR av1RateControlInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_RATE_CONTROL_INFO_KHR}; + // The rate control state is tracked per session: "VkVideoBeginCodingInfoKHR" must describe the current state, and changes are applied via "vkCmdControlVideoCodingKHR" + const bool needsSessionReset = !session.IsResetRecorded(); + const bool needsRateControlUpdate = !needsSessionReset && !IsVideoEncodeRateControlEqual(session.GetRateControl(), rateControlDesc); + + VideoEncodeRateControlVK rateControl = {}; + FillVideoEncodeRateControl(rateControl, rateControlDesc, session.GetDesc()); + + VideoEncodeRateControlVK currentRateControl = {}; + + if (needsRateControlUpdate) + FillVideoEncodeRateControl(currentRateControl, session.GetRateControl(), session.GetDesc()); + + // A begin scope with a CBR/VBR state needs the GOP remaining frames, if required + const bool requiresAV1GopRemainingFrames = session.GetDesc().codec == VideoCodec::AV1 && session.DoesAV1RequireGopRemainingFrames(); + auto chainAV1GopRemainingFrameInfo = [&](VkVideoEncodeAV1GopRemainingFrameInfoKHR& info, const VideoEncodeRateControlVK& state, VideoEncodeRateControlMode mode) -> const void* { + if (!requiresAV1GopRemainingFrames || mode == VideoEncodeRateControlMode::CQP) + return &state.info; + + info.useGopRemainingFrames = VK_TRUE; + info.gopRemainingIntra = (pictureDesc.frameType == VideoFrameType::IDR || pictureDesc.frameType == VideoFrameType::I) ? 1 : 0; + info.gopRemainingPredictive = state.av1.gopFrameCount ? state.av1.gopFrameCount - 1 : 0; + info.gopRemainingBipredictive = state.av1.consecutiveBipredictiveFrameCount; + info.pNext = &state.info; + + return &info; + }; + VkVideoEncodeAV1GopRemainingFrameInfoKHR av1GopRemainingFrameInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_GOP_REMAINING_FRAME_INFO_KHR}; VkVideoEncodeQualityLevelInfoKHR qualityLevelInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_INFO_KHR}; - const void* beginPNext = &rateControlInfo; - FillVideoEncodeRateControl(rateControlDesc, rateControlInfo, rateControlLayer); - if (session.GetDesc().codec == VideoCodec::H264) { - h264RateControlInfo.gopFrameCount = session.GetDesc().maxReferenceNum ? 60 : 1; - h264RateControlInfo.idrPeriod = h264RateControlInfo.gopFrameCount; - h264RateControlInfo.consecutiveBFrameCount = session.GetDesc().maxReferenceNum > 1 ? 1 : 0; - h264RateControlInfo.temporalLayerCount = 1; - rateControlInfo.pNext = &h264RateControlInfo; - } else if (session.GetDesc().codec == VideoCodec::H265) { - h265RateControlInfo.gopFrameCount = session.GetDesc().maxReferenceNum ? 60 : 1; - h265RateControlInfo.idrPeriod = h265RateControlInfo.gopFrameCount; - h265RateControlInfo.consecutiveBFrameCount = session.GetDesc().maxReferenceNum > 1 ? 1 : 0; - h265RateControlInfo.subLayerCount = 1; - rateControlInfo.pNext = &h265RateControlInfo; - } else if (session.GetDesc().codec == VideoCodec::AV1) { - av1RateControlInfo.flags = VK_VIDEO_ENCODE_AV1_RATE_CONTROL_REGULAR_GOP_BIT_KHR | VK_VIDEO_ENCODE_AV1_RATE_CONTROL_REFERENCE_PATTERN_FLAT_BIT_KHR; - av1RateControlInfo.gopFrameCount = 300; - av1RateControlInfo.keyFramePeriod = 300; - av1RateControlInfo.consecutiveBipredictiveFrameCount = 1; - rateControlInfo.pNext = &av1RateControlInfo; - qualityLevelInfo.pNext = &rateControlInfo; - if (session.DoesAV1RequireGopRemainingFrames() && rateControlDesc.mode != VideoEncodeRateControlMode::CQP) { - av1GopRemainingFrameInfo.useGopRemainingFrames = VK_TRUE; - av1GopRemainingFrameInfo.gopRemainingIntra = (pictureDesc.frameType == VideoFrameType::IDR || pictureDesc.frameType == VideoFrameType::I) ? 1 : 0; - av1GopRemainingFrameInfo.gopRemainingPredictive = av1RateControlInfo.gopFrameCount ? av1RateControlInfo.gopFrameCount - 1 : 0; - av1GopRemainingFrameInfo.gopRemainingBipredictive = av1RateControlInfo.consecutiveBipredictiveFrameCount; - av1GopRemainingFrameInfo.pNext = &rateControlInfo; - beginPNext = &av1GopRemainingFrameInfo; - } - } + const void* beginPNext = chainAV1GopRemainingFrameInfo(av1GopRemainingFrameInfo, rateControl, rateControlDesc.mode); + + if (session.GetDesc().codec == VideoCodec::AV1) + qualityLevelInfo.pNext = &rateControl.info; VkVideoBeginCodingInfoKHR beginInfo = {VK_STRUCTURE_TYPE_VIDEO_BEGIN_CODING_INFO_KHR}; beginInfo.pNext = beginPNext; @@ -1357,22 +1381,32 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD if (useEncodeFeedback) vk.CmdResetQueryPool(m_Handle, session.GetEncodeFeedbackQueryPool(), encodeFeedbackQueryIndex, 1); - const bool needsSessionReset = !session.IsResetRecorded(); - if (needsSessionReset) { - VkVideoBeginCodingInfoKHR initBeginInfo = beginInfo; - initBeginInfo.pNext = nullptr; + // Reset or rate control change: the control scope begins with the current state (none after reset) and ends with the new one + if (needsSessionReset || needsRateControlUpdate) { + VkVideoEncodeAV1GopRemainingFrameInfoKHR controlAV1GopRemainingFrameInfo = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_GOP_REMAINING_FRAME_INFO_KHR}; + VkVideoBeginCodingInfoKHR controlBeginInfo = beginInfo; + controlBeginInfo.pNext = needsSessionReset ? nullptr : chainAV1GopRemainingFrameInfo(controlAV1GopRemainingFrameInfo, currentRateControl, session.GetRateControl().mode); + + const bool setsQualityLevel = needsSessionReset && session.GetDesc().codec == VideoCodec::AV1; VkVideoCodingControlInfoKHR controlInfo = {VK_STRUCTURE_TYPE_VIDEO_CODING_CONTROL_INFO_KHR}; + controlInfo.flags = VK_VIDEO_CODING_CONTROL_ENCODE_RATE_CONTROL_BIT_KHR; + + if (needsSessionReset) + controlInfo.flags |= VK_VIDEO_CODING_CONTROL_RESET_BIT_KHR; - vk.CmdBeginVideoCodingKHR(m_Handle, &initBeginInfo); - controlInfo.flags = VK_VIDEO_CODING_CONTROL_RESET_BIT_KHR | VK_VIDEO_CODING_CONTROL_ENCODE_RATE_CONTROL_BIT_KHR; - if (session.GetDesc().codec == VideoCodec::AV1) + if (setsQualityLevel) controlInfo.flags |= VK_VIDEO_CODING_CONTROL_ENCODE_QUALITY_LEVEL_BIT_KHR; - controlInfo.pNext = session.GetDesc().codec == VideoCodec::AV1 ? (const void*)&qualityLevelInfo : (const void*)&rateControlInfo; + controlInfo.pNext = setsQualityLevel ? (const void*)&qualityLevelInfo : (const void*)&rateControl.info; + + vk.CmdBeginVideoCodingKHR(m_Handle, &controlBeginInfo); vk.CmdControlVideoCodingKHR(m_Handle, &controlInfo); vk.CmdEndVideoCodingKHR(m_Handle, &endInfo); + session.SetResetRecorded(); + session.SetRateControl(rateControlDesc); } + vk.CmdBeginVideoCodingKHR(m_Handle, &beginInfo); if (useEncodeFeedback) diff --git a/Source/VK/DeviceVK.h b/Source/VK/DeviceVK.h index 5117a6ca..aa7c8e7b 100644 --- a/Source/VK/DeviceVK.h +++ b/Source/VK/DeviceVK.h @@ -221,6 +221,7 @@ struct DeviceVK final : public DeviceBase { VkFramebuffer GetOrCreateFramebuffer(const FramebufferDesc& desc); void FillCreateInfo(const BufferDesc& bufferDesc, VkBufferCreateInfo& info) const; void FillCreateInfo(const TextureDesc& bufferDesc, VkImageCreateInfo& info) const; + void AppendVideoProfileList(const TextureDesc& textureDesc, VkImageCreateInfo& info, VideoResourceProfileListVK& videoProfiles) const; // "videoProfiles" must outlive "info" void FillCreateInfo(const SamplerDesc& samplerDesc, VkSamplerCreateInfo& info, VkSamplerReductionModeCreateInfo& reductionModeInfo, VkSamplerCustomBorderColorCreateInfoEXT& borderColorInfo) const; void GetMemoryDesc2(const BufferDesc& bufferDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; void GetMemoryDesc2(const TextureDesc& textureDesc, MemoryLocation memoryLocation, MemoryDesc& memoryDesc) const; diff --git a/Source/VK/DeviceVK.hpp b/Source/VK/DeviceVK.hpp index 6aeed958..a77c7729 100644 --- a/Source/VK/DeviceVK.hpp +++ b/Source/VK/DeviceVK.hpp @@ -168,6 +168,8 @@ static constexpr VkImageUsageFlags GetImageUsageFlags(TextureUsageBits textureUs if (textureUsageBits & TextureUsageBits::VIDEO_DECODE) { if (textureUsageBits & TextureUsageBits::VIDEO_REFERENCE_ONLY) flags |= VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR; + else if (textureUsageBits & TextureUsageBits::VIDEO_OUTPUT_ONLY) + flags |= VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR; else flags |= VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR | VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR; } @@ -175,6 +177,8 @@ static constexpr VkImageUsageFlags GetImageUsageFlags(TextureUsageBits textureUs if (textureUsageBits & TextureUsageBits::VIDEO_ENCODE) { if (textureUsageBits & TextureUsageBits::VIDEO_REFERENCE_ONLY) flags |= VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR; + else if (textureUsageBits & TextureUsageBits::VIDEO_OUTPUT_ONLY) + flags |= VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR; else flags |= VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR | VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR; } @@ -1772,6 +1776,21 @@ void DeviceVK::FillCreateInfo(const TextureDesc& textureDesc, VkImageCreateInfo& info.initialLayout = IsMemoryZeroInitializationEnabled() ? VK_IMAGE_LAYOUT_ZERO_INITIALIZED_EXT : VK_IMAGE_LAYOUT_UNDEFINED; } +void DeviceVK::AppendVideoProfileList(const TextureDesc& textureDesc, VkImageCreateInfo& info, VideoResourceProfileListVK& videoProfiles) const { + const bool isVideoDecode = (textureDesc.usage & TextureUsageBits::VIDEO_DECODE) != 0; + const bool isVideoEncode = (textureDesc.usage & TextureUsageBits::VIDEO_ENCODE) != 0; + + if (!isVideoDecode && !isVideoEncode) + return; + + videoProfiles.Fill(isVideoDecode, isVideoEncode, textureDesc.format, textureDesc.videoCodec, GetVideoCodecOperations(isVideoDecode, isVideoEncode)); + + if (videoProfiles.list.profileCount) { + videoProfiles.list.pNext = info.pNext; + info.pNext = &videoProfiles.list; + } +} + void DeviceVK::FillCreateInfo(const SamplerDesc& samplerDesc, VkSamplerCreateInfo& info, VkSamplerReductionModeCreateInfo& reductionModeInfo, VkSamplerCustomBorderColorCreateInfoEXT& borderColorInfo) const { info = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; // should be already set info.magFilter = GetFilter(samplerDesc.filters.mag); @@ -1847,6 +1866,9 @@ void DeviceVK::GetMemoryDesc2(const TextureDesc& textureDesc, MemoryLocation mem VkMemoryRequirements2 requirements = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; requirements.pNext = &dedicatedRequirements; + VideoResourceProfileListVK videoProfiles = {}; + AppendVideoProfileList(textureDesc, createInfo, videoProfiles); + VkDeviceImageMemoryRequirements imageMemoryRequirements = {VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; imageMemoryRequirements.pCreateInfo = &createInfo; diff --git a/Source/VK/TextureVK.hpp b/Source/VK/TextureVK.hpp index 014a3062..c591c9d1 100644 --- a/Source/VK/TextureVK.hpp +++ b/Source/VK/TextureVK.hpp @@ -19,15 +19,7 @@ Result TextureVK::Create(const TextureDesc& textureDesc) { m_IsConcurrent = info.sharingMode == VK_SHARING_MODE_CONCURRENT; VideoResourceProfileListVK videoProfiles = {}; - const bool isVideoDecode = (m_Desc.usage & TextureUsageBits::VIDEO_DECODE) != 0; - const bool isVideoEncode = (m_Desc.usage & TextureUsageBits::VIDEO_ENCODE) != 0; - if (isVideoDecode || isVideoEncode) { - videoProfiles.Fill(isVideoDecode, isVideoEncode, m_Desc.format, m_Desc.videoCodec, m_Device.GetVideoCodecOperations(isVideoDecode, isVideoEncode)); - if (videoProfiles.list.profileCount) { - videoProfiles.list.pNext = info.pNext; - info.pNext = &videoProfiles.list; - } - } + m_Device.AppendVideoProfileList(m_Desc, info, videoProfiles); const auto& vk = m_Device.GetDispatchTable(); VkResult vkResult = vk.CreateImage(m_Device, &info, m_Device.GetVkAllocationCallbacks(), &m_Handle); @@ -72,12 +64,16 @@ Result TextureVK::Create(const TextureVKDesc& textureVKDesc) { if ((textureVKDesc.vkImageUsageFlags & hostTransferUsage) == hostTransferUsage) m_Desc.usage |= TextureUsageBits::HOST_TRANSFER; - if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR) + if ((textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR) && !(textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR)) + m_Desc.usage |= TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_OUTPUT_ONLY; + else if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR) m_Desc.usage |= TextureUsageBits::VIDEO_DECODE; else if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR) m_Desc.usage |= TextureUsageBits::VIDEO_DECODE | TextureUsageBits::VIDEO_REFERENCE_ONLY; - if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR) + if ((textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR) && !(textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR)) + m_Desc.usage |= TextureUsageBits::VIDEO_ENCODE | TextureUsageBits::VIDEO_OUTPUT_ONLY; + else if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR) m_Desc.usage |= TextureUsageBits::VIDEO_ENCODE; else if (textureVKDesc.vkImageUsageFlags & VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR) m_Desc.usage |= TextureUsageBits::VIDEO_ENCODE | TextureUsageBits::VIDEO_REFERENCE_ONLY; diff --git a/Source/VK/VideoHelpersVK.h b/Source/VK/VideoHelpersVK.h index ea22a369..3a5cbedc 100644 --- a/Source/VK/VideoHelpersVK.h +++ b/Source/VK/VideoHelpersVK.h @@ -51,6 +51,61 @@ static inline void FillVideoEncodeRateControl(const VideoEncodeRateControlDesc& info.initialVirtualBufferSizeInMs = desc.initialVirtualBufferSizeMs ? desc.initialVirtualBufferSizeMs : info.virtualBufferSizeInMs; } +struct VideoEncodeRateControlVK { + VkVideoEncodeRateControlInfoKHR info = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_INFO_KHR}; + VkVideoEncodeRateControlLayerInfoKHR layer = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_LAYER_INFO_KHR}; + VkVideoEncodeH264RateControlInfoKHR h264 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H264_RATE_CONTROL_INFO_KHR}; + VkVideoEncodeH265RateControlInfoKHR h265 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H265_RATE_CONTROL_INFO_KHR}; + VkVideoEncodeAV1RateControlInfoKHR av1 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_RATE_CONTROL_INFO_KHR}; +}; + +// Fills a self-referencing native chain: "rateControl" must not be copied or moved afterwards +static inline void FillVideoEncodeRateControl(VideoEncodeRateControlVK& rateControl, const VideoEncodeRateControlDesc& desc, const VideoSessionDesc& sessionDesc) { + FillVideoEncodeRateControl(desc, rateControl.info, rateControl.layer); + + if (sessionDesc.codec == VideoCodec::H264) { + rateControl.h264.gopFrameCount = sessionDesc.maxReferenceNum ? 60 : 1; + rateControl.h264.idrPeriod = rateControl.h264.gopFrameCount; + rateControl.h264.consecutiveBFrameCount = sessionDesc.maxReferenceNum > 1 ? 1 : 0; + rateControl.h264.temporalLayerCount = 1; + rateControl.info.pNext = &rateControl.h264; + } else if (sessionDesc.codec == VideoCodec::H265) { + rateControl.h265.gopFrameCount = sessionDesc.maxReferenceNum ? 60 : 1; + rateControl.h265.idrPeriod = rateControl.h265.gopFrameCount; + rateControl.h265.consecutiveBFrameCount = sessionDesc.maxReferenceNum > 1 ? 1 : 0; + rateControl.h265.subLayerCount = 1; + rateControl.info.pNext = &rateControl.h265; + } else if (sessionDesc.codec == VideoCodec::AV1) { + rateControl.av1.flags = VK_VIDEO_ENCODE_AV1_RATE_CONTROL_REGULAR_GOP_BIT_KHR | VK_VIDEO_ENCODE_AV1_RATE_CONTROL_REFERENCE_PATTERN_FLAT_BIT_KHR; + rateControl.av1.gopFrameCount = 300; + rateControl.av1.keyFramePeriod = 300; + rateControl.av1.consecutiveBipredictiveFrameCount = 1; + rateControl.info.pNext = &rateControl.av1; + } +} + +// Compares the native rate control state produced by two descriptions (QP values are per-picture, not part of the state) +static inline bool IsVideoEncodeRateControlEqual(const VideoEncodeRateControlDesc& a, const VideoEncodeRateControlDesc& b) { + VkVideoEncodeRateControlInfoKHR infoA = {}; + VkVideoEncodeRateControlInfoKHR infoB = {}; + VkVideoEncodeRateControlLayerInfoKHR layerA = {}; + VkVideoEncodeRateControlLayerInfoKHR layerB = {}; + FillVideoEncodeRateControl(a, infoA, layerA); + FillVideoEncodeRateControl(b, infoB, layerB); + + if (infoA.rateControlMode != infoB.rateControlMode || infoA.layerCount != infoB.layerCount) + return false; + + if (infoA.virtualBufferSizeInMs != infoB.virtualBufferSizeInMs || infoA.initialVirtualBufferSizeInMs != infoB.initialVirtualBufferSizeInMs) + return false; + + if (!infoA.layerCount) + return true; + + return layerA.averageBitrate == layerB.averageBitrate && layerA.maxBitrate == layerB.maxBitrate && layerA.frameRateNumerator == layerB.frameRateNumerator + && layerA.frameRateDenominator == layerB.frameRateDenominator; +} + static inline VkVideoReferenceSlotInfoKHR GetVideoSetupReferenceSlotForBegin(const VkVideoReferenceSlotInfoKHR& setupReferenceSlot) { VkVideoReferenceSlotInfoKHR beginReferenceSlot = setupReferenceSlot; beginReferenceSlot.slotIndex = -1; @@ -133,6 +188,40 @@ static inline uint8_t GetVideoAV1SizeBitsMinus1(uint32_t value) { return bits - 1; } +// "general_level_idc" is 30 times the level number (H.265 A.4.1) +static inline StdVideoH265LevelIdc GetVideoH265LevelIdc(uint8_t generalLevelIdc) { + switch (generalLevelIdc) { + case 30: + return STD_VIDEO_H265_LEVEL_IDC_1_0; + case 60: + return STD_VIDEO_H265_LEVEL_IDC_2_0; + case 63: + return STD_VIDEO_H265_LEVEL_IDC_2_1; + case 90: + return STD_VIDEO_H265_LEVEL_IDC_3_0; + case 93: + return STD_VIDEO_H265_LEVEL_IDC_3_1; + case 120: + return STD_VIDEO_H265_LEVEL_IDC_4_0; + case 123: + return STD_VIDEO_H265_LEVEL_IDC_4_1; + case 150: + return STD_VIDEO_H265_LEVEL_IDC_5_0; + case 153: + return STD_VIDEO_H265_LEVEL_IDC_5_1; + case 156: + return STD_VIDEO_H265_LEVEL_IDC_5_2; + case 180: + return STD_VIDEO_H265_LEVEL_IDC_6_0; + case 183: + return STD_VIDEO_H265_LEVEL_IDC_6_1; + case 186: + return STD_VIDEO_H265_LEVEL_IDC_6_2; + default: + return STD_VIDEO_H265_LEVEL_IDC_INVALID; + } +} + static inline void FillVideoH265ProfileTierLevel(StdVideoH265ProfileTierLevel& profileTierLevel, const VideoH265ProfileTierLevelDesc& desc) { profileTierLevel = {}; profileTierLevel.flags.general_tier_flag = !!(desc.flags & VideoH265ProfileTierLevelBits::TIER); @@ -141,7 +230,7 @@ static inline void FillVideoH265ProfileTierLevel(StdVideoH265ProfileTierLevel& p profileTierLevel.flags.general_non_packed_constraint_flag = !!(desc.flags & VideoH265ProfileTierLevelBits::NON_PACKED_CONSTRAINT); profileTierLevel.flags.general_frame_only_constraint_flag = !!(desc.flags & VideoH265ProfileTierLevelBits::FRAME_ONLY_CONSTRAINT); profileTierLevel.general_profile_idc = (StdVideoH265ProfileIdc)desc.generalProfileIdc; - profileTierLevel.general_level_idc = (StdVideoH265LevelIdc)desc.generalLevelIdc; + profileTierLevel.general_level_idc = GetVideoH265LevelIdc(desc.generalLevelIdc); } static inline void FillVideoH265DecPicBufMgr(StdVideoH265DecPicBufMgr& decPicBufMgr, const VideoH265DecPicBufMgrDesc& desc) { @@ -508,8 +597,27 @@ static inline void FillVideoDecodeAV1ReferenceInfo(StdVideoDecodeAV1ReferenceInf } } +// "OrderHints[]" is indexed by reference name: "OrderHints[LAST_FRAME + i]" (AV1 7.20) +static inline void FillVideoDecodeAV1OrderHints(uint8_t* orderHints, const VideoAV1DecodePictureDesc& desc) { + if (desc.orderHints) + std::memcpy(orderHints, desc.orderHints, STD_VIDEO_AV1_NUM_REF_FRAMES); + else + orderHints[0] = desc.orderHint; + + for (uint32_t i = 0; i < desc.referenceNum; i++) { + const VideoAV1ReferenceDesc& reference = desc.references[i]; + const uint8_t referenceNameIndex = video::av1::GetReferenceNameIndex(reference.name); + + if (referenceNameIndex < VK_MAX_VIDEO_AV1_REFERENCES_PER_FRAME_KHR) + orderHints[STD_VIDEO_AV1_REFERENCE_NAME_LAST_FRAME + referenceNameIndex] = reference.orderHint; + } +} + static inline void FillVideoDecodeAV1SetupReferenceInfo(StdVideoDecodeAV1ReferenceInfo& info, const VideoAV1DecodePictureDesc& desc, VideoAV1PictureBits pictureFlags) { - FillVideoDecodeAV1ReferenceInfo(info, desc.frameType, desc.orderHint); + info = {}; + info.frame_type = (uint8_t)GetVideoAV1FrameType(desc.frameType); + info.OrderHint = desc.orderHint; + FillVideoDecodeAV1OrderHints(info.SavedOrderHints, desc); // "SavedOrderHints[i][j] = OrderHints[j]" (AV1 7.20) info.flags.disable_frame_end_update_cdf = !!(pictureFlags & VideoAV1PictureBits::DISABLE_FRAME_END_UPDATE_CDF); info.flags.segmentation_enabled = !!(pictureFlags & VideoAV1PictureBits::SEGMENTATION_ENABLED); } @@ -712,22 +820,26 @@ static inline void FillVideoDecodeAV1PictureInfo(StdVideoDecodeAV1PictureInfo& i info.OrderHint = desc.orderHint; info.primary_ref_frame = video::av1::GetReferenceNameIndex(desc.primaryReferenceName); info.refresh_frame_flags = desc.refreshFrameFlags; - info.interpolation_filter = desc.interpolationFilter ? (StdVideoAV1InterpolationFilter)desc.interpolationFilter : STD_VIDEO_AV1_INTERPOLATION_FILTER_SWITCHABLE; - info.TxMode = desc.txMode ? (StdVideoAV1TxMode)desc.txMode : STD_VIDEO_AV1_TX_MODE_SELECT; + info.interpolation_filter = (StdVideoAV1InterpolationFilter)desc.interpolationFilter; // 0 = EIGHTTAP + info.TxMode = (StdVideoAV1TxMode)desc.txMode; // 0 = ONLY_4X4 info.delta_q_res = desc.deltaQRes; info.delta_lf_res = desc.deltaLfRes; info.coded_denom = desc.codedDenom; - if (desc.orderHints) - std::memcpy(info.OrderHints, desc.orderHints, sizeof(info.OrderHints)); - else - info.OrderHints[0] = desc.orderHint; - info.expectedFrameId[0] = desc.currentFrameId; + info.SkipModeFrame[0] = (uint8_t)desc.skipModeFrames[0]; + info.SkipModeFrame[1] = (uint8_t)desc.skipModeFrames[1]; + static_assert((uint8_t)VideoAV1ReferenceName::LAST == STD_VIDEO_AV1_REFERENCE_NAME_LAST_FRAME, "Unexpected"); + static_assert((uint8_t)VideoAV1ReferenceName::ALTREF == STD_VIDEO_AV1_REFERENCE_NAME_ALTREF_FRAME, "Unexpected"); + + // "OrderHints[]" is indexed by reference name, "expectedFrameId[]" by reference name index ("i" in "ref_frame_idx[i]") + FillVideoDecodeAV1OrderHints(info.OrderHints, desc); for (uint32_t i = 0; i < desc.referenceNum; i++) { const VideoAV1ReferenceDesc& reference = desc.references[i]; - info.OrderHints[reference.refFrameIndex] = reference.orderHint; - info.expectedFrameId[reference.refFrameIndex] = reference.frameId; + const uint8_t referenceNameIndex = video::av1::GetReferenceNameIndex(reference.name); + + if (referenceNameIndex < VK_MAX_VIDEO_AV1_REFERENCES_PER_FRAME_KHR) + info.expectedFrameId[referenceNameIndex] = reference.frameId; } } @@ -849,7 +961,12 @@ static inline void FillVideoEncodeAV1LoopFilter(StdVideoAV1LoopFilter& info, con info.flags.loop_filter_delta_update = desc->loopFilter->deltaUpdate != 0; std::memcpy(info.loop_filter_level, desc->loopFilter->level, sizeof(info.loop_filter_level)); info.loop_filter_sharpness = desc->loopFilter->sharpness; - info.update_mode_delta = desc->loopFilter->updateModeDelta; + + // Signal all ref/mode deltas on update, otherwise the provided deltas are not coded + if (info.flags.loop_filter_delta_enabled && info.flags.loop_filter_delta_update) { + info.update_ref_delta = (uint8_t)((1u << STD_VIDEO_AV1_TOTAL_REFS_PER_FRAME) - 1); + info.update_mode_delta = (uint8_t)((1u << STD_VIDEO_AV1_LOOP_FILTER_ADJUSTMENTS) - 1); + } std::memcpy(info.loop_filter_ref_deltas, desc->loopFilter->refDeltas, sizeof(info.loop_filter_ref_deltas)); std::memcpy(info.loop_filter_mode_deltas, desc->loopFilter->modeDeltas, sizeof(info.loop_filter_mode_deltas)); return; @@ -940,12 +1057,31 @@ static inline void FillVideoDecodeAV1FilmGrain(StdVideoAV1FilmGrain& info, const std::memcpy(info.ar_coeffs_cr_plus_128, desc.arCoeffsCrPlus128, sizeof(info.ar_coeffs_cr_plus_128)); } -static inline StdVideoH265LevelIdc GetVideoH265LevelIdc(uint32_t width, uint32_t height) { +// Returns the lowest of levels 3.1, 4.1, 5.1 and 6.1 (as "general_level_idc") whose Table A.8 limits allow the picture size at up to 60 frames per second +static inline uint8_t GetVideoH265DefaultGeneralLevelIdc(uint32_t width, uint32_t height) { + struct Level { + uint8_t generalLevelIdc; + uint64_t maxLumaPs; + uint64_t maxLumaSr; + }; + + static constexpr Level levels[] = { + {93, 983040, 33177600}, + {123, 2228224, 133693440}, + {153, 8912896, 534773760}, + {183, 35651584, 2139095040}, + }; + const uint64_t samples = uint64_t(width) * height; - if (samples <= 512ull * 512ull) - return STD_VIDEO_H265_LEVEL_IDC_3_1; - return STD_VIDEO_H265_LEVEL_IDC_4_1; + for (const Level& level : levels) { + const uint64_t maxDimSquared = level.maxLumaPs * 8; + + if (samples <= level.maxLumaPs && (uint64_t(width) * width) <= maxDimSquared && (uint64_t(height) * height) <= maxDimSquared && (samples * 60) <= level.maxLumaSr) + return level.generalLevelIdc; + } + + return levels[std::size(levels) - 1].generalLevelIdc; } } // namespace nri diff --git a/Source/VK/VideoPictureVK.hpp b/Source/VK/VideoPictureVK.hpp index 962b0cc6..af601e06 100644 --- a/Source/VK/VideoPictureVK.hpp +++ b/Source/VK/VideoPictureVK.hpp @@ -25,7 +25,10 @@ NRI_INLINE Result VideoPictureVK::Create(const VideoPictureDesc& videoPictureDes switch (videoPictureDesc.usage) { case VideoPictureUsage::DECODE_OUTPUT: - usageInfo.usage |= VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR | VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR; + usageInfo.usage |= VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR; + + if (!(textureDesc.usage & TextureUsageBits::VIDEO_OUTPUT_ONLY)) + usageInfo.usage |= VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR; // coincide mode: the output is also the setup picture break; case VideoPictureUsage::DECODE_REFERENCE: usageInfo.usage |= VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR; diff --git a/Source/VK/VideoSessionParametersVK.h b/Source/VK/VideoSessionParametersVK.h index 1eac8203..5c651ecb 100644 --- a/Source/VK/VideoSessionParametersVK.h +++ b/Source/VK/VideoSessionParametersVK.h @@ -8,7 +8,8 @@ struct VideoSessionVK; struct VideoSessionParametersVK final : public DebugNameBase { inline VideoSessionParametersVK(DeviceVK& device) - : m_Device(device) { + : m_Device(device) + , m_ReferenceIndexDefaults(device.GetStdAllocator()) { } inline DeviceVK& GetDevice() const { @@ -42,8 +43,17 @@ struct VideoSessionParametersVK final : public DebugNameBase { //================================================================================================================ Result Create(const VideoSessionParametersDesc& videoSessionParametersDesc); + void GetH264ReferenceIndexDefaults(uint8_t pictureParameterSetId, uint8_t& l0DefaultActiveMinus1, uint8_t& l1DefaultActiveMinus1) const; + void GetH265ReferenceIndexDefaults(uint8_t sequenceParameterSetId, uint8_t pictureParameterSetId, uint8_t& l0DefaultActiveMinus1, uint8_t& l1DefaultActiveMinus1) const; private: + struct ReferenceIndexDefaults { + uint8_t sequenceParameterSetId; + uint8_t pictureParameterSetId; + uint8_t l0DefaultActiveMinus1; + uint8_t l1DefaultActiveMinus1; + }; + Result CreateNative(VideoSessionVK& session, const void* pNext); Result CreateH265(VideoSessionVK& session, const VideoH265SessionParametersDesc* parameters); Result CreateAV1(VideoSessionVK& session, const VideoAV1SessionParametersDesc* parameters); @@ -51,6 +61,7 @@ struct VideoSessionParametersVK final : public DebugNameBase { DeviceVK& m_Device; VideoSessionVK* m_Session = nullptr; VkVideoSessionParametersKHR m_Handle = VK_NULL_HANDLE; + Vector m_ReferenceIndexDefaults; // PPS "num_ref_idx_lX_default_active_minus1" for H.264/H.265 encode slice headers StdVideoAV1ColorConfig m_AV1ColorConfig = {}; StdVideoAV1TimingInfo m_AV1TimingInfo = {}; StdVideoAV1SequenceHeader m_AV1SequenceHeader = {}; diff --git a/Source/VK/VideoSessionParametersVK.hpp b/Source/VK/VideoSessionParametersVK.hpp index 2c790665..2d01d3f7 100644 --- a/Source/VK/VideoSessionParametersVK.hpp +++ b/Source/VK/VideoSessionParametersVK.hpp @@ -60,6 +60,7 @@ static StdVideoH264SequenceParameterSet GetVideoH264SequenceParameterSet(const V sps.flags.separate_colour_plane_flag = !!(desc.flags & VideoH264SequenceParameterSetBits::SEPARATE_COLOUR_PLANE); sps.flags.gaps_in_frame_num_value_allowed_flag = !!(desc.flags & VideoH264SequenceParameterSetBits::GAPS_IN_FRAME_NUM_ALLOWED); sps.flags.qpprime_y_zero_transform_bypass_flag = !!(desc.flags & VideoH264SequenceParameterSetBits::QPPRIME_Y_ZERO_TRANSFORM_BYPASS); + sps.flags.frame_cropping_flag = !!(desc.flags & VideoH264SequenceParameterSetBits::FRAME_CROPPING); sps.profile_idc = (StdVideoH264ProfileIdc)desc.profileIdc; sps.level_idc = GetVideoH264LevelIdc(desc.levelIdc); sps.chroma_format_idc = (StdVideoH264ChromaFormatIdc)desc.chromaFormatIdc; @@ -74,6 +75,14 @@ static StdVideoH264SequenceParameterSet GetVideoH264SequenceParameterSet(const V sps.max_num_ref_frames = desc.referenceFrameNum; sps.pic_width_in_mbs_minus1 = desc.pictureWidthInMbsMinus1; sps.pic_height_in_map_units_minus1 = desc.pictureHeightInMapUnitsMinus1; + + if (sps.flags.frame_cropping_flag) { + sps.frame_crop_left_offset = desc.frameCropLeftOffset; + sps.frame_crop_right_offset = desc.frameCropRightOffset; + sps.frame_crop_top_offset = desc.frameCropTopOffset; + sps.frame_crop_bottom_offset = desc.frameCropBottomOffset; + } + return sps; } @@ -98,147 +107,292 @@ static StdVideoH264PictureParameterSet GetVideoH264PictureParameterSet(const Vid return pps; } -static bool SkipVideoAV1TimingInfo(video::av1::BitReader& reader) { - uint32_t ignored = 0; - uint8_t equalPictureInterval = 0; - if (!reader.ReadBits(32, ignored) || !reader.ReadBits(32, ignored) || !reader.ReadFlag(equalPictureInterval)) - return false; - if (!equalPictureInterval) - return true; - +// Sequence header fields affecting frame header syntax or decoding; level, tier, operating points, timing and color description values are not included +struct VideoAV1SequenceSyntaxVK { + uint32_t seqProfile; + uint32_t reducedStillPictureHeader; + uint32_t decoderModelInfoPresent; + uint32_t equalPictureInterval; + uint32_t bufferRemovalTimeLengthMinus1; + uint32_t framePresentationTimeLengthMinus1; + uint32_t frameWidthBitsMinus1; + uint32_t frameHeightBitsMinus1; + uint32_t maxFrameWidthMinus1; + uint32_t maxFrameHeightMinus1; + uint32_t frameIdNumbersPresent; + uint32_t deltaFrameIdLengthMinus2; + uint32_t additionalFrameIdLengthMinus1; + uint32_t use128x128Superblock; + uint32_t enableFilterIntra; + uint32_t enableIntraEdgeFilter; + uint32_t enableInterintraCompound; + uint32_t enableMaskedCompound; + uint32_t enableWarpedMotion; + uint32_t enableDualFilter; + uint32_t enableOrderHint; + uint32_t enableJntComp; + uint32_t enableRefFrameMvs; + uint32_t seqForceScreenContentTools; + uint32_t seqForceIntegerMv; + uint32_t orderHintBitsMinus1; + uint32_t enableSuperres; + uint32_t enableCdef; + uint32_t enableRestoration; + uint32_t bitDepth; + uint32_t monochrome; + uint32_t subsamplingX; + uint32_t subsamplingY; + uint32_t separateUvDeltaQ; + uint32_t filmGrainParamsPresent; +}; + +static bool ReadVideoAV1Uvlc(video::av1::BitReader& reader) { + uint32_t leadingZeros = 0; uint32_t bit = 0; - do { + while (true) { if (!reader.ReadBits(1, bit)) return false; - } while (bit); + if (bit) + break; + if (++leadingZeros >= 32) + return false; + } - return true; + uint32_t ignored = 0; + return reader.ReadBits(leadingZeros, ignored); } -static bool SkipVideoAV1DecoderModelInfo(video::av1::BitReader& reader, uint32_t& bufferDelayLength) { - uint32_t ignored = 0; - if (!reader.ReadBits(5, bufferDelayLength) || !reader.ReadBits(32, ignored) || !reader.ReadBits(5, ignored) || !reader.ReadBits(5, ignored)) +// AV1 "color_config" +static bool ReadVideoAV1ColorConfig(video::av1::BitReader& reader, VideoAV1SequenceSyntaxVK& syntax) { + uint32_t highBitdepth = 0; + uint32_t twelveBit = 0; + if (!reader.ReadBits(1, highBitdepth) || (syntax.seqProfile == 2 && highBitdepth && !reader.ReadBits(1, twelveBit))) return false; - bufferDelayLength++; - return true; + syntax.bitDepth = twelveBit ? 12 : (highBitdepth ? 10 : 8); + if (syntax.seqProfile != video::av1::PROFILE_HIGH && !reader.ReadBits(1, syntax.monochrome)) + return false; + + uint32_t colorDescriptionPresent = 0; + uint32_t colorPrimaries = 2; + uint32_t transferCharacteristics = 2; + uint32_t matrixCoefficients = 2; + if (!reader.ReadBits(1, colorDescriptionPresent)) + return false; + if (colorDescriptionPresent && (!reader.ReadBits(8, colorPrimaries) || !reader.ReadBits(8, transferCharacteristics) || !reader.ReadBits(8, matrixCoefficients))) + return false; + + uint32_t ignored = 0; + if (syntax.monochrome) { + syntax.subsamplingX = 1; + syntax.subsamplingY = 1; + return reader.ReadBits(1, ignored); // color_range + } + + if (colorPrimaries == 1 && transferCharacteristics == 13 && matrixCoefficients == 0) { + syntax.subsamplingX = 0; + syntax.subsamplingY = 0; + } else { + if (!reader.ReadBits(1, ignored)) // color_range + return false; + + if (syntax.seqProfile == 0) { + syntax.subsamplingX = 1; + syntax.subsamplingY = 1; + } else if (syntax.seqProfile == 1) { + syntax.subsamplingX = 0; + syntax.subsamplingY = 0; + } else if (syntax.bitDepth == 12) { + if (!reader.ReadBits(1, syntax.subsamplingX) || (syntax.subsamplingX && !reader.ReadBits(1, syntax.subsamplingY))) + return false; + } else { + syntax.subsamplingX = 1; + syntax.subsamplingY = 0; + } + + if (syntax.subsamplingX && syntax.subsamplingY && !reader.ReadBits(2, ignored)) // chroma_sample_position + return false; + } + + return reader.ReadBits(1, syntax.separateUvDeltaQ); } -static bool ApplyVideoEncodeAV1SequenceHeaderOverride(StdVideoAV1SequenceHeader& header, const uint8_t* data, size_t size) { - size_t cursor = 0; - while (cursor < size) { - video::av1::ObuSpan span = {}; - if (!video::av1::ReadObuHeader(data, size, cursor, span)) +// AV1 "sequence_header_obu" payload +static bool ReadVideoAV1SequenceSyntax(const uint8_t* payload, size_t payloadSize, VideoAV1SequenceSyntaxVK& syntax) { + syntax = {}; + + video::av1::BitReader reader{payload, payloadSize, 0}; + uint32_t ignored = 0; + if (!reader.ReadBits(3, syntax.seqProfile) || !reader.ReadBits(1, ignored) || !reader.ReadBits(1, syntax.reducedStillPictureHeader)) + return false; + + if (syntax.reducedStillPictureHeader) { + if (!reader.ReadBits(5, ignored)) return false; - if (span.type != video::av1::ObuType::SequenceHeader) - continue; - - video::av1::BitReader reader{data + span.payloadOffset, span.payloadSize, 0}; - uint32_t ignored = 0; - uint8_t reducedStillPictureHeader = 0; - uint8_t ignoredFlag = 0; - if (!reader.ReadBits(3, ignored) || !reader.ReadFlag(ignoredFlag) || !reader.ReadFlag(reducedStillPictureHeader)) + } else { + uint32_t timingInfoPresent = 0; + if (!reader.ReadBits(1, timingInfoPresent)) return false; - uint8_t decoderModelInfoPresent = 0; - uint8_t initialDisplayDelayPresent = 0; - uint32_t bufferDelayLength = 0; - if (reducedStillPictureHeader) { - if (!reader.ReadBits(5, ignored)) + if (timingInfoPresent) { + if (!reader.ReadBits(32, ignored) || !reader.ReadBits(32, ignored) || !reader.ReadBits(1, syntax.equalPictureInterval)) return false; - } else { - uint8_t timingInfoPresent = 0; - if (!reader.ReadFlag(timingInfoPresent)) + if (syntax.equalPictureInterval && !ReadVideoAV1Uvlc(reader)) + return false; + if (!reader.ReadBits(1, syntax.decoderModelInfoPresent)) + return false; + } + + uint32_t bufferDelayLengthMinus1 = 0; + if (syntax.decoderModelInfoPresent) { + if (!reader.ReadBits(5, bufferDelayLengthMinus1) || !reader.ReadBits(32, ignored) || !reader.ReadBits(5, syntax.bufferRemovalTimeLengthMinus1) || !reader.ReadBits(5, syntax.framePresentationTimeLengthMinus1)) + return false; + } else + syntax.equalPictureInterval = 0; // used only with the decoder model + + uint32_t initialDisplayDelayPresent = 0; + uint32_t operatingPointNumMinus1 = 0; + if (!reader.ReadBits(1, initialDisplayDelayPresent) || !reader.ReadBits(5, operatingPointNumMinus1)) + return false; + + for (uint32_t i = 0; i <= operatingPointNumMinus1; i++) { + uint32_t seqLevelIdx = 0; + if (!reader.ReadBits(12, ignored) || !reader.ReadBits(5, seqLevelIdx)) + return false; + if (seqLevelIdx > 7 && !reader.ReadBits(1, ignored)) return false; - if (timingInfoPresent) { - if (!SkipVideoAV1TimingInfo(reader) || !reader.ReadFlag(decoderModelInfoPresent)) + + uint32_t isPresent = 0; + if (syntax.decoderModelInfoPresent) { + if (!reader.ReadBits(1, isPresent)) return false; - if (decoderModelInfoPresent && !SkipVideoAV1DecoderModelInfo(reader, bufferDelayLength)) + if (isPresent && (!reader.ReadBits(bufferDelayLengthMinus1 + 1, ignored) || !reader.ReadBits(bufferDelayLengthMinus1 + 1, ignored) || !reader.ReadBits(1, ignored))) return false; } - if (!reader.ReadFlag(initialDisplayDelayPresent) || !reader.ReadBits(5, ignored)) - return false; - const uint32_t operatingPointNum = ignored + 1; - for (uint32_t i = 0; i < operatingPointNum; i++) { - uint32_t seqLevelIdx = 0; - if (!reader.ReadBits(12, ignored) || !reader.ReadBits(5, seqLevelIdx)) + if (initialDisplayDelayPresent) { + if (!reader.ReadBits(1, isPresent)) return false; - if (seqLevelIdx > 7 && !reader.ReadBits(1, ignored)) + if (isPresent && !reader.ReadBits(4, ignored)) return false; - if (decoderModelInfoPresent) { - uint8_t decoderModelPresentForThisOp = 0; - if (!reader.ReadFlag(decoderModelPresentForThisOp)) - return false; - if (decoderModelPresentForThisOp && (!reader.ReadBits(bufferDelayLength, ignored) || !reader.ReadBits(bufferDelayLength, ignored) || !reader.ReadBits(1, ignored))) - return false; - } - if (initialDisplayDelayPresent) { - uint8_t initialDisplayDelayPresentForThisOp = 0; - if (!reader.ReadFlag(initialDisplayDelayPresentForThisOp)) - return false; - if (initialDisplayDelayPresentForThisOp && !reader.ReadBits(4, ignored)) - return false; - } } } + } - uint32_t frameWidthBitsMinus1 = 0; - uint32_t frameHeightBitsMinus1 = 0; - uint32_t maxFrameWidthMinus1 = 0; - uint32_t maxFrameHeightMinus1 = 0; - if (!reader.ReadBits(4, frameWidthBitsMinus1) || !reader.ReadBits(4, frameHeightBitsMinus1) || !reader.ReadBits(frameWidthBitsMinus1 + 1, maxFrameWidthMinus1) || !reader.ReadBits(frameHeightBitsMinus1 + 1, maxFrameHeightMinus1)) - return false; + if (!reader.ReadBits(4, syntax.frameWidthBitsMinus1) || !reader.ReadBits(4, syntax.frameHeightBitsMinus1) + || !reader.ReadBits(syntax.frameWidthBitsMinus1 + 1, syntax.maxFrameWidthMinus1) || !reader.ReadBits(syntax.frameHeightBitsMinus1 + 1, syntax.maxFrameHeightMinus1)) + return false; - uint8_t frameIdNumbersPresent = 0; - if (!reducedStillPictureHeader && !reader.ReadFlag(frameIdNumbersPresent)) - return false; - if (frameIdNumbersPresent && (!reader.ReadBits(4, ignored) || !reader.ReadBits(3, ignored))) + if (!syntax.reducedStillPictureHeader && !reader.ReadBits(1, syntax.frameIdNumbersPresent)) + return false; + if (syntax.frameIdNumbersPresent && (!reader.ReadBits(4, syntax.deltaFrameIdLengthMinus2) || !reader.ReadBits(3, syntax.additionalFrameIdLengthMinus1))) + return false; + if (!reader.ReadBits(1, syntax.use128x128Superblock) || !reader.ReadBits(1, syntax.enableFilterIntra) || !reader.ReadBits(1, syntax.enableIntraEdgeFilter)) + return false; + + syntax.seqForceScreenContentTools = STD_VIDEO_AV1_SELECT_SCREEN_CONTENT_TOOLS; + syntax.seqForceIntegerMv = STD_VIDEO_AV1_SELECT_INTEGER_MV; + if (!syntax.reducedStillPictureHeader) { + if (!reader.ReadBits(1, syntax.enableInterintraCompound) || !reader.ReadBits(1, syntax.enableMaskedCompound) || !reader.ReadBits(1, syntax.enableWarpedMotion) + || !reader.ReadBits(1, syntax.enableDualFilter) || !reader.ReadBits(1, syntax.enableOrderHint)) return false; - if (!reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored)) + if (syntax.enableOrderHint && (!reader.ReadBits(1, syntax.enableJntComp) || !reader.ReadBits(1, syntax.enableRefFrameMvs))) return false; - uint32_t seqForceScreenContentTools = STD_VIDEO_AV1_SELECT_SCREEN_CONTENT_TOOLS; - uint32_t seqForceIntegerMv = STD_VIDEO_AV1_SELECT_INTEGER_MV; - if (!reducedStillPictureHeader) { - uint8_t enableOrderHint = 0; - if (!reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored) || !reader.ReadFlag(enableOrderHint)) - return false; - if (enableOrderHint && (!reader.ReadBits(1, ignored) || !reader.ReadBits(1, ignored))) - return false; + uint32_t seqChooseScreenContentTools = 0; + if (!reader.ReadBits(1, seqChooseScreenContentTools) || (!seqChooseScreenContentTools && !reader.ReadBits(1, syntax.seqForceScreenContentTools))) + return false; - uint8_t seqChooseScreenContentTools = 0; - if (!reader.ReadFlag(seqChooseScreenContentTools)) + if (syntax.seqForceScreenContentTools > 0) { + uint32_t seqChooseIntegerMv = 0; + if (!reader.ReadBits(1, seqChooseIntegerMv) || (!seqChooseIntegerMv && !reader.ReadBits(1, syntax.seqForceIntegerMv))) return false; - if (!seqChooseScreenContentTools && !reader.ReadBits(1, seqForceScreenContentTools)) - return false; - if (seqForceScreenContentTools > 0) { - uint8_t seqChooseIntegerMv = 0; - if (!reader.ReadFlag(seqChooseIntegerMv)) - return false; - if (!seqChooseIntegerMv && !reader.ReadBits(1, seqForceIntegerMv)) - return false; - } } - header.frame_width_bits_minus_1 = (uint8_t)frameWidthBitsMinus1; - header.frame_height_bits_minus_1 = (uint8_t)frameHeightBitsMinus1; - header.max_frame_width_minus_1 = (uint16_t)maxFrameWidthMinus1; - header.max_frame_height_minus_1 = (uint16_t)maxFrameHeightMinus1; - header.seq_force_screen_content_tools = (uint8_t)seqForceScreenContentTools; - header.seq_force_integer_mv = (uint8_t)seqForceIntegerMv; - return true; + if (syntax.enableOrderHint && !reader.ReadBits(3, syntax.orderHintBitsMinus1)) + return false; + } + + if (!reader.ReadBits(1, syntax.enableSuperres) || !reader.ReadBits(1, syntax.enableCdef) || !reader.ReadBits(1, syntax.enableRestoration)) + return false; + + return ReadVideoAV1ColorConfig(reader, syntax) && reader.ReadBits(1, syntax.filmGrainParamsPresent); +} + +static bool FindVideoAV1SequenceSyntax(const uint8_t* data, size_t size, VideoAV1SequenceSyntaxVK& syntax) { + size_t cursor = 0; + while (cursor < size) { + video::av1::ObuSpan span = {}; + if (!video::av1::ReadObuHeader(data, size, cursor, span) || span.payloadSize > (size - span.payloadOffset)) + return false; + + if (span.type == video::av1::ObuType::SequenceHeader) + return ReadVideoAV1SequenceSyntax(data + span.payloadOffset, (size_t)span.payloadSize, syntax); } return false; } +static bool ApplyVideoEncodeAV1SequenceHeaderOverride(StdVideoAV1SequenceHeader& header, const uint8_t* data, size_t size) { + VideoAV1SequenceSyntaxVK syntax = {}; + if (!FindVideoAV1SequenceSyntax(data, size, syntax)) + return false; + + header.frame_width_bits_minus_1 = (uint8_t)syntax.frameWidthBitsMinus1; + header.frame_height_bits_minus_1 = (uint8_t)syntax.frameHeightBitsMinus1; + header.max_frame_width_minus_1 = (uint16_t)syntax.maxFrameWidthMinus1; + header.max_frame_height_minus_1 = (uint16_t)syntax.maxFrameHeightMinus1; + header.seq_force_screen_content_tools = (uint8_t)syntax.seqForceScreenContentTools; + header.seq_force_integer_mv = (uint8_t)syntax.seqForceIntegerMv; + + return true; +} + +// The app writes the sequence header with "WriteVideoAV1ObuHeaders" from the same desc, so a driver override must not change what frame headers and decoding depend on +static bool IsVideoAV1SequenceHeaderOverridden(const VideoAV1SequenceDesc& desc, const uint8_t* data, size_t size) { + std::array written = {}; + video::bitstream::ByteWriter writer = {written.data(), written.size()}; + if (video::av1::WriteSequenceHeaderPayload(desc, writer) != Result::SUCCESS || writer.overflow) + return true; + + VideoAV1SequenceSyntaxVK expected = {}; + VideoAV1SequenceSyntaxVK overridden = {}; + if (!ReadVideoAV1SequenceSyntax(written.data(), (size_t)writer.writtenSize, expected) || !FindVideoAV1SequenceSyntax(data, size, overridden)) + return true; + + return std::memcmp(&expected, &overridden, sizeof(expected)) != 0; +} + VideoSessionParametersVK::~VideoSessionParametersVK() { const auto& vk = m_Device.GetDispatchTable(); if (m_Handle) vk.DestroyVideoSessionParametersKHR(m_Device, m_Handle, m_Device.GetVkAllocationCallbacks()); } +void VideoSessionParametersVK::GetH264ReferenceIndexDefaults(uint8_t pictureParameterSetId, uint8_t& l0DefaultActiveMinus1, uint8_t& l1DefaultActiveMinus1) const { + l0DefaultActiveMinus1 = 0; + l1DefaultActiveMinus1 = 0; + + for (const ReferenceIndexDefaults& defaults : m_ReferenceIndexDefaults) { + if (defaults.pictureParameterSetId == pictureParameterSetId) { + l0DefaultActiveMinus1 = defaults.l0DefaultActiveMinus1; + l1DefaultActiveMinus1 = defaults.l1DefaultActiveMinus1; + } + } +} + +void VideoSessionParametersVK::GetH265ReferenceIndexDefaults(uint8_t sequenceParameterSetId, uint8_t pictureParameterSetId, uint8_t& l0DefaultActiveMinus1, uint8_t& l1DefaultActiveMinus1) const { + l0DefaultActiveMinus1 = 0; + l1DefaultActiveMinus1 = 0; + + for (const ReferenceIndexDefaults& defaults : m_ReferenceIndexDefaults) { + if (defaults.sequenceParameterSetId == sequenceParameterSetId && defaults.pictureParameterSetId == pictureParameterSetId) { + l0DefaultActiveMinus1 = defaults.l0DefaultActiveMinus1; + l1DefaultActiveMinus1 = defaults.l1DefaultActiveMinus1; + } + } +} + NRI_INLINE Result VideoSessionParametersVK::CreateNative(VideoSessionVK& session, const void* pNext) { m_Session = &session; @@ -283,9 +437,12 @@ NRI_INLINE Result VideoSessionParametersVK::Create(const VideoSessionParametersD } Scratch h264Pps = NRI_ALLOCATE_SCRATCH(m_Device, StdVideoH264PictureParameterSet, h264Parameters.pictureParameterSetNum); + m_ReferenceIndexDefaults.resize(h264Parameters.pictureParameterSetNum); for (uint32_t i = 0; i < h264Parameters.pictureParameterSetNum; i++) { h264Pps[i] = GetVideoH264PictureParameterSet(h264Parameters.pictureParameterSets[i]); h264Pps[i].pScalingLists = &defaultScalingLists; + + m_ReferenceIndexDefaults[i] = {h264Pps[i].seq_parameter_set_id, h264Pps[i].pic_parameter_set_id, h264Pps[i].num_ref_idx_l0_default_active_minus1, h264Pps[i].num_ref_idx_l1_default_active_minus1}; } VkVideoDecodeH264SessionParametersAddInfoKHR decodeAddInfo = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H264_SESSION_PARAMETERS_ADD_INFO_KHR}; @@ -324,7 +481,7 @@ NRI_INLINE Result VideoSessionParametersVK::CreateH265(VideoSessionVK& session, defaultVps.profileTierLevel.generalProfileIdc = (uint8_t)((session.GetDesc().format == Format::P010_UNORM || session.GetDesc().format == Format::P016_UNORM) ? STD_VIDEO_H265_PROFILE_IDC_MAIN_10 : STD_VIDEO_H265_PROFILE_IDC_MAIN); - defaultVps.profileTierLevel.generalLevelIdc = (uint8_t)GetVideoH265LevelIdc(session.GetDesc().width, session.GetDesc().height); + defaultVps.profileTierLevel.generalLevelIdc = GetVideoH265DefaultGeneralLevelIdc(session.GetDesc().width, session.GetDesc().height); defaultVps.decPicBufMgr.maxDecPicBufferingMinus1[0] = (uint8_t)std::min(session.GetDesc().maxReferenceNum ? session.GetDesc().maxReferenceNum : 1u, 15u); defaultVps.decPicBufMgr.maxNumReorderPics[0] = session.GetDesc().maxReferenceNum > 1 ? 1 : 0; @@ -405,6 +562,7 @@ NRI_INLINE Result VideoSessionParametersVK::CreateH265(VideoSessionVK& session, firstShortTermRefPicSet += sps.numShortTermRefPicSets; } + m_ReferenceIndexDefaults.resize(parameters->pictureParameterSetNum); for (uint32_t i = 0; i < parameters->pictureParameterSetNum; i++) { const VideoH265PictureParameterSetDesc& pps = parameters->pictureParameterSets[i]; const StdVideoH265ScalingLists* scalingLists = nullptr; @@ -413,6 +571,8 @@ NRI_INLINE Result VideoSessionParametersVK::CreateH265(VideoSessionVK& session, scalingLists = &ppsScalingLists[i]; } pictureParameterSets[i] = GetVideoH265PictureParameterSet(pps, scalingLists); + + m_ReferenceIndexDefaults[i] = {pps.sequenceParameterSetId, pps.pictureParameterSetId, pps.refIndexL0DefaultActiveMinus1, pps.refIndexL1DefaultActiveMinus1}; } VkVideoDecodeH265SessionParametersAddInfoKHR decodeAddInfo = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H265_SESSION_PARAMETERS_ADD_INFO_KHR}; @@ -491,7 +651,6 @@ NRI_INLINE Result VideoSessionParametersVK::CreateAV1(VideoSessionVK& session, c } if (session.GetDesc().type == VideoSessionType::ENCODE) { - m_AV1SequenceHeader.seq_force_screen_content_tools = 0; m_AV1OperatingPoint.decoder_buffer_delay = 1; m_AV1OperatingPoint.encoder_buffer_delay = 2; } @@ -530,7 +689,21 @@ NRI_INLINE Result VideoSessionParametersVK::CreateAV1(VideoSessionVK& session, c Scratch data = NRI_ALLOCATE_SCRATCH(m_Device, uint8_t, dataSize); vkResult = vk.GetEncodedVideoSessionParametersKHR(m_Device, &getInfo, &feedbackInfo, &dataSize, data); - if (vkResult != VK_SUCCESS || !feedbackInfo.hasOverrides || !ApplyVideoEncodeAV1SequenceHeaderOverride(m_AV1SequenceHeader, data, dataSize)) + if (vkResult != VK_SUCCESS || !feedbackInfo.hasOverrides) + return Result::SUCCESS; + + // The app emits the sequence header with "WriteVideoAV1ObuHeaders" from the same desc, which can't reproduce driver overrides + if (parameters) { + if (IsVideoAV1SequenceHeaderOverridden(parameters->sequence, data, dataSize)) { + NRI_REPORT_ERROR(&m_Device, "Vulkan AV1 encode driver overrides the sequence header, which 'WriteVideoAV1ObuHeaders' can't reproduce"); + + return Result::UNSUPPORTED; + } + + return Result::SUCCESS; + } + + if (!ApplyVideoEncodeAV1SequenceHeaderOverride(m_AV1SequenceHeader, data, dataSize)) return Result::SUCCESS; vk.DestroyVideoSessionParametersKHR(m_Device, m_Handle, m_Device.GetVkAllocationCallbacks()); diff --git a/Source/VK/VideoSessionVK.h b/Source/VK/VideoSessionVK.h index f648df2e..046b131a 100644 --- a/Source/VK/VideoSessionVK.h +++ b/Source/VK/VideoSessionVK.h @@ -116,6 +116,14 @@ struct VideoSessionVK final : public DebugNameBase { m_ResetRecorded = true; } + inline const VideoEncodeRateControlDesc& GetRateControl() const { + return m_RateControl; + } + + inline void SetRateControl(const VideoEncodeRateControlDesc& rateControlDesc) { + m_RateControl = rateControlDesc; + } + inline VkQueryPool GetEncodeFeedbackQueryPool() const { return m_EncodeFeedbackQueryPool; } @@ -164,6 +172,7 @@ struct VideoSessionVK final : public DebugNameBase { std::array m_EncodeFeedbackPayloadReadbacks = {}; Vector m_Memory; VideoSessionDesc m_Desc = {}; + VideoEncodeRateControlDesc m_RateControl = {}; // recorded rate control state, valid if "m_ResetRecorded" is true uint32_t m_BitstreamOffsetAlignment = 1; uint32_t m_BitstreamSizeAlignment = 1; uint32_t m_RateControlModes = 0; diff --git a/Source/VK/VideoSessionVK.hpp b/Source/VK/VideoSessionVK.hpp index 1889cc89..dfbe2057 100644 --- a/Source/VK/VideoSessionVK.hpp +++ b/Source/VK/VideoSessionVK.hpp @@ -136,17 +136,15 @@ static inline VkVideoComponentBitDepthFlagsKHR GetVideoBitDepth(Format format) { return (format == Format::P010_UNORM || format == Format::P016_UNORM) ? VK_VIDEO_COMPONENT_BIT_DEPTH_10_BIT_KHR : VK_VIDEO_COMPONENT_BIT_DEPTH_8_BIT_KHR; } -static Result IsVideoFormatSupported(DeviceVK& device, const VideoSessionDesc& videoSessionDesc, const VkVideoProfileInfoKHR& profile, bool& isSupported) { +static Result IsVideoFormatSupported(DeviceVK& device, const VideoSessionDesc& videoSessionDesc, const VkVideoProfileInfoKHR& profile, VkImageUsageFlags videoUsage, bool& isSupported) { isSupported = false; VkVideoProfileListInfoKHR profileList = {VK_STRUCTURE_TYPE_VIDEO_PROFILE_LIST_INFO_KHR}; profileList.profileCount = 1; profileList.pProfiles = &profile; + // Matches "GetImageUsageFlags" constexpr VkImageUsageFlags transferUsage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - const VkImageUsageFlags videoUsage = videoSessionDesc.type == VideoSessionType::DECODE - ? VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR | VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR - : VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR | VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR; VkPhysicalDeviceVideoFormatInfoKHR formatInfo = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_FORMAT_INFO_KHR}; formatInfo.pNext = &profileList; @@ -155,6 +153,9 @@ static Result IsVideoFormatSupported(DeviceVK& device, const VideoSessionDesc& v const auto& vk = device.GetDispatchTable(); uint32_t formatNum = 0; VkResult vkResult = vk.GetPhysicalDeviceVideoFormatPropertiesKHR(device, &formatInfo, &formatNum, nullptr); + + if (vkResult == VK_ERROR_IMAGE_USAGE_NOT_SUPPORTED_KHR || vkResult == VK_ERROR_FORMAT_NOT_SUPPORTED) + return Result::SUCCESS; // the usage combination is not supported NRI_RETURN_ON_BAD_VKRESULT(&device, vkResult, "vkGetPhysicalDeviceVideoFormatPropertiesKHR"); if (!formatNum) @@ -269,17 +270,41 @@ static Result GetVideoCapabilities(DeviceVK& deviceVK, const VideoSessionDesc& v VkResult vkResult = vk.GetPhysicalDeviceVideoCapabilitiesKHR(deviceVK, &profile, &capabilities); NRI_RETURN_ON_BAD_VKRESULT(&deviceVK, vkResult, "vkGetPhysicalDeviceVideoCapabilitiesKHR"); - bool isVideoFormatSupported = false; - Result result = IsVideoFormatSupported(deviceVK, videoSessionDesc, profile, isVideoFormatSupported); + // Output/input ("VIDEO_OUTPUT_ONLY") and DPB ("VIDEO_REFERENCE_ONLY") textures are checked separately, the combined usage ("VIDEO_DECODE" or "VIDEO_ENCODE" alone) too. + // Decode: coincide mode needs the combined usage, distinct mode the separate ones. Encode: either is enough + const bool isDecode = videoSessionDesc.type == VideoSessionType::DECODE; + const VkImageUsageFlags outputUsage = isDecode ? VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR : VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR; + const VkImageUsageFlags dpbUsage = isDecode ? VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR : VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR; + + bool isOutputSupported = false; + Result result = IsVideoFormatSupported(deviceVK, videoSessionDesc, profile, outputUsage, isOutputSupported); if (result != Result::SUCCESS) return result; - if (!isVideoFormatSupported) + + bool isDpbSupported = false; + result = IsVideoFormatSupported(deviceVK, videoSessionDesc, profile, dpbUsage, isDpbSupported); + if (result != Result::SUCCESS) + return result; + + bool isOutputAndDpbSupported = false; + if (!isDecode || (decodeCapabilities.flags & VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_COINCIDE_BIT_KHR)) { + result = IsVideoFormatSupported(deviceVK, videoSessionDesc, profile, outputUsage | dpbUsage, isOutputAndDpbSupported); + if (result != Result::SUCCESS) + return result; + } + + const bool isSeparateSupported = isOutputSupported && isDpbSupported; + if (!isDecode && !isOutputAndDpbSupported && !isSeparateSupported) return Result::UNSUPPORTED; FillVideoCapabilities(videoCapabilities, videoSessionDesc, capabilities); - if (videoSessionDesc.type == VideoSessionType::DECODE) { - videoCapabilities.decodeDpbAndOutputCoincide = (decodeCapabilities.flags & VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_COINCIDE_BIT_KHR) != 0; - videoCapabilities.decodeDpbAndOutputDistinct = (decodeCapabilities.flags & VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR) != 0; + + if (isDecode) { + videoCapabilities.decodeDpbAndOutputCoincide = isOutputAndDpbSupported; + videoCapabilities.decodeDpbAndOutputDistinct = isSeparateSupported && (decodeCapabilities.flags & VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR) != 0; + + if (!videoCapabilities.decodeDpbAndOutputCoincide && !videoCapabilities.decodeDpbAndOutputDistinct) + return Result::UNSUPPORTED; } else if ((encodeCapabilities.supportedEncodeFeedbackFlags & VIDEO_ENCODE_REQUIRED_FEEDBACK_FLAGS) == VIDEO_ENCODE_REQUIRED_FEEDBACK_FLAGS) { videoCapabilities.resolvedMetadataOffsetAlignment = 8; videoCapabilities.resolvedMetadataSize = sizeof(VideoEncodeFeedback) + sizeof(uint64_t) * 3 + sizeof(uint32_t); @@ -407,6 +432,8 @@ NRI_INLINE Result VideoSessionVK::GetEncodeFeedback(BufferVK& resolvedMetadataRe constexpr uint64_t queryPayloadSize = sizeof(uint64_t) * 3 + sizeof(uint32_t); const uint64_t queryPayloadOffset = resolvedMetadataOffset + sizeof(VideoEncodeFeedback); + NRI_CHECK(resolvedMetadataReadback.GetMappedMemory(), "'resolvedMetadataReadback' must be CPU-visible"); + const uint8_t* queryPayload = (const uint8_t*)resolvedMetadataReadback.Map(queryPayloadOffset, queryPayloadSize); if (!queryPayload) return Result::FAILURE; From af45e722d94b57fd8a3308da2d7c435cab1b4abd Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:56:24 +0200 Subject: [PATCH 05/20] D3D12: fix video decode/encode defects - legacy barriers: per-layer/mip barriers on planar formats (NV12/P010/P016) transition every plane (debug layer id 538) - decode: advertise D3D12_VIDEO_DECODE_MIN_BITSTREAM_OFFSET_ALIGNMENT (debug layer id 1110) - AV1 decode: pass interp_filter and tx_mode through, filter_intra from the sequence, order_hint_bits 0 without order hints, warped_motion from the frame flag, derive tile sizes for uniform layouts without size arrays (null dereference) - AV1 encode: key frames always refresh 0xFF; set driver-required picture control flags (frame segmentation auto, force integer MV); pass explicit interpolation filter / CDEF damping values through - AV1 metadata-only decode info: frame type, order hint, refresh flags, frame id and interpolation filter from the submitted picture desc; bitstreamOffset relative to encodedBitstreamOffset - rate control: enable QP range, initial QP, max frame size and VBV flags when values are supplied and supported by the encoder - H.264 decode: UsedForReferenceFlags = 3 for frame references - H.265 decode: sort StCurrBefore/StCurrAfter by POC; spec default scaling lists when enabled without list data - H.265 encode: PPS id from h265PictureDesc - encode feedback: don't read unmapped buffers; null-check descs - barriers: PlaneBits::COLOR on multi-planar formats covers all planes Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/D3D12/BufferD3D12.h | 4 + Source/D3D12/CommandBufferD3D12.hpp | 163 +++++++++++++++++++++------- Source/D3D12/ImplD3D12.cpp | 4 +- Source/D3D12/VideoHelpersD3D12.h | 59 +++++++++- Source/D3D12/VideoSessionD3D12.h | 10 ++ Source/D3D12/VideoSessionD3D12.hpp | 66 +++++++---- 7 files changed, 238 insertions(+), 70 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index d7cd4b1d..2320b56d 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -900,7 +900,7 @@ NriStruct(VideoAV1EncodeDecodeInfoDesc) { const NriPtr(VideoAV1SequenceDesc) sequence; NriOptional const uint8_t* encodedPayloadHeader; // first bytes of the encoded payload; returned bitstream ranges are bounded by "feedback" uint64_t encodedPayloadHeaderSize; - NriOptional const NriPtr(VideoAV1ReferenceDesc) references; // previous AV1 DPB snapshot; required for inter frames + NriOptional const NriPtr(VideoAV1ReferenceDesc) references; // previous AV1 DPB snapshot; required for inter frames, without it the frame is a key frame (as encoded with "FORCE_KEY_FRAME") NriOptional uint32_t referenceNum; NriOptional const NriPtr(VideoEncodePictureDesc) pictureDesc; // submitted picture description; required if "encodedPayloadHeader" is not provided NriOptional const NriPtr(VideoAV1EncodePictureDesc) av1PictureDesc; // submitted AV1 picture description; required if "encodedPayloadHeader" is not provided diff --git a/Source/D3D12/BufferD3D12.h b/Source/D3D12/BufferD3D12.h index b0e38c7e..1917b609 100644 --- a/Source/D3D12/BufferD3D12.h +++ b/Source/D3D12/BufferD3D12.h @@ -34,6 +34,10 @@ struct BufferD3D12 final : public DebugNameBase { return m_Device; } + inline bool IsMapped() const { + return m_MappedMemory != nullptr; + } + Result Create(const BufferDesc& bufferDesc); Result Create(const BufferD3D12Desc& bufferD3D12Desc); Result Allocate(MemoryLocation memoryLocation, float priority, bool committed); diff --git a/Source/D3D12/CommandBufferD3D12.hpp b/Source/D3D12/CommandBufferD3D12.hpp index 0f2c0f01..dce30c9f 100644 --- a/Source/D3D12/CommandBufferD3D12.hpp +++ b/Source/D3D12/CommandBufferD3D12.hpp @@ -440,6 +440,14 @@ static inline bool HasVideoBufferUsage(BufferUsageBits usage) { return usage & (BufferUsageBits::VIDEO_DECODE | BufferUsageBits::VIDEO_ENCODE); } +static inline uint32_t GetLegacyBarrierPlaneNum(Format format, PlaneBits planes) { + // Multi-planar YUV: "ALL", "COLOR" or "PLANE_0 | PLANE_1" requires a transition per plane subresource + const bool isMultiPlanar = format == Format::NV12_UNORM || format == Format::P010_UNORM || format == Format::P016_UNORM; + const bool isAllPlanes = planes == PlaneBits::ALL || (planes & PlaneBits::COLOR) || ((planes & PlaneBits::PLANE_0) && (planes & PlaneBits::PLANE_1)); + + return (isMultiPlanar && isAllPlanes) ? 2 : 1; +} + static inline void ConvertRects(const Rect* in, uint32_t rectNum, D3D12_RECT* out) { for (uint32_t i = 0; i < rectNum; i++) { out[i].left = in[i].x; @@ -523,6 +531,27 @@ static inline uint8_t GetVideoDecodeAV1FrameType(VideoFrameType frameType) { return (frameType == VideoFrameType::IDR || frameType == VideoFrameType::I) ? 0 : 1; } +static inline void FillVideoDecodeAV1TileSizes(uint32_t miNum, uint32_t sbShift, uint32_t tileNum, const uint16_t* sizesInSuperblocksMinus1, const uint16_t* miStarts, USHORT* sizes) { + if (sizesInSuperblocksMinus1) { + for (uint32_t i = 0; i < tileNum; i++) + sizes[i] = (USHORT)(sizesInSuperblocksMinus1[i] + 1); + } else if (miStarts) { + for (uint32_t i = 0; i < tileNum; i++) + sizes[i] = (USHORT)((miStarts[i + 1] - miStarts[i] + (1u << sbShift) - 1) >> sbShift); + } else { + // Uniform spacing (AV1 "tile_info"): "tileLog2 = tile_log2(1, tileNum)", all tiles but the last one have the same size + const uint32_t sbNum = (miNum + (1u << sbShift) - 1) >> sbShift; + + const uint32_t tileLog2 = video::av1::TileLog2(1, tileNum); + const uint32_t tileSizeInSuperblocks = (sbNum + (1u << tileLog2) - 1) >> tileLog2; + + for (uint32_t i = 0; i < tileNum; i++) { + const uint32_t start = i * tileSizeInSuperblocks; + sizes[i] = (USHORT)(start < sbNum ? std::min(tileSizeInSuperblocks, sbNum - start) : 0); + } + } +} + static inline bool GetVideoDecodeReferenceSlotCount(const VideoReference* references, uint32_t referenceNum, uint32_t& slotCount) { slotCount = 0; for (uint32_t i = 0; i < referenceNum; i++) { @@ -608,6 +637,9 @@ static bool BuildVideoDecodeH264Arguments(const VideoH264SessionParametersDesc& pictureParameters.FieldOrderCntList[i][0] = reference.topFieldOrderCount; pictureParameters.FieldOrderCntList[i][1] = reference.bottomFieldOrderCount; pictureParameters.FrameNumList[i] = (USHORT)reference.frameNum; + + if ((reference.flags & (VideoH264DecodeReferenceBits::TOP_FIELD | VideoH264DecodeReferenceBits::BOTTOM_FIELD)) == 0) // frame reference + pictureParameters.UsedForReferenceFlags |= 3u << (i * 2); if (reference.flags & VideoH264DecodeReferenceBits::TOP_FIELD) pictureParameters.UsedForReferenceFlags |= 1u << (i * 2); if (reference.flags & VideoH264DecodeReferenceBits::BOTTOM_FIELD) @@ -657,7 +689,15 @@ static bool BuildVideoDecodeH264Arguments(const VideoH264SessionParametersDesc& return true; } -static inline void FillVideoH265ScalingLists(DXVA_Qmatrix_HEVC& matrix, const VideoH265ScalingListsDesc* scalingLists) { +static inline void FillVideoH265ScalingLists(DXVA_Qmatrix_HEVC& matrix, const VideoH265ScalingListsDesc* scalingLists, bool isScalingListEnabled) { + // H.265 Table 7-6: default 8x8 (and up-sampled 16x16, 32x32) lists in coded (up-right diagonal) order + constexpr uint8_t defaultIntra[64] = { + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20, 21, 20, 19, 21, 24, 22, 22, 24, + 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115}; + constexpr uint8_t defaultInter[64] = { + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20, 20, 20, 20, 20, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91}; + matrix = {}; if (scalingLists) { std::memcpy(matrix.ucScalingLists0, scalingLists->scalingList4x4, sizeof(matrix.ucScalingLists0)); @@ -676,6 +716,18 @@ static inline void FillVideoH265ScalingLists(DXVA_Qmatrix_HEVC& matrix, const Vi std::memset(matrix.ucScalingLists3, 16, sizeof(matrix.ucScalingLists3)); std::memset(matrix.ucScalingListDCCoefSizeID2, 16, sizeof(matrix.ucScalingListDCCoefSizeID2)); std::memset(matrix.ucScalingListDCCoefSizeID3, 16, sizeof(matrix.ucScalingListDCCoefSizeID3)); + + // "scaling_list_enabled_flag" without explicit lists: spec default lists (matrixId 0-2 intra, 3-5 inter) + if (isScalingListEnabled) { + for (uint32_t i = 0; i < 6; i++) { + const uint8_t* defaultList = i < 3 ? defaultIntra : defaultInter; + std::memcpy(matrix.ucScalingLists1[i], defaultList, sizeof(matrix.ucScalingLists1[i])); + std::memcpy(matrix.ucScalingLists2[i], defaultList, sizeof(matrix.ucScalingLists2[i])); + } + + std::memcpy(matrix.ucScalingLists3[0], defaultIntra, sizeof(matrix.ucScalingLists3[0])); + std::memcpy(matrix.ucScalingLists3[1], defaultInter, sizeof(matrix.ucScalingLists3[1])); + } } static bool BuildVideoDecodeH265Arguments(const VideoH265SessionParametersDesc& parameters, const VideoH265DecodePictureDesc& pictureDesc, uint64_t bitstreamSize, @@ -809,7 +861,12 @@ static bool BuildVideoDecodeH265Arguments(const VideoH265SessionParametersDesc& return false; } - FillVideoH265ScalingLists(inverseQuantizationMatrix, pps->scalingLists ? pps->scalingLists : sps->scalingLists); + // "RefPicSetStCurrBefore" in descending and "RefPicSetStCurrAfter" in ascending POC order (H.265 8.3.2) + const INT* poc = pictureParameters.PicOrderCntValList; + std::sort(pictureParameters.RefPicSetStCurrBefore, pictureParameters.RefPicSetStCurrBefore + beforeNum, [poc](UCHAR a, UCHAR b) { return poc[a] > poc[b]; }); + std::sort(pictureParameters.RefPicSetStCurrAfter, pictureParameters.RefPicSetStCurrAfter + afterNum, [poc](UCHAR a, UCHAR b) { return poc[a] < poc[b]; }); + + FillVideoH265ScalingLists(inverseQuantizationMatrix, pps->scalingLists ? pps->scalingLists : sps->scalingLists, pictureParameters.scaling_list_enabled_flag); for (uint32_t i = 0; i < sliceNum; i++) { const uint32_t offset = pictureDesc.sliceSegmentOffsets[i]; @@ -830,6 +887,30 @@ static bool BuildVideoDecodeH265Arguments(const VideoH265SessionParametersDesc& } #if NRI_ENABLE_AGILITY_SDK_SUPPORT +// Also used to rebuild the frame header from metadata ("GetVideoAV1EncodeDecodeInfo") +static inline D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAGS GetVideoEncodeAV1PictureControlFlags(VideoAV1PictureBits pictureFlags, uint32_t featureFlags, uint32_t requiredFeatureFlags) { + D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAGS flags = D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_NONE; + + if (pictureFlags & VideoAV1PictureBits::ERROR_RESILIENT_MODE) + flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_ENABLE_ERROR_RESILIENT_MODE; + + if (((featureFlags & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_FORCED_INTEGER_MOTION_VECTORS) && (pictureFlags & VideoAV1PictureBits::FORCE_INTEGER_MV)) || (requiredFeatureFlags & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_FORCED_INTEGER_MOTION_VECTORS)) + flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_FORCE_INTEGER_MOTION_VECTORS; + + if (((featureFlags & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_AUTO_SEGMENTATION) && (pictureFlags & VideoAV1PictureBits::SEGMENTATION_ENABLED)) || (requiredFeatureFlags & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_AUTO_SEGMENTATION)) + flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_ENABLE_FRAME_SEGMENTATION_AUTO; + + return flags; +} + +// "txMode = 0" selects the default +static inline uint8_t GetVideoEncodeAV1TxMode(const VideoAV1EncodePictureDesc* av1PictureDesc, VideoFrameType frameType) { + if (av1PictureDesc && av1PictureDesc->txMode) + return av1PictureDesc->txMode; + + return frameType == VideoFrameType::P ? video::av1::TX_MODE_SELECT : video::av1::TX_MODE_LARGEST; +} + static inline D3D12_VIDEO_ENCODER_AV1_FRAME_TYPE GetVideoEncodeAV1FrameType(VideoFrameType frameType) { switch (frameType) { case VideoFrameType::IDR: @@ -1054,24 +1135,23 @@ NRI_INLINE void CommandBufferD3D12::DecodeVideo(const VideoDecodeDesc& videoDeco av1PictureParameters.superres_denom = desc.superresDenom ? desc.superresDenom : 8; av1PictureParameters.bitdepth = sequence.bitDepth; av1PictureParameters.seq_profile = sequence.seqProfile; - av1PictureParameters.tiles.cols = 1; - av1PictureParameters.tiles.rows = 1; - av1PictureParameters.tiles.widths[0] = (USHORT)((sessionDesc.width + 63) / 64); - av1PictureParameters.tiles.heights[0] = (USHORT)((sessionDesc.height + 63) / 64); - if (desc.tileLayout) { - av1PictureParameters.tiles.cols = desc.tileLayout->columnNum; - av1PictureParameters.tiles.rows = desc.tileLayout->rowNum; - av1PictureParameters.tiles.context_update_id = desc.tileLayout->contextUpdateTileId; - for (uint32_t i = 0; i < desc.tileLayout->columnNum; i++) - av1PictureParameters.tiles.widths[i] = desc.tileLayout->widthInSuperblocksMinus1[i] + 1; - for (uint32_t i = 0; i < desc.tileLayout->rowNum; i++) - av1PictureParameters.tiles.heights[i] = desc.tileLayout->heightInSuperblocksMinus1[i] + 1; - } + + const uint32_t miCols = 2 * ((sessionDesc.width + 7) >> 3); + const uint32_t miRows = 2 * ((sessionDesc.height + 7) >> 3); + const uint32_t sbShift = (sequence.flags & VideoAV1SequenceBits::USE_128X128_SUPERBLOCK) ? 5 : 4; + const VideoAV1TileLayoutDesc singleTileLayout = {1, 1}; + const VideoAV1TileLayoutDesc& tileLayout = desc.tileLayout ? *desc.tileLayout : singleTileLayout; + av1PictureParameters.tiles.cols = tileLayout.columnNum; + av1PictureParameters.tiles.rows = tileLayout.rowNum; + av1PictureParameters.tiles.context_update_id = tileLayout.contextUpdateTileId; + FillVideoDecodeAV1TileSizes(miCols, sbShift, tileLayout.columnNum, tileLayout.widthInSuperblocksMinus1, tileLayout.miColumnStarts, av1PictureParameters.tiles.widths); + FillVideoDecodeAV1TileSizes(miRows, sbShift, tileLayout.rowNum, tileLayout.heightInSuperblocksMinus1, tileLayout.miRowStarts, av1PictureParameters.tiles.heights); av1PictureParameters.coding.use_128x128_superblock = !!(sequence.flags & VideoAV1SequenceBits::USE_128X128_SUPERBLOCK); + av1PictureParameters.coding.filter_intra = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_FILTER_INTRA); av1PictureParameters.coding.intra_edge_filter = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_INTRA_EDGE_FILTER); av1PictureParameters.coding.interintra_compound = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_INTERINTRA_COMPOUND); av1PictureParameters.coding.masked_compound = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_MASKED_COMPOUND); - av1PictureParameters.coding.warped_motion = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_WARPED_MOTION); + av1PictureParameters.coding.warped_motion = !!(pictureFlags & VideoAV1PictureBits::ALLOW_WARPED_MOTION); av1PictureParameters.coding.dual_filter = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_DUAL_FILTER); av1PictureParameters.coding.jnt_comp = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_JNT_COMP); av1PictureParameters.coding.enable_ref_frame_mvs = !!(sequence.flags & VideoAV1SequenceBits::ENABLE_REF_FRAME_MVS); @@ -1089,7 +1169,7 @@ NRI_INLINE void CommandBufferD3D12::DecodeVideo(const VideoDecodeDesc& videoDeco av1PictureParameters.coding.skip_mode = !!(pictureFlags & VideoAV1PictureBits::SKIP_MODE_PRESENT); av1PictureParameters.coding.reduced_tx_set = !!(pictureFlags & VideoAV1PictureBits::REDUCED_TX_SET); av1PictureParameters.coding.superres = !!(pictureFlags & VideoAV1PictureBits::USE_SUPERRES); - av1PictureParameters.coding.tx_mode = desc.txMode ? desc.txMode : 2; + av1PictureParameters.coding.tx_mode = desc.txMode; av1PictureParameters.coding.use_ref_frame_mvs = !!(pictureFlags & VideoAV1PictureBits::USE_REF_FRAME_MVS); av1PictureParameters.coding.reference_frame_update = desc.refreshFrameFlags != 0; av1PictureParameters.format.frame_type = GetVideoDecodeAV1FrameType(desc.frameType); @@ -1100,7 +1180,7 @@ NRI_INLINE void CommandBufferD3D12::DecodeVideo(const VideoDecodeDesc& videoDeco av1PictureParameters.format.mono_chrome = !!(sequence.flags & VideoAV1SequenceBits::MONO_CHROME); av1PictureParameters.primary_ref_frame = (UCHAR)video::av1::GetReferenceNameIndex(desc.primaryReferenceName); av1PictureParameters.order_hint = desc.orderHint; - av1PictureParameters.order_hint_bits = (UCHAR)(sequence.orderHintBitsMinus1 + 1); + av1PictureParameters.order_hint_bits = (sequence.flags & VideoAV1SequenceBits::ENABLE_ORDER_HINT) ? (UCHAR)(sequence.orderHintBitsMinus1 + 1) : 0; std::memset(av1PictureParameters.RefFrameMapTextureIndex, 0xFF, sizeof(av1PictureParameters.RefFrameMapTextureIndex)); for (uint32_t i = 0; i < video::av1::REFERENCE_NAME_NUM; i++) av1PictureParameters.frame_refs[i].Index = 0xFF; @@ -1147,7 +1227,7 @@ NRI_INLINE void CommandBufferD3D12::DecodeVideo(const VideoDecodeDesc& videoDeco av1PictureParameters.cdef.uv_strengths[i].secondary = desc.cdef->uvSecondaryStrength[i]; } } - av1PictureParameters.interp_filter = desc.interpolationFilter ? desc.interpolationFilter : 4; + av1PictureParameters.interp_filter = desc.interpolationFilter; av1PictureParameters.loop_filter.delta_lf_present = !!(pictureFlags & VideoAV1PictureBits::DELTA_LF_PRESENT); av1PictureParameters.loop_filter.delta_lf_multi = !!(pictureFlags & VideoAV1PictureBits::DELTA_LF_MULTI); av1PictureParameters.loop_filter.delta_lf_res = desc.deltaLfRes; @@ -1339,7 +1419,7 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco } } - const VideoEncodeRateControlDesc defaultRateControl = {VideoEncodeRateControlMode::CQP, 26, 28, 30, 0, 51, 30, 1, 0, 0, 0, 0, 0}; + const VideoEncodeRateControlDesc& defaultRateControl = VIDEO_ENCODE_DEFAULT_RATE_CONTROL; const VideoEncodeRateControlDesc& rateControlDesc = videoEncodeDesc.rateControlDesc ? *videoEncodeDesc.rateControlDesc : defaultRateControl; if ((session.GetRateControlModes() & video::GetEncodeRateControlModeMask(rateControlDesc.mode)) == 0) { NRI_REPORT_ERROR(&m_Device, "Unsupported D3D12 video encode rate control mode"); @@ -1347,7 +1427,7 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco } VideoEncodeRateControlStateD3D12 rateControlState; - FillVideoEncodeRateControl(rateControlDesc, rateControlState); + FillVideoEncodeRateControl(rateControlDesc, GetVideoEncodeCodec(sessionDesc.codec), (D3D12_VIDEO_ENCODER_SUPPORT_FLAGS)session.GetEncodeSupportFlags(rateControlDesc.mode), rateControlState); D3D12_VIDEO_ENCODER_SEQUENCE_GOP_STRUCTURE_H264 h264Gop = {}; h264Gop.GOPLength = sessionDesc.maxReferenceNum ? 60 : 1; @@ -1493,7 +1573,7 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco hevcReferenceDescriptors[i].TemporalLayerIndex = referenceDesc ? referenceDesc->temporalLayer : 0; } - hevcPicture.slice_pic_parameter_set_id = 0; + hevcPicture.slice_pic_parameter_set_id = videoEncodeDesc.h265PictureDesc ? videoEncodeDesc.h265PictureDesc->pictureParameterSetId : 0; hevcPicture.PictureOrderCountNumber = (UINT)pictureDesc.pictureOrderCount; hevcPicture.TemporalLayerIndex = pictureDesc.temporalLayer; hevcPicture.List0ReferenceFramesCount = hevcReferenceLists.list0Num; @@ -1519,30 +1599,23 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco const VideoAV1PictureBits pictureFlags = (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->flags != VideoAV1PictureBits::NONE) ? videoEncodeDesc.av1PictureDesc->flags : video::av1::GetDefaultPictureFlags(); - if (pictureFlags & VideoAV1PictureBits::ERROR_RESILIENT_MODE) - av1Picture.Flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_ENABLE_ERROR_RESILIENT_MODE; if (session.GetAV1FeatureFlags() & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_LOOP_RESTORATION_FILTER) { for (auto& type : av1Picture.FrameRestorationConfig.FrameRestorationType) type = D3D12_VIDEO_ENCODER_AV1_RESTORATION_TYPE_DISABLED; for (auto& tileSize : av1Picture.FrameRestorationConfig.LoopRestorationPixelSize) tileSize = D3D12_VIDEO_ENCODER_AV1_RESTORATION_TILESIZE_DISABLED; } - if ((session.GetAV1FeatureFlags() & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_FORCED_INTEGER_MOTION_VECTORS) && (pictureFlags & VideoAV1PictureBits::FORCE_INTEGER_MV)) - av1Picture.Flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_FORCE_INTEGER_MOTION_VECTORS; if (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->segmentation) { NRI_REPORT_ERROR(&m_Device, "D3D12 AV1 encode does not support explicit segmentation"); return; } - if ((session.GetAV1FeatureFlags() & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_AUTO_SEGMENTATION) && (pictureFlags & VideoAV1PictureBits::SEGMENTATION_ENABLED)) - av1Picture.Flags |= D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_ENABLE_FRAME_SEGMENTATION_AUTO; + av1Picture.Flags |= GetVideoEncodeAV1PictureControlFlags(pictureFlags, session.GetAV1FeatureFlags(), session.GetAV1RequiredFeatureFlags()); av1Picture.FrameType = frameType; av1Picture.CompoundPredictionType = D3D12_VIDEO_ENCODER_AV1_COMP_PREDICTION_TYPE_SINGLE_REFERENCE; - av1Picture.InterpolationFilter = (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->interpolationFilter) + av1Picture.InterpolationFilter = videoEncodeDesc.av1PictureDesc ? (D3D12_VIDEO_ENCODER_AV1_INTERPOLATION_FILTERS)videoEncodeDesc.av1PictureDesc->interpolationFilter : D3D12_VIDEO_ENCODER_AV1_INTERPOLATION_FILTERS_SWITCHABLE; - av1Picture.TxMode = (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->txMode) - ? (D3D12_VIDEO_ENCODER_AV1_TX_MODE)videoEncodeDesc.av1PictureDesc->txMode - : (pictureDesc.frameType == VideoFrameType::P ? D3D12_VIDEO_ENCODER_AV1_TX_MODE_SELECT : D3D12_VIDEO_ENCODER_AV1_TX_MODE_LARGEST); + av1Picture.TxMode = (D3D12_VIDEO_ENCODER_AV1_TX_MODE)GetVideoEncodeAV1TxMode(videoEncodeDesc.av1PictureDesc, pictureDesc.frameType); av1Picture.OrderHint = videoEncodeDesc.av1PictureDesc ? videoEncodeDesc.av1PictureDesc->orderHint : (UINT)pictureDesc.pictureOrderCount; av1Picture.PictureIndex = videoEncodeDesc.av1PictureDesc ? videoEncodeDesc.av1PictureDesc->currentFrameId : pictureDesc.frameIndex; av1Picture.TemporalLayerIndexPlus1 = pictureDesc.temporalLayer + 1; @@ -1551,7 +1624,7 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco av1Picture.RefreshFrameFlags = videoEncodeDesc.av1PictureDesc ? videoEncodeDesc.av1PictureDesc->refreshFrameFlags : ((pictureDesc.frameType == VideoFrameType::IDR && sessionDesc.maxReferenceNum) ? 0xFF : 0); if (frameType == D3D12_VIDEO_ENCODER_AV1_FRAME_TYPE_KEY_FRAME) { av1Picture.PrimaryRefFrame = 7; - av1Picture.RefreshFrameFlags = sessionDesc.maxReferenceNum ? 0xFF : 0; + av1Picture.RefreshFrameFlags = 0xFF; // AV1 requires all reference frames to be refreshed by shown key frames } av1Picture.Quantization.BaseQIndex = (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->baseQIndex) ? videoEncodeDesc.av1PictureDesc->baseQIndex @@ -1605,7 +1678,7 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco av1Picture.LoopFilter.ModeDeltas[i] = loopFilter.modeDeltas[i]; } if (session.GetAV1FeatureFlags() & D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAG_CDEF_FILTERING) { - av1Picture.CDEF.CdefDampingMinus3 = (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->cdefDampingMinus3) ? videoEncodeDesc.av1PictureDesc->cdefDampingMinus3 : 3; + av1Picture.CDEF.CdefDampingMinus3 = videoEncodeDesc.av1PictureDesc ? videoEncodeDesc.av1PictureDesc->cdefDampingMinus3 : 3; av1Picture.CDEF.CdefBits = videoEncodeDesc.av1PictureDesc ? videoEncodeDesc.av1PictureDesc->cdefBits : 0; if (videoEncodeDesc.av1PictureDesc && videoEncodeDesc.av1PictureDesc->cdef) { const VideoAV1CdefDesc& cdef = *videoEncodeDesc.av1PictureDesc->cdef; @@ -2509,9 +2582,11 @@ NRI_INLINE void CommandBufferD3D12::Barrier(const BarrierDesc& barrierDesc) { out.Subresources.NumArraySlices = layerNum; const FormatProps& formatProps = GetFormatProps(textureDesc.format); + if (textureDesc.format == Format::NV12_UNORM || textureDesc.format == Format::P010_UNORM || textureDesc.format == Format::P016_UNORM) { - const bool plane0 = in.planes == PlaneBits::ALL || (in.planes & PlaneBits::PLANE_0); - const bool plane1 = in.planes == PlaneBits::ALL || (in.planes & PlaneBits::PLANE_1); + const bool isAllPlanes = in.planes == PlaneBits::ALL || (in.planes & PlaneBits::COLOR); + const bool plane0 = isAllPlanes || (in.planes & PlaneBits::PLANE_0); + const bool plane1 = isAllPlanes || (in.planes & PlaneBits::PLANE_1); out.Subresources.FirstPlane = plane0 ? 0 : 1; out.Subresources.NumPlanes = (plane0 && plane1) ? 2 : 1; } else { @@ -2597,7 +2672,7 @@ NRI_INLINE void CommandBufferD3D12::Barrier(const BarrierDesc& barrierDesc) { else if (layerNum == textureDesc.layerNum && mipNum == textureDesc.mipNum && barrier.planes == PlaneBits::ALL) barrierNum++; else - barrierNum += layerNum * mipNum; + barrierNum += layerNum * mipNum * GetLegacyBarrierPlaneNum(textureDesc.format, barrier.planes); } bool isGlobalUavBarrierNeeded = false; @@ -2655,10 +2730,16 @@ NRI_INLINE void CommandBufferD3D12::Barrier(const BarrierDesc& barrierDesc) { } else if (layerNum == textureDesc.layerNum && mipNum == textureDesc.mipNum && barrier.planes == PlaneBits::ALL) ptr += AddResourceBarrier(commandListType, texture, barrier.before.access, barrier.after.access, *ptr, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); else { - for (Dim_t layer = 0; layer < layerNum; layer++) { - for (Dim_t mip = 0; mip < mipNum; mip++) { - uint32_t subresource = GetSubresourceIndex(barrier.layerOffset + layer, textureDesc.layerNum, barrier.mipOffset + mip, textureDesc.mipNum, barrier.planes); - ptr += AddResourceBarrier(commandListType, texture, barrier.before.access, barrier.after.access, *ptr, subresource); + const uint32_t planeNum = GetLegacyBarrierPlaneNum(textureDesc.format, barrier.planes); + + for (uint32_t plane = 0; plane < planeNum; plane++) { + const PlaneBits planes = planeNum == 1 ? barrier.planes : (plane ? PlaneBits::PLANE_1 : PlaneBits::PLANE_0); + + for (Dim_t layer = 0; layer < layerNum; layer++) { + for (Dim_t mip = 0; mip < mipNum; mip++) { + uint32_t subresource = GetSubresourceIndex(barrier.layerOffset + layer, textureDesc.layerNum, barrier.mipOffset + mip, textureDesc.mipNum, planes); + ptr += AddResourceBarrier(commandListType, texture, barrier.before.access, barrier.after.access, *ptr, subresource); + } } } } diff --git a/Source/D3D12/ImplD3D12.cpp b/Source/D3D12/ImplD3D12.cpp index 2438210e..63cbcb60 100644 --- a/Source/D3D12/ImplD3D12.cpp +++ b/Source/D3D12/ImplD3D12.cpp @@ -1271,8 +1271,8 @@ static Result NRI_CALL GetVideoEncodeFeedback(VideoSession&, Buffer& resolvedMet return GetVideoEncodeFeedback((BufferD3D12&)resolvedMetadataReadback, resolvedMetadataOffset, feedback); } -static Result NRI_CALL GetVideoAV1EncodeDecodeInfo(VideoSession&, Buffer& resolvedMetadataReadback, uint64_t resolvedMetadataOffset, const VideoAV1EncodeDecodeInfoDesc& desc, VideoAV1EncodeDecodeInfo& info) { - return GetVideoAV1EncodeDecodeInfo((BufferD3D12&)resolvedMetadataReadback, resolvedMetadataOffset, desc, info); +static Result NRI_CALL GetVideoAV1EncodeDecodeInfo(VideoSession& videoSession, Buffer& resolvedMetadataReadback, uint64_t resolvedMetadataOffset, const VideoAV1EncodeDecodeInfoDesc& desc, VideoAV1EncodeDecodeInfo& info) { + return GetVideoAV1EncodeDecodeInfo((VideoSessionD3D12&)videoSession, (BufferD3D12&)resolvedMetadataReadback, resolvedMetadataOffset, desc, info); } Result DeviceD3D12::FillFunctionTable(VideoInterface& table) const { diff --git a/Source/D3D12/VideoHelpersD3D12.h b/Source/D3D12/VideoHelpersD3D12.h index df7ff488..382ec201 100644 --- a/Source/D3D12/VideoHelpersD3D12.h +++ b/Source/D3D12/VideoHelpersD3D12.h @@ -9,6 +9,7 @@ constexpr uint32_t VIDEO_D3D12_ENCODE_SUPPORT_PROBE_SIZE = 512; constexpr uint32_t VIDEO_AV1_LEVEL_4_1 = 41; constexpr uint32_t VIDEO_D3D12_ENCODE_AV1_MIN_Q_INDEX = 1; constexpr uint32_t VIDEO_D3D12_ENCODE_AV1_MAX_Q_INDEX = 255; +constexpr VideoEncodeRateControlDesc VIDEO_ENCODE_DEFAULT_RATE_CONTROL = {VideoEncodeRateControlMode::CQP, 26, 28, 30, 0, 51, 30, 1, 0, 0, 0, 0, 0}; static inline GUID GetVideoDecodeProfile(VideoCodec codec, Format format) { switch (codec) { @@ -32,7 +33,7 @@ static inline void FillVideoCapabilities(VideoCapabilities& videoCapabilities, c videoCapabilities.pictureAccessGranularityWidth = 1; videoCapabilities.pictureAccessGranularityHeight = 1; videoCapabilities.maxReferenceNum = videoSessionDesc.maxReferenceNum; - videoCapabilities.bitstreamOffsetAlignment = 1; + videoCapabilities.bitstreamOffsetAlignment = videoSessionDesc.type == VideoSessionType::DECODE ? D3D12_VIDEO_DECODE_MIN_BITSTREAM_OFFSET_ALIGNMENT : 1; videoCapabilities.bitstreamSizeAlignment = 1; videoCapabilities.bitstreamSizeMax = videoSessionDesc.type == VideoSessionType::DECODE ? UINT32_MAX : uint64_t(-1); videoCapabilities.metadataOffsetAlignment = 1; @@ -166,13 +167,36 @@ static inline uint32_t GetSupportedVideoEncodeRateControlModes(ID3D12VideoDevice return modes; } -static inline void FillVideoEncodeRateControl(const VideoEncodeRateControlDesc& desc, VideoEncodeRateControlStateD3D12& state) { +static inline D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAGS GetVideoEncodeRateControlFlags(const VideoEncodeRateControlDesc& desc, D3D12_VIDEO_ENCODER_SUPPORT_FLAGS supportFlags) { + D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAGS flags = D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAG_NONE; + + if ((desc.qpMin || desc.qpMax) && (supportFlags & D3D12_VIDEO_ENCODER_SUPPORT_FLAG_RATE_CONTROL_ADJUSTABLE_QP_RANGE_AVAILABLE)) + flags |= D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAG_ENABLE_QP_RANGE; + + if (desc.qpP && (supportFlags & D3D12_VIDEO_ENCODER_SUPPORT_FLAG_RATE_CONTROL_INITIAL_QP_AVAILABLE)) + flags |= D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAG_ENABLE_INITIAL_QP; + + if (desc.maxFrameBitSize && (supportFlags & D3D12_VIDEO_ENCODER_SUPPORT_FLAG_RATE_CONTROL_MAX_FRAME_SIZE_AVAILABLE)) + flags |= D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAG_ENABLE_MAX_FRAME_SIZE; + + if ((desc.virtualBufferSizeMs || desc.initialVirtualBufferSizeMs) && (supportFlags & D3D12_VIDEO_ENCODER_SUPPORT_FLAG_RATE_CONTROL_VBV_SIZE_CONFIG_AVAILABLE)) + flags |= D3D12_VIDEO_ENCODER_RATE_CONTROL_FLAG_ENABLE_VBV_SIZES; + + return flags; +} + +// CBR/VBR QP range: H.264/HEVC QP, AV1 Q index +static inline uint32_t GetVideoEncodeQpMax(D3D12_VIDEO_ENCODER_CODEC codec) { + return codec == D3D12_VIDEO_ENCODER_CODEC_AV1 ? 255 : 51; +} + +static inline void FillVideoEncodeRateControl(const VideoEncodeRateControlDesc& desc, D3D12_VIDEO_ENCODER_CODEC codec, D3D12_VIDEO_ENCODER_SUPPORT_FLAGS supportFlags, VideoEncodeRateControlStateD3D12& state) { state = {}; const uint32_t frameRateNumerator = desc.frameRateNumerator ? desc.frameRateNumerator : 30; const uint32_t frameRateDenominator = desc.frameRateDenominator ? desc.frameRateDenominator : 1; const uint32_t qpMin = desc.qpMin; - const uint32_t qpMax = desc.qpMax ? desc.qpMax : 51; + const uint32_t qpMax = desc.qpMax ? desc.qpMax : GetVideoEncodeQpMax(codec); const uint32_t qpInitial = desc.qpP; const uint64_t maxBitrate = desc.maxBitrate ? desc.maxBitrate : desc.targetBitrate; const uint32_t virtualBufferSizeMs = desc.virtualBufferSizeMs ? desc.virtualBufferSizeMs : 1000; @@ -191,11 +215,13 @@ static inline void FillVideoEncodeRateControl(const VideoEncodeRateControlDesc& break; case VideoEncodeRateControlMode::CBR: state.cbr = {qpInitial, qpMin, qpMax, desc.maxFrameBitSize, desc.targetBitrate, vbvCapacity, initialVbvFullness}; + state.rateControl.Flags = GetVideoEncodeRateControlFlags(desc, supportFlags); state.rateControl.ConfigParams.DataSize = sizeof(state.cbr); state.rateControl.ConfigParams.pConfiguration_CBR = &state.cbr; break; case VideoEncodeRateControlMode::VBR: state.vbr = {qpInitial, qpMin, qpMax, desc.maxFrameBitSize, desc.targetBitrate, maxBitrate, vbvCapacity, initialVbvFullness}; + state.rateControl.Flags = GetVideoEncodeRateControlFlags(desc, supportFlags); state.rateControl.ConfigParams.DataSize = sizeof(state.vbr); state.rateControl.ConfigParams.pConfiguration_VBR = &state.vbr; break; @@ -204,6 +230,29 @@ static inline void FillVideoEncodeRateControl(const VideoEncodeRateControlDesc& } } +// Rate-control capability bits in "SupportFlags" depend on the queried rate-control mode, so query them per mode +template +static inline void GetVideoEncodeRateControlSupportFlags(ID3D12VideoDevice* videoDevice, D3D12_FEATURE_VIDEO feature, T encoderSupport, uint32_t rateControlModes, std::array& supportFlags) { + constexpr std::array rateControlModesToQuery = {VideoEncodeRateControlMode::CBR, VideoEncodeRateControlMode::VBR}; + + for (VideoEncodeRateControlMode mode : rateControlModesToQuery) { + if ((rateControlModes & video::GetEncodeRateControlModeMask(mode)) == 0) + continue; + + VideoEncodeRateControlDesc rateControlDesc = VIDEO_ENCODE_DEFAULT_RATE_CONTROL; + rateControlDesc.mode = mode; + rateControlDesc.targetBitrate = 1000000; + VideoEncodeRateControlStateD3D12 rateControlState; + FillVideoEncodeRateControl(rateControlDesc, encoderSupport.Codec, D3D12_VIDEO_ENCODER_SUPPORT_FLAG_NONE, rateControlState); + + encoderSupport.RateControl = rateControlState.rateControl; + HRESULT hr = videoDevice->CheckFeatureSupport(feature, &encoderSupport, sizeof(encoderSupport)); + + if (SUCCEEDED(hr)) + supportFlags[(size_t)mode] = encoderSupport.SupportFlags; + } +} + static inline D3D12_VIDEO_ENCODER_CODEC GetVideoEncodeCodec(VideoCodec codec) { switch (codec) { case VideoCodec::H264: @@ -357,9 +406,9 @@ static bool IsVideoEncodeSessionSupported(ID3D12VideoDevice* videoDevice, const if ((rateControlModes & video::ENCODE_RATE_CONTROL_CQP) == 0) return false; - const VideoEncodeRateControlDesc defaultRateControl = {VideoEncodeRateControlMode::CQP, 26, 28, 30, 0, 51, 30, 1, 0, 0, 0, 0, 0}; + const VideoEncodeRateControlDesc& defaultRateControl = VIDEO_ENCODE_DEFAULT_RATE_CONTROL; VideoEncodeRateControlStateD3D12 rateControlState; - FillVideoEncodeRateControl(defaultRateControl, rateControlState); + FillVideoEncodeRateControl(defaultRateControl, d3d12Codec, D3D12_VIDEO_ENCODER_SUPPORT_FLAG_NONE, rateControlState); D3D12_VIDEO_ENCODER_SEQUENCE_GOP_STRUCTURE_H264 h264Gop = {}; h264Gop.GOPLength = videoSessionDesc.maxReferenceNum ? 60 : 1; diff --git a/Source/D3D12/VideoSessionD3D12.h b/Source/D3D12/VideoSessionD3D12.h index 43fea59f..69e08fdf 100644 --- a/Source/D3D12/VideoSessionD3D12.h +++ b/Source/D3D12/VideoSessionD3D12.h @@ -31,6 +31,14 @@ struct VideoSessionD3D12 final : public DebugNameBase { return m_AV1FeatureFlags; } + inline uint32_t GetAV1RequiredFeatureFlags() const { + return m_AV1RequiredFeatureFlags; + } + + inline uint32_t GetEncodeSupportFlags(VideoEncodeRateControlMode rateControlMode) const { + return m_EncodeSupportFlags[(size_t)rateControlMode]; + } + inline uint32_t GetRateControlModes() const { return m_RateControlModes; } @@ -86,6 +94,8 @@ struct VideoSessionD3D12 final : public DebugNameBase { ComPtr m_Heap; VideoSessionDesc m_Desc = {}; uint32_t m_AV1FeatureFlags = 0; + uint32_t m_AV1RequiredFeatureFlags = 0; + std::array m_EncodeSupportFlags = {}; // "D3D12_VIDEO_ENCODER_SUPPORT_FLAGS" per rate-control mode uint32_t m_RateControlModes = 0; bool m_BFrameSupported = false; }; diff --git a/Source/D3D12/VideoSessionD3D12.hpp b/Source/D3D12/VideoSessionD3D12.hpp index d6afc79c..e8463081 100644 --- a/Source/D3D12/VideoSessionD3D12.hpp +++ b/Source/D3D12/VideoSessionD3D12.hpp @@ -93,10 +93,9 @@ static Result GetVideoAV1Capabilities(DeviceD3D12& device, const VideoSessionDes static Result GetVideoEncodeFeedback(BufferD3D12& resolvedMetadataReadback, uint64_t resolvedMetadataOffset, VideoEncodeFeedback& feedback) { #if NRI_ENABLE_AGILITY_SDK_SUPPORT - const void* metadata = resolvedMetadataReadback.Map(resolvedMetadataOffset); - if (!metadata) - return Result::FAILURE; + NRI_CHECK(resolvedMetadataReadback.IsMapped(), "'resolvedMetadataReadback' must be CPU-visible"); + const void* metadata = resolvedMetadataReadback.Map(resolvedMetadataOffset); const auto& d3d12Feedback = *(const D3D12_VIDEO_ENCODER_OUTPUT_METADATA*)metadata; const auto* subregions = (const D3D12_VIDEO_ENCODER_FRAME_SUBREGION_METADATA*)((const uint8_t*)metadata + sizeof(D3D12_VIDEO_ENCODER_OUTPUT_METADATA)); @@ -120,18 +119,22 @@ static Result GetVideoEncodeFeedback(BufferD3D12& resolvedMetadataReadback, uint #endif } -static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, uint64_t resolvedMetadataOffset, const VideoAV1EncodeDecodeInfoDesc& desc, VideoAV1EncodeDecodeInfo& info) { +static Result GetVideoAV1EncodeDecodeInfo(const VideoSessionD3D12& session, BufferD3D12& resolvedMetadataReadback, uint64_t resolvedMetadataOffset, const VideoAV1EncodeDecodeInfoDesc& desc, VideoAV1EncodeDecodeInfo& info) { info = {}; #if NRI_ENABLE_AGILITY_SDK_SUPPORT + NRI_CHECK(desc.feedback && desc.sequence, "'feedback' and 'sequence' must be valid"); + if (desc.feedback->errorFlags || !desc.feedback->encodedBitstreamWrittenBytes || !desc.feedback->writtenSubregionNum) return Result::FAILURE; + if (desc.encodedPayloadHeader && desc.encodedPayloadHeaderSize) return video::av1::GetEncodeDecodeInfoFromHeader(desc, info); - const void* metadata = resolvedMetadataReadback.Map(resolvedMetadataOffset); - if (!metadata) - return Result::FAILURE; + // Metadata only: picture header fields not reported by the resolved metadata come from the submitted picture description + NRI_CHECK(desc.pictureDesc && desc.av1PictureDesc, "'pictureDesc' and 'av1PictureDesc' are required without 'encodedPayloadHeader'"); + NRI_CHECK(resolvedMetadataReadback.IsMapped(), "'resolvedMetadataReadback' must be CPU-visible"); + const void* metadata = resolvedMetadataReadback.Map(resolvedMetadataOffset); const auto* bytes = (const uint8_t*)metadata; const auto& output = *(const D3D12_VIDEO_ENCODER_OUTPUT_METADATA*)bytes; const auto& subregion = *(const D3D12_VIDEO_ENCODER_FRAME_SUBREGION_METADATA*)(bytes + sizeof(D3D12_VIDEO_ENCODER_OUTPUT_METADATA)); @@ -156,7 +159,7 @@ static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, video::av1::FillSingleTileLayout(info, width, height); info.tileLayout.contextUpdateTileId = (uint16_t)tilesLayout.ContextUpdateTileId; - info.bitstreamOffset = subregion.bStartOffset; + info.bitstreamOffset = 0; // "feedback.encodedBitstreamOffset" already includes "bStartOffset" info.bitstreamSize = tilePayloadSize; info.tiles[0] = {0, (uint32_t)tilePayloadSize, 0, 0, 0xFF}; @@ -183,14 +186,19 @@ static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, for (uint32_t i = 0; i < 2; i++) info.loopFilter.modeDeltas[i] = (int8_t)post.LoopFilter.ModeDeltas[i]; - info.picture.frameType = VideoFrameType::IDR; - info.picture.orderHint = 0; - info.picture.refreshFrameFlags = 0xFF; + // Without references the encode was forced to a key frame ("FORCE_KEY_FRAME" is not part of "desc") + const VideoAV1EncodePictureDesc& av1PictureDesc = *desc.av1PictureDesc; + const bool isKeyFrame = desc.pictureDesc->frameType == VideoFrameType::IDR || desc.pictureDesc->frameType == VideoFrameType::I || !desc.references || !desc.referenceNum; + const VideoFrameType encodedFrameType = isKeyFrame ? VideoFrameType::IDR : desc.pictureDesc->frameType; + + info.picture.frameType = isKeyFrame ? VideoFrameType::IDR : VideoFrameType::P; + info.picture.orderHint = av1PictureDesc.orderHint; + info.picture.refreshFrameFlags = isKeyFrame ? 0xFF : av1PictureDesc.refreshFrameFlags; info.picture.primaryReferenceName = VideoAV1ReferenceName::NONE; - info.picture.currentFrameId = 0; + info.picture.currentFrameId = av1PictureDesc.currentFrameId; info.picture.flags = VideoAV1PictureBits::ERROR_RESILIENT_MODE | VideoAV1PictureBits::FORCE_INTEGER_MV | VideoAV1PictureBits::SHOW_FRAME; - if (desc.referenceNum) { + if (!isKeyFrame) { std::array refFrameIndices = {}; for (uint32_t i = 0; i < refFrameIndices.size(); i++) { @@ -203,10 +211,21 @@ static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, if (post.PrimaryRefFrame > 7 || !video::av1::BuildInterFrameReferences(desc, refFrameIndices, info)) return Result::FAILURE; - info.picture.frameType = VideoFrameType::P; - info.picture.refreshFrameFlags = 0; - info.picture.primaryReferenceName = video::av1::GetReferenceNameFromReferenceIndex((uint32_t)post.PrimaryRefFrame); + info.picture.primaryReferenceName = video::av1::GetReferenceNameFromReferenceIndex((uint32_t)post.PrimaryRefFrame); // driver-reported + + // Only the flags passed to D3D12 ("CmdEncodeVideo"), the others are not coded + const VideoAV1PictureBits pictureFlags = av1PictureDesc.flags != VideoAV1PictureBits::NONE ? av1PictureDesc.flags : video::av1::GetDefaultPictureFlags(); + const D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAGS controlFlags = GetVideoEncodeAV1PictureControlFlags(pictureFlags, session.GetAV1FeatureFlags(), session.GetAV1RequiredFeatureFlags()); info.picture.flags = VideoAV1PictureBits::SHOW_FRAME; + + if (controlFlags & D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_ENABLE_ERROR_RESILIENT_MODE) + info.picture.flags |= VideoAV1PictureBits::ERROR_RESILIENT_MODE; + + if (controlFlags & D3D12_VIDEO_ENCODER_AV1_PICTURE_CONTROL_FLAG_FORCE_INTEGER_MOTION_VECTORS) + info.picture.flags |= VideoAV1PictureBits::FORCE_INTEGER_MV; + + if (av1PictureDesc.interpolationFilter == video::av1::INTERPOLATION_FILTER_SWITCHABLE) + info.picture.flags |= VideoAV1PictureBits::IS_FILTER_SWITCHABLE; } if (post.QuantizationDelta.DeltaQPresent) { @@ -247,8 +266,8 @@ static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, info.picture.renderWidthMinus1 = (uint16_t)(width - 1); info.picture.renderHeightMinus1 = (uint16_t)(height - 1); info.picture.baseQIndex = (uint8_t)post.Quantization.BaseQIndex; - info.picture.interpolationFilter = video::av1::INTERPOLATION_FILTER_EIGHTTAP; - info.picture.txMode = video::av1::TX_MODE_SELECT; + info.picture.interpolationFilter = av1PictureDesc.interpolationFilter; + info.picture.txMode = GetVideoEncodeAV1TxMode(&av1PictureDesc, encodedFrameType); info.picture.cdefDampingMinus3 = (uint8_t)post.CDEF.CdefDampingMinus3; info.picture.cdefBits = (uint8_t)post.CDEF.CdefBits; info.picture.tileNum = 1; @@ -265,7 +284,7 @@ static Result GetVideoAV1EncodeDecodeInfo(BufferD3D12& resolvedMetadataReadback, return Result::SUCCESS; #else - MaybeUnused(resolvedMetadataReadback, resolvedMetadataOffset, desc); + MaybeUnused(session, resolvedMetadataReadback, resolvedMetadataOffset, desc); return Result::UNSUPPORTED; #endif @@ -411,6 +430,7 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { const uint32_t supportedFeatureFlags = (av1Caps.RequiredFeatureFlags | av1Caps.SupportedFeatureFlags) & (uint32_t)GetSupportedVideoEncodeAV1FeatureFlags(); av1Config.FeatureFlags = (D3D12_VIDEO_ENCODER_AV1_FEATURE_FLAGS)(av1Caps.RequiredFeatureFlags | supportedFeatureFlags); m_AV1FeatureFlags = av1Config.FeatureFlags; + m_AV1RequiredFeatureFlags = av1Caps.RequiredFeatureFlags; } D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION codecConfig = {}; @@ -429,9 +449,9 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { if ((m_RateControlModes & video::ENCODE_RATE_CONTROL_CQP) == 0) return Result::UNSUPPORTED; - const VideoEncodeRateControlDesc defaultRateControl = {VideoEncodeRateControlMode::CQP, 26, 28, 30, 0, 51, 30, 1, 0, 0, 0, 0, 0}; + const VideoEncodeRateControlDesc& defaultRateControl = VIDEO_ENCODE_DEFAULT_RATE_CONTROL; VideoEncodeRateControlStateD3D12 rateControlState; - FillVideoEncodeRateControl(defaultRateControl, rateControlState); + FillVideoEncodeRateControl(defaultRateControl, codec, D3D12_VIDEO_ENCODER_SUPPORT_FLAG_NONE, rateControlState); D3D12_VIDEO_ENCODER_SEQUENCE_GOP_STRUCTURE_H264 h264Gop = {}; h264Gop.GOPLength = videoSessionDesc.maxReferenceNum ? 60 : 1; @@ -507,6 +527,8 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { } m_BFrameSupported = videoSessionDesc.maxReferenceNum > 1; + m_EncodeSupportFlags[(size_t)VideoEncodeRateControlMode::CQP] = encoderSupport.SupportFlags; + GetVideoEncodeRateControlSupportFlags(videoDevice, D3D12_FEATURE_VIDEO_ENCODER_SUPPORT1, encoderSupport, m_RateControlModes, m_EncodeSupportFlags); } else { D3D12_FEATURE_DATA_VIDEO_ENCODER_SUPPORT encoderSupport = {}; encoderSupport.Codec = codec; @@ -534,6 +556,8 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { } m_BFrameSupported = videoSessionDesc.maxReferenceNum > 1; + m_EncodeSupportFlags[(size_t)VideoEncodeRateControlMode::CQP] = encoderSupport.SupportFlags; + GetVideoEncodeRateControlSupportFlags(videoDevice, D3D12_FEATURE_VIDEO_ENCODER_SUPPORT, encoderSupport, m_RateControlModes, m_EncodeSupportFlags); } D3D12_VIDEO_ENCODER_DESC encoderDesc = {}; From c43fe9ee3cc50a1571c6f0658ce26dc34ce267ca Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 18:13:01 +0200 Subject: [PATCH 06/20] Validation: GetVideoPictureState accepts DPB roles for coincide decode output pictures CmdDecodeVideo accepts a DECODE_OUTPUT picture (not OUTPUT_ONLY) as a decode reference or setup picture, GetVideoPictureState rejected the same roles. Co-Authored-By: Claude Opus 5.5 --- Source/Validation/ImplVal.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index 014328a4..9418b95b 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -200,10 +200,14 @@ static inline bool IsVideoPictureDescValid(const VideoPictureDesc& desc, const T return (textureDesc.usage & requiredUsage) != 0 && (!requiresOperationUsage || !isReferenceOnly) && (requiresOperationUsage || !isOutputOnly) && desc.layer < layerNum && (!desc.width || desc.width <= textureDesc.width) && (!desc.height || desc.height <= textureDesc.height); } -static inline bool IsVideoPictureRoleCompatible(VideoPictureUsage usage, VideoPictureRole role) { +static inline bool IsVideoPictureRoleCompatible(VideoPictureUsage usage, bool isOutputOnly, VideoPictureRole role) { if ((uint8_t)role >= (uint8_t)VideoPictureRole::MAX_NUM) return false; + // A decode output picture (coincide mode) is also the DPB picture, as accepted by "CmdDecodeVideo" + if (usage == VideoPictureUsage::DECODE_OUTPUT && !isOutputOnly && (role == VideoPictureRole::DECODE_REFERENCE || role == VideoPictureRole::DECODE_SETUP)) + return true; + static constexpr std::array usages = { VideoPictureUsage::DECODE_OUTPUT, // DECODE_OUTPUT VideoPictureUsage::DECODE_REFERENCE, // DECODE_REFERENCE @@ -1893,7 +1897,7 @@ static void NRI_CALL DestroyVideoPicture(VideoPicture* videoPicture) { static Result NRI_CALL GetVideoPictureState(const VideoPicture& videoPicture, VideoPictureRole role, VideoPictureState& state) { const VideoPictureVal& videoPictureVal = (const VideoPictureVal&)videoPicture; - NRI_RETURN_ON_FAILURE(&videoPictureVal.GetDevice(), IsVideoPictureRoleCompatible(videoPictureVal.GetUsage(), role), Result::INVALID_ARGUMENT, "'role' is incompatible with 'videoPicture' usage"); + NRI_RETURN_ON_FAILURE(&videoPictureVal.GetDevice(), IsVideoPictureRoleCompatible(videoPictureVal.GetUsage(), videoPictureVal.IsOutputOnly(), role), Result::INVALID_ARGUMENT, "'role' is incompatible with 'videoPicture' usage"); return videoPictureVal.GetDevice().GetVideoInterfaceImpl().GetVideoPictureState(*videoPictureVal.GetImpl(), role, state); } From 8ef36daa0f1e3ea69946d3eb4bc9434f859e5659 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 18:13:01 +0200 Subject: [PATCH 07/20] VK: pass the encode setup slot for non-reference pictures A session with DPB slots requires pSetupReferenceSlot for every encode (VVL: pSetupReferenceSlot is NULL but the session was created with maxDpbSlots). B frames and AV1 pictures with refreshFrameFlags = 0 passed none. The std is_reference flag still follows the frame type. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/VK/CommandBufferVK.hpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 2320b56d..e7f15897 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -935,7 +935,7 @@ NriStruct(VideoEncodeDesc) { NriOptional const NriPtr(VideoEncodePictureDesc) pictureDesc; NriOptional const NriPtr(VideoEncodeRateControlDesc) rateControlDesc; Nri(VideoEncodeBits) flags; - NriOptional NriPtr(VideoPicture) reconstructedPicture; + NriOptional NriPtr(VideoPicture) reconstructedPicture; // reconstructed/DPB setup picture; required for sessions with DPB slots, also for non-reference pictures (B frames, AV1 "refreshFrameFlags = 0"): the slot is written, but not referenced afterwards NriOptional NriPtr(Buffer) metadata; // backend encode metadata; required if "VideoCapabilities::metadataSize" is non-zero uint64_t metadataOffset; NriOptional NriPtr(Buffer) resolvedMetadata; // backend metadata consumed by "GetVideoEncodeFeedback" after the required resolve operation; a pending range must not be reused diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index d6b0f6b2..a93d42b3 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -1280,7 +1280,8 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD } } - const bool hasSetupReferenceSlot = isUsedAsReferencePicture; + // The setup slot is required by the session even if the picture is not used as a reference (non-reference pictures write a slot that is never referenced) + const bool hasSetupReferenceSlot = videoEncodeDesc.reconstructedPicture != nullptr && session.GetDesc().maxReferenceNum != 0; VkVideoReferenceSlotInfoKHR setupReferenceSlot = {VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR}; if (hasSetupReferenceSlot) { From 76169b17021d1225183be16d43667d3fe87b657d Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 18:22:13 +0200 Subject: [PATCH 08/20] VK: keep the video decode picture structures alive until the command buffer is re-recorded NVIDIA (610.57.04) reads the chained codec picture structures after vkCmdDecodeVideoKHR returned: H.264 decode with 3 or more references crashed in vkQueueSubmit2 (null pointer in the driver, depends on the stack contents). The structures and arrays chained into the decode command now live in per-command-buffer storage, released by Begin and the destructor. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/VK/CommandBufferVK.h | 28 +++++- Source/VK/CommandBufferVK.hpp | 157 ++++++++++++++++++++++++---------- Source/VK/VideoHelpersVK.h | 16 ++++ 4 files changed, 154 insertions(+), 49 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index e7f15897..ef96c80f 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -707,7 +707,7 @@ NriStruct(VideoAV1TileLayoutDesc) { uint8_t columnNum; uint8_t rowNum; uint8_t tileSizeBytesMinus1; - uint8_t uniformSpacing; + uint8_t uniformSpacing; // if set, omitted arrays are derived from the frame size uint16_t contextUpdateTileId; NriOptional const uint16_t* miColumnStarts; // if provided, must include "columnNum + 1" entries NriOptional const uint16_t* miRowStarts; // if provided, must include "rowNum + 1" entries diff --git a/Source/VK/CommandBufferVK.h b/Source/VK/CommandBufferVK.h index 19be8fc5..f3580b4c 100644 --- a/Source/VK/CommandBufferVK.h +++ b/Source/VK/CommandBufferVK.h @@ -16,7 +16,8 @@ struct InputAttachmentRange { struct CommandBufferVK final : public DebugNameBase { inline CommandBufferVK(DeviceVK& device) : m_Device(device) - , m_InputAttachmentRanges(device.GetStdAllocator()) { + , m_InputAttachmentRanges(device.GetStdAllocator()) + , m_VideoStorage(device.GetStdAllocator()) { } inline operator VkCommandBuffer() const { @@ -98,11 +99,36 @@ struct CommandBufferVK final : public DebugNameBase { void EncodeVideo(const VideoEncodeDesc& videoEncodeDesc); void ResolveVideoEncodeFeedback(VideoSession& videoSession, Buffer& resolvedMetadata, uint64_t resolvedMetadataOffset); +private: + void FreeVideoStorage(); + + // WORKAROUND: NVIDIA (610.57) reads the codec picture structures of a video command after "vkCmdDecodeVideoKHR" returned (crash with 3 or more H.264 references), + // so the memory chained into video commands lives until the command buffer is re-recorded or destroyed + template + inline T& PersistVideoStorage(const T& value) { + T* storage = (T*)AllocateVideoStorage(sizeof(T), alignof(T)); + *storage = value; + + return *storage; + } + + template + inline T* PersistVideoStorageArray(size_t num) { + T* storage = num ? (T*)AllocateVideoStorage(sizeof(T) * num, alignof(T)) : nullptr; + for (size_t i = 0; i < num; i++) + storage[i] = T{}; + + return storage; + } + + void* AllocateVideoStorage(size_t size, size_t alignment); + private: DeviceVK& m_Device; const PipelineLayoutVK* m_PipelineLayout = nullptr; const DescriptorVK* m_DepthStencil = nullptr; Vector m_InputAttachmentRanges; + Vector m_VideoStorage; VkCommandBuffer m_Handle = VK_NULL_HANDLE; VkCommandPool m_CommandPool = VK_NULL_HANDLE; QueueType m_Type = (QueueType)0; diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index a93d42b3..08367cbd 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -431,7 +431,26 @@ static inline VkAccessFlags2 GetAccessFlags(AccessBits accessBits) { return flags; } +void* CommandBufferVK::AllocateVideoStorage(size_t size, size_t alignment) { + const AllocationCallbacks& allocationCallbacks = m_Device.GetAllocationCallbacks(); + void* storage = allocationCallbacks.Allocate(allocationCallbacks.userArg, size, alignment); + NRI_CHECK(storage, "Out of memory"); + std::memset(storage, 0, size); + m_VideoStorage.push_back(storage); + + return storage; +} + +void CommandBufferVK::FreeVideoStorage() { + const AllocationCallbacks& allocationCallbacks = m_Device.GetAllocationCallbacks(); + for (void* storage : m_VideoStorage) + allocationCallbacks.Free(allocationCallbacks.userArg, storage); + m_VideoStorage.clear(); +} + CommandBufferVK::~CommandBufferVK() { + FreeVideoStorage(); + if (m_CommandPool) { const auto& vk = m_Device.GetDispatchTable(); vk.FreeCommandBuffers(m_Device, m_CommandPool, 1, &m_Handle); @@ -467,6 +486,7 @@ NRI_INLINE Result CommandBufferVK::Begin(const DescriptorPool*) { m_PipelineLayout = nullptr; m_PipelineBindPoint = BindPoint::INHERIT; m_InputAttachmentRanges.clear(); + FreeVideoStorage(); return Result::SUCCESS; } @@ -485,16 +505,65 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD BufferVK& bitstream = *(BufferVK*)videoDecodeDesc.bitstream.buffer; + // WORKAROUND: see "PersistVideoStorage" + struct CodecStorage { + VkVideoDecodeH264PictureInfoKHR h264Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H264_PICTURE_INFO_KHR}; + StdVideoDecodeH264PictureInfo h264StdPicture = {}; + VkVideoDecodeH264DpbSlotInfoKHR h264DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H264_DPB_SLOT_INFO_KHR}; + StdVideoDecodeH264ReferenceInfo h264StdReference = {}; + VkVideoDecodeH265PictureInfoKHR h265Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H265_PICTURE_INFO_KHR}; + StdVideoDecodeH265PictureInfo h265StdPicture = {}; + VkVideoDecodeH265DpbSlotInfoKHR h265DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H265_DPB_SLOT_INFO_KHR}; + StdVideoDecodeH265ReferenceInfo h265StdReference = {}; + VkVideoDecodeAV1PictureInfoKHR av1Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_PICTURE_INFO_KHR}; + StdVideoDecodeAV1PictureInfo av1StdPicture = {}; + VkVideoDecodeAV1DpbSlotInfoKHR av1DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_DPB_SLOT_INFO_KHR}; + StdVideoDecodeAV1ReferenceInfo av1StdReference = {}; + StdVideoAV1TileInfo av1TileInfo = {}; + StdVideoAV1Quantization av1Quantization = {}; + StdVideoAV1LoopFilter av1LoopFilter = {}; + StdVideoAV1LoopRestoration av1LoopRestoration = {}; + StdVideoAV1Segmentation av1Segmentation = {}; + StdVideoAV1CDEF av1Cdef = {}; + StdVideoAV1GlobalMotion av1GlobalMotion = {}; + StdVideoAV1FilmGrain av1FilmGrain = {}; + VkVideoReferenceSlotInfoKHR setupReferenceSlot = {VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR}; + VkVideoDecodeInfoKHR decodeInfo = {VK_STRUCTURE_TYPE_VIDEO_DECODE_INFO_KHR}; + }; + CodecStorage& codec = *new (AllocateVideoStorage(sizeof(CodecStorage), alignof(CodecStorage))) CodecStorage(); + VkVideoDecodeH264PictureInfoKHR& h264Picture = codec.h264Picture; + StdVideoDecodeH264PictureInfo& h264StdPicture = codec.h264StdPicture; + VkVideoDecodeH264DpbSlotInfoKHR& h264DpbSlot = codec.h264DpbSlot; + StdVideoDecodeH264ReferenceInfo& h264StdReference = codec.h264StdReference; + VkVideoDecodeH265PictureInfoKHR& h265Picture = codec.h265Picture; + StdVideoDecodeH265PictureInfo& h265StdPicture = codec.h265StdPicture; + VkVideoDecodeH265DpbSlotInfoKHR& h265DpbSlot = codec.h265DpbSlot; + StdVideoDecodeH265ReferenceInfo& h265StdReference = codec.h265StdReference; + VkVideoDecodeAV1PictureInfoKHR& av1Picture = codec.av1Picture; + StdVideoDecodeAV1PictureInfo& av1StdPicture = codec.av1StdPicture; + VkVideoDecodeAV1DpbSlotInfoKHR& av1DpbSlot = codec.av1DpbSlot; + StdVideoDecodeAV1ReferenceInfo& av1StdReference = codec.av1StdReference; + StdVideoAV1TileInfo& av1TileInfo = codec.av1TileInfo; + StdVideoAV1Quantization& av1Quantization = codec.av1Quantization; + StdVideoAV1LoopFilter& av1LoopFilter = codec.av1LoopFilter; + StdVideoAV1LoopRestoration& av1LoopRestoration = codec.av1LoopRestoration; + StdVideoAV1Segmentation& av1Segmentation = codec.av1Segmentation; + StdVideoAV1CDEF& av1Cdef = codec.av1Cdef; + StdVideoAV1GlobalMotion& av1GlobalMotion = codec.av1GlobalMotion; + StdVideoAV1FilmGrain& av1FilmGrain = codec.av1FilmGrain; + VkVideoReferenceSlotInfoKHR& setupReferenceSlot = codec.setupReferenceSlot; + VkVideoDecodeInfoKHR& decodeInfo = codec.decodeInfo; + const uint32_t h264ReferenceNum = session.GetDesc().codec == VideoCodec::H264 ? videoDecodeDesc.referenceNum : 0; const uint32_t h265ReferenceNum = session.GetDesc().codec == VideoCodec::H265 ? videoDecodeDesc.referenceNum : 0; const uint32_t av1ReferenceNum = session.GetDesc().codec == VideoCodec::AV1 ? videoDecodeDesc.referenceNum : 0; - Scratch referenceSlots = NRI_ALLOCATE_SCRATCH(m_Device, VkVideoReferenceSlotInfoKHR, videoDecodeDesc.referenceNum + 1); - Scratch h264StdReferences = NRI_ALLOCATE_SCRATCH(m_Device, StdVideoDecodeH264ReferenceInfo, h264ReferenceNum); - Scratch h264References = NRI_ALLOCATE_SCRATCH(m_Device, VkVideoDecodeH264DpbSlotInfoKHR, h264ReferenceNum); - Scratch h265StdReferences = NRI_ALLOCATE_SCRATCH(m_Device, StdVideoDecodeH265ReferenceInfo, h265ReferenceNum); - Scratch h265References = NRI_ALLOCATE_SCRATCH(m_Device, VkVideoDecodeH265DpbSlotInfoKHR, h265ReferenceNum); - Scratch av1StdReferences = NRI_ALLOCATE_SCRATCH(m_Device, StdVideoDecodeAV1ReferenceInfo, av1ReferenceNum); - Scratch av1References = NRI_ALLOCATE_SCRATCH(m_Device, VkVideoDecodeAV1DpbSlotInfoKHR, av1ReferenceNum); + VkVideoReferenceSlotInfoKHR* referenceSlots = PersistVideoStorageArray(videoDecodeDesc.referenceNum + 1); + StdVideoDecodeH264ReferenceInfo* h264StdReferences = PersistVideoStorageArray(h264ReferenceNum); + VkVideoDecodeH264DpbSlotInfoKHR* h264References = PersistVideoStorageArray(h264ReferenceNum); + StdVideoDecodeH265ReferenceInfo* h265StdReferences = PersistVideoStorageArray(h265ReferenceNum); + VkVideoDecodeH265DpbSlotInfoKHR* h265References = PersistVideoStorageArray(h265ReferenceNum); + StdVideoDecodeAV1ReferenceInfo* av1StdReferences = PersistVideoStorageArray(av1ReferenceNum); + VkVideoDecodeAV1DpbSlotInfoKHR* av1References = PersistVideoStorageArray(av1ReferenceNum); for (uint32_t i = 0; i < videoDecodeDesc.referenceNum; i++) { VideoPictureVK& picture = *(VideoPictureVK*)videoDecodeDesc.references[i].picture; referenceSlots[i] = {VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR}; @@ -537,37 +606,20 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD } } - VkVideoDecodeH264PictureInfoKHR h264Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H264_PICTURE_INFO_KHR}; - StdVideoDecodeH264PictureInfo h264StdPicture = {}; - VkVideoDecodeH264DpbSlotInfoKHR h264DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H264_DPB_SLOT_INFO_KHR}; - StdVideoDecodeH264ReferenceInfo h264StdReference = {}; - VkVideoDecodeH265PictureInfoKHR h265Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H265_PICTURE_INFO_KHR}; - StdVideoDecodeH265PictureInfo h265StdPicture = {}; - VkVideoDecodeH265DpbSlotInfoKHR h265DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_H265_DPB_SLOT_INFO_KHR}; - StdVideoDecodeH265ReferenceInfo h265StdReference = {}; - VkVideoDecodeAV1PictureInfoKHR av1Picture = {VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_PICTURE_INFO_KHR}; - StdVideoDecodeAV1PictureInfo av1StdPicture = {}; - VkVideoDecodeAV1DpbSlotInfoKHR av1DpbSlot = {VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_DPB_SLOT_INFO_KHR}; - StdVideoDecodeAV1ReferenceInfo av1StdReference = {}; - StdVideoAV1TileInfo av1TileInfo = {}; - StdVideoAV1Quantization av1Quantization = {}; - StdVideoAV1LoopFilter av1LoopFilter = {}; - StdVideoAV1LoopRestoration av1LoopRestoration = {}; - StdVideoAV1Segmentation av1Segmentation = {}; - StdVideoAV1CDEF av1Cdef = {}; - StdVideoAV1GlobalMotion av1GlobalMotion = {}; - StdVideoAV1FilmGrain av1FilmGrain = {}; #if defined(VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_INLINE_SESSION_PARAMETERS_INFO_KHR) - VkVideoDecodeAV1InlineSessionParametersInfoKHR av1InlineSessionParameters = {VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_INLINE_SESSION_PARAMETERS_INFO_KHR}; + VkVideoDecodeAV1InlineSessionParametersInfoKHR& av1InlineSessionParameters = PersistVideoStorage(VkVideoDecodeAV1InlineSessionParametersInfoKHR{VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_INLINE_SESSION_PARAMETERS_INFO_KHR}); #endif - Scratch av1TileOffsets = NRI_ALLOCATE_SCRATCH(m_Device, uint32_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); - Scratch av1TileSizes = NRI_ALLOCATE_SCRATCH(m_Device, uint32_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); - Scratch h264SliceOffsets = NRI_ALLOCATE_SCRATCH(m_Device, uint32_t, videoDecodeDesc.h264PictureDesc ? std::max(videoDecodeDesc.h264PictureDesc->sliceOffsetNum, 1u) : 0); - Scratch h265SliceSegmentOffsets = NRI_ALLOCATE_SCRATCH(m_Device, uint32_t, videoDecodeDesc.h265PictureDesc ? std::max(videoDecodeDesc.h265PictureDesc->sliceSegmentOffsetNum, 1u) : 0); - Scratch av1MiColStarts = NRI_ALLOCATE_SCRATCH(m_Device, uint16_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum + 1, 2u) : 0); - Scratch av1MiRowStarts = NRI_ALLOCATE_SCRATCH(m_Device, uint16_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum + 1, 2u) : 0); - Scratch av1WidthInSbsMinus1 = NRI_ALLOCATE_SCRATCH(m_Device, uint16_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); - Scratch av1HeightInSbsMinus1 = NRI_ALLOCATE_SCRATCH(m_Device, uint16_t, videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); + uint32_t* av1TileOffsets = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); + uint32_t* av1TileSizes = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? std::max(videoDecodeDesc.av1PictureDesc->tileNum, 1u) : 0); + uint32_t* h264SliceOffsets = PersistVideoStorageArray(videoDecodeDesc.h264PictureDesc ? std::max(videoDecodeDesc.h264PictureDesc->sliceOffsetNum, 1u) : 0); + uint32_t* h265SliceSegmentOffsets = PersistVideoStorageArray(videoDecodeDesc.h265PictureDesc ? std::max(videoDecodeDesc.h265PictureDesc->sliceSegmentOffsetNum, 1u) : 0); + const VideoAV1TileLayoutDesc* av1TileLayout = videoDecodeDesc.av1PictureDesc ? videoDecodeDesc.av1PictureDesc->tileLayout : nullptr; + const uint32_t av1TileColumnNum = av1TileLayout ? std::max(av1TileLayout->columnNum, 1) : 1; + const uint32_t av1TileRowNum = av1TileLayout ? std::max(av1TileLayout->rowNum, 1) : 1; + uint16_t* av1MiColStarts = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? av1TileColumnNum + 1 : 0); + uint16_t* av1MiRowStarts = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? av1TileRowNum + 1 : 0); + uint16_t* av1WidthInSbsMinus1 = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? av1TileColumnNum : 0); + uint16_t* av1HeightInSbsMinus1 = PersistVideoStorageArray(videoDecodeDesc.av1PictureDesc ? av1TileRowNum : 0); void* codecPictureInfo = nullptr; const void* setupReferenceInfo = nullptr; if (session.GetDesc().codec == VideoCodec::H264) { @@ -676,15 +728,28 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD FillVideoAV1DefaultTileInfo(av1TileInfo, av1MiColStarts, av1MiRowStarts, av1WidthInSbsMinus1, av1HeightInSbsMinus1, session.GetDesc().width, session.GetDesc().height); if (desc.tileLayout) { - av1TileInfo.flags.uniform_tile_spacing_flag = desc.tileLayout->uniformSpacing != 0; - av1TileInfo.TileCols = desc.tileLayout->columnNum; - av1TileInfo.TileRows = desc.tileLayout->rowNum; - av1TileInfo.context_update_tile_id = desc.tileLayout->contextUpdateTileId; - av1TileInfo.tile_size_bytes_minus_1 = desc.tileLayout->tileSizeBytesMinus1; - av1TileInfo.pMiColStarts = desc.tileLayout->miColumnStarts; - av1TileInfo.pMiRowStarts = desc.tileLayout->miRowStarts; - av1TileInfo.pWidthInSbsMinus1 = desc.tileLayout->widthInSuperblocksMinus1; - av1TileInfo.pHeightInSbsMinus1 = desc.tileLayout->heightInSuperblocksMinus1; + const VideoAV1TileLayoutDesc& tileLayout = *desc.tileLayout; + av1TileInfo.flags.uniform_tile_spacing_flag = tileLayout.uniformSpacing != 0; + av1TileInfo.TileCols = tileLayout.columnNum; + av1TileInfo.TileRows = tileLayout.rowNum; + av1TileInfo.context_update_tile_id = tileLayout.contextUpdateTileId; + av1TileInfo.tile_size_bytes_minus_1 = tileLayout.tileSizeBytesMinus1; + + // Copied, the command buffer outlives "desc". Missing arrays (uniform spacing) are derived from the frame size + const uint32_t sbShift = parameters.GetAV1SequenceHeader().flags.use_128x128_superblock ? 5 : 4; + const uint32_t miCols = 2 * ((session.GetDesc().width + 7) >> 3); + const uint32_t miRows = 2 * ((session.GetDesc().height + 7) >> 3); + FillVideoAV1UniformTileSizes(miCols, sbShift, av1TileColumnNum, av1MiColStarts, av1WidthInSbsMinus1); + FillVideoAV1UniformTileSizes(miRows, sbShift, av1TileRowNum, av1MiRowStarts, av1HeightInSbsMinus1); + + if (tileLayout.miColumnStarts) + std::memcpy(av1MiColStarts, tileLayout.miColumnStarts, (av1TileColumnNum + 1) * sizeof(uint16_t)); + if (tileLayout.miRowStarts) + std::memcpy(av1MiRowStarts, tileLayout.miRowStarts, (av1TileRowNum + 1) * sizeof(uint16_t)); + if (tileLayout.widthInSuperblocksMinus1) + std::memcpy(av1WidthInSbsMinus1, tileLayout.widthInSuperblocksMinus1, av1TileColumnNum * sizeof(uint16_t)); + if (tileLayout.heightInSuperblocksMinus1) + std::memcpy(av1HeightInSbsMinus1, tileLayout.heightInSuperblocksMinus1, av1TileRowNum * sizeof(uint16_t)); } FillVideoDecodeAV1Quantization(av1Quantization, desc); FillVideoDecodeAV1LoopFilter(av1LoopFilter, desc); @@ -725,7 +790,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD VideoPictureVK& setupPicture = videoDecodeDesc.setupPicture ? *(VideoPictureVK*)videoDecodeDesc.setupPicture : dstPicture; const bool hasDpbSlots = session.GetDesc().maxReferenceNum != 0; - VkVideoReferenceSlotInfoKHR setupReferenceSlot = {VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR}; setupReferenceSlot.pNext = setupReferenceInfo; const uint32_t setupReferenceSlotIndex = video::GetDecodeSetupSlot(videoDecodeDesc); setupReferenceSlot.slotIndex = hasDpbSlots ? (int32_t)setupReferenceSlotIndex : -1; @@ -743,7 +807,6 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD beginInfo.referenceSlotCount++; } - VkVideoDecodeInfoKHR decodeInfo = {VK_STRUCTURE_TYPE_VIDEO_DECODE_INFO_KHR}; decodeInfo.pNext = codecPictureInfo; decodeInfo.srcBuffer = bitstream.GetHandle(); decodeInfo.srcBufferOffset = videoDecodeDesc.bitstream.offset; diff --git a/Source/VK/VideoHelpersVK.h b/Source/VK/VideoHelpersVK.h index 3a5cbedc..0194dca9 100644 --- a/Source/VK/VideoHelpersVK.h +++ b/Source/VK/VideoHelpersVK.h @@ -641,6 +641,22 @@ static inline void FillVideoAV1DefaultTileInfo(StdVideoAV1TileInfo& info, uint16 info.pHeightInSbsMinus1 = heightInSbsMinus1; } +// Uniform AV1 tile spacing ("tile_info"): all tiles but the last one have the same size in superblocks +static inline void FillVideoAV1UniformTileSizes(uint32_t miNum, uint32_t sbShift, uint32_t tileNum, uint16_t* miStarts, uint16_t* sizesInSbsMinus1) { + const uint32_t sbNum = (miNum + (1u << sbShift) - 1) >> sbShift; + const uint32_t tileLog2 = video::av1::TileLog2(1, tileNum); + const uint32_t tileSizeInSbs = (sbNum + (1u << tileLog2) - 1) >> tileLog2; + + for (uint32_t i = 0; i < tileNum; i++) { + const uint32_t startSb = std::min(i * tileSizeInSbs, sbNum); + const uint32_t endSb = std::min(startSb + tileSizeInSbs, sbNum); + miStarts[i] = (uint16_t)std::min(startSb << sbShift, miNum); + sizesInSbsMinus1[i] = (uint16_t)(endSb > startSb ? endSb - startSb - 1 : 0); + } + + miStarts[tileNum] = (uint16_t)miNum; +} + static inline bool BuildVideoEncodeH265ReferenceLists(const VideoReference* references, const VideoH265ReferenceDesc* referenceDescs, uint32_t referenceNum, VideoFrameType frameType, int32_t currentPictureOrderCount, VideoEncodeH265ReferenceListsVK& lists) { lists = {}; From b2f2aaaca2dd0a27d7393d55f7dce056cb6a1107 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 18:47:32 +0200 Subject: [PATCH 09/20] VK: always pass the QP range for CBR and VBR encode NVIDIA (610.57) ignored the bitrate without it: 8 H.264 frames took 4045 bytes for 300 and 80000 kbit/s alike, with the range they take 16 KB and 481 KB. qpMin/qpMax were ignored by the Vulkan backend (D3D12 applies them), the default is the full codec range. A QP range change is a rate control change. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/VK/VideoHelpersVK.h | 37 +++++++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index ef96c80f..8d900b85 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -661,7 +661,7 @@ NriStruct(VideoEncodeRateControlDesc) { uint8_t qpI; uint8_t qpP; uint8_t qpB; - NriOptional uint8_t qpMin; + NriOptional uint8_t qpMin; // CBR/VBR QP range (AV1: Q index), defaults to the full codec range NriOptional uint8_t qpMax; uint32_t frameRateNumerator; uint32_t frameRateDenominator; diff --git a/Source/VK/VideoHelpersVK.h b/Source/VK/VideoHelpersVK.h index 0194dca9..8c61c06a 100644 --- a/Source/VK/VideoHelpersVK.h +++ b/Source/VK/VideoHelpersVK.h @@ -57,12 +57,45 @@ struct VideoEncodeRateControlVK { VkVideoEncodeH264RateControlInfoKHR h264 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H264_RATE_CONTROL_INFO_KHR}; VkVideoEncodeH265RateControlInfoKHR h265 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H265_RATE_CONTROL_INFO_KHR}; VkVideoEncodeAV1RateControlInfoKHR av1 = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_RATE_CONTROL_INFO_KHR}; + VkVideoEncodeH264RateControlLayerInfoKHR h264Layer = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H264_RATE_CONTROL_LAYER_INFO_KHR}; + VkVideoEncodeH265RateControlLayerInfoKHR h265Layer = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_H265_RATE_CONTROL_LAYER_INFO_KHR}; + VkVideoEncodeAV1RateControlLayerInfoKHR av1Layer = {VK_STRUCTURE_TYPE_VIDEO_ENCODE_AV1_RATE_CONTROL_LAYER_INFO_KHR}; }; // Fills a self-referencing native chain: "rateControl" must not be copied or moved afterwards static inline void FillVideoEncodeRateControl(VideoEncodeRateControlVK& rateControl, const VideoEncodeRateControlDesc& desc, const VideoSessionDesc& sessionDesc) { FillVideoEncodeRateControl(desc, rateControl.info, rateControl.layer); + // WORKAROUND: NVIDIA (610.57) ignores the CBR/VBR bitrate (the same output for 300 and 80000 kbit/s) unless the QP range is enabled + // (H.264/H.265 QP, AV1 Q index), so the range is always passed: "qpMin/qpMax" or the full codec range + if (desc.mode != VideoEncodeRateControlMode::CQP) { + if (sessionDesc.codec == VideoCodec::H264) { + const int32_t qpMin = desc.qpMin; + const int32_t qpMax = desc.qpMax ? desc.qpMax : 51; + rateControl.h264Layer.useMinQp = VK_TRUE; + rateControl.h264Layer.minQp = {qpMin, qpMin, qpMin}; + rateControl.h264Layer.useMaxQp = VK_TRUE; + rateControl.h264Layer.maxQp = {qpMax, qpMax, qpMax}; + rateControl.layer.pNext = &rateControl.h264Layer; + } else if (sessionDesc.codec == VideoCodec::H265) { + const int32_t qpMin = desc.qpMin; + const int32_t qpMax = desc.qpMax ? desc.qpMax : 51; + rateControl.h265Layer.useMinQp = VK_TRUE; + rateControl.h265Layer.minQp = {qpMin, qpMin, qpMin}; + rateControl.h265Layer.useMaxQp = VK_TRUE; + rateControl.h265Layer.maxQp = {qpMax, qpMax, qpMax}; + rateControl.layer.pNext = &rateControl.h265Layer; + } else if (sessionDesc.codec == VideoCodec::AV1) { + const uint32_t qIndexMin = desc.qpMin ? desc.qpMin : 1; + const uint32_t qIndexMax = desc.qpMax ? desc.qpMax : 255; + rateControl.av1Layer.useMinQIndex = VK_TRUE; + rateControl.av1Layer.minQIndex = {qIndexMin, qIndexMin, qIndexMin}; + rateControl.av1Layer.useMaxQIndex = VK_TRUE; + rateControl.av1Layer.maxQIndex = {qIndexMax, qIndexMax, qIndexMax}; + rateControl.layer.pNext = &rateControl.av1Layer; + } + } + if (sessionDesc.codec == VideoCodec::H264) { rateControl.h264.gopFrameCount = sessionDesc.maxReferenceNum ? 60 : 1; rateControl.h264.idrPeriod = rateControl.h264.gopFrameCount; @@ -84,7 +117,7 @@ static inline void FillVideoEncodeRateControl(VideoEncodeRateControlVK& rateCont } } -// Compares the native rate control state produced by two descriptions (QP values are per-picture, not part of the state) +// Compares the native rate control state produced by two descriptions (QP values are per-picture, not part of the state, the QP range is) static inline bool IsVideoEncodeRateControlEqual(const VideoEncodeRateControlDesc& a, const VideoEncodeRateControlDesc& b) { VkVideoEncodeRateControlInfoKHR infoA = {}; VkVideoEncodeRateControlInfoKHR infoB = {}; @@ -103,7 +136,7 @@ static inline bool IsVideoEncodeRateControlEqual(const VideoEncodeRateControlDes return true; return layerA.averageBitrate == layerB.averageBitrate && layerA.maxBitrate == layerB.maxBitrate && layerA.frameRateNumerator == layerB.frameRateNumerator - && layerA.frameRateDenominator == layerB.frameRateDenominator; + && layerA.frameRateDenominator == layerB.frameRateDenominator && a.qpMin == b.qpMin && a.qpMax == b.qpMax; } static inline VkVideoReferenceSlotInfoKHR GetVideoSetupReferenceSlotForBegin(const VkVideoReferenceSlotInfoKHR& setupReferenceSlot) { From bf858ed63efcb26d7bdb24be39f65253e6957581 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 19:17:55 +0200 Subject: [PATCH 10/20] VK: H.264 slice offsets point at the start code The offsets landed on the NAL header (+4 of the documented 4-byte start code), H.265 was fixed to +1 already. NVIDIA 580.142 (RTX 3080) decoded every H.264 picture as garbage (4.8 dB), ffmpeg decodes the same stream at 43.6 dB. Co-Authored-By: Claude Opus 5.5 --- Source/VK/CommandBufferVK.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index 08367cbd..ba849995 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -637,7 +637,7 @@ NRI_INLINE void CommandBufferVK::DecodeVideo(const VideoDecodeDesc& videoDecodeD h264StdPicture.PicOrderCnt[0] = desc.topFieldOrderCount; h264StdPicture.PicOrderCnt[1] = desc.bottomFieldOrderCount; for (uint32_t i = 0; i < desc.sliceOffsetNum; i++) - h264SliceOffsets[i] = desc.sliceOffsets[i] + 4; + h264SliceOffsets[i] = desc.sliceOffsets[i] + 1; // skip the leading zero byte of the documented 4-byte start code, pointing at "00 00 01" h264Picture.pStdPictureInfo = &h264StdPicture; h264Picture.sliceCount = desc.sliceOffsetNum; From 3e5e10a86cec3bc0fb2b6653e91a73aa6a7ebb9f Mon Sep 17 00:00:00 2001 From: "Claude (station test)" Date: Wed, 14 Oct 2026 20:36:16 +0200 Subject: [PATCH 11/20] Shared: AV1 CDEF secondary strengths are passed as coded The header parser stored cdef_y/uv_sec_strength with the AV1 3 -> 4 adjustment applied. Vulkan expects the coded value 0..3 and adjusts it itself: NVIDIA 580.142 decoded SVT-AV1 streams with luma errors of up to 3 in every picture that has a coded strength of 3 (bit-exact once the coded value is passed). Co-Authored-By: Claude Sonnet 5.5 --- Include/Extensions/NRIVideo.h | 8 ++++---- Source/Shared/SharedVideo.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 8d900b85..8d26b897 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -739,10 +739,10 @@ NriStruct(VideoAV1LoopFilterDesc) { }; NriStruct(VideoAV1CdefDesc) { - uint8_t yPrimaryStrength[8]; - uint8_t ySecondaryStrength[8]; - uint8_t uvPrimaryStrength[8]; - uint8_t uvSecondaryStrength[8]; + uint8_t yPrimaryStrength[8]; // 0..15 + uint8_t ySecondaryStrength[8]; // 0..3 as coded in "cdef_y_sec_strength" (3 stands for 4, the backends pass the coded value) + uint8_t uvPrimaryStrength[8]; // 0..15 + uint8_t uvSecondaryStrength[8]; // 0..3 as coded in "cdef_uv_sec_strength" }; NriStruct(VideoAV1SegmentationDesc) { diff --git a/Source/Shared/SharedVideo.h b/Source/Shared/SharedVideo.h index 63d00be6..2b15141b 100644 --- a/Source/Shared/SharedVideo.h +++ b/Source/Shared/SharedVideo.h @@ -1600,7 +1600,7 @@ static inline bool ParseGeneratedFrameHeader(const VideoAV1EncodeDecodeInfoDesc& if (!reader.ReadBits(2, value)) return false; - info.cdef.ySecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); + info.cdef.ySecondaryStrength[i] = (uint8_t)value; // as coded: the decoders apply the 3 -> 4 adjustment if (planeNum > 1) { if (!reader.ReadBits(4, value)) @@ -1609,7 +1609,7 @@ static inline bool ParseGeneratedFrameHeader(const VideoAV1EncodeDecodeInfoDesc& if (!reader.ReadBits(2, value)) return false; - info.cdef.uvSecondaryStrength[i] = (uint8_t)(value == 3 ? 4 : value); + info.cdef.uvSecondaryStrength[i] = (uint8_t)value; } } } From 6e304e1cb9ac9a4a76ff8646ba8a7c214a1f8aea Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 20:18:34 +0200 Subject: [PATCH 12/20] D3D12: encode GOP structure follows the application's SPS The driver writes the slice headers with log2_max_frame_num, pic_order_cnt_type and log2_max_pic_order_cnt_lsb from the GOP structure, which was hardwired to 0, so a SPS with other values (as the Vulkan path accepts) produced undecodable streams. Co-Authored-By: Claude Sonnet 5.5 --- Source/D3D12/CommandBufferD3D12.hpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Source/D3D12/CommandBufferD3D12.hpp b/Source/D3D12/CommandBufferD3D12.hpp index dce30c9f..ad647b79 100644 --- a/Source/D3D12/CommandBufferD3D12.hpp +++ b/Source/D3D12/CommandBufferD3D12.hpp @@ -1437,6 +1437,27 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco hevcGop.GOPLength = sessionDesc.maxReferenceNum ? 60 : 1; hevcGop.PPicturePeriod = sessionDesc.maxReferenceNum > 1 ? 2 : 1; + // The driver writes slice headers: "frame_num" and "pic_order_cnt_lsb" widths and the POC type must match the SPS written by the application + const VideoSessionParametersD3D12* encodeParameters = (VideoSessionParametersD3D12*)videoEncodeDesc.parameters; + if (encodeParameters && encodeParameters->GetH264Parameters() && sessionDesc.codec == VideoCodec::H264) { + const VideoH264SessionParametersDesc& parameters = *encodeParameters->GetH264Parameters(); + const VideoH264PictureParameterSetDesc* pps = video::FindParameterSet(parameters.pictureParameterSets, parameters.pictureParameterSetNum, &VideoH264PictureParameterSetDesc::pictureParameterSetId, + videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->pictureParameterSetId : 0); + const VideoH264SequenceParameterSetDesc* sps = pps ? video::FindParameterSet(parameters.sequenceParameterSets, parameters.sequenceParameterSetNum, &VideoH264SequenceParameterSetDesc::sequenceParameterSetId, pps->sequenceParameterSetId) : nullptr; + if (sps) { + h264Gop.pic_order_cnt_type = sps->pictureOrderCountType; + h264Gop.log2_max_frame_num_minus4 = sps->log2MaxFrameNumMinus4; + h264Gop.log2_max_pic_order_cnt_lsb_minus4 = sps->log2MaxPictureOrderCountLsbMinus4; + } + } + if (encodeParameters && encodeParameters->GetH265Parameters() && sessionDesc.codec == VideoCodec::H265) { + const VideoH265SessionParametersDesc& parameters = *encodeParameters->GetH265Parameters(); + const VideoH265SequenceParameterSetDesc* sps = video::FindParameterSet(parameters.sequenceParameterSets, parameters.sequenceParameterSetNum, &VideoH265SequenceParameterSetDesc::sequenceParameterSetId, + videoEncodeDesc.h265PictureDesc ? videoEncodeDesc.h265PictureDesc->sequenceParameterSetId : 0); + if (sps) + hevcGop.log2_max_pic_order_cnt_lsb_minus4 = sps->log2MaxPictureOrderCountLsbMinus4; + } + D3D12_VIDEO_ENCODER_ENCODEFRAME_INPUT_ARGUMENTS1 input = {}; D3D12_VIDEO_ENCODER_ENCODEFRAME_OUTPUT_ARGUMENTS1 output = {}; D3D12_VIDEO_ENCODER_COMPRESSED_BITSTREAM& bitstream = output.Bitstream.FrameOutputBuffer; From 19d52cbd5cc1b1251a1da477b955389b0260e128 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 14 Oct 2026 20:31:07 +0200 Subject: [PATCH 13/20] D3D12: request num_ref_idx_active_override_flag when the active references differ from the PPS defaults The driver writes slice headers without the override flag unless it is requested, so P pictures with more than one reference (and B pictures) decoded with the wrong list sizes. The H.265 active counts are passed as well. Co-Authored-By: Claude Sonnet 5.5 --- Source/D3D12/CommandBufferD3D12.hpp | 37 +++++++++++++++++++++++++++++ Source/D3D12/VideoSessionD3D12.h | 6 +++++ Source/D3D12/VideoSessionD3D12.hpp | 13 ++++++++++ 3 files changed, 56 insertions(+) diff --git a/Source/D3D12/CommandBufferD3D12.hpp b/Source/D3D12/CommandBufferD3D12.hpp index ad647b79..1189b1df 100644 --- a/Source/D3D12/CommandBufferD3D12.hpp +++ b/Source/D3D12/CommandBufferD3D12.hpp @@ -1547,6 +1547,24 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco h264Picture.pList0ReferenceFrames = h264List0ReferenceNum ? (UINT*)h264List0References : nullptr; h264Picture.List1ReferenceFramesCount = h264List1ReferenceNum; h264Picture.pList1ReferenceFrames = h264List1ReferenceNum ? (UINT*)h264List1References : nullptr; + // The driver does not know the PPS: the slice header carries "num_ref_idx_active_override_flag" only if requested (otherwise the active counts equal the PPS defaults) + if (sessionDesc.codec == VideoCodec::H264 && encodeParameters && encodeParameters->GetH264Parameters()) { + const VideoH264SessionParametersDesc& parameters = *encodeParameters->GetH264Parameters(); + const VideoH264PictureParameterSetDesc* pps = video::FindParameterSet(parameters.pictureParameterSets, parameters.pictureParameterSetNum, &VideoH264PictureParameterSetDesc::pictureParameterSetId, (uint8_t)h264Picture.pic_parameter_set_id); + const bool isInterPicture = pictureDesc.frameType == VideoFrameType::P || pictureDesc.frameType == VideoFrameType::B; + if (pps && isInterPicture) { + const bool isL0Different = h264List0ReferenceNum != pps->refIndexL0DefaultActiveMinus1 + 1u; + const bool isL1Different = pictureDesc.frameType == VideoFrameType::B && h264List1ReferenceNum != pps->refIndexL1DefaultActiveMinus1 + 1u; + if (isL0Different || isL1Different) { + if (!(session.GetCodecConfigurationSupportFlags() & D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_H264_FLAG_NUM_REF_IDX_ACTIVE_OVERRIDE_FLAG_SLICE_SUPPORT)) { + NRI_REPORT_ERROR(&m_Device, "D3D12 H.264 encode doesn't support 'num_ref_idx_active_override_flag': the active reference counts must match the PPS defaults"); + return; + } + + h264Picture.Flags |= D3D12_VIDEO_ENCODER_PICTURE_CONTROL_CODEC_DATA_H264_FLAG_REQUEST_NUM_REF_IDX_ACTIVE_OVERRIDE_FLAG_SLICE; + } + } + } h264Picture.ReferenceFramesReconPictureDescriptorsCount = videoEncodeDesc.referenceNum; h264Picture.pReferenceFramesReconPictureDescriptors = videoEncodeDesc.referenceNum ? (D3D12_VIDEO_ENCODER_REFERENCE_PICTURE_DESCRIPTOR_H264*)h264ReferenceDescriptors : nullptr; @@ -1601,6 +1619,25 @@ NRI_INLINE void CommandBufferD3D12::EncodeVideo(const VideoEncodeDesc& videoEnco hevcPicture.pList0ReferenceFrames = hevcReferenceLists.list0Num ? (UINT*)hevcList0References : nullptr; hevcPicture.List1ReferenceFramesCount = hevcReferenceLists.list1Num; hevcPicture.pList1ReferenceFrames = hevcReferenceLists.list1Num ? (UINT*)hevcList1References : nullptr; + hevcPicture.num_ref_idx_l0_active_minus1 = hevcReferenceLists.list0Num ? hevcReferenceLists.list0Num - 1 : 0; + hevcPicture.num_ref_idx_l1_active_minus1 = hevcReferenceLists.list1Num ? hevcReferenceLists.list1Num - 1 : 0; + if (encodeParameters && encodeParameters->GetH265Parameters()) { + const VideoH265SessionParametersDesc& parameters = *encodeParameters->GetH265Parameters(); + const VideoH265PictureParameterSetDesc* pps = video::FindParameterSet(parameters.pictureParameterSets, parameters.pictureParameterSetNum, &VideoH265PictureParameterSetDesc::pictureParameterSetId, (uint8_t)hevcPicture.slice_pic_parameter_set_id); + const bool isInterPicture = pictureDesc.frameType == VideoFrameType::P || pictureDesc.frameType == VideoFrameType::B; + if (pps && isInterPicture) { + const bool isL0Different = hevcReferenceLists.list0Num != pps->refIndexL0DefaultActiveMinus1 + 1u; + const bool isL1Different = pictureDesc.frameType == VideoFrameType::B && hevcReferenceLists.list1Num != pps->refIndexL1DefaultActiveMinus1 + 1u; + if (isL0Different || isL1Different) { + if (!(session.GetCodecConfigurationSupportFlags() & D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_HEVC_FLAG_NUM_REF_IDX_ACTIVE_OVERRIDE_FLAG_SLICE_SUPPORT)) { + NRI_REPORT_ERROR(&m_Device, "D3D12 H.265 encode doesn't support 'num_ref_idx_active_override_flag': the active reference counts must match the PPS defaults"); + return; + } + + hevcPicture.Flags |= D3D12_VIDEO_ENCODER_PICTURE_CONTROL_CODEC_DATA_HEVC_FLAG_REQUEST_NUM_REF_IDX_ACTIVE_OVERRIDE_FLAG_SLICE; + } + } + } hevcPicture.ReferenceFramesReconPictureDescriptorsCount = videoEncodeDesc.referenceNum; hevcPicture.pReferenceFramesReconPictureDescriptors = videoEncodeDesc.referenceNum ? (D3D12_VIDEO_ENCODER_REFERENCE_PICTURE_DESCRIPTOR_HEVC*)hevcReferenceDescriptors : nullptr; } diff --git a/Source/D3D12/VideoSessionD3D12.h b/Source/D3D12/VideoSessionD3D12.h index 69e08fdf..9c602bb6 100644 --- a/Source/D3D12/VideoSessionD3D12.h +++ b/Source/D3D12/VideoSessionD3D12.h @@ -35,6 +35,11 @@ struct VideoSessionD3D12 final : public DebugNameBase { return m_AV1RequiredFeatureFlags; } + // "D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_H264_FLAGS" or "D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_HEVC_FLAGS" + inline uint32_t GetCodecConfigurationSupportFlags() const { + return m_CodecConfigurationSupportFlags; + } + inline uint32_t GetEncodeSupportFlags(VideoEncodeRateControlMode rateControlMode) const { return m_EncodeSupportFlags[(size_t)rateControlMode]; } @@ -95,6 +100,7 @@ struct VideoSessionD3D12 final : public DebugNameBase { VideoSessionDesc m_Desc = {}; uint32_t m_AV1FeatureFlags = 0; uint32_t m_AV1RequiredFeatureFlags = 0; + uint32_t m_CodecConfigurationSupportFlags = 0; std::array m_EncodeSupportFlags = {}; // "D3D12_VIDEO_ENCODER_SUPPORT_FLAGS" per rate-control mode uint32_t m_RateControlModes = 0; bool m_BFrameSupported = false; diff --git a/Source/D3D12/VideoSessionD3D12.hpp b/Source/D3D12/VideoSessionD3D12.hpp index e8463081..61b6cb69 100644 --- a/Source/D3D12/VideoSessionD3D12.hpp +++ b/Source/D3D12/VideoSessionD3D12.hpp @@ -370,6 +370,17 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { h264Config.DirectModeConfig = D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_H264_DIRECT_MODES_DISABLED; h264Config.DisableDeblockingFilterConfig = D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_H264_SLICES_DEBLOCKING_MODE_0_ALL_LUMA_CHROMA_SLICE_BLOCK_EDGES_ALWAYS_FILTERED; + if (videoSessionDesc.codec == VideoCodec::H264) { + D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_H264 h264Caps = {}; + D3D12_FEATURE_DATA_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT h264ConfigSupport = {}; + h264ConfigSupport.Codec = codec; + h264ConfigSupport.Profile = profile; + h264ConfigSupport.CodecSupportLimits.DataSize = sizeof(h264Caps); + h264ConfigSupport.CodecSupportLimits.pH264Support = &h264Caps; + if (SUCCEEDED(videoDevice->CheckFeatureSupport(D3D12_FEATURE_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT, &h264ConfigSupport, sizeof(h264ConfigSupport))) && h264ConfigSupport.IsSupported) + m_CodecConfigurationSupportFlags = h264Caps.SupportFlags; + } + D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_HEVC hevcConfig = {}; hevcConfig.MinLumaCodingUnitSize = D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_HEVC_CUSIZE_8x8; hevcConfig.MaxLumaCodingUnitSize = D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_HEVC_CUSIZE_32x32; @@ -396,6 +407,8 @@ Result VideoSessionD3D12::Create(const VideoSessionDesc& videoSessionDesc) { if (!hevcConfigSupport.IsSupported) return Result::UNSUPPORTED; + m_CodecConfigurationSupportFlags = hevcCaps.SupportFlags; + if (hevcCaps.SupportFlags & D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_HEVC_FLAG_ASYMETRIC_MOTION_PARTITION_SUPPORT || hevcCaps.SupportFlags & D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_HEVC_FLAG_ASYMETRIC_MOTION_PARTITION_REQUIRED) hevcConfig.ConfigurationFlags |= D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_HEVC_FLAG_USE_ASYMETRIC_MOTION_PARTITION; if (hevcCaps.SupportFlags & D3D12_VIDEO_ENCODER_CODEC_CONFIGURATION_SUPPORT_HEVC_FLAG_SAO_FILTER_SUPPORT) From 83b952d511ed972555c7c1863f714041a283add7 Mon Sep 17 00:00:00 2001 From: Claude-station Date: Wed, 14 Oct 2026 22:22:13 +0200 Subject: [PATCH 14/20] VK: IDR pictures keep the earlier pictures that are waiting for output H.264/H.265 encode set no_output_of_prior_pics_flag on every IDR. With reordered B pictures, a conformant decoder (ffmpeg) then dropped the last pictures before the IDR (2 of 20 frames of a BBBP stream with idr period 7). Co-Authored-By: Claude Sonnet 5.5 --- Source/VK/CommandBufferVK.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index ba849995..1858fb56 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -931,7 +931,7 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD isUsedAsReferencePicture = video::IsEncodePictureUsedAsReference(session.GetDesc().codec, pictureDesc.frameType, session.GetDesc().maxReferenceNum, videoEncodeDesc.reconstructedPicture != nullptr, 0); h264StdPicture.flags.is_reference = isUsedAsReferencePicture; - h264StdPicture.flags.no_output_of_prior_pics_flag = pictureDesc.frameType == VideoFrameType::IDR; + h264StdPicture.flags.no_output_of_prior_pics_flag = false; // an IDR must not discard the pictures still waiting for output h264StdPicture.seq_parameter_set_id = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->sequenceParameterSetId : 0; h264StdPicture.pic_parameter_set_id = videoEncodeDesc.h264PictureDesc ? videoEncodeDesc.h264PictureDesc->pictureParameterSetId : 0; @@ -978,7 +978,7 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD session.GetDesc().maxReferenceNum, videoEncodeDesc.reconstructedPicture != nullptr, 0); h265StdPicture.flags.is_reference = isUsedAsReferencePicture; h265StdPicture.flags.pic_output_flag = true; - h265StdPicture.flags.no_output_of_prior_pics_flag = pictureDesc.frameType == VideoFrameType::IDR; + h265StdPicture.flags.no_output_of_prior_pics_flag = false; // an IDR must not discard the pictures still waiting for output h265StdPicture.flags.short_term_ref_pic_set_sps_flag = false; h265StdPicture.flags.slice_temporal_mvp_enabled_flag = false; for (uint8_t& entry : h265ReferenceLists.RefPicList0) From 2c2933099e58f6d8b2e2e1dae9ecc00c46a1de24 Mon Sep 17 00:00:00 2001 From: Claude-station Date: Wed, 14 Oct 2026 23:04:52 +0200 Subject: [PATCH 15/20] VK: omitted CBR/VBR QP bounds use the codec range of the implementation The NVIDIA workaround passed 0/51 (AV1 1/255) when qpMin/qpMax were omitted. That leaves the advertised capability range (Intel ANV: minQp 10, VUID useMinQp-08286). Keep the queried minQp/maxQp (H.264/H.265) and minQIndex/maxQIndex (AV1) on the session, use them for omitted bounds and clamp explicit bounds to them. The range is still always enabled. Co-Authored-By: Claude Sonnet 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/VK/CommandBufferVK.hpp | 4 ++-- Source/VK/VideoHelpersVK.h | 17 +++++++---------- Source/VK/VideoSessionVK.h | 11 +++++++++++ Source/VK/VideoSessionVK.hpp | 6 ++++++ 5 files changed, 27 insertions(+), 13 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 8d26b897..a5c3c780 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -661,7 +661,7 @@ NriStruct(VideoEncodeRateControlDesc) { uint8_t qpI; uint8_t qpP; uint8_t qpB; - NriOptional uint8_t qpMin; // CBR/VBR QP range (AV1: Q index), defaults to the full codec range + NriOptional uint8_t qpMin; // CBR/VBR QP range (AV1: Q index), defaults to the codec range (VK: reported by the implementation, D3D12: 0..51, AV1 0..255), explicit bounds are clamped to it (VK) NriOptional uint8_t qpMax; uint32_t frameRateNumerator; uint32_t frameRateDenominator; diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index 1858fb56..3673dc8a 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -1385,12 +1385,12 @@ NRI_INLINE void CommandBufferVK::EncodeVideo(const VideoEncodeDesc& videoEncodeD const bool needsRateControlUpdate = !needsSessionReset && !IsVideoEncodeRateControlEqual(session.GetRateControl(), rateControlDesc); VideoEncodeRateControlVK rateControl = {}; - FillVideoEncodeRateControl(rateControl, rateControlDesc, session.GetDesc()); + FillVideoEncodeRateControl(rateControl, rateControlDesc, session.GetDesc(), session.GetEncodeQpMin(), session.GetEncodeQpMax()); VideoEncodeRateControlVK currentRateControl = {}; if (needsRateControlUpdate) - FillVideoEncodeRateControl(currentRateControl, session.GetRateControl(), session.GetDesc()); + FillVideoEncodeRateControl(currentRateControl, session.GetRateControl(), session.GetDesc(), session.GetEncodeQpMin(), session.GetEncodeQpMax()); // A begin scope with a CBR/VBR state needs the GOP remaining frames, if required const bool requiresAV1GopRemainingFrames = session.GetDesc().codec == VideoCodec::AV1 && session.DoesAV1RequireGopRemainingFrames(); diff --git a/Source/VK/VideoHelpersVK.h b/Source/VK/VideoHelpersVK.h index 8c61c06a..4e209ac9 100644 --- a/Source/VK/VideoHelpersVK.h +++ b/Source/VK/VideoHelpersVK.h @@ -63,35 +63,32 @@ struct VideoEncodeRateControlVK { }; // Fills a self-referencing native chain: "rateControl" must not be copied or moved afterwards -static inline void FillVideoEncodeRateControl(VideoEncodeRateControlVK& rateControl, const VideoEncodeRateControlDesc& desc, const VideoSessionDesc& sessionDesc) { +static inline void FillVideoEncodeRateControl(VideoEncodeRateControlVK& rateControl, const VideoEncodeRateControlDesc& desc, const VideoSessionDesc& sessionDesc, int32_t codecQpMin, int32_t codecQpMax) { FillVideoEncodeRateControl(desc, rateControl.info, rateControl.layer); // WORKAROUND: NVIDIA (610.57) ignores the CBR/VBR bitrate (the same output for 300 and 80000 kbit/s) unless the QP range is enabled - // (H.264/H.265 QP, AV1 Q index), so the range is always passed: "qpMin/qpMax" or the full codec range + // (H.264/H.265 QP, AV1 Q index), so the range is always passed: "qpMin/qpMax" or the codec range reported by the implementation. + // Explicit bounds are clamped to that range (VUID-vkCmdBeginVideoCodingKHR-pBeginInfo-useMinQp/useMaxQp: the range must lie within the capabilities) if (desc.mode != VideoEncodeRateControlMode::CQP) { + const int32_t qpMin = desc.qpMin ? std::clamp(desc.qpMin, codecQpMin, codecQpMax) : codecQpMin; + const int32_t qpMax = desc.qpMax ? std::clamp(desc.qpMax, codecQpMin, codecQpMax) : codecQpMax; if (sessionDesc.codec == VideoCodec::H264) { - const int32_t qpMin = desc.qpMin; - const int32_t qpMax = desc.qpMax ? desc.qpMax : 51; rateControl.h264Layer.useMinQp = VK_TRUE; rateControl.h264Layer.minQp = {qpMin, qpMin, qpMin}; rateControl.h264Layer.useMaxQp = VK_TRUE; rateControl.h264Layer.maxQp = {qpMax, qpMax, qpMax}; rateControl.layer.pNext = &rateControl.h264Layer; } else if (sessionDesc.codec == VideoCodec::H265) { - const int32_t qpMin = desc.qpMin; - const int32_t qpMax = desc.qpMax ? desc.qpMax : 51; rateControl.h265Layer.useMinQp = VK_TRUE; rateControl.h265Layer.minQp = {qpMin, qpMin, qpMin}; rateControl.h265Layer.useMaxQp = VK_TRUE; rateControl.h265Layer.maxQp = {qpMax, qpMax, qpMax}; rateControl.layer.pNext = &rateControl.h265Layer; } else if (sessionDesc.codec == VideoCodec::AV1) { - const uint32_t qIndexMin = desc.qpMin ? desc.qpMin : 1; - const uint32_t qIndexMax = desc.qpMax ? desc.qpMax : 255; rateControl.av1Layer.useMinQIndex = VK_TRUE; - rateControl.av1Layer.minQIndex = {qIndexMin, qIndexMin, qIndexMin}; + rateControl.av1Layer.minQIndex = {(uint32_t)qpMin, (uint32_t)qpMin, (uint32_t)qpMin}; rateControl.av1Layer.useMaxQIndex = VK_TRUE; - rateControl.av1Layer.maxQIndex = {qIndexMax, qIndexMax, qIndexMax}; + rateControl.av1Layer.maxQIndex = {(uint32_t)qpMax, (uint32_t)qpMax, (uint32_t)qpMax}; rateControl.layer.pNext = &rateControl.av1Layer; } } diff --git a/Source/VK/VideoSessionVK.h b/Source/VK/VideoSessionVK.h index 046b131a..4db82c04 100644 --- a/Source/VK/VideoSessionVK.h +++ b/Source/VK/VideoSessionVK.h @@ -108,6 +108,15 @@ struct VideoSessionVK final : public DebugNameBase { return m_H265MaxL1ReferenceCount; } + // Codec QP range of the implementation (H.264/H.265 QP, AV1 Q index) + inline int32_t GetEncodeQpMin() const { + return m_EncodeQpMin; + } + + inline int32_t GetEncodeQpMax() const { + return m_EncodeQpMax; + } + inline bool IsResetRecorded() const { return m_ResetRecorded; } @@ -191,6 +200,8 @@ struct VideoSessionVK final : public DebugNameBase { bool m_AV1RequiresGopRemainingFrames = false; bool m_ResetRecorded = false; bool m_UseInlineSessionParameters = false; + int32_t m_EncodeQpMin = 0; + int32_t m_EncodeQpMax = 51; uint32_t m_H264MaxBPictureL0ReferenceCount = 0; uint32_t m_H264MaxL1ReferenceCount = 0; uint32_t m_H265MaxBPictureL0ReferenceCount = 0; diff --git a/Source/VK/VideoSessionVK.hpp b/Source/VK/VideoSessionVK.hpp index dfbe2057..78aba200 100644 --- a/Source/VK/VideoSessionVK.hpp +++ b/Source/VK/VideoSessionVK.hpp @@ -556,10 +556,14 @@ Result VideoSessionVK::Create(const VideoSessionDesc& videoSessionDesc) { if (videoSessionDesc.codec == VideoCodec::H264) { m_H264MaxBPictureL0ReferenceCount = encodeH264Capabilities.maxBPictureL0ReferenceCount; m_H264MaxL1ReferenceCount = encodeH264Capabilities.maxL1ReferenceCount; + m_EncodeQpMin = encodeH264Capabilities.minQp; + m_EncodeQpMax = encodeH264Capabilities.maxQp; } if (videoSessionDesc.codec == VideoCodec::H265) { m_H265MaxBPictureL0ReferenceCount = encodeH265Capabilities.maxBPictureL0ReferenceCount; m_H265MaxL1ReferenceCount = encodeH265Capabilities.maxL1ReferenceCount; + m_EncodeQpMin = encodeH265Capabilities.minQp; + m_EncodeQpMax = encodeH265Capabilities.maxQp; } if (videoSessionDesc.codec == VideoCodec::AV1) { m_AV1CapabilityFlags = encodeAV1Capabilities.flags; @@ -574,6 +578,8 @@ Result VideoSessionVK::Create(const VideoSessionDesc& videoSessionDesc) { m_AV1MaxTileSize = encodeAV1Capabilities.maxTileSize; m_AV1MinQIndex = encodeAV1Capabilities.minQIndex; m_AV1MaxQIndex = encodeAV1Capabilities.maxQIndex; + m_EncodeQpMin = (int32_t)encodeAV1Capabilities.minQIndex; + m_EncodeQpMax = (int32_t)encodeAV1Capabilities.maxQIndex; m_AV1RequiresGopRemainingFrames = encodeAV1Capabilities.requiresGopRemainingFrames != VK_FALSE; } } From 7ca67036d1a7a5d1ca0ab3f4d2308c2facd6fc43 Mon Sep 17 00:00:00 2001 From: Claude-station Date: Wed, 14 Oct 2026 23:06:55 +0200 Subject: [PATCH 16/20] Validation: encode requires reconstructedPicture in sessions with DPB slots reconstructedPicture is documented as required when maxReferenceNum > 0, also for non-reference pictures (B, AV1 refreshFrameFlags = 0), but a null one was forwarded and the Vulkan backend then passed no setup slot (VUID-vkCmdEncodeVideoKHR-pEncodeInfo-08377). This replaces the AV1-only check. Sessions without DPB slots are unchanged. Adds VID-REG-031 and the missing pictures in three existing validation tests. Co-Authored-By: Claude Sonnet 5.5 --- Source/Validation/CommandBufferVal.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Source/Validation/CommandBufferVal.hpp b/Source/Validation/CommandBufferVal.hpp index a4e9a58e..0f20de80 100644 --- a/Source/Validation/CommandBufferVal.hpp +++ b/Source/Validation/CommandBufferVal.hpp @@ -1927,7 +1927,8 @@ NRI_INLINE void CommandBufferVal::EncodeVideo(const VideoEncodeDesc& videoEncode return; } - NRI_RETURN_ON_FAILURE(&m_Device, sessionVal.GetDesc().codec != VideoCodec::AV1 || videoEncodeDesc.av1PictureDesc || !sessionVal.GetDesc().maxReferenceNum || videoEncodeDesc.reconstructedPicture, ReturnVoid(), "default AV1 key frames in sessions with DPB slots require 'reconstructedPicture'"); + // The setup slot is always written (VUID-vkCmdEncodeVideoKHR-pEncodeInfo-08377), also for non-reference pictures (B frames, AV1 "refreshFrameFlags = 0") + NRI_RETURN_ON_FAILURE(&m_Device, !sessionVal.GetDesc().maxReferenceNum || videoEncodeDesc.reconstructedPicture, ReturnVoid(), "'reconstructedPicture' is required in sessions with DPB slots ('maxReferenceNum' > 0), also for non-reference pictures"); VideoEncodeDesc videoEncodeDescImpl = videoEncodeDesc; videoEncodeDescImpl.session = videoEncodeDesc.session ? ((VideoSessionVal*)videoEncodeDesc.session)->GetImpl() : nullptr; From 5e8c45c6fcf1ae4b0073191644fa99f9be42d90c Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 21 Oct 2026 11:59:20 +0200 Subject: [PATCH 17/20] Validation: H.265 'generalLevelIdc' must be a Table A.8 level Zero is not a level and has no native Vulkan enum (it became STD_VIDEO_H265_LEVEL_IDC_INVALID), and the Annex B writer would code it as is. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/Validation/ImplVal.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index a5c3c780..0e1ceda0 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -413,7 +413,7 @@ NriStruct(VideoH264SessionParametersDesc) { NriStruct(VideoH265ProfileTierLevelDesc) { Nri(VideoH265ProfileTierLevelBits) flags; uint8_t generalProfileIdc; - uint8_t generalLevelIdc; // "general_level_idc" as coded in the bitstream: 30 times the level number (e.g. 120 = level 4), or 0 (unspecified) + uint8_t generalLevelIdc; // "general_level_idc" as coded in the bitstream: 30 times the level number (e.g. 120 = level 4) }; NriStruct(VideoH265DecPicBufMgrDesc) { diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index 9418b95b..b86e9a01 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -60,9 +60,9 @@ static inline uint8_t GetVideoSessionBitDepth(Format format) { return format == Format::NV12_UNORM ? 8 : 10; } -// "general_level_idc" (H.265 Table A.8, 30 times the level number) or 0 +// "general_level_idc" (H.265 Table A.8, 30 times the level number) static inline bool IsVideoH265LevelIdcValid(uint8_t generalLevelIdc) { - constexpr std::array levels = {0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183, 186}; + constexpr std::array levels = {30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183, 186}; return std::find(levels.begin(), levels.end(), generalLevelIdc) != levels.end(); } @@ -1830,7 +1830,7 @@ static Result NRI_CALL CreateVideoSessionParameters(Device& device, const VideoS NRI_RETURN_ON_FAILURE(&deviceVal, IsVideoSessionParametersDescValid(sessionVal.GetDesc(), sessionVal.GetCapabilities(), videoSessionParametersDesc), Result::INVALID_ARGUMENT, "'videoSessionParametersDesc' is invalid for the fixed session profile, format or picture layout"); NRI_RETURN_ON_FAILURE(&deviceVal, AreVideoH265LevelsValid(videoSessionParametersDesc), Result::INVALID_ARGUMENT, - "H.265 'generalLevelIdc' must be 0 or 30 times a level of H.265 Table A.8 (30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183 or 186)"); + "H.265 'generalLevelIdc' must be 30 times a level of H.265 Table A.8 (30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183 or 186)"); VideoSessionParametersDesc descImpl = videoSessionParametersDesc; descImpl.session = sessionVal.GetImpl(); From f3b6638e3a8de19051b4fac2cc173ee1ea6b5871 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 21 Oct 2026 12:06:22 +0200 Subject: [PATCH 18/20] Validation: H.265 Annex B parameter sets require a Table A.8 level Co-Authored-By: Claude Opus 5.5 --- Source/Validation/ImplVal.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index b86e9a01..6db0d0f8 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -1909,6 +1909,9 @@ static Result NRI_CALL WriteVideoAnnexBParameterSets(VideoAnnexBParameterSetsDes } else if (annexBParameterSetsDesc.codec == VideoCodec::H265) { if (!annexBParameterSetsDesc.h265Vps || !annexBParameterSetsDesc.h265Sps || !annexBParameterSetsDesc.h265Pps) return Result::INVALID_ARGUMENT; + + if (!IsVideoH265LevelIdcValid(annexBParameterSetsDesc.h265Vps->profileTierLevel.generalLevelIdc) || !IsVideoH265LevelIdcValid(annexBParameterSetsDesc.h265Sps->profileTierLevel.generalLevelIdc)) + return Result::INVALID_ARGUMENT; } else return Result::UNSUPPORTED; From f73763480cfaf83e12a90650266913ea63ece01d Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Wed, 21 Oct 2026 13:10:04 +0200 Subject: [PATCH 19/20] Validation: H.264 'levelIdc' must be a Table A-1 level Like H.265 level 0, H.264 levelIdc 0 (and level 1b, coded as 9) has no native Vulkan level and became STD_VIDEO_H264_LEVEL_IDC_INVALID; the Annex B writer would code it as is. Both session parameters and the validated Annex B writer now reject it. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/Validation/ImplVal.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 0e1ceda0..95624bb0 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -369,7 +369,7 @@ NriStruct(VideoPictureState) { NriStruct(VideoH264SequenceParameterSetDesc) { Nri(VideoH264SequenceParameterSetBits) flags; uint8_t profileIdc; - uint8_t levelIdc; + uint8_t levelIdc; // "level_idc" as coded in the bitstream: 10 times the level number (e.g. 41 = level 4.1), level 1b is not supported uint8_t chromaFormatIdc; uint8_t sequenceParameterSetId; uint8_t bitDepthLumaMinus8; diff --git a/Source/Validation/ImplVal.cpp b/Source/Validation/ImplVal.cpp index 6db0d0f8..2ce420a2 100644 --- a/Source/Validation/ImplVal.cpp +++ b/Source/Validation/ImplVal.cpp @@ -60,6 +60,26 @@ static inline uint8_t GetVideoSessionBitDepth(Format format) { return format == Format::NV12_UNORM ? 8 : 10; } +// "level_idc" (H.264 Table A-1, 10 times the level number), except level 1b which has no native Vulkan level +static inline bool IsVideoH264LevelIdcValid(uint8_t levelIdc) { + constexpr std::array levels = {10, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, 60, 61, 62}; + + return std::find(levels.begin(), levels.end(), levelIdc) != levels.end(); +} + +static inline bool AreVideoH264LevelsValid(const VideoSessionParametersDesc& desc) { + if (!desc.h264Parameters) + return true; + + const VideoH264SessionParametersDesc& parameters = *desc.h264Parameters; + for (uint32_t i = 0; i < parameters.sequenceParameterSetNum; i++) { + if (!IsVideoH264LevelIdcValid(parameters.sequenceParameterSets[i].levelIdc)) + return false; + } + + return true; +} + // "general_level_idc" (H.265 Table A.8, 30 times the level number) static inline bool IsVideoH265LevelIdcValid(uint8_t generalLevelIdc) { constexpr std::array levels = {30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183, 186}; @@ -1829,6 +1849,8 @@ static Result NRI_CALL CreateVideoSessionParameters(Device& device, const VideoS VideoSessionVal& sessionVal = *(VideoSessionVal*)videoSessionParametersDesc.session; NRI_RETURN_ON_FAILURE(&deviceVal, IsVideoSessionParametersDescValid(sessionVal.GetDesc(), sessionVal.GetCapabilities(), videoSessionParametersDesc), Result::INVALID_ARGUMENT, "'videoSessionParametersDesc' is invalid for the fixed session profile, format or picture layout"); + NRI_RETURN_ON_FAILURE(&deviceVal, AreVideoH264LevelsValid(videoSessionParametersDesc), Result::INVALID_ARGUMENT, + "H.264 'levelIdc' must be 10 times a level of H.264 Table A-1 (10, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, 60, 61 or 62)"); NRI_RETURN_ON_FAILURE(&deviceVal, AreVideoH265LevelsValid(videoSessionParametersDesc), Result::INVALID_ARGUMENT, "H.265 'generalLevelIdc' must be 30 times a level of H.265 Table A.8 (30, 60, 63, 90, 93, 120, 123, 150, 153, 156, 180, 183 or 186)"); @@ -1906,6 +1928,9 @@ static Result NRI_CALL WriteVideoAnnexBParameterSets(VideoAnnexBParameterSetsDes if (annexBParameterSetsDesc.codec == VideoCodec::H264) { if (!annexBParameterSetsDesc.h264Sps || !annexBParameterSetsDesc.h264Pps || !video::h264::IsFrameCroppingValid(*annexBParameterSetsDesc.h264Sps)) return Result::INVALID_ARGUMENT; + + if (!IsVideoH264LevelIdcValid(annexBParameterSetsDesc.h264Sps->levelIdc)) + return Result::INVALID_ARGUMENT; } else if (annexBParameterSetsDesc.codec == VideoCodec::H265) { if (!annexBParameterSetsDesc.h265Vps || !annexBParameterSetsDesc.h265Sps || !annexBParameterSetsDesc.h265Pps) return Result::INVALID_ARGUMENT; From 90112642c592ad2eb45f465335636bff3ddbb9e0 Mon Sep 17 00:00:00 2001 From: Bjorn Schobben Date: Fri, 2 Oct 2026 23:58:19 +0200 Subject: [PATCH 20/20] VK: work around NVIDIA encode feedback query copy hang On NVIDIA (driver 610.57.04, RTX 5080) vkCmdCopyQueryPoolResults on a VK_QUERY_TYPE_VIDEO_ENCODE_FEEDBACK_KHR pool never completes on graphics or compute queues (WAIT_BIT hangs the queue, otherwise VK_ERROR_DEVICE_LOST). Reproduced with a minimal NRI-free Vulkan program that is clean under the validation layers. CmdResolveVideoEncodeFeedback now only records the query index; the results are fetched on the host with vkGetQueryPoolResults (64-bit, WITH_STATUS) in GetVideoEncodeFeedback, which returns FAILURE while the query is not ready. The resolved metadata range shrinks accordingly (no device-side results). The same driver writes the offset and the size as packed 32-bit values when VK_QUERY_RESULT_64_BIT is requested (status lands in the third 64-bit slot), so NVIDIA reads them as 32-bit and caps "bitstreamSizeMax" of encode sessions to UINT32_MAX; Validation now also checks "dstBitstream.size" against it. Co-Authored-By: Claude Opus 5.5 --- Include/Extensions/NRIVideo.h | 2 +- Source/VK/CommandBufferVK.hpp | 9 ++++---- Source/VK/VideoSessionVK.hpp | 30 ++++++++++++++++++++++---- Source/Validation/CommandBufferVal.hpp | 3 ++- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/Include/Extensions/NRIVideo.h b/Include/Extensions/NRIVideo.h index 95624bb0..a43eb51a 100644 --- a/Include/Extensions/NRIVideo.h +++ b/Include/Extensions/NRIVideo.h @@ -290,7 +290,7 @@ NriStruct(VideoCapabilities) { uint32_t maxReferenceNum; uint32_t bitstreamOffsetAlignment; uint32_t bitstreamSizeAlignment; - uint64_t bitstreamSizeMax; + uint64_t bitstreamSizeMax; // maximum "bitstream.size" for decode and "dstBitstream.size" for encode uint32_t metadataOffsetAlignment; uint32_t resolvedMetadataOffsetAlignment; uint32_t encodeFeedbackMaxPendingNum; // maximum per-session feedback ranges not yet consumed by "GetVideoEncodeFeedback"; reset by "ResetVideoSession" diff --git a/Source/VK/CommandBufferVK.hpp b/Source/VK/CommandBufferVK.hpp index 3673dc8a..dca05687 100644 --- a/Source/VK/CommandBufferVK.hpp +++ b/Source/VK/CommandBufferVK.hpp @@ -1497,12 +1497,11 @@ NRI_INLINE void CommandBufferVK::ResolveVideoEncodeFeedback(VideoSession& videoS } const auto& vk = m_Device.GetDispatchTable(); - constexpr VkDeviceSize queryResultSize = sizeof(uint64_t) * 3; - const uint64_t queryResultOffset = resolvedMetadataOffset + sizeof(VideoEncodeFeedback); + const uint64_t queryIndexOffset = resolvedMetadataOffset + sizeof(VideoEncodeFeedback); - vk.CmdCopyQueryPoolResults(m_Handle, session.GetEncodeFeedbackQueryPool(), encodeFeedbackQueryIndex, 1, feedbackBuffer.GetHandle(), queryResultOffset, queryResultSize, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_WITH_STATUS_BIT_KHR); - vk.CmdFillBuffer(m_Handle, feedbackBuffer.GetHandle(), queryResultOffset + queryResultSize, sizeof(uint32_t), encodeFeedbackQueryIndex); + // WORKAROUND: no "vkCmdCopyQueryPoolResults" for encode feedback queries. NVIDIA (610.57) never completes the copy + // ("WAIT_BIT" hangs, otherwise "DEVICE_LOST"). Only the query index is recorded, the results are read on the host in "GetEncodeFeedback" + vk.CmdFillBuffer(m_Handle, feedbackBuffer.GetHandle(), queryIndexOffset, sizeof(uint32_t), encodeFeedbackQueryIndex); session.SetEncodeFeedbackQueryResolved(encodeFeedbackQueryIndex); } diff --git a/Source/VK/VideoSessionVK.hpp b/Source/VK/VideoSessionVK.hpp index 78aba200..11364bd3 100644 --- a/Source/VK/VideoSessionVK.hpp +++ b/Source/VK/VideoSessionVK.hpp @@ -299,6 +299,10 @@ static Result GetVideoCapabilities(DeviceVK& deviceVK, const VideoSessionDesc& v FillVideoCapabilities(videoCapabilities, videoSessionDesc, capabilities); + // WORKAROUND: NVIDIA encode feedback is read as 32-bit (see "VideoSessionVK::GetEncodeFeedback") + if (!isDecode && deviceVK.GetDesc().adapterDesc.vendor == Vendor::NVIDIA) + videoCapabilities.bitstreamSizeMax = UINT32_MAX; + if (isDecode) { videoCapabilities.decodeDpbAndOutputCoincide = isOutputAndDpbSupported; videoCapabilities.decodeDpbAndOutputDistinct = isSeparateSupported && (decodeCapabilities.flags & VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR) != 0; @@ -307,7 +311,7 @@ static Result GetVideoCapabilities(DeviceVK& deviceVK, const VideoSessionDesc& v return Result::UNSUPPORTED; } else if ((encodeCapabilities.supportedEncodeFeedbackFlags & VIDEO_ENCODE_REQUIRED_FEEDBACK_FLAGS) == VIDEO_ENCODE_REQUIRED_FEEDBACK_FLAGS) { videoCapabilities.resolvedMetadataOffsetAlignment = 8; - videoCapabilities.resolvedMetadataSize = sizeof(VideoEncodeFeedback) + sizeof(uint64_t) * 3 + sizeof(uint32_t); + videoCapabilities.resolvedMetadataSize = sizeof(VideoEncodeFeedback) + sizeof(uint32_t); // + query index videoCapabilities.resolvedMetadataState = {AccessBits::COPY_DESTINATION, StageBits::COPY}; videoCapabilities.resolvedMetadataQueueType = QueueType::GRAPHICS; videoCapabilities.encodeFeedbackMaxPendingNum = VIDEO_ENCODE_FEEDBACK_QUERY_NUM; @@ -430,7 +434,7 @@ NRI_INLINE Result VideoSessionVK::GetEncodeFeedback(BufferVK& resolvedMetadataRe if (m_EncodeFeedbackQueryPool == VK_NULL_HANDLE) return Result::UNSUPPORTED; - constexpr uint64_t queryPayloadSize = sizeof(uint64_t) * 3 + sizeof(uint32_t); + constexpr uint64_t queryPayloadSize = sizeof(uint32_t); const uint64_t queryPayloadOffset = resolvedMetadataOffset + sizeof(VideoEncodeFeedback); NRI_CHECK(resolvedMetadataReadback.GetMappedMemory(), "'resolvedMetadataReadback' must be CPU-visible"); @@ -438,8 +442,7 @@ NRI_INLINE Result VideoSessionVK::GetEncodeFeedback(BufferVK& resolvedMetadataRe if (!queryPayload) return Result::FAILURE; - const uint64_t* queryResult = (const uint64_t*)queryPayload; - const uint32_t queryIndex = *(const uint32_t*)(queryPayload + sizeof(uint64_t) * 3); + const uint32_t queryIndex = *(const uint32_t*)queryPayload; if (queryIndex >= VIDEO_ENCODE_FEEDBACK_QUERY_NUM) return Result::FAILURE; @@ -447,6 +450,25 @@ NRI_INLINE Result VideoSessionVK::GetEncodeFeedback(BufferVK& resolvedMetadataRe if (!payloadReadback.active || !payloadReadback.resolvedByCommand) return Result::FAILURE; + // WORKAROUND: host readback (see "CommandBufferVK::ResolveVideoEncodeFeedback") + uint64_t queryResult[3] = {}; + const auto& vk = m_Device.GetDispatchTable(); + VkResult vkResult = VK_SUCCESS; + if (m_Device.GetDesc().adapterDesc.vendor == Vendor::NVIDIA) { + // WORKAROUND: NVIDIA (610.57) packs the offset and the size as 32-bit values with "64_BIT", read them as 32-bit ("bitstreamSizeMax" keeps them in range) + uint32_t queryResult32[3] = {}; + vkResult = vk.GetQueryPoolResults(m_Device, m_EncodeFeedbackQueryPool, queryIndex, 1, sizeof(queryResult32), queryResult32, sizeof(queryResult32), VK_QUERY_RESULT_WITH_STATUS_BIT_KHR); + queryResult[0] = queryResult32[0]; + queryResult[1] = queryResult32[1]; + queryResult[2] = (uint64_t)(int64_t)(int32_t)queryResult32[2]; // the status is signed + } else + vkResult = vk.GetQueryPoolResults(m_Device, m_EncodeFeedbackQueryPool, queryIndex, 1, sizeof(queryResult), queryResult, sizeof(queryResult), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_STATUS_BIT_KHR); + + if (vkResult == VK_NOT_READY) + return Result::FAILURE; + + NRI_RETURN_ON_BAD_VKRESULT(&m_Device, vkResult, "vkGetQueryPoolResults"); + FillVideoEncodeFeedback(feedback, queryResult); ClearEncodeFeedbackQuery(queryIndex); diff --git a/Source/Validation/CommandBufferVal.hpp b/Source/Validation/CommandBufferVal.hpp index 0f20de80..5822c41f 100644 --- a/Source/Validation/CommandBufferVal.hpp +++ b/Source/Validation/CommandBufferVal.hpp @@ -1815,9 +1815,10 @@ NRI_INLINE void CommandBufferVal::EncodeVideo(const VideoEncodeDesc& videoEncode && videoEncodeDesc.dstBitstream.size <= dstBitstreamDesc.size - videoEncodeDesc.dstBitstream.offset && (capabilities.encodeBitstreamRangeSizeSupported || videoEncodeDesc.dstBitstream.size == dstBitstreamDesc.size - videoEncodeDesc.dstBitstream.offset) && videoEncodeDesc.bitstreamMetadataSize <= videoEncodeDesc.dstBitstream.size + && videoEncodeDesc.dstBitstream.size <= capabilities.bitstreamSizeMax && IsAligned(videoEncodeDesc.dstBitstream.offset, capabilities.bitstreamOffsetAlignment) && IsAligned(videoEncodeDesc.dstBitstream.size, capabilities.bitstreamSizeAlignment); - NRI_RETURN_ON_FAILURE(&m_Device, isDstBitstreamRangeValid, ReturnVoid(), "'dstBitstream' must be an aligned VIDEO_ENCODE buffer range containing 'bitstreamMetadataSize'; this session may require the range to extend to the end of the buffer"); + NRI_RETURN_ON_FAILURE(&m_Device, isDstBitstreamRangeValid, ReturnVoid(), "'dstBitstream' must be an aligned VIDEO_ENCODE buffer range containing 'bitstreamMetadataSize' and within 'bitstreamSizeMax'; this session may require the range to extend to the end of the buffer"); NRI_RETURN_ON_FAILURE(&m_Device, !capabilities.metadataSize || metadataVal, ReturnVoid(), "'metadata' is required by the video session"); if (metadataVal) {