diff --git a/.gitignore b/.gitignore index e251e72..92bbd24 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ _Build/ _Shaders/ _Data/ _Tmp/ +_Smoke/ pso_cache.bin # can be a symbolic link diff --git a/CMakeLists.txt b/CMakeLists.txt index 33fe002..8eee0a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -208,6 +208,23 @@ add_sample(Streamer cpp) add_sample(TextureTypes cpp) add_sample(Triangle cpp) +add_sample(VideoEncodeDecode cpp) +target_sources(VideoEncodeDecode PRIVATE + Source/VideoEncodeDecode/Decoder.cpp + Source/VideoEncodeDecode/Decoder.h + Source/VideoEncodeDecode/Encoder.cpp + Source/VideoEncodeDecode/Encoder.h + Source/VideoEncodeDecode/Shared.h + Source/VideoEncodeDecode/Stream.cpp + Source/VideoEncodeDecode/Stream.h +) +# "SharedVideo.h" of the NRI that is built (NRI_SOURCE_OVERRIDE_DIR aware) +target_include_directories(VideoEncodeDecode PRIVATE "${NRI_SOURCE_DIR}/Source/Shared") + +if(WIN32) + target_link_libraries(VideoEncodeDecode PRIVATE d3d12) +endif() + # Wrapper depends on Vulkan SDK availability if(DEFINED ENV{VULKAN_SDK}) add_sample(Wrapper cpp) diff --git a/External/NRIFramework b/External/NRIFramework index 3091268..a9241a8 160000 --- a/External/NRIFramework +++ b/External/NRIFramework @@ -1 +1 @@ -Subproject commit 3091268f774d41806b377e7bfd94ca8fa1a074e1 +Subproject commit a9241a854952cae822778a57623d172f31e0f5f3 diff --git a/README.md b/README.md index 40df3af..b6f2e2c 100644 --- a/README.md +++ b/README.md @@ -88,5 +88,13 @@ The executables from `_Bin` directory load resources from `_Data`, therefore the - Streamer - buffer and texture streaming testing - TextureTypes - 1D, 2D array, cube and 3D texture/view testing - Triangle - simple textured triangle rendering (also multiview demonstration in _FLEXIBLE_ mode) +- VideoEncodeDecode - H.264/H.265/AV1 NV12 video encode/decode round trip; built only when the selected NRI source provides the NRIVideo extension - Wrapper - shows how to wrap native D3D11/D3D12/VK objects into *NRI* entities +### VideoEncodeDecode AV1 notes + +`VideoEncodeDecode --codec=AV1 --av1Frame=P` encodes a static generated source image as an IDR reference followed by a P frame. The source is intentionally frozen for this permutation so the left generated image and right decoded image can be compared directly while validating AV1 reference/DPB handling. It is not intended to demonstrate animated AV1 P-frame motion. + +The framework `--width` and `--height` arguments control the sample output window size only. Use `--videoWidth` and `--videoHeight` to select the NV12 encode/decode surface size. The default video size is 1920x1080. + +The sample uses CQP rate control by default. Use `--qpI`, `--qpP`, and `--qpB` to change the per-frame-type quantizers, and `--av1BaseQIndex` to change AV1's frame base quantizer. H.264/H.265 QP values must be in the 0..51 range; AV1 quantizer values use the 0..255 range. Lower values generally produce higher quality and larger bitstreams. diff --git a/Scripts/Linux/VerifyVideoDump.sh b/Scripts/Linux/VerifyVideoDump.sh new file mode 100755 index 0000000..d502a22 --- /dev/null +++ b/Scripts/Linux/VerifyVideoDump.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# usage: verify-dump.sh DUMPDIR (the directory passed to --dump) +# Per case: decodes stream.* with ffmpeg (cropped to the video size) and reports whether it is bit-exact to the NRI decode (decoded.yuv) +# and its luma PSNR against source.yuv. Needs ffmpeg and ffprobe. +D=$1 +for c in "$D"/*/; do + c=${c%/}; n=$(basename "$c"); s=$(ls "$c"/stream.* 2>/dev/null | head -1) + [ -z "$s" ] || [ ! -f "$c/info.txt" ] && continue + v=$(sed -n 's/^video=//p' "$c/info.txt"); w=${v%x*}; h=${v#*x} + if [ ! -s "$c/decoded.yuv" ]; then echo "$n: encode-only, stream $(stat -c %s "$s") bytes"; continue; fi + ffmpeg -v error -y -i "$s" -vf crop=$w:$h:0:0 -f rawvideo -pix_fmt nv12 "$c/ffmpeg.yuv" 2>"$c/ffmpeg.log" + if cmp -s "$c/ffmpeg.yuv" "$c/decoded.yuv"; then ex="bit-exact"; else ex="DIFFERENT"; fi + p=$(ffmpeg -hide_banner -f rawvideo -pix_fmt nv12 -s $v -i "$c/source.yuv" -f rawvideo -pix_fmt nv12 -s $v -i "$c/ffmpeg.yuv" -lavfi psnr -f null - 2>&1 | grep -o "y:[0-9.]*" | head -1) + echo "$n: $v ffmpeg-vs-NRI-decode=$ex ffmpeg-psnr-$p" +done diff --git a/Scripts/SmokeVideoEncodeDecode.bat b/Scripts/SmokeVideoEncodeDecode.bat new file mode 100644 index 0000000..c3aaf7c --- /dev/null +++ b/Scripts/SmokeVideoEncodeDecode.bat @@ -0,0 +1,231 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +set "DURATION_SEC=6" +set "WINDOW_WIDTH=3840" +set "WINDOW_HEIGHT=2160" +set "VIDEO_WIDTH=1280" +set "VIDEO_HEIGHT=720" +set "APIS=D3D12" +set "CASE_FILTER=" +set "NO_BUILD=0" +set "INCLUDE_DEBUG=0" +set "INCLUDE_VULKAN=0" + +call :ParseArgs %* + +set "SCRIPT_DIR=%~dp0" +for %%I in ("%SCRIPT_DIR%..") do set "REPO_ROOT=%%~fI" +set "EXE_PATH=%REPO_ROOT%\_Bin\Release\VideoEncodeDecode.exe" + +set "TS=%DATE%_%TIME%" +set "TS=%TS:/=%" +set "TS=%TS:.=%" +set "TS=%TS::=%" +set "TS=%TS:,=%" +set "TS=%TS: =0%" +set "TIMESTAMP=%TS%" +set "OUT_DIR=%REPO_ROOT%\_Smoke\VideoEncodeDecode_%TIMESTAMP%" +set "LOG_PATH=%OUT_DIR%\VideoEncodeDecodeSmoke.log" +mkdir "%OUT_DIR%" >nul 2>nul + +if "%NO_BUILD%"=="0" ( + call :WriteLog "Building VideoEncodeDecode Release target..." + cmake --build "%REPO_ROOT%\_Build" --config Release --target VideoEncodeDecode > "%OUT_DIR%\build.tmp.log" 2> "%OUT_DIR%\build.tmp.err" + set "BUILD_EXIT=!ERRORLEVEL!" + type "%OUT_DIR%\build.tmp.log" >> "%LOG_PATH%" 2>nul + type "%OUT_DIR%\build.tmp.err" >> "%LOG_PATH%" 2>nul + del "%OUT_DIR%\build.tmp.log" "%OUT_DIR%\build.tmp.err" >nul 2>nul + if not "!BUILD_EXIT!"=="0" ( + call :WriteLog "BUILD FAILED: exit code !BUILD_EXIT!" + exit /b !BUILD_EXIT! + ) +) + +if not exist "%EXE_PATH%" ( + call :WriteLog "Executable not found: %EXE_PATH%" + exit /b 1 +) + +if "%INCLUDE_VULKAN%"=="1" call :AddApi VULKAN + +set "CASE_COUNT=0" +set "PASS_COUNT=0" +set "FAIL_COUNT=0" + +call :WriteLog "VideoEncodeDecode smoke started" +echo %DATE% %TIME% Output directory: %OUT_DIR% +>> "%LOG_PATH%" echo %DATE% %TIME% Output directory: %OUT_DIR% +call :WriteLog "Duration per run: %DURATION_SEC% seconds" +call :WriteLog "Window: %WINDOW_WIDTH%x%WINDOW_HEIGHT%, video: %VIDEO_WIDTH%x%VIDEO_HEIGHT%" +echo %DATE% %TIME% APIs: %APIS% +>> "%LOG_PATH%" echo %DATE% %TIME% APIs: %APIS% + +for %%A in (%APIS%) do ( + for %%C in (H264 H265) do ( + for %%F in (IDR P B) do ( + call :MaybeRunCase "%%A-%%C-%%F-cqp" %%A %%C h26Frame %%F cqp 0 + call :MaybeRunCase "%%A-%%C-%%F-lossless" %%A %%C h26Frame %%F lossless 1 + ) + ) + + for %%F in (IDR P) do ( + call :MaybeRunCase "%%A-AV1-%%F-cqp" %%A AV1 av1Frame %%F cqp 0 + call :MaybeRunCase "%%A-AV1-%%F-near-lossless" %%A AV1 av1Frame %%F near-lossless 1 + ) +) + +if not "%CASE_FILTER%"=="" ( + call :WriteLog "Case filter: %CASE_FILTER%" + call :WriteLog "Filtered cases: %CASE_COUNT%" + if "%CASE_COUNT%"=="0" ( + call :WriteLog "No cases matched filter" + exit /b 1 + ) +) + +call :WriteLog "" +call :WriteLog "VideoEncodeDecode smoke finished: %PASS_COUNT% passed, %FAIL_COUNT% failed" +call :WriteLog "Log: %LOG_PATH%" + +if not "%FAIL_COUNT%"=="0" exit /b 1 +exit /b 0 + +::======================================================================================== +:ParseArgs +if "%~1"=="" exit /b 0 +if /I "%~1"=="--videoWidth" set "VIDEO_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "%~1"=="--videoHeight" set "VIDEO_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +set "ARG=%~1" + +if /I "!ARG!"=="-NoBuild" set "NO_BUILD=1" & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--no-build" set "NO_BUILD=1" & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-IncludeVulkan" set "INCLUDE_VULKAN=1" & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--include-vulkan" set "INCLUDE_VULKAN=1" & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-IncludeDebug" set "INCLUDE_DEBUG=1" & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--include-debug" set "INCLUDE_DEBUG=1" & shift /1 & goto :ParseArgs + +if /I "!ARG!"=="-DurationSec" set "DURATION_SEC=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--duration" set "DURATION_SEC=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--durationSec" set "DURATION_SEC=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-WindowWidth" set "WINDOW_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--width" set "WINDOW_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--windowWidth" set "WINDOW_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-WindowHeight" set "WINDOW_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--height" set "WINDOW_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--windowHeight" set "WINDOW_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-VideoWidth" set "VIDEO_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--videoWidth" set "VIDEO_WIDTH=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-VideoHeight" set "VIDEO_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--videoHeight" set "VIDEO_HEIGHT=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-Apis" set "APIS=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--apis" set "APIS=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="-CaseFilter" set "CASE_FILTER=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--filter" set "CASE_FILTER=%~2" & shift /1 & shift /1 & goto :ParseArgs +if /I "!ARG!"=="--caseFilter" set "CASE_FILTER=%~2" & shift /1 & shift /1 & goto :ParseArgs + +call :ParseEquals "%ARG%" +shift /1 +goto :ParseArgs + +::======================================================================================== +:ParseEquals +set "ARG=%~1" +for /f "tokens=1,* delims==" %%K in ("!ARG!") do ( + set "KEY=%%K" + set "VALUE=%%L" +) +if /I "!KEY!"=="--duration" set "DURATION_SEC=!VALUE!" +if /I "!KEY!"=="--durationSec" set "DURATION_SEC=!VALUE!" +if /I "!KEY!"=="-DurationSec" set "DURATION_SEC=!VALUE!" +if /I "!KEY!"=="--width" set "WINDOW_WIDTH=!VALUE!" +if /I "!KEY!"=="--windowWidth" set "WINDOW_WIDTH=!VALUE!" +if /I "!KEY!"=="-WindowWidth" set "WINDOW_WIDTH=!VALUE!" +if /I "!KEY!"=="--height" set "WINDOW_HEIGHT=!VALUE!" +if /I "!KEY!"=="--windowHeight" set "WINDOW_HEIGHT=!VALUE!" +if /I "!KEY!"=="-WindowHeight" set "WINDOW_HEIGHT=!VALUE!" +if /I "!KEY!"=="--videoWidth" set "VIDEO_WIDTH=!VALUE!" +if /I "!KEY!"=="-VideoWidth" set "VIDEO_WIDTH=!VALUE!" +if /I "!KEY!"=="--videoHeight" set "VIDEO_HEIGHT=!VALUE!" +if /I "!KEY!"=="-VideoHeight" set "VIDEO_HEIGHT=!VALUE!" +if /I "!KEY!"=="--apis" set "APIS=!VALUE!" +if /I "!KEY!"=="-Apis" set "APIS=!VALUE!" +if /I "!KEY!"=="--filter" set "CASE_FILTER=!VALUE!" +if /I "!KEY!"=="--caseFilter" set "CASE_FILTER=!VALUE!" +if /I "!KEY!"=="-CaseFilter" set "CASE_FILTER=!VALUE!" +exit /b 0 + +::======================================================================================== +:AddApi +echo %APIS% | findstr /I /C:"%~1" >nul +if errorlevel 1 set "APIS=%APIS% %~1" +exit /b 0 + +::======================================================================================== +:WriteLog +echo %DATE% %TIME% %~1 +>> "%LOG_PATH%" echo %DATE% %TIME% %~1 +exit /b 0 + +::======================================================================================== +:MaybeRunCase +set "CASE_NAME=%~1" +if not "%CASE_FILTER%"=="" ( + echo %CASE_NAME% | findstr /I /R /C:"%CASE_FILTER%" >nul + if errorlevel 1 exit /b 0 +) + +call :RunCase %* +exit /b 0 + +::======================================================================================== +:RunCase +set "CASE_NAME=%~1" +set "API=%~2" +set "CODEC=%~3" +set "FRAME_ARG_NAME=%~4" +set "FRAME_ARG_VALUE=%~5" +set "SUFFIX=%~6" +set "LOSSLESS=%~7" + +set /a CASE_COUNT+=1 +set "CASE_OUT=%OUT_DIR%\%CASE_NAME%.stdout.tmp" +set "CASE_ERR=%OUT_DIR%\%CASE_NAME%.stderr.tmp" + +set "CASE_ARGS=--api=%API% --width=%WINDOW_WIDTH% --height=%WINDOW_HEIGHT% --videoWidth=%VIDEO_WIDTH% --videoHeight=%VIDEO_HEIGHT% --codec=%CODEC% --timeLimit=%DURATION_SEC% --alwaysActive --requireVideoRoundTrip --%FRAME_ARG_NAME%=%FRAME_ARG_VALUE%" +if "%LOSSLESS%"=="1" set "CASE_ARGS=%CASE_ARGS% --lossless" +if "%INCLUDE_DEBUG%"=="1" set "CASE_ARGS=%CASE_ARGS% --debugAPI --debugNRI" + +call :WriteLog "" +call :WriteLog "[%CASE_COUNT%] START %CASE_NAME%" +call :WriteLog "Command: ""%EXE_PATH%"" %CASE_ARGS%" + +pushd "%REPO_ROOT%" >nul +"%EXE_PATH%" %CASE_ARGS% > "%CASE_OUT%" 2> "%CASE_ERR%" +set "EXIT_CODE=%ERRORLEVEL%" +popd >nul + +call :WriteLog "ExitCode: %EXIT_CODE%" +>> "%LOG_PATH%" echo ----- stdout: %CASE_NAME% ----- +type "%CASE_OUT%" >> "%LOG_PATH%" 2>nul +>> "%LOG_PATH%" echo ----- stderr: %CASE_NAME% ----- +type "%CASE_ERR%" >> "%LOG_PATH%" 2>nul + +set "CASE_FAILED=0" +if not "%EXIT_CODE%"=="0" set "CASE_FAILED=1" +findstr /R /C:"\" /C:"\" "%CASE_OUT%" "%CASE_ERR%" >nul 2>nul +if not errorlevel 1 set "CASE_FAILED=1" +findstr /C:"VIDEO_ROUND_TRIP_OK" "%CASE_OUT%" >nul 2>nul +if errorlevel 1 set "CASE_FAILED=1" + +del "%CASE_OUT%" "%CASE_ERR%" >nul 2>nul + +if "%CASE_FAILED%"=="1" ( + set /a FAIL_COUNT+=1 + call :WriteLog "FAILED %CASE_NAME%" +) else ( + set /a PASS_COUNT+=1 + call :WriteLog "OK %CASE_NAME%" +) + +exit /b 0 diff --git a/Shaders/Shaders.cfg b/Shaders/Shaders.cfg index 203ed46..53d6e18 100644 --- a/Shaders/Shaders.cfg +++ b/Shaders/Shaders.cfg @@ -8,6 +8,7 @@ Box5.fs.hlsl -T ps Box6.fs.hlsl -T ps Box7.fs.hlsl -T ps Compute.cs.hlsl -T cs +VideoEncodePattern.cs.hlsl -T cs DescriptorIndexing.cs.hlsl -T cs -m 6_6 -s Pool --compilerOptionsSPIRV "-fvk-bind-resource-heap 2 0 -fvk-bind-sampler-heap 0 0" GenerateSceneDrawCalls.cs.hlsl -T cs GraphicsPipelineStates.fs.hlsl -T ps diff --git a/Shaders/VideoEncodePattern.cs.hlsl b/Shaders/VideoEncodePattern.cs.hlsl new file mode 100644 index 0000000..ae465d4 --- /dev/null +++ b/Shaders/VideoEncodePattern.cs.hlsl @@ -0,0 +1,248 @@ +// © 2021 NVIDIA Corporation + +#include "NRI.hlsl" + +NRI_RESOURCE(RWBuffer, g_Nv12Buffer, u, 0, 0); +NRI_FORMAT("rgba8") NRI_RESOURCE(RWTexture2D, g_SourcePreview, u, 1, 0); +NRI_FORMAT("rgba8") NRI_RESOURCE(RWTexture2D, g_DecodePreview, u, 2, 0); + +static const uint OP_GENERATE_PATTERN = 0u; +static const uint OP_NV12_TO_PREVIEW = 1u; + +struct PatternRootConstants { + uint width; + uint height; + uint yOffsetBytes; + uint yRowPitchBytes; + uint uvRowPitchBytes; + uint uvOffsetBytes; + uint operation; + float time; + float motionSpeed; + float detailStrength; + float diffStrength; + uint showDifference; + uint frameIndex; +}; + +NRI_ROOT_CONSTANTS(PatternRootConstants, g_Pattern, 0, 0); + +float Stripe(float v, float frequency, float width) { + const float phase = frac(v * frequency); + return smoothstep(width, 0.0f, min(phase, 1.0f - phase)); +} + +float RectMask(float2 p, float2 minP, float2 maxP, float feather) { + const float2 lo = smoothstep(minP, minP + feather, p); + const float2 hi = 1.0f - smoothstep(maxP - feather, maxP, p); + return lo.x * lo.y * hi.x * hi.y; +} + +float3 ColorWheel(float phase) { + const float a = phase * 6.283185307179586f; + return saturate(0.5f + 0.5f * cos(a + float3(0.0f, 4.1887902047863905f, 2.0943951023931953f))); +} + +float3 MakePatternColor(float2 normalizedPixelPos, float time, uint frameIndex) { + const float fx = normalizedPixelPos.x; + const float fy = normalizedPixelPos.y; + const float cx = fx - 0.5f; + const float cy = fy - 0.5f; + const float radius = sqrt(cx * cx + cy * cy); + const float angle = atan2(cy, cx); + const float t = time * g_Pattern.motionSpeed; + const float detail = g_Pattern.detailStrength; + const float detail01 = saturate(detail); + + // Quiet base image: broad gradients and mild chroma rotation reveal banding + // and color drift without hiding problems under noise. + const float lumaRamp = fx; + const float verticalRamp = fy; + const float radialFalloff = saturate(1.0f - radius * 1.45f); + float3 color = lerp(float3(lumaRamp, lumaRamp, lumaRamp), float3(0.12f + 0.78f * lumaRamp, 0.10f + 0.72f * verticalRamp, 0.18f + 0.62f * radialFalloff), 0.42f); + + // Top-left: clean grayscale and chroma ramps for banding/chroma subsampling. + const float rampPanel = RectMask(normalizedPixelPos, float2(0.035f, 0.055f), float2(0.325f, 0.390f), 0.006f); + const float graySteps = floor(fx * 32.0f) / 31.0f; + const float smoothGray = saturate((fx - 0.035f) / 0.290f); + const float panelSplit = step(0.225f, fy); + const float3 rampColor = lerp(float3(smoothGray, smoothGray, smoothGray), ColorWheel(smoothGray + 0.08f * sin(t)), panelSplit); + color = lerp(color, rampColor, rampPanel); + color = lerp(color, float3(graySteps, graySteps, graySteps), rampPanel * (1.0f - panelSplit) * 0.28f * detail01); + + // Center: moving slanted hard edge plus soft rings. Ringing and block edges + // are easy to see here, but the region remains spatially coherent. + const float edgePanel = RectMask(normalizedPixelPos, float2(0.365f, 0.070f), float2(0.665f, 0.610f), 0.006f); + const float edge = smoothstep(-0.004f, 0.004f, (fx - 0.515f) + (fy - 0.33f) * 0.82f + sin(t * 0.7f) * 0.085f); + const float rings = sin((radius * 20.0f - t * 0.75f) * 6.283185307179586f) * 0.5f + 0.5f; + const float3 edgeColor = lerp(float3(0.04f, 0.06f, 0.08f), float3(0.92f, 0.90f, 0.84f), edge); + color = lerp(color, lerp(edgeColor, float3(rings, rings * 0.65f, 1.0f - rings), 0.22f), edgePanel); + + // Right: bounded detail patterns with no frame-to-frame flicker. This exposes + // luma blur, chroma bleed and block behavior without high-contrast temporal noise. + const float detailPanel = RectMask(normalizedPixelPos, float2(0.700f, 0.070f), float2(0.965f, 0.610f), 0.006f); + const float2 detailUv = saturate((normalizedPixelPos - float2(0.700f, 0.070f)) / float2(0.265f, 0.540f)); + const float barFreq = lerp(10.0f, 28.0f, detail01); + const float lumaBars = 0.5f + 0.38f * sin((detailUv.x * barFreq + 0.12f * sin(t * 0.35f)) * 6.283185307179586f); + const float chromaWave = 0.5f + 0.35f * sin((detailUv.y * 7.0f - t * 0.035f) * 6.283185307179586f); + const float diagonalWedge = smoothstep(0.012f, 0.0f, abs(frac((detailUv.x + detailUv.y) * 8.0f) - 0.5f)); + const float3 softBars = lerp(float3(lumaBars, lumaBars, lumaBars), float3(0.78f, 0.24f + 0.48f * chromaWave, 0.28f + 0.42f * (1.0f - chromaWave)), 0.42f); + const float3 wedgeColor = lerp(softBars, float3(0.18f, 0.22f, 0.26f), diagonalWedge * 0.28f * detail01); + color = lerp(color, wedgeColor, detailPanel); + + // Bottom: moving color wheel and measuring grid. Temporal glitches, repeated + // frames and chroma phase issues are obvious but still structured. + const float motionPanel = RectMask(normalizedPixelPos, float2(0.035f, 0.665f), float2(0.965f, 0.935f), 0.006f); + const float wheel = frac(fx * 1.75f + t * 0.10f); + const float markerX = frac(t * 0.16f); + const float marker = smoothstep(0.018f, 0.0f, abs(fx - markerX)) * smoothstep(0.0f, 0.04f, fy - 0.665f) * smoothstep(0.0f, 0.04f, 0.935f - fy); + const float frameBlink = ((frameIndex / 8u) & 1u) ? 1.0f : 0.0f; + const float grid = max(Stripe(fx, 16.0f, 0.018f), Stripe(fy, 9.0f, 0.020f)); + float3 motionColor = ColorWheel(wheel); + motionColor = lerp(motionColor, float3(0.0f, 0.0f, 0.0f), grid * 0.35f * detail01); + motionColor = lerp(motionColor, lerp(float3(1.0f, 1.0f, 1.0f), float3(0.0f, 0.0f, 0.0f), frameBlink), marker); + color = lerp(color, motionColor, motionPanel); + + return saturate(color); +} + +uint ClampToByte(float v) { + return (v <= 0.0f) ? 0u : (v >= 255.0f ? 255u : uint(v)); +} + +uint RGBToY(uint3 rgb) { + return ClampToByte(16.0f + 0.257f * float(rgb.x) + 0.504f * float(rgb.y) + 0.098f * float(rgb.z)); +} + +uint RGBToU(uint3 rgb) { + return ClampToByte(128.0f - 0.148f * float(rgb.x) - 0.291f * float(rgb.y) + 0.439f * float(rgb.z)); +} + +uint RGBToV(uint3 rgb) { + return ClampToByte(128.0f + 0.439f * float(rgb.x) - 0.368f * float(rgb.y) - 0.071f * float(rgb.z)); +} + +float3 YuvToRgb(uint y, uint u, uint v) { + const float yy = float(y); + const float uu = float(u) - 128.0f; + const float vv = float(v) - 128.0f; + + const float r = clamp((298.082f * (yy - 16.0f) + 408.583f * vv + 128.0f) / 256.0f, 0.0f, 255.0f); + const float g = clamp((298.082f * (yy - 16.0f) - 100.291f * uu - 208.120f * vv + 128.0f) / 256.0f, 0.0f, 255.0f); + const float b = clamp((298.082f * (yy - 16.0f) + 516.412f * uu + 128.0f) / 256.0f, 0.0f, 255.0f); + + return float3(r / 255.0f, g / 255.0f, b / 255.0f); +} + +float4 LoadPatternColor(uint px, uint py) { + return float4(MakePatternColor(float2(px, py) / float2(g_Pattern.width - 1u, g_Pattern.height - 1u), g_Pattern.time, g_Pattern.frameIndex), 1.0f); +} + +uint3 LoadPatternRgb8(uint px, uint py) { + return uint3(LoadPatternColor(px, py).rgb * 255.0f); +} + +float3 LoadPatternNv12Rgb(uint px, uint py) { + const uint chromaX = px & ~1u; + const uint chromaY = py & ~1u; + + const uint3 rgb = LoadPatternRgb8(px, py); + const uint3 chromaRgb0 = LoadPatternRgb8(chromaX + 0u, chromaY + 0u); + const uint3 chromaRgb1 = LoadPatternRgb8(chromaX + 1u, chromaY + 0u); + const uint3 chromaRgb2 = LoadPatternRgb8(chromaX + 0u, chromaY + 1u); + const uint3 chromaRgb3 = LoadPatternRgb8(chromaX + 1u, chromaY + 1u); + + const uint yValue = RGBToY(rgb); + const uint uValue = (RGBToU(chromaRgb0) + RGBToU(chromaRgb1) + RGBToU(chromaRgb2) + RGBToU(chromaRgb3) + 2u) >> 2u; + const uint vValue = (RGBToV(chromaRgb0) + RGBToV(chromaRgb1) + RGBToV(chromaRgb2) + RGBToV(chromaRgb3) + 2u) >> 2u; + + return YuvToRgb(yValue, uValue, vValue); +} + +void StorePreview(uint2 pixel, float4 color) { + if (g_Pattern.operation == OP_NV12_TO_PREVIEW) + g_DecodePreview[pixel] = color; + else + g_SourcePreview[pixel] = color; +} + +[numthreads(1, 1, 1)] +void main(uint3 dispatchThreadID : SV_DispatchThreadID) +{ + const uint blockX = dispatchThreadID.x * 4u; + const uint y = dispatchThreadID.y; + + if (blockX + 3u >= g_Pattern.width || y >= g_Pattern.height) + return; + + const float4 c0 = LoadPatternColor(blockX + 0u, y); + const float4 c1 = LoadPatternColor(blockX + 1u, y); + const float4 c2 = LoadPatternColor(blockX + 2u, y); + const float4 c3 = LoadPatternColor(blockX + 3u, y); + + if (g_Pattern.operation == OP_GENERATE_PATTERN) { + StorePreview(uint2(blockX + 0u, y), c0); + StorePreview(uint2(blockX + 1u, y), c1); + StorePreview(uint2(blockX + 2u, y), c2); + StorePreview(uint2(blockX + 3u, y), c3); + + const uint3 rgb0 = LoadPatternRgb8(blockX + 0u, y); + const uint3 rgb1 = LoadPatternRgb8(blockX + 1u, y); + const uint3 rgb2 = LoadPatternRgb8(blockX + 2u, y); + const uint3 rgb3 = LoadPatternRgb8(blockX + 3u, y); + + const uint y0 = RGBToY(rgb0); + const uint y1 = RGBToY(rgb1); + const uint y2 = RGBToY(rgb2); + const uint y3 = RGBToY(rgb3); + + const uint packedY = y0 | (y1 << 8u) | (y2 << 16u) | (y3 << 24u); + const uint yWordIndex = (g_Pattern.yOffsetBytes + y * g_Pattern.yRowPitchBytes + blockX) / 4u; + g_Nv12Buffer[yWordIndex] = packedY; + + if ((y & 1u) != 0u) + return; + if (y + 1u >= g_Pattern.height) + return; + + const uint3 rgb4 = LoadPatternRgb8(blockX + 0u, y + 1u); + const uint3 rgb5 = LoadPatternRgb8(blockX + 1u, y + 1u); + const uint3 rgb6 = LoadPatternRgb8(blockX + 2u, y + 1u); + const uint3 rgb7 = LoadPatternRgb8(blockX + 3u, y + 1u); + + const uint u0 = (RGBToU(rgb0) + RGBToU(rgb1) + RGBToU(rgb4) + RGBToU(rgb5) + 2u) >> 2u; + const uint v0 = (RGBToV(rgb0) + RGBToV(rgb1) + RGBToV(rgb4) + RGBToV(rgb5) + 2u) >> 2u; + const uint u1 = (RGBToU(rgb2) + RGBToU(rgb3) + RGBToU(rgb6) + RGBToU(rgb7) + 2u) >> 2u; + const uint v1 = (RGBToV(rgb2) + RGBToV(rgb3) + RGBToV(rgb6) + RGBToV(rgb7) + 2u) >> 2u; + + const uint packedUV = u0 | (v0 << 8u) | (u1 << 16u) | (v1 << 24u); + const uint uvWordIndex = (g_Pattern.uvOffsetBytes + ((y >> 1u) * g_Pattern.uvRowPitchBytes + blockX)) / 4u; + g_Nv12Buffer[uvWordIndex] = packedUV; + return; + } + + if (g_Pattern.operation == OP_NV12_TO_PREVIEW) { + const uint uvBase = (g_Pattern.uvOffsetBytes + (y >> 1u) * g_Pattern.uvRowPitchBytes + blockX) + ((y & 1u) * 0u); + for (uint i = 0; i < 4; i++) { + const uint px = blockX + i; + const uint yIndex = y * g_Pattern.yRowPitchBytes + px + g_Pattern.yOffsetBytes; + const uint yWord = g_Nv12Buffer[yIndex / 4u]; + const uint yValue = (yWord >> ((yIndex & 3u) * 8u)) & 255u; + + const uint uvOffset = uvBase + (i & 2u); + const uint uvWord = g_Nv12Buffer[(uvOffset) / 4u]; + const uint uvShift = (uvOffset & 3u) * 8u; + const uint uValue = (uvWord >> uvShift) & 255u; + const uint vValue = (uvWord >> (uvShift + 8u)) & 255u; + + const float3 decodedRgb = YuvToRgb(yValue, uValue, vValue); + if (g_Pattern.showDifference != 0u) { + const float3 sourceRgb = LoadPatternNv12Rgb(px, y); + const float3 diffRgb = saturate(abs(sourceRgb - decodedRgb) * g_Pattern.diffStrength); + StorePreview(uint2(px, y), float4(diffRgb, 1.0f)); + } else { + StorePreview(uint2(px, y), float4(decodedRgb, 1.0f)); + } + } + } +} diff --git a/Source/VideoEncodeDecode.cpp b/Source/VideoEncodeDecode.cpp new file mode 100644 index 0000000..caef9da --- /dev/null +++ b/Source/VideoEncodeDecode.cpp @@ -0,0 +1,1231 @@ +// © 2021 NVIDIA Corporation + +#if defined(_WIN32) +# include +#endif + +#include "NRIFramework.h" +#include "VideoEncodeDecode/Decoder.h" +#include "VideoEncodeDecode/Encoder.h" +#include "VideoEncodeDecode/Stream.h" + +#include "Extensions/NRIVideo.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using video_sample::AlignUp; +using video_sample::DEFAULT_VIDEO_HEIGHT; +using video_sample::DEFAULT_VIDEO_WIDTH; +using video_sample::GetCodecName; +using video_sample::GetNriCodec; +using video_sample::MakeNv12BufferLayout; +using video_sample::Nv12BufferLayout; +using video_sample::OP_GENERATE_PATTERN; +using video_sample::OP_NV12_TO_PREVIEW; +using video_sample::PatternOperation; +using video_sample::QueuedFrame; +using video_sample::ROUND_TRIP_INTERVAL_SEC; +using video_sample::SampleCodec; +using video_sample::SubmitOneTime; + +struct PatternConstants { + uint32_t width = DEFAULT_VIDEO_WIDTH; + uint32_t height = DEFAULT_VIDEO_HEIGHT; + uint32_t yOffsetBytes = 0; + uint32_t yRowPitchBytes = 0; + uint32_t uvRowPitchBytes = 0; + uint32_t uvOffsetBytes = 0; + uint32_t operation = OP_GENERATE_PATTERN; + float time = 0.0f; + float motionSpeed = 1.0f; + float detailStrength = 1.0f; + float diffStrength = 6.0f; + uint32_t showDifference = 0; + uint32_t frameIndex = 0; +}; + +} // namespace + +class Sample : public SampleBase { +public: + Sample() = default; + ~Sample(); + + bool Initialize(nri::GraphicsAPI graphicsAPI, bool) override; + void InitCmdLine(cmdline::parser& cmdLine) override; + void ReadCmdLine(cmdline::parser& cmdLine) override; + void LatencySleep(uint32_t frameIndex) override; + void PrepareFrame(uint32_t frameIndex) override; + void RenderFrame(uint32_t frameIndex) override; + bool AppShouldClose() override; + +private: + bool InitializeGraphics(nri::GraphicsAPI graphicsAPI); + bool TryInitializePreviewTextures(nri::GraphicsAPI graphicsAPI); + void InitializeGeneratedFrames(float timeSec); + bool CanRunRoundTrip() const; + void TryInitializeVideo(nri::GraphicsAPI graphicsAPI); + PatternConstants MakePatternConstants(PatternOperation operation, float timeSec) const; + bool GeneratePatternWithCompute(const PatternConstants& constants, nri::Descriptor* previewTexture, bool returnSourceBufferToShaderStorage = false, nri::AccessStage uploadBufferBefore = {}); + bool TryRunRoundTrip(float timeSec); + int32_t RunHeadless(nri::GraphicsAPI graphicsAPI); + void DrawTexturePanel(const char* label, nri::Descriptor* texture, const ImVec2& size); + +private: + NRIInterface NRI = {}; + nri::VideoInterface Video = {}; + std::unique_ptr m_Encoder; + std::unique_ptr m_Decoder; + video_sample::VideoConfig m_VideoConfig = {}; + video_sample::VideoQuality m_VideoQuality = {}; + video_sample::VideoSize m_VideoSize = {}; + video_sample::CodecParameters m_CodecParameters = {}; + nri::GraphicsAPI m_GraphicsAPI = nri::GraphicsAPI::NONE; + + nri::Device* m_Device = nullptr; + nri::Streamer* m_Streamer = nullptr; + nri::SwapChain* m_SwapChain = nullptr; + nri::Queue* m_GraphicsQueue = nullptr; + nri::Queue* m_VideoEncodeQueue = nullptr; + nri::Queue* m_VideoDecodeQueue = nullptr; + nri::Fence* m_FrameFence = nullptr; + + nri::Texture* m_SourcePreviewTexture = nullptr; + nri::Texture* m_DecodePreviewTexture = nullptr; + nri::Buffer* m_UploadBuffer = nullptr; + nri::Descriptor* m_UploadBufferView = nullptr; + nri::Descriptor* m_SourcePreviewStorage = nullptr; + nri::Descriptor* m_DecodePreviewStorage = nullptr; + nri::Descriptor* m_SourcePreviewTextureView = nullptr; + nri::Descriptor* m_DecodePreviewTextureView = nullptr; + nri::PipelineLayout* m_GeneratePipelineLayout = nullptr; + nri::Pipeline* m_GenerateComputePipeline = nullptr; + nri::DescriptorPool* m_GenerateDescriptorPool = nullptr; + nri::DescriptorSet* m_GenerateDescriptorSet = nullptr; + std::vector m_QueuedFrames; + std::vector m_SwapChainTextures; + + Nv12BufferLayout m_Nv12Layout = {}; + std::vector m_Plans; + size_t m_PlanIndex = 0; + video_sample::StreamOptions m_StreamOptions = {}; + std::string m_StreamMode; // "", "stream", "matrix", "list", "decodeFile" + std::string m_DecodeFile; + std::string m_RefYuv; + std::string m_CaseFilter; + std::string m_GopArg; + std::string m_DecodeDpbArg = "auto"; + std::string m_DpbLayoutArg = "auto"; + std::string m_EncodeInputArg = "outputOnly"; + std::string m_FeedbackArg = "on"; + std::string m_Av1InfoArg = "auto"; + std::string m_RateControlArg = "cqp"; + std::string m_RateControlChangeArg; + std::string m_H264IdsArg = "0,0"; + std::string m_H265IdsArg = "0,0,0"; + std::string m_DumpArg; + std::string m_NameArg = "stream"; + nri::Format m_SwapChainFormat = nri::Format::UNKNOWN; + std::string m_VideoStatus = "Initializing video"; + std::string m_PreviewStatus = "Initializing preview"; + std::string m_CodecArg = "H264"; + std::string m_AV1FrameArg = "IDR"; + std::string m_H26FrameArg = "IDR"; + uint32_t m_VideoWidth = DEFAULT_VIDEO_WIDTH; + uint32_t m_VideoHeight = DEFAULT_VIDEO_HEIGHT; + uint32_t m_CodedVideoWidth = DEFAULT_VIDEO_WIDTH; + uint32_t m_CodedVideoHeight = DEFAULT_VIDEO_HEIGHT; + uint32_t m_DecodeBitstreamSizeAlignment = 256; + uint32_t m_QpI = 20; + uint32_t m_QpP = 22; + uint32_t m_QpB = 24; + uint32_t m_AV1BaseQIndex = 20; + bool m_Lossless = false; + float m_PatternMotionSpeed = 1.0f; + float m_PatternDetailStrength = 1.0f; + float m_DiffStrength = 6.0f; + PatternConstants m_PendingEncodedPatternConstants = {}; + SampleCodec m_Codec = SampleCodec::H264; + video_sample::VisualFrameMode m_H26FrameMode = video_sample::VisualFrameMode::IDR; + double m_StartTimeSec = 0.0; + double m_LastRoundTripTimeSec = -ROUND_TRIP_INTERVAL_SEC; + bool m_VideoReady = false; + bool m_VideoQueuesRequested = false; + bool m_EnhancedBarriers = false; + bool m_DecodePreviewReady = false; + bool m_PreviewTexturesShaderReadable = false; + bool m_SourcePreviewReady = false; + bool m_AV1PFrameVisual = false; + bool m_ShowDifference = false; + bool m_HasPendingEncodedPatternConstants = false; + bool m_RequireVideoRoundTrip = false; + bool m_VideoSizeExplicit = false; + bool m_SmokeRoundTripComplete = false; + bool m_SmokeRoundTripFailed = false; + uint32_t m_PatternFrameIndex = 0; +}; + +Sample::~Sample() { + if (NRI.HasCore()) { + NRI.DeviceWaitIdle(m_Device); + + m_Decoder.reset(); + m_Encoder.reset(); + + if (m_GenerateDescriptorPool) + NRI.DestroyDescriptorPool(m_GenerateDescriptorPool); + if (m_GenerateComputePipeline) + NRI.DestroyPipeline(m_GenerateComputePipeline); + if (m_GeneratePipelineLayout) + NRI.DestroyPipelineLayout(m_GeneratePipelineLayout); + if (m_UploadBufferView) + NRI.DestroyDescriptor(m_UploadBufferView); + if (m_UploadBuffer) + NRI.DestroyBuffer(m_UploadBuffer); + if (m_SourcePreviewStorage) + NRI.DestroyDescriptor(m_SourcePreviewStorage); + if (m_DecodePreviewStorage) + NRI.DestroyDescriptor(m_DecodePreviewStorage); + if (m_SourcePreviewTextureView) + NRI.DestroyDescriptor(m_SourcePreviewTextureView); + if (m_DecodePreviewTextureView) + NRI.DestroyDescriptor(m_DecodePreviewTextureView); + if (m_SourcePreviewTexture) + NRI.DestroyTexture(m_SourcePreviewTexture); + if (m_DecodePreviewTexture) + NRI.DestroyTexture(m_DecodePreviewTexture); + for (QueuedFrame& queuedFrame : m_QueuedFrames) { + NRI.DestroyCommandBuffer(queuedFrame.commandBuffer); + NRI.DestroyCommandAllocator(queuedFrame.commandAllocator); + } + + for (SwapChainTexture& swapChainTexture : m_SwapChainTextures) { + NRI.DestroyFence(swapChainTexture.acquireSemaphore); + NRI.DestroyFence(swapChainTexture.releaseSemaphore); + NRI.DestroyDescriptor(swapChainTexture.colorAttachment); + } + + NRI.DestroyFence(m_FrameFence); + } + + if (NRI.HasSwapChain()) + NRI.DestroySwapChain(m_SwapChain); + + if (NRI.HasStreamer()) + NRI.DestroyStreamer(m_Streamer); + + DestroyImgui(); + + if (m_Device) + nri::nriDestroyDevice(m_Device); +} + +void Sample::InitCmdLine(cmdline::parser& cmdLine) { + cmdLine.add("codec", 0, "video codec: H264, H265, or AV1", false, m_CodecArg, cmdline::oneof("H264", "H265", "AV1")); + cmdLine.add("av1Frame", 0, "AV1 visual frame permutation: IDR or P", false, m_AV1FrameArg, cmdline::oneof("IDR", "P")); + cmdLine.add("h26Frame", 0, "H.264/H.265 visual frame permutation: IDR, P, or B", false, m_H26FrameArg, cmdline::oneof("IDR", "P", "B")); + cmdLine.add("videoWidth", 0, "NV12 video encode/decode width", false, m_VideoWidth); + cmdLine.add("videoHeight", 0, "NV12 video encode/decode height", false, m_VideoHeight); + cmdLine.add("qpI", 0, "CQP quantizer for I/IDR frames", false, m_QpI); + cmdLine.add("qpP", 0, "CQP quantizer for P frames", false, m_QpP); + cmdLine.add("qpB", 0, "CQP quantizer for B frames", false, m_QpB); + cmdLine.add("av1BaseQIndex", 0, "AV1 base quantizer index", false, m_AV1BaseQIndex); + cmdLine.add("lossless", 0, "force zero quantizers for lossless-capable codec modes"); + cmdLine.add("requireVideoRoundTrip", 0, "exit smoke runs only after a real encode/decode round trip"); + + // Headless runs: encode -> decode of a generated frame sequence, PSNR check, exit code 0 = pass, 1 = fail, 2 = unsupported (NRI validation is always on) + cmdLine.add("stream", 0, "headless: encode and decode a frame sequence with the options below, then exit"); + cmdLine.add("matrix", 0, "headless: run the built-in case matrix (640x360 base size), then exit"); + cmdLine.add("listCases", 0, "list the built-in matrix cases and exit"); + cmdLine.add("case", 0, "matrix: run only the case with this name, or the cases whose name contains this text", false, ""); + cmdLine.add("frames", 0, "stream: number of frames", false, 8); + cmdLine.add("gop", 0, "stream: kinds of the frames after the first IDR in display order, repeated: P, p (non-reference P), B (non-reference), I (IDR); e.g. BBP", false, m_GopArg); + cmdLine.add("refs", 0, "stream: maximum number of reference frames, 1..8 (B pictures need 2, AV1 uses 1)", false, 1); + cmdLine.add("idrPeriod", 0, "stream: IDR period in frames, 0 - only the first frame", false, 0); + cmdLine.add("decodeDpb", 0, "stream: decode output and DPB setup picture", false, m_DecodeDpbArg, cmdline::oneof("auto", "coincide", "distinct")); + cmdLine.add("dpbLayout", 0, "stream: DPB pictures as layers of one texture or separate textures", false, m_DpbLayoutArg, cmdline::oneof("auto", "array", "separate")); + cmdLine.add("encodeInput", 0, "stream: encode source texture usage", false, m_EncodeInputArg, cmdline::oneof("outputOnly", "plain")); + cmdLine.add("rc", 0, "stream: rate control mode", false, m_RateControlArg, cmdline::oneof("cqp", "cbr", "vbr")); + cmdLine.add("bitrate", 0, "stream: CBR/VBR target bitrate in kbit/s", false, 4000); + cmdLine.add("maxBitrate", 0, "stream: VBR peak bitrate in kbit/s, 0 - target", false, 0); + cmdLine.add("rcChange", 0, "stream: change rate control at a coding index, FRAME:MODE:KBPS[:MAXKBPS], e.g. 4:vbr:2000:4000", false, ""); + cmdLine.add("feedback", 0, "stream: resolve encode feedback, 'off' scans the bitstream", false, m_FeedbackArg, cmdline::oneof("on", "off")); + cmdLine.add("av1Info", 0, "stream: AV1 decode info source, metadata uses the submitted descriptions only (D3D12)", false, m_Av1InfoArg, cmdline::oneof("auto", "header", "metadata")); + cmdLine.add("h264Ids", 0, "stream: H.264 SPS,PPS ids", false, m_H264IdsArg); + cmdLine.add("h264PpsRefs", 0, "stream: H.264 PPS num_ref_idx_l0_default_active_minus1", false, 0); + cmdLine.add("codedAlign", 0, "stream: minimum alignment of the coded size", false, 1); + cmdLine.add("qpMin", 0, "stream: CBR/VBR QP range minimum", false, 0); + cmdLine.add("qpMax", 0, "stream: CBR/VBR QP range maximum", false, 0); + cmdLine.add("maxFrameBits", 0, "stream: CBR/VBR maximum frame size in bits", false, 0); + cmdLine.add("vbvMs", 0, "stream: CBR/VBR virtual buffer size in ms", false, 0); + cmdLine.add("vbvInitialMs", 0, "stream: CBR/VBR initial virtual buffer fullness in ms", false, 0); + cmdLine.add("picturePlanes", 0, "video picture barriers address the planes with ALL, COLOR or PLANES (PLANE_0 | PLANE_1)", false, "all", cmdline::oneof("all", "color", "planes")); + cmdLine.add("enhancedBarriers", 0, "D3D12: use enhanced barriers (off by default for the video queues)"); + cmdLine.add("h265Ids", 0, "stream: H.265 VPS,SPS,PPS ids", false, m_H265IdsArg); + cmdLine.add("h265DefaultParams", 0, "stream: create the H.265 encode session without parameter sets (backend defaults, level by size)"); + cmdLine.add("noH265ListsModification", 0, "stream: clear the H.265 PPS lists_modification_present_flag"); + cmdLine.add("noReverseRefs", 0, "stream: H.265 encode references are always passed in the same order"); + cmdLine.add("noReverseDecodeRefs", 0, "stream: H.265 decode references are always passed in the same order"); + cmdLine.add("decodeFile", 0, "headless: decode an AV1 OBU file (one OBU_FRAME per picture, e.g. from libaom) instead of encoding", false, ""); + cmdLine.add("refYuv", 0, "decodeFile: NV12 reference of the shown pictures, the decode must be bit-exact", false, ""); + cmdLine.add("verbose", 0, "headless: log every picture before it is submitted"); + cmdLine.add("encodeOnly", 0, "stream: skip the decoder (the encoded stream is still dumped)"); + cmdLine.add("dump", 0, "headless: write stream, decoded.yuv, source.yuv and frames.csv of every case into this directory", false, ""); + cmdLine.add("minPsnr", 0, "stream: minimum luma PSNR in dB per frame", false, 30.0); + cmdLine.add("name", 0, "stream: name of the run (dump subdirectory)", false, m_NameArg); +} + +static bool ParseIds(const std::string& text, uint32_t* values, uint32_t count) { + uint32_t parsed = 0; + const char* p = text.c_str(); + while (*p && parsed < count) { + char* end = nullptr; + const unsigned long value = std::strtoul(p, &end, 10); + if (end == p || value > 255) + return false; + values[parsed++] = (uint32_t)value; + p = *end == ',' ? end + 1 : end; + } + return parsed == count && !*p; +} + +void Sample::ReadCmdLine(cmdline::parser& cmdLine) { + m_CodecArg = cmdLine.get("codec"); + m_AV1FrameArg = cmdLine.get("av1Frame"); + m_H26FrameArg = cmdLine.get("h26Frame"); + m_VideoWidth = cmdLine.get("videoWidth"); + m_VideoHeight = cmdLine.get("videoHeight"); + if (!cmdLine.exist("videoWidth") && cmdLine.exist("width")) + m_VideoWidth = m_OutputResolution.x; + if (!cmdLine.exist("videoHeight") && cmdLine.exist("height")) + m_VideoHeight = m_OutputResolution.y; + m_QpI = cmdLine.get("qpI"); + m_QpP = cmdLine.get("qpP"); + m_QpB = cmdLine.get("qpB"); + m_AV1BaseQIndex = cmdLine.get("av1BaseQIndex"); + m_Lossless = cmdLine.exist("lossless"); + m_RequireVideoRoundTrip = cmdLine.exist("requireVideoRoundTrip"); + m_Codec = m_CodecArg == "H265" ? SampleCodec::H265 : (m_CodecArg == "AV1" ? SampleCodec::AV1 : SampleCodec::H264); + m_H26FrameMode = m_H26FrameArg == "B" ? video_sample::VisualFrameMode::B : (m_H26FrameArg == "P" ? video_sample::VisualFrameMode::P : video_sample::VisualFrameMode::IDR); + m_AV1PFrameVisual = m_Codec == SampleCodec::AV1 && m_AV1FrameArg == "P"; + + // Headless + m_StreamMode = cmdLine.exist("listCases") ? "list" : (cmdLine.exist("matrix") ? "matrix" : (cmdLine.exist("stream") ? "stream" : "")); + if (cmdLine.exist("decodeFile")) { + m_StreamMode = "decodeFile"; + m_DecodeFile = cmdLine.get("decodeFile"); + m_RefYuv = cmdLine.get("refYuv"); + } + m_CaseFilter = cmdLine.get("case"); + m_VideoSizeExplicit = cmdLine.exist("videoWidth") || cmdLine.exist("videoHeight"); + + video_sample::StreamOptions& options = m_StreamOptions; + options.name = cmdLine.get("name"); + options.config.codec = m_Codec; + options.config.videoWidth = m_VideoWidth; + options.config.videoHeight = m_VideoHeight; + options.config.referenceNum = cmdLine.get("refs"); + options.config.h264TransformBypass = m_Lossless; + options.config.h265ListsModification = !cmdLine.exist("noH265ListsModification"); + options.config.reverseReferences = !cmdLine.exist("noReverseRefs"); + options.config.reverseDecodeReferences = !cmdLine.exist("noReverseDecodeRefs"); + options.config.codedAlignment = std::max(cmdLine.get("codedAlign"), 1u); + options.config.h264PpsRefIdxL0DefaultActiveMinus1 = (uint8_t)cmdLine.get("h264PpsRefs"); + const std::string decodeDpb = cmdLine.get("decodeDpb"); + options.config.decodeDpb = decodeDpb == "coincide" ? video_sample::DecodeDpbMode::COINCIDE : (decodeDpb == "distinct" ? video_sample::DecodeDpbMode::DISTINCT : video_sample::DecodeDpbMode::AUTO); + const std::string dpbLayout = cmdLine.get("dpbLayout"); + options.config.dpbLayout = dpbLayout == "array" ? video_sample::DpbLayout::ARRAY : (dpbLayout == "separate" ? video_sample::DpbLayout::SEPARATE : video_sample::DpbLayout::AUTO); + options.config.encodeInputOutputOnly = cmdLine.get("encodeInput") == "outputOnly"; + options.config.encodeFeedback = cmdLine.get("feedback") == "on"; + const std::string av1Info = cmdLine.get("av1Info"); + options.config.av1Info = av1Info == "header" ? video_sample::Av1InfoMode::HEADER : (av1Info == "metadata" ? video_sample::Av1InfoMode::METADATA : video_sample::Av1InfoMode::AUTO); + options.config.h265DefaultParameters = cmdLine.exist("h265DefaultParams"); + uint32_t h264Ids[2] = {}; + uint32_t h265Ids[3] = {}; + if (!ParseIds(cmdLine.get("h264Ids"), h264Ids, 2) || !ParseIds(cmdLine.get("h265Ids"), h265Ids, 3)) + std::fprintf(stderr, "Invalid --h264Ids / --h265Ids, expected comma-separated numbers\n"); + options.config.h264SpsId = (uint8_t)h264Ids[0]; + options.config.h264PpsId = (uint8_t)h264Ids[1]; + options.config.h265VpsId = (uint8_t)h265Ids[0]; + options.config.h265SpsId = (uint8_t)h265Ids[1]; + options.config.h265PpsId = (uint8_t)h265Ids[2]; + + options.frameNum = cmdLine.get("frames"); + options.gop = cmdLine.get("gop"); + options.idrPeriod = cmdLine.get("idrPeriod"); + options.minPsnr = cmdLine.get("minPsnr"); + options.encodeOnly = cmdLine.exist("encodeOnly"); + options.verbose = cmdLine.exist("verbose"); + options.dumpDir = cmdLine.get("dump"); + + options.quality.qpI = m_QpI; + options.quality.qpP = m_QpP; + options.quality.qpB = m_QpB; + options.quality.av1BaseQIndex = m_AV1BaseQIndex; + options.quality.lossless = m_Lossless; + const std::string rc = cmdLine.get("rc"); + options.quality.rateControl.kind = rc == "cbr" ? video_sample::RateControlKind::CBR : (rc == "vbr" ? video_sample::RateControlKind::VBR : video_sample::RateControlKind::CQP); + options.quality.rateControl.bitrateKbps = cmdLine.get("bitrate"); + options.quality.rateControl.maxBitrateKbps = cmdLine.get("maxBitrate"); + options.quality.rateControl.qpMin = cmdLine.get("qpMin"); + options.quality.rateControl.qpMax = cmdLine.get("qpMax"); + options.quality.rateControl.maxFrameBits = cmdLine.get("maxFrameBits"); + options.quality.rateControl.vbvMs = cmdLine.get("vbvMs"); + options.quality.rateControl.vbvInitialMs = cmdLine.get("vbvInitialMs"); + m_EnhancedBarriers = cmdLine.exist("enhancedBarriers"); + const std::string picturePlanes = cmdLine.get("picturePlanes"); + video_sample::g_PicturePlanes = picturePlanes == "color" ? nri::PlaneBits::COLOR : (picturePlanes == "planes" ? (nri::PlaneBits::PLANE_0 | nri::PlaneBits::PLANE_1) : nri::PlaneBits::ALL); + + // FRAME:MODE:KBPS[:MAXKBPS] + const std::string rcChange = cmdLine.get("rcChange"); + if (!rcChange.empty()) { + char mode[8] = {}; + uint32_t frame = 0; + uint32_t kbps = 0; + uint32_t maxKbps = 0; + const int32_t parsed = std::sscanf(rcChange.c_str(), "%u:%7[a-z]:%u:%u", &frame, mode, &kbps, &maxKbps); + if (parsed < 2) { + std::fprintf(stderr, "Invalid --rcChange, expected FRAME:MODE:KBPS[:MAXKBPS]\n"); + } else { + options.rateControlChangeFrame = (int32_t)frame; + options.rateControlB.kind = !std::strcmp(mode, "cbr") ? video_sample::RateControlKind::CBR : (!std::strcmp(mode, "vbr") ? video_sample::RateControlKind::VBR : video_sample::RateControlKind::CQP); + options.rateControlB.bitrateKbps = parsed >= 3 ? kbps : 4000; + options.rateControlB.maxBitrateKbps = parsed >= 4 ? maxKbps : 0; + } + } +} + +bool Sample::Initialize(nri::GraphicsAPI graphicsAPI, bool) { + if (!m_VideoWidth || !m_VideoHeight || (m_VideoWidth % 4) != 0 || (m_VideoHeight % 2) != 0 || m_VideoWidth > 65535 || m_VideoHeight > 65535) { + m_VideoStatus = "Video size must be non-zero, width must be divisible by 4, height must be even, and both dimensions must fit 16-bit video descriptors"; + std::fprintf(stderr, "%s\n", m_VideoStatus.c_str()); + return false; + } + const uint32_t minCodecQp = m_Codec == SampleCodec::AV1 ? 1 : 0; + const uint32_t maxCodecQp = m_Codec == SampleCodec::AV1 ? 255 : 51; + if (m_QpI < minCodecQp || m_QpI > maxCodecQp || m_QpP < minCodecQp || m_QpP > maxCodecQp || m_QpB < minCodecQp || m_QpB > maxCodecQp || m_AV1BaseQIndex < minCodecQp || m_AV1BaseQIndex > 255) { + m_VideoStatus = m_Codec == SampleCodec::AV1 ? "AV1 quantizers must be in the 1..255 range on current hardware encode paths" : "H.264/H.265 QP values must be in the 0..51 range"; + std::fprintf(stderr, "%s\n", m_VideoStatus.c_str()); + return false; + } + + if (!m_StreamMode.empty()) + std::exit(RunHeadless(graphicsAPI)); + + m_GraphicsAPI = graphicsAPI; + m_VideoConfig.codec = m_Codec; + m_VideoConfig.videoWidth = m_VideoWidth; + m_VideoConfig.videoHeight = m_VideoHeight; + m_VideoConfig.h264TransformBypass = m_Lossless; + m_VideoConfig.av1PFrameVisual = m_AV1PFrameVisual; + m_VideoConfig.h26FrameMode = m_H26FrameMode; + m_VideoConfig.hasBFrames = m_Codec != SampleCodec::AV1 && m_H26FrameMode == video_sample::VisualFrameMode::B; + m_VideoConfig.referenceNum = m_VideoConfig.hasBFrames ? 2 : 1; + m_VideoQuality.qpI = m_QpI; + m_VideoQuality.qpP = m_QpP; + m_VideoQuality.qpB = m_QpB; + m_VideoQuality.av1BaseQIndex = m_AV1BaseQIndex; + m_VideoQuality.lossless = m_Lossless; + + // Interactive cycle: IDR, IDR + P, or IDR + P + B (decoded as IDR, P, B), the last picture is displayed + const char* gop = m_Codec == SampleCodec::AV1 ? (m_AV1PFrameVisual ? "P" : "I") : (m_H26FrameMode == video_sample::VisualFrameMode::B ? "BP" : (m_H26FrameMode == video_sample::VisualFrameMode::P ? "P" : "I")); + m_Plans = video_sample::BuildFramePlans(m_VideoConfig, gop, 1 + (uint32_t)std::strlen(gop) - (gop[0] == 'I' ? 1 : 0), 0); + m_VideoConfig.reorderNum = video_sample::GetReorderNum(m_Plans); + for (video_sample::FramePlan& plan : m_Plans) + plan.isDisplay = &plan == &m_Plans.back(); + + if (!InitializeGraphics(graphicsAPI)) + return false; + + m_StartTimeSec = m_Timer.GetTimeStamp() * 0.001; + if (!TryInitializePreviewTextures(graphicsAPI)) + return false; + TryInitializeVideo(graphicsAPI); + InitializeGeneratedFrames(0.0f); + + return InitImgui(*m_Device); +} + +bool Sample::InitializeGraphics(nri::GraphicsAPI graphicsAPI) { + nri::AdapterDesc adapterDesc[2] = {}; + uint32_t adapterDescsNum = helper::GetCountOf(adapterDesc); + NRI_ABORT_ON_FAILURE(nri::nriEnumerateAdapters(adapterDesc, adapterDescsNum)); + + const nri::AdapterDesc& selectedAdapter = adapterDesc[std::min(m_AdapterIndex, adapterDescsNum - 1)]; + m_VideoQueuesRequested = graphicsAPI != nri::GraphicsAPI::D3D11 && selectedAdapter.queueNum[(uint32_t)nri::QueueType::VIDEO_ENCODE] && selectedAdapter.queueNum[(uint32_t)nri::QueueType::VIDEO_DECODE]; + + nri::QueueFamilyDesc queueFamilies[3] = {}; + uint32_t queueFamilyNum = 0; + queueFamilies[queueFamilyNum].queueNum = 1; + queueFamilies[queueFamilyNum++].queueType = nri::QueueType::GRAPHICS; + if (m_VideoQueuesRequested) { + queueFamilies[queueFamilyNum].queueNum = 1; + queueFamilies[queueFamilyNum++].queueType = nri::QueueType::VIDEO_ENCODE; + queueFamilies[queueFamilyNum].queueNum = 1; + queueFamilies[queueFamilyNum++].queueType = nri::QueueType::VIDEO_DECODE; + } + + nri::DeviceCreationDesc deviceCreationDesc = {}; + + deviceCreationDesc.graphicsAPI = graphicsAPI; + deviceCreationDesc.enableGraphicsAPIValidation = m_DebugAPI; + deviceCreationDesc.enableNRIValidation = m_DebugNRI; + deviceCreationDesc.enableD3D11CommandBufferEmulation = D3D11_ENABLE_COMMAND_BUFFER_EMULATION; + // D3D12 video encode command lists fail to close with enhanced barriers enabled. + deviceCreationDesc.disableD3D12EnhancedBarriers = graphicsAPI == nri::GraphicsAPI::D3D12 ? !m_EnhancedBarriers : D3D12_DISABLE_ENHANCED_BARRIERS; + deviceCreationDesc.vkBindingOffsets = VK_BINDING_OFFSETS; + deviceCreationDesc.adapterDesc = &selectedAdapter; + deviceCreationDesc.allocationCallbacks = m_AllocationCallbacks; + deviceCreationDesc.queueFamilies = queueFamilies; + deviceCreationDesc.queueFamilyNum = queueFamilyNum; + NRI_ABORT_ON_FAILURE(nri::nriCreateDevice(deviceCreationDesc, m_Device)); + + NRI_ABORT_ON_FAILURE(nri::nriGetInterface(*m_Device, NRI_INTERFACE(nri::CoreInterface), (nri::CoreInterface*)&NRI)); + NRI_ABORT_ON_FAILURE(nri::nriGetInterface(*m_Device, NRI_INTERFACE(nri::HelperInterface), (nri::HelperInterface*)&NRI)); + NRI_ABORT_ON_FAILURE(nri::nriGetInterface(*m_Device, NRI_INTERFACE(nri::StreamerInterface), (nri::StreamerInterface*)&NRI)); + NRI_ABORT_ON_FAILURE(nri::nriGetInterface(*m_Device, NRI_INTERFACE(nri::SwapChainInterface), (nri::SwapChainInterface*)&NRI)); + m_Nv12Layout = MakeNv12BufferLayout(NRI.GetDeviceDesc(*m_Device), m_VideoWidth, m_VideoHeight); + + nri::StreamerDesc streamerDesc = {}; + streamerDesc.dynamicBufferMemoryLocation = nri::MemoryLocation::HOST_UPLOAD; + streamerDesc.dynamicBufferDesc = {0, 0, nri::BufferUsageBits::VERTEX | nri::BufferUsageBits::INDEX}; + streamerDesc.constantBufferMemoryLocation = nri::MemoryLocation::HOST_UPLOAD; + streamerDesc.queuedFrameNum = GetQueuedFrameNum(); + streamerDesc.hostDataCapacity = IMGUI_HOST_DATA_CAPACITY; + NRI_ABORT_ON_FAILURE(NRI.CreateStreamer(*m_Device, streamerDesc, m_Streamer)); + + NRI_ABORT_ON_FAILURE(NRI.GetQueue(*m_Device, nri::QueueType::GRAPHICS, 0, m_GraphicsQueue)); + NRI_ABORT_ON_FAILURE(NRI.CreateFence(*m_Device, 0, m_FrameFence)); + + nri::SwapChainDesc swapChainDesc = {}; + swapChainDesc.window = GetWindow(); + swapChainDesc.queue = m_GraphicsQueue; + swapChainDesc.format = nri::SwapChainFormat::BT709_G22_8BIT; + swapChainDesc.flags = (m_Vsync ? nri::SwapChainBits::VSYNC : nri::SwapChainBits::NONE) | nri::SwapChainBits::ALLOW_TEARING; + swapChainDesc.width = (uint16_t)GetOutputResolution().x; + swapChainDesc.height = (uint16_t)GetOutputResolution().y; + swapChainDesc.textureNum = GetOptimalSwapChainTextureNum(); + swapChainDesc.queuedFrameNum = GetQueuedFrameNum(); + NRI_ABORT_ON_FAILURE(NRI.CreateSwapChain(*m_Device, swapChainDesc, m_SwapChain)); + + uint32_t swapChainTextureNum; + nri::Texture* const* swapChainTextures = NRI.GetSwapChainTextures(*m_SwapChain, swapChainTextureNum); + m_SwapChainFormat = NRI.GetTextureDesc(*swapChainTextures[0]).format; + + for (uint32_t i = 0; i < swapChainTextureNum; i++) { + nri::TextureViewDesc textureViewDesc = {swapChainTextures[i], nri::TextureView::COLOR_ATTACHMENT, m_SwapChainFormat}; + + nri::Descriptor* colorAttachment = nullptr; + NRI_ABORT_ON_FAILURE(NRI.CreateTextureView(textureViewDesc, colorAttachment)); + + nri::Fence* acquireSemaphore = nullptr; + NRI_ABORT_ON_FAILURE(NRI.CreateFence(*m_Device, nri::SWAPCHAIN_SEMAPHORE, acquireSemaphore)); + + nri::Fence* releaseSemaphore = nullptr; + NRI_ABORT_ON_FAILURE(NRI.CreateFence(*m_Device, nri::SWAPCHAIN_SEMAPHORE, releaseSemaphore)); + + SwapChainTexture& swapChainTexture = m_SwapChainTextures.emplace_back(); + swapChainTexture = {}; + swapChainTexture.acquireSemaphore = acquireSemaphore; + swapChainTexture.releaseSemaphore = releaseSemaphore; + swapChainTexture.texture = swapChainTextures[i]; + swapChainTexture.colorAttachment = colorAttachment; + swapChainTexture.attachmentFormat = m_SwapChainFormat; + } + + m_QueuedFrames.resize(GetQueuedFrameNum() + swapChainTextureNum); + for (QueuedFrame& queuedFrame : m_QueuedFrames) { + NRI_ABORT_ON_FAILURE(NRI.CreateCommandAllocator(*m_GraphicsQueue, queuedFrame.commandAllocator)); + NRI_ABORT_ON_FAILURE(NRI.CreateCommandBuffer(*queuedFrame.commandAllocator, queuedFrame.commandBuffer)); + } + + return true; +} + +PatternConstants Sample::MakePatternConstants(PatternOperation operation, float timeSec) const { + PatternConstants patternConstants = {}; + patternConstants.width = m_VideoWidth; + patternConstants.height = m_VideoHeight; + patternConstants.yRowPitchBytes = m_Nv12Layout.yRowPitchBytes; + patternConstants.uvRowPitchBytes = m_Nv12Layout.uvRowPitchBytes; + patternConstants.uvOffsetBytes = (uint32_t)m_Nv12Layout.uvOffsetBytes; + patternConstants.operation = operation; + patternConstants.time = timeSec; + patternConstants.motionSpeed = m_PatternMotionSpeed; + patternConstants.detailStrength = m_PatternDetailStrength; + patternConstants.diffStrength = m_DiffStrength; + patternConstants.showDifference = m_ShowDifference ? 1 : 0; + patternConstants.frameIndex = m_PatternFrameIndex; + return patternConstants; +} + +void Sample::InitializeGeneratedFrames(float timeSec) { + if (!m_SourcePreviewTexture || !m_SourcePreviewStorage || !m_UploadBuffer || !m_UploadBufferView) + return; + + PatternConstants patternConstants = MakePatternConstants(OP_GENERATE_PATTERN, timeSec); + if (!GeneratePatternWithCompute(patternConstants, m_SourcePreviewStorage, true)) { + m_PreviewStatus = "Failed to generate source pattern via compute"; + return; + } + + m_PreviewStatus = "Source preview is generated by compute"; + m_SourcePreviewReady = true; +} + +bool Sample::GeneratePatternWithCompute(const PatternConstants& constants, nri::Descriptor* previewTexture, bool returnSourceBufferToShaderStorage, nri::AccessStage uploadBufferBefore) { + if (!m_GeneratePipelineLayout || !m_GenerateComputePipeline || !m_GenerateDescriptorSet || !m_UploadBufferView || !previewTexture) + return false; + if ((constants.width % 4) != 0 || (constants.height % 2) != 0) + return false; + + const uint32_t dispatchX = (constants.width + 3) / 4; + const uint32_t dispatchY = constants.height; + + const bool previewTexturesShaderReadable = m_PreviewTexturesShaderReadable; + const bool submitted = SubmitOneTime( + NRI, + *m_GraphicsQueue, + m_GenerateDescriptorPool, + [this, &constants, dispatchX, dispatchY, previewTexturesShaderReadable, returnSourceBufferToShaderStorage, uploadBufferBefore](nri::CommandBuffer& commandBuffer) { + nri::SetDescriptorSetDesc descriptorSet = {0, m_GenerateDescriptorSet}; + + nri::BufferBarrierDesc bufferBarrier = {}; + bufferBarrier.buffer = m_UploadBuffer; + bufferBarrier.before = uploadBufferBefore; + bufferBarrier.after = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + + nri::TextureBarrierDesc textureBarriers[2] = {}; + textureBarriers[0].texture = m_SourcePreviewTexture; + textureBarriers[1].texture = m_DecodePreviewTexture; + for (nri::TextureBarrierDesc& textureBarrier : textureBarriers) { + if (previewTexturesShaderReadable) + textureBarrier.before = {nri::AccessBits::SHADER_RESOURCE, nri::Layout::SHADER_RESOURCE, nri::StageBits::ALL}; + else + textureBarrier.before = {nri::AccessBits::NONE, nri::Layout::UNDEFINED, nri::StageBits::ALL}; + textureBarrier.after = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::Layout::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + textureBarrier.mipNum = nri::REMAINING; + textureBarrier.layerNum = nri::REMAINING; + textureBarrier.planes = nri::PlaneBits::ALL; + } + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = &bufferBarrier; + barrierDesc.bufferNum = 1; + barrierDesc.textures = textureBarriers; + barrierDesc.textureNum = helper::GetCountOf(textureBarriers); + + nri::SetRootConstantsDesc rootConstants = {0, &constants, sizeof(PatternConstants)}; + NRI.CmdBarrier(commandBuffer, barrierDesc); + NRI.CmdSetPipelineLayout(commandBuffer, nri::BindPoint::COMPUTE, *m_GeneratePipelineLayout); + NRI.CmdSetDescriptorSet(commandBuffer, descriptorSet); + NRI.CmdSetPipeline(commandBuffer, *m_GenerateComputePipeline); + NRI.CmdSetRootConstants(commandBuffer, rootConstants); + NRI.CmdDispatch(commandBuffer, {dispatchX, dispatchY, 1}); + + bufferBarrier.before = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + if (returnSourceBufferToShaderStorage) + bufferBarrier.after = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + else + bufferBarrier.after = {nri::AccessBits::COPY_SOURCE, nri::StageBits::COPY}; + for (nri::TextureBarrierDesc& textureBarrier : textureBarriers) { + textureBarrier.before = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::Layout::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + textureBarrier.after = {nri::AccessBits::SHADER_RESOURCE, nri::Layout::SHADER_RESOURCE, nri::StageBits::ALL}; + } + NRI.CmdBarrier(commandBuffer, barrierDesc); + }); + + if (submitted) + m_PreviewTexturesShaderReadable = true; + + return submitted; +} + +bool Sample::TryInitializePreviewTextures(nri::GraphicsAPI) { + if (m_SourcePreviewTexture && m_DecodePreviewTexture && m_SourcePreviewTextureView && m_DecodePreviewTextureView) + return true; + + nri::TextureDesc previewTextureDesc = {}; + previewTextureDesc.type = nri::TextureType::TEXTURE_2D; + previewTextureDesc.format = nri::Format::RGBA8_UNORM; + previewTextureDesc.width = (nri::Dim_t)m_VideoWidth; + previewTextureDesc.height = (nri::Dim_t)m_VideoHeight; + previewTextureDesc.mipNum = 1; + previewTextureDesc.layerNum = 1; + previewTextureDesc.usage = nri::TextureUsageBits::SHADER_RESOURCE | nri::TextureUsageBits::SHADER_RESOURCE_STORAGE; + + if (!m_SourcePreviewTexture) { + if (NRI.CreateCommittedTexture(*m_Device, nri::MemoryLocation::DEVICE, 0.0f, previewTextureDesc, m_SourcePreviewTexture) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create source preview texture"; + return false; + } + NRI.SetDebugName(m_SourcePreviewTexture, "VideoSourcePreviewTexture"); + } + + if (!m_DecodePreviewTexture) { + if (NRI.CreateCommittedTexture(*m_Device, nri::MemoryLocation::DEVICE, 0.0f, previewTextureDesc, m_DecodePreviewTexture) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create decode preview texture"; + return false; + } + NRI.SetDebugName(m_DecodePreviewTexture, "VideoDecodePreviewTexture"); + } + + if (!m_PreviewTexturesShaderReadable) { + const bool initialized = SubmitOneTime(NRI, *m_GraphicsQueue, [&](nri::CommandBuffer& commandBuffer) { + nri::TextureBarrierDesc textureBarriers[2] = {}; + textureBarriers[0].texture = m_SourcePreviewTexture; + textureBarriers[1].texture = m_DecodePreviewTexture; + + for (nri::TextureBarrierDesc& textureBarrier : textureBarriers) { + textureBarrier.before = {nri::AccessBits::NONE, nri::Layout::UNDEFINED, nri::StageBits::ALL}; + textureBarrier.after = {nri::AccessBits::SHADER_RESOURCE, nri::Layout::SHADER_RESOURCE, nri::StageBits::ALL}; + textureBarrier.mipNum = nri::REMAINING; + textureBarrier.layerNum = nri::REMAINING; + textureBarrier.planes = nri::PlaneBits::ALL; + } + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.textures = textureBarriers; + barrierDesc.textureNum = helper::GetCountOf(textureBarriers); + NRI.CmdBarrier(commandBuffer, barrierDesc); + }); + + if (!initialized) { + m_PreviewStatus = "Failed to initialize preview texture layouts"; + return false; + } + + m_PreviewTexturesShaderReadable = true; + } + + nri::TextureViewDesc sourceTextureViewDesc = {m_SourcePreviewTexture, nri::TextureView::TEXTURE, previewTextureDesc.format}; + nri::TextureViewDesc decodeTextureViewDesc = {m_DecodePreviewTexture, nri::TextureView::TEXTURE, previewTextureDesc.format}; + + if (!m_SourcePreviewTextureView) { + if (NRI.CreateTextureView(sourceTextureViewDesc, m_SourcePreviewTextureView) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create source preview ImGui texture view"; + return false; + } + } + + if (!m_DecodePreviewTextureView) { + if (NRI.CreateTextureView(decodeTextureViewDesc, m_DecodePreviewTextureView) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create decode preview ImGui texture view"; + return false; + } + } + + nri::TextureViewDesc sourceStorageTextureViewDesc = {m_SourcePreviewTexture, nri::TextureView::STORAGE_TEXTURE, nri::Format::RGBA8_UNORM}; + nri::TextureViewDesc decodeStorageTextureViewDesc = {m_DecodePreviewTexture, nri::TextureView::STORAGE_TEXTURE, nri::Format::RGBA8_UNORM}; + + if (!m_SourcePreviewStorage) { + if (NRI.CreateTextureView(sourceStorageTextureViewDesc, m_SourcePreviewStorage) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create source preview storage texture view"; + return false; + } + } + + if (!m_DecodePreviewStorage) { + if (NRI.CreateTextureView(decodeStorageTextureViewDesc, m_DecodePreviewStorage) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create decode preview storage texture view"; + return false; + } + } + + if (!m_UploadBuffer) { + nri::BufferDesc uploadBufferDesc = {}; + uploadBufferDesc.size = m_Nv12Layout.totalSizeBytes; + uploadBufferDesc.usage = nri::BufferUsageBits::SHADER_RESOURCE_STORAGE; + + if (NRI.CreateCommittedBuffer(*m_Device, nri::MemoryLocation::DEVICE, 0.0f, uploadBufferDesc, m_UploadBuffer) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create compute NV12 buffer"; + return false; + } + } + + if (!m_UploadBufferView) { + nri::BufferViewDesc uploadBufferViewDesc = {}; + uploadBufferViewDesc.buffer = m_UploadBuffer; + uploadBufferViewDesc.format = nri::Format::R32_UINT; + uploadBufferViewDesc.type = nri::BufferView::STORAGE_BUFFER; + uploadBufferViewDesc.size = NRI.GetBufferDesc(*m_UploadBuffer).size; + + if (NRI.CreateBufferView(uploadBufferViewDesc, m_UploadBufferView) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create compute NV12 buffer view"; + return false; + } + } + + if (!m_GeneratePipelineLayout) { + nri::DescriptorRangeDesc descriptorRanges[] = { + {0, 1, nri::DescriptorType::STORAGE_BUFFER, nri::StageBits::COMPUTE_SHADER}, + {1, 1, nri::DescriptorType::STORAGE_TEXTURE, nri::StageBits::COMPUTE_SHADER}, + {2, 1, nri::DescriptorType::STORAGE_TEXTURE, nri::StageBits::COMPUTE_SHADER}, + }; + nri::DescriptorSetDesc descriptorSetDescs[] = {{0, descriptorRanges, helper::GetCountOf(descriptorRanges)}}; + + nri::RootConstantDesc rootConstantDesc = {}; + rootConstantDesc.registerIndex = 0; + rootConstantDesc.size = sizeof(PatternConstants); + rootConstantDesc.shaderStages = nri::StageBits::COMPUTE_SHADER; + + nri::PipelineLayoutDesc pipelineLayoutDesc = {}; + pipelineLayoutDesc.rootConstantNum = 1; + pipelineLayoutDesc.rootConstants = &rootConstantDesc; + pipelineLayoutDesc.descriptorSetNum = helper::GetCountOf(descriptorSetDescs); + pipelineLayoutDesc.descriptorSets = descriptorSetDescs; + pipelineLayoutDesc.shaderStages = nri::StageBits::COMPUTE_SHADER; + if (NRI.CreatePipelineLayout(*m_Device, pipelineLayoutDesc, m_GeneratePipelineLayout) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create compute pipeline layout for pattern generation"; + return false; + } + } + + if (!m_GenerateComputePipeline) { + const nri::DeviceDesc& deviceDesc = NRI.GetDeviceDesc(*m_Device); + utils::ShaderCodeStorage shaderCodeStorage; + nri::ComputePipelineDesc computePipelineDesc = {}; + computePipelineDesc.pipelineLayout = m_GeneratePipelineLayout; + computePipelineDesc.shader = utils::LoadShader(deviceDesc.graphicsAPI, "VideoEncodePattern.cs", shaderCodeStorage); + if (NRI.CreateComputePipeline(*m_Device, computePipelineDesc, m_GenerateComputePipeline) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create pattern generation compute pipeline"; + return false; + } + } + + if (!m_GenerateDescriptorPool) { + nri::DescriptorPoolDesc descriptorPoolDesc = {}; + descriptorPoolDesc.descriptorSetMaxNum = 1; + descriptorPoolDesc.storageBufferMaxNum = 1; + descriptorPoolDesc.storageTextureMaxNum = 2; + if (NRI.CreateDescriptorPool(*m_Device, descriptorPoolDesc, m_GenerateDescriptorPool) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to create compute descriptor pool for pattern generation"; + return false; + } + } + + if (!m_GenerateDescriptorSet) { + if (NRI.AllocateDescriptorSets(*m_GenerateDescriptorPool, *m_GeneratePipelineLayout, 0, &m_GenerateDescriptorSet, 1, 0) != nri::Result::SUCCESS) { + m_PreviewStatus = "Failed to allocate compute descriptor set for pattern generation"; + return false; + } + + nri::UpdateDescriptorRangeDesc updateDescriptorRangeDescs[] = { + {m_GenerateDescriptorSet, 0, 0, &m_UploadBufferView, 1}, + {m_GenerateDescriptorSet, 1, 0, &m_SourcePreviewStorage, 1}, + {m_GenerateDescriptorSet, 2, 0, &m_DecodePreviewStorage, 1}, + }; + NRI.UpdateDescriptorRanges(updateDescriptorRangeDescs, helper::GetCountOf(updateDescriptorRangeDescs)); + } + + return true; +} + +void Sample::TryInitializeVideo(nri::GraphicsAPI graphicsAPI) { + const nri::DeviceDesc& deviceDesc = NRI.GetDeviceDesc(*m_Device); + + if (graphicsAPI == nri::GraphicsAPI::D3D11) { + m_VideoStatus = "D3D11 does not expose NRI video queues"; + return; + } + + if (!m_VideoQueuesRequested || !deviceDesc.adapterDesc.queueNum[(uint32_t)nri::QueueType::VIDEO_ENCODE] || !deviceDesc.adapterDesc.queueNum[(uint32_t)nri::QueueType::VIDEO_DECODE]) { + m_VideoStatus = "Adapter has no NRI video encode/decode queues"; + return; + } + + if (nri::nriGetInterface(*m_Device, NRI_INTERFACE(nri::VideoInterface), &Video) != nri::Result::SUCCESS || !Video.CreateVideoSession) { + m_VideoStatus = "NRI video interface is unavailable"; + return; + } + + if (NRI.GetQueue(*m_Device, nri::QueueType::VIDEO_ENCODE, 0, m_VideoEncodeQueue) != nri::Result::SUCCESS || NRI.GetQueue(*m_Device, nri::QueueType::VIDEO_DECODE, 0, m_VideoDecodeQueue) != nri::Result::SUCCESS) { + m_VideoStatus = "Failed to get video queues"; + return; + } + + video_sample::VideoContext videoContext = {}; + videoContext.nri = &NRI; + videoContext.video = &Video; + videoContext.device = m_Device; + videoContext.graphicsQueue = m_GraphicsQueue; + videoContext.encodeQueue = m_VideoEncodeQueue; + videoContext.decodeQueue = m_VideoDecodeQueue; + videoContext.graphicsAPI = graphicsAPI; + + bool isUnsupported = false; + if (!video_sample::QueryVideoSize(videoContext, m_VideoConfig, m_VideoSize, isUnsupported, m_VideoStatus)) + return; + + m_CodedVideoWidth = m_VideoSize.codedWidth; + m_CodedVideoHeight = m_VideoSize.codedHeight; + m_CodecParameters = video_sample::MakeCodecParameters(graphicsAPI, m_VideoConfig, m_CodedVideoWidth, m_CodedVideoHeight); + + m_Encoder = std::make_unique(); + if (!m_Encoder->Initialize(videoContext, m_VideoConfig, m_VideoSize, m_CodecParameters)) { + m_VideoStatus = m_Encoder->GetStatus(); + return; + } + + m_Decoder = std::make_unique(); + if (!m_Decoder->Initialize(videoContext, m_VideoConfig, m_VideoSize, m_CodecParameters)) { + m_VideoStatus = m_Decoder->GetStatus(); + return; + } + + m_VideoReady = true; + m_VideoStatus = std::string("NRI video queues and ") + GetCodecName(m_Codec) + " encode/decode objects initialized"; +} + +// Encodes and decodes the next picture of the cycle, returns true after the displayed picture +bool Sample::TryRunRoundTrip(float timeSec) { + if (!CanRunRoundTrip()) { + m_VideoStatus = std::string(GetCodecName(m_Codec)) + " round trip is not currently supported in this configuration"; + return false; + } + + const video_sample::FramePlan& plan = m_Plans[m_PlanIndex]; + m_PlanIndex = (m_PlanIndex + 1) % m_Plans.size(); + + m_PatternFrameIndex++; + PatternConstants patternConstants = MakePatternConstants(OP_GENERATE_PATTERN, timeSec); + if (!GeneratePatternWithCompute(patternConstants, m_SourcePreviewStorage, true)) { + m_VideoStatus = "Failed to generate NV12 source pattern via compute"; + return false; + } + m_PendingEncodedPatternConstants = patternConstants; + m_HasPendingEncodedPatternConstants = true; + + video_sample::EncodeRequest encodeRequest = {}; + encodeRequest.nv12Buffer = m_UploadBuffer; + encodeRequest.nv12BufferState = {nri::AccessBits::SHADER_RESOURCE_STORAGE, nri::StageBits::COMPUTE_SHADER}; + encodeRequest.nv12Layout = &m_Nv12Layout; + encodeRequest.nv12Width = m_VideoWidth; + encodeRequest.nv12Height = m_VideoHeight; + encodeRequest.quality = m_VideoQuality; + encodeRequest.plan = plan; + video_sample::EncodedFrame encodedFrame = {}; + if (!m_Encoder->Encode(encodeRequest, encodedFrame)) { + m_VideoStatus = m_Encoder->GetStatus(); + return false; + } + + video_sample::DecodedFrame decodedFrame = {}; + video_sample::DecodeRequest decodeRequest = {}; + decodeRequest.frame = &encodedFrame; + decodeRequest.nv12ReadbackBuffer = m_UploadBuffer; + decodeRequest.nv12Layout = &m_Nv12Layout; + if (!m_Decoder->Decode(decodeRequest, decodedFrame)) { + m_VideoStatus = m_Decoder->GetStatus(); + return false; + } + + if (!plan.isDisplay) + return false; + + patternConstants = m_HasPendingEncodedPatternConstants ? m_PendingEncodedPatternConstants : MakePatternConstants(OP_NV12_TO_PREVIEW, timeSec); + patternConstants.operation = OP_NV12_TO_PREVIEW; + patternConstants.diffStrength = m_DiffStrength; + patternConstants.showDifference = m_ShowDifference ? 1 : 0; + if (!GeneratePatternWithCompute(patternConstants, m_DecodePreviewStorage, true)) { + m_VideoStatus = "Failed to convert decoded NV12 to preview texture"; + return false; + } + m_HasPendingEncodedPatternConstants = false; + m_DecodePreviewReady = true; + + char message[128] = {}; + std::snprintf(message, sizeof(message), "%s encode/decode round trip complete, encoded %llu bytes", GetCodecName(m_Codec), (unsigned long long)encodedFrame.feedback.encodedBitstreamWrittenBytes); + m_VideoStatus = message; + if (!m_SmokeRoundTripComplete) { + std::printf("VIDEO_ROUND_TRIP_OK: %s\n", message); + m_SmokeRoundTripComplete = true; + } + return true; +} + +int32_t Sample::RunHeadless(nri::GraphicsAPI graphicsAPI) { + using namespace video_sample; + + RunEnvironment environment = {}; + environment.graphicsAPI = graphicsAPI; + environment.adapterIndex = m_AdapterIndex; + environment.debugAPI = m_DebugAPI; + environment.debugNRI = true; + environment.enhancedBarriers = m_EnhancedBarriers; + + if (m_StreamMode == "decodeFile") { + const StreamResult result = RunDecodeFile(environment, m_DecodeFile, m_RefYuv, m_StreamOptions.name, m_StreamOptions.dumpDir, m_StreamOptions.verbose); + std::printf("[%s] %s api=%s adapter=\"%s\" frames=%u bytes=%llu psnrY(min/avg)=%.2f/%.2f nriErrors=%u nriWarnings=%u %s%s%s\n", + GetStreamStatusName(result.status), m_StreamOptions.name.c_str(), nri::nriGetGraphicsAPIString(graphicsAPI), result.adapterName.c_str(), result.frameNum, (unsigned long long)result.byteNum, result.psnrMin, result.psnrAvg, result.nriErrorNum, result.nriWarningNum, + result.notes.c_str(), result.message.empty() ? "" : " | ", result.message.c_str()); + std::fflush(stdout); + return result.status == StreamStatus::PASS ? 0 : (result.status == StreamStatus::FAIL ? 1 : 2); + } + + StreamOptions base = m_StreamOptions; + if (m_StreamMode != "stream") { + // Matrix base: small, not 16-aligned (cropping), CQP + base.config = VideoConfig(); + base.config.videoWidth = m_VideoSizeExplicit ? m_VideoWidth : 640; + base.config.videoHeight = m_VideoSizeExplicit ? m_VideoHeight : 360; + base.gop = "P"; + base.frameNum = 8; + base.idrPeriod = 0; + base.minPsnr = 30.0; + base.rateControlChangeFrame = -1; + base.verbose = m_StreamOptions.verbose; + base.encodeOnly = m_StreamOptions.encodeOnly; + } + + std::vector cases; + if (m_StreamMode == "stream") + cases.push_back(base); + else { + // An exact name selects one case, otherwise the filter is a substring + const std::vector all = MakeMatrixCases(base); + bool isExact = false; + for (const StreamOptions& options : all) + isExact = isExact || options.name == m_CaseFilter; + for (const StreamOptions& options : all) { + if (m_CaseFilter.empty() || (isExact ? options.name == m_CaseFilter : options.name.find(m_CaseFilter) != std::string::npos)) + cases.push_back(options); + } + } + + if (m_StreamMode == "list") { + for (const StreamOptions& options : cases) + std::printf("%s\n", options.name.c_str()); + return 0; + } + + uint32_t passNum = 0; + uint32_t failNum = 0; + uint32_t skipNum = 0; + for (const StreamOptions& options : cases) { + const StreamResult result = RunStream(environment, options); + + if (result.status == StreamStatus::PASS) + passNum++; + else if (result.status == StreamStatus::FAIL) + failNum++; + else + skipNum++; + + std::printf("[%s] %s api=%s adapter=\"%s\" frames=%u bytes=%llu psnrY(min/avg)=%.2f/%.2f nriErrors=%u nriWarnings=%u %s%s%s\n", + GetStreamStatusName(result.status), options.name.c_str(), nri::nriGetGraphicsAPIString(graphicsAPI), result.adapterName.c_str(), result.frameNum, (unsigned long long)result.byteNum, result.psnrMin, result.psnrAvg, result.nriErrorNum, result.nriWarningNum, + result.notes.c_str(), result.message.empty() ? "" : " | ", result.message.c_str()); + std::fflush(stdout); + } + + std::printf("SUMMARY: pass=%u fail=%u skip=%u\n", passNum, failNum, skipNum); + std::fflush(stdout); + return failNum ? 1 : (passNum ? 0 : 2); +} + +bool Sample::CanRunRoundTrip() const { + return m_VideoReady && m_Encoder && m_Encoder->IsReady() && m_Decoder && m_Decoder->IsReady() && m_GraphicsQueue && m_VideoEncodeQueue && m_VideoDecodeQueue && m_UploadBuffer && m_UploadBufferView && m_SourcePreviewStorage && m_DecodePreviewStorage && m_GeneratePipelineLayout && m_GenerateComputePipeline && m_GenerateDescriptorSet; +} + +void Sample::LatencySleep(uint32_t frameIndex) { + const uint32_t commandFrameNum = (uint32_t)m_QueuedFrames.size(); + const uint32_t queuedFrameNum = GetQueuedFrameNum(); + uint32_t queuedFrameIndex = frameIndex % commandFrameNum; + const QueuedFrame& queuedFrame = m_QueuedFrames[queuedFrameIndex]; + const uint64_t waitValue = frameIndex >= queuedFrameNum ? 1 + frameIndex - queuedFrameNum : 0; + + NRI.Wait(*m_FrameFence, waitValue); + NRI.ResetCommandAllocator(*queuedFrame.commandAllocator); +} + +void Sample::DrawTexturePanel(const char* label, nri::Descriptor* texture, const ImVec2& size) { + ImGui::Text("%s", label); + if (!texture) { + ImGui::Text("Not ready"); + return; + } + ImGui::Image((ImTextureID)texture, size); +} + +void Sample::PrepareFrame(uint32_t) { + const double timeSec = m_Timer.GetTimeStamp() * 0.001 - m_StartTimeSec; + const bool canRunRoundTrip = CanRunRoundTrip(); + + InitializeGeneratedFrames((float)timeSec); + + if (m_RequireVideoRoundTrip && !m_SmokeRoundTripComplete && !canRunRoundTrip && !m_SmokeRoundTripFailed) { + std::fprintf(stderr, "VIDEO_ROUND_TRIP_FAILED: %s\n", m_VideoStatus.c_str()); + m_SmokeRoundTripFailed = true; + } + + if (canRunRoundTrip && timeSec - m_LastRoundTripTimeSec >= ROUND_TRIP_INTERVAL_SEC) { + if (TryRunRoundTrip((float)timeSec)) + m_LastRoundTripTimeSec = timeSec; + } + + ImGui::NewFrame(); + { + ImGui::SetNextWindowPos({20.0f, 20.0f}, ImGuiCond_Once); + ImGui::SetNextWindowSize({900.0f, 520.0f}, ImGuiCond_Once); + ImGui::Begin("NRI Video Encode / Decode"); + { + const uint32_t minCodecQp = m_Codec == SampleCodec::AV1 ? 1 : 0; + const uint32_t effectiveQpI = m_VideoQuality.lossless ? minCodecQp : std::max(m_VideoQuality.qpI, minCodecQp); + const uint32_t effectiveQpP = m_VideoQuality.lossless ? minCodecQp : std::max(m_VideoQuality.qpP, minCodecQp); + const uint32_t effectiveQpB = m_VideoQuality.lossless ? minCodecQp : std::max(m_VideoQuality.qpB, minCodecQp); + ImGui::Text("Codec: %s, format: NV12, size: %ux%u", GetCodecName(m_Codec), m_VideoWidth, m_VideoHeight); + ImGui::Text("Startup-only: codec, video size, AV1/H.26x frame mode"); + ImGui::Text("CQP: I=%u, P=%u, B=%u%s", effectiveQpI, effectiveQpP, effectiveQpB, m_Codec == SampleCodec::AV1 ? ", AV1 baseQIndex follows below" : ""); + if (m_Codec == SampleCodec::AV1) { + const uint32_t effectiveAv1BaseQIndex = m_VideoQuality.lossless ? 1 : std::max(m_VideoQuality.av1BaseQIndex, 1u); + ImGui::Text("AV1: frame=%s, baseQIndex=%u", m_AV1FrameArg.c_str(), effectiveAv1BaseQIndex); + } else + ImGui::Text("H.26x frame permutation: %s", m_H26FrameArg.c_str()); + ImGui::TextWrapped("Video: %s", m_VideoStatus.c_str()); + ImGui::TextWrapped("Preview: %s", m_PreviewStatus.c_str()); + ImGui::Text("Encode queue: %s, decode queue: %s", m_VideoEncodeQueue ? "yes" : "no", m_VideoDecodeQueue ? "yes" : "no"); + const bool roundTripSupported = CanRunRoundTrip(); + ImGui::Text("Round trip: %s", roundTripSupported ? "running" : "backend must support NRI video encode/decode"); + if (m_VideoReady && !m_DecodePreviewReady) + ImGui::Text("Decode preview: waiting for first decoded frame"); + + ImGui::Separator(); + ImGui::Text("Live controls"); + ImGui::Checkbox("Lossless / zero quantizers", &m_VideoQuality.lossless); + if (m_VideoQuality.lossless) { + if (m_Codec == SampleCodec::AV1) + ImGui::TextWrapped("AV1 hardware encode rejects baseQIndex 0 on current backends, so lossless mode uses near-lossless baseQIndex 1."); + else + ImGui::TextWrapped("%s forces CQP 0%s.", GetCodecName(m_Codec), m_Codec == SampleCodec::H264 ? " with transform bypass advertised in the SPS" : ""); + } + int qpI = (int)m_VideoQuality.qpI; + int qpP = (int)m_VideoQuality.qpP; + int qpB = (int)m_VideoQuality.qpB; + const int qpMin = m_Codec == SampleCodec::AV1 ? 1 : 0; + const int qpMax = m_Codec == SampleCodec::AV1 ? 255 : 51; + if (ImGui::SliderInt("QP I / IDR", &qpI, qpMin, qpMax)) + m_VideoQuality.qpI = (uint32_t)qpI; + if (ImGui::SliderInt("QP P", &qpP, qpMin, qpMax)) + m_VideoQuality.qpP = (uint32_t)qpP; + if (ImGui::SliderInt("QP B", &qpB, qpMin, qpMax)) + m_VideoQuality.qpB = (uint32_t)qpB; + if (m_Codec == SampleCodec::AV1) { + int av1BaseQIndex = (int)m_VideoQuality.av1BaseQIndex; + if (ImGui::SliderInt("AV1 base Q index", &av1BaseQIndex, 1, 255)) + m_VideoQuality.av1BaseQIndex = (uint32_t)av1BaseQIndex; + } + ImGui::SliderFloat("Pattern motion", &m_PatternMotionSpeed, 0.0f, 4.0f, "%.2f"); + ImGui::SliderFloat("Pattern detail", &m_PatternDetailStrength, 0.0f, 2.5f, "%.2f"); + ImGui::Checkbox("Show artifact diff", &m_ShowDifference); + if (m_ShowDifference) + ImGui::SliderFloat("Diff amplification", &m_DiffStrength, 1.0f, 20.0f, "%.1f"); + + ImGui::Separator(); + if (ImGui::BeginTable("PreviewPanels", 2, ImGuiTableFlags_SizingStretchSame)) { + ImGui::TableNextColumn(); + float width = std::max(200.0f, ImGui::GetContentRegionAvail().x); + DrawTexturePanel("Generated source", m_SourcePreviewTextureView, {width, width * float(m_VideoHeight) / float(m_VideoWidth)}); + + ImGui::TableNextColumn(); + width = std::max(200.0f, ImGui::GetContentRegionAvail().x); + DrawTexturePanel(m_DecodePreviewReady ? (m_ShowDifference ? "Artifact diff" : "Decoded preview") : "Decoded preview pending", m_DecodePreviewReady ? m_DecodePreviewTextureView : nullptr, {width, width * float(m_VideoHeight) / float(m_VideoWidth)}); + ImGui::EndTable(); + } + } + ImGui::End(); + } + ImGui::EndFrame(); + ImGui::Render(); +} + +bool Sample::AppShouldClose() { + return m_RequireVideoRoundTrip && (m_SmokeRoundTripComplete || m_SmokeRoundTripFailed); +} + +void Sample::RenderFrame(uint32_t frameIndex) { + uint32_t queuedFrameIndex = frameIndex % (uint32_t)m_QueuedFrames.size(); + const QueuedFrame& queuedFrame = m_QueuedFrames[queuedFrameIndex]; + + uint32_t recycledSemaphoreIndex = frameIndex % (uint32_t)m_SwapChainTextures.size(); + nri::Fence* swapChainAcquireSemaphore = m_SwapChainTextures[recycledSemaphoreIndex].acquireSemaphore; + + uint32_t currentSwapChainTextureIndex = 0; + NRI.AcquireNextTexture(*m_SwapChain, *swapChainAcquireSemaphore, currentSwapChainTextureIndex); + + const SwapChainTexture& swapChainTexture = m_SwapChainTextures[currentSwapChainTextureIndex]; + + nri::CommandBuffer& commandBuffer = *queuedFrame.commandBuffer; + NRI.BeginCommandBuffer(commandBuffer, nullptr); + { + nri::TextureBarrierDesc textureBarriers = {}; + textureBarriers.texture = swapChainTexture.texture; + textureBarriers.after = {nri::AccessBits::COLOR_ATTACHMENT, nri::Layout::COLOR_ATTACHMENT}; + textureBarriers.layerNum = 1; + textureBarriers.mipNum = 1; + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.textureNum = 1; + barrierDesc.textures = &textureBarriers; + NRI.CmdBarrier(commandBuffer, barrierDesc); + + nri::AttachmentDesc colorAttachmentDesc = {}; + colorAttachmentDesc.descriptor = swapChainTexture.colorAttachment; + colorAttachmentDesc.clearValue.color.f = {0.03f, 0.03f, 0.03f, 1.0f}; + colorAttachmentDesc.loadOp = nri::LoadOp::CLEAR; + colorAttachmentDesc.storeOp = nri::StoreOp::STORE; + + nri::RenderingDesc renderingDesc = {}; + renderingDesc.colorNum = 1; + renderingDesc.colors = &colorAttachmentDesc; + + const nri::ImguiRenderData imguiRenderData = CmdCopyImguiData(commandBuffer, *m_Streamer); + + NRI.CmdBeginRendering(commandBuffer, renderingDesc); + CmdDrawImgui(commandBuffer, imguiRenderData, swapChainTexture.attachmentFormat, 1.0f, true); + NRI.CmdEndRendering(commandBuffer); + + textureBarriers.before = textureBarriers.after; + textureBarriers.after = {nri::AccessBits::NONE, nri::Layout::PRESENT, nri::StageBits::NONE}; + NRI.CmdBarrier(commandBuffer, barrierDesc); + } + NRI.EndCommandBuffer(commandBuffer); + + nri::FenceSubmitDesc textureAcquiredFence = {}; + textureAcquiredFence.fence = swapChainAcquireSemaphore; + textureAcquiredFence.stages = nri::StageBits::COLOR_ATTACHMENT; + + nri::FenceSubmitDesc renderingFinishedFence = {}; + renderingFinishedFence.fence = swapChainTexture.releaseSemaphore; + + nri::QueueSubmitDesc queueSubmitDesc = {}; + queueSubmitDesc.waitFences = &textureAcquiredFence; + queueSubmitDesc.waitFenceNum = 1; + queueSubmitDesc.commandBuffers = &queuedFrame.commandBuffer; + queueSubmitDesc.commandBufferNum = 1; + queueSubmitDesc.signalFences = &renderingFinishedFence; + queueSubmitDesc.signalFenceNum = 1; + NRI.QueueSubmit(*m_GraphicsQueue, queueSubmitDesc); + + NRI.EndStreamerFrame(*m_Streamer); + NRI.QueuePresent(*m_SwapChain, *swapChainTexture.releaseSemaphore, 0); + + nri::FenceSubmitDesc signalFence = {}; + signalFence.fence = m_FrameFence; + signalFence.value = 1 + frameIndex; + + nri::QueueSubmitDesc signalSubmitDesc = {}; + signalSubmitDesc.signalFences = &signalFence; + signalSubmitDesc.signalFenceNum = 1; + NRI.QueueSubmit(*m_GraphicsQueue, signalSubmitDesc); +} + +SAMPLE_MAIN(Sample, 0); diff --git a/Source/VideoEncodeDecode/Decoder.cpp b/Source/VideoEncodeDecode/Decoder.cpp new file mode 100644 index 0000000..09c32bc --- /dev/null +++ b/Source/VideoEncodeDecode/Decoder.cpp @@ -0,0 +1,494 @@ +// © 2021 NVIDIA Corporation + +#include "Decoder.h" + +#include + +namespace video_sample { + +Decoder::~Decoder() { + if (!m_Context.nri) + return; + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + + if (video.DestroyVideoPicture) { + for (PictureSlot& slot : m_Dpb) { + if (slot.picture) + video.DestroyVideoPicture(slot.picture); + } + if (m_Output.picture) + video.DestroyVideoPicture(m_Output.picture); + if (m_Parameters) + video.DestroyVideoSessionParameters(m_Parameters); + if (m_Session) + video.DestroyVideoSession(m_Session); + } + + if (m_DecodeBitstreamBuffer) + nri.DestroyBuffer(m_DecodeBitstreamBuffer); + for (nri::Texture* texture : m_Textures) + nri.DestroyTexture(texture); +} + +bool Decoder::Initialize(const VideoContext& context, const VideoConfig& config, const VideoSize& size, const CodecParameters& codecParameters) { + m_Context = context; + m_Config = config; + m_Size = size; + m_CodecParameters = codecParameters; + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + + nri::VideoSessionDesc sessionDesc = {}; + sessionDesc.type = nri::VideoSessionType::DECODE; + sessionDesc.codec = GetNriCodec(m_Config.codec); + sessionDesc.format = nri::Format::NV12_UNORM; + sessionDesc.width = m_Size.codedWidth; + sessionDesc.height = m_Size.codedHeight; + sessionDesc.maxReferenceNum = m_Config.referenceNum; + sessionDesc.av1FilmGrain = m_Config.av1FilmGrain; + + if (video.GetVideoCapabilities(*m_Context.device, sessionDesc, m_Capabilities) != nri::Result::SUCCESS || m_Config.referenceNum > m_Capabilities.maxReferenceNum) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " decode with " + std::to_string(m_Config.referenceNum) + " reference(s) is unsupported"; + m_Unsupported = true; + return false; + } + + // Decode output and DPB setup picture: the same subresource (coincide) or separate pictures (distinct, "VIDEO_OUTPUT_ONLY" output) + // Film grain goes to a distinct output, the DPB keeps the picture without it. If distinct mode isn't advertised (VK), it's + // allowed only for pictures applying film grain: the DPB coincides with the output of the other pictures + m_IsFilmGrainOutputOnly = m_Config.av1FilmGrain && !m_Capabilities.decodeDpbAndOutputDistinct; + if (m_Config.av1FilmGrain) + m_IsDistinct = !m_IsFilmGrainOutputOnly; + else if (m_Config.decodeDpb == DecodeDpbMode::COINCIDE) + m_IsDistinct = false; + else if (m_Config.decodeDpb == DecodeDpbMode::DISTINCT) + m_IsDistinct = true; + else + m_IsDistinct = !m_Capabilities.decodeDpbAndOutputCoincide; + + if (m_IsDistinct ? !m_Capabilities.decodeDpbAndOutputDistinct : !m_Capabilities.decodeDpbAndOutputCoincide) { + m_Status = std::string("Decode DPB and output ") + (m_IsDistinct ? "distinct" : "coincide") + " mode is unsupported"; + m_Unsupported = true; + return false; + } + + if (!(m_Capabilities.decodeBitstreamSourceMask & nri::VideoDecodeBitstreamSourceBits::BUFFER)) { + m_Status = "Decode from a bitstream buffer is unsupported"; + m_Unsupported = true; + return false; + } + + const bool useArray = m_Config.dpbLayout == DpbLayout::ARRAY || (m_Config.dpbLayout == DpbLayout::AUTO && m_Capabilities.dpbTextureArrayRequired); + if (m_Capabilities.dpbTextureArrayRequired && !useArray) { + m_Status = "The backend requires DPB texture arrays"; + m_Unsupported = true; + return false; + } + + if (video.CreateVideoSession(*m_Context.device, sessionDesc, m_Session) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to create ") + GetCodecName(m_Config.codec) + " decode session"; + return false; + } + + nri::VideoH264SessionParametersDesc h264Parameters = {}; + h264Parameters.sequenceParameterSets = &m_CodecParameters.h264Sps; + h264Parameters.sequenceParameterSetNum = 1; + h264Parameters.pictureParameterSets = &m_CodecParameters.h264Pps; + h264Parameters.pictureParameterSetNum = 1; + h264Parameters.maxSequenceParameterSetNum = 1; + h264Parameters.maxPictureParameterSetNum = 1; + + nri::VideoH265SessionParametersDesc h265Parameters = {}; + h265Parameters.videoParameterSets = &m_CodecParameters.h265Vps; + h265Parameters.videoParameterSetNum = 1; + h265Parameters.sequenceParameterSets = &m_CodecParameters.h265Sps; + h265Parameters.sequenceParameterSetNum = 1; + h265Parameters.pictureParameterSets = &m_CodecParameters.h265Pps; + h265Parameters.pictureParameterSetNum = 1; + h265Parameters.maxVideoParameterSetNum = 1; + h265Parameters.maxSequenceParameterSetNum = 1; + h265Parameters.maxPictureParameterSetNum = 1; + + nri::VideoAV1SessionParametersDesc av1Parameters = {}; + av1Parameters.sequence = m_CodecParameters.av1Sequence; + + nri::VideoSessionParametersDesc parametersDesc = {}; + parametersDesc.session = m_Session; + parametersDesc.h264Parameters = m_Config.codec == SampleCodec::H264 ? &h264Parameters : nullptr; + parametersDesc.h265Parameters = m_Config.codec == SampleCodec::H265 ? &h265Parameters : nullptr; + parametersDesc.av1Parameters = m_Config.codec == SampleCodec::AV1 ? &av1Parameters : nullptr; + + if (video.CreateVideoSessionParameters(*m_Context.device, parametersDesc, m_Parameters) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to create ") + GetCodecName(m_Config.codec) + " decode parameters"; + return false; + } + + nri::TextureDesc textureDesc = {}; + textureDesc.type = nri::TextureType::TEXTURE_2D; + textureDesc.usage = nri::TextureUsageBits::VIDEO_DECODE; + textureDesc.format = nri::Format::NV12_UNORM; + textureDesc.width = (nri::Dim_t)m_Size.codedWidth; + textureDesc.height = (nri::Dim_t)m_Size.codedHeight; + textureDesc.mipNum = 1; + textureDesc.layerNum = 1; + textureDesc.videoCodec = GetNriCodec(m_Config.codec); + textureDesc.videoAV1FilmGrain = m_Config.av1FilmGrain; + + m_DpbSlotNum = std::max(m_Config.referenceNum + 1, useArray ? m_Capabilities.dpbTextureArrayMinLayerNum : 0u); + m_DpbSlotNum = std::min(m_DpbSlotNum, MAX_DPB_SLOT_NUM); + + const uint32_t pictureWidth = m_Config.decodePictureAtVideoSize ? m_Size.videoWidth : 0; + const uint32_t pictureHeight = m_Config.decodePictureAtVideoSize ? m_Size.videoHeight : 0; + bool isCreated = false; + if (m_IsDistinct) { + textureDesc.usage |= nri::TextureUsageBits::VIDEO_REFERENCE_ONLY; + isCreated = CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::DECODE_REFERENCE, useArray, m_DpbSlotNum, "VideoDecodeDpb", m_Dpb, m_Textures, pictureWidth, pictureHeight); + + textureDesc.usage = nri::TextureUsageBits::VIDEO_DECODE | nri::TextureUsageBits::VIDEO_OUTPUT_ONLY; + isCreated = isCreated && CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::DECODE_OUTPUT, false, 1, "VideoDecodeOutput", &m_Output, m_Textures, pictureWidth, pictureHeight); + } else { + isCreated = CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::DECODE_OUTPUT, useArray, m_DpbSlotNum, "VideoDecodeDpb", m_Dpb, m_Textures, pictureWidth, pictureHeight); + + if (m_IsFilmGrainOutputOnly) { + textureDesc.usage = nri::TextureUsageBits::VIDEO_DECODE | nri::TextureUsageBits::VIDEO_OUTPUT_ONLY; + isCreated = isCreated && CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::DECODE_OUTPUT, false, 1, "VideoDecodeOutput", &m_Output, m_Textures, pictureWidth, pictureHeight); + } + } + if (!isCreated) { + m_Status = "Failed to create NV12 decode pictures"; + return false; + } + + if (!InitializePictureLayouts(nri, *m_Context.graphicsQueue, m_Textures)) { + m_Status = "Failed to initialize decode texture layouts"; + return false; + } + + nri::BufferDesc decodeBitstreamBufferDesc = {}; + decodeBitstreamBufferDesc.size = m_Size.bitstreamSize; + decodeBitstreamBufferDesc.usage = nri::BufferUsageBits::VIDEO_DECODE; + if (CreateDecodeBitstreamBuffer(nri, *m_Context.device, 0.0f, decodeBitstreamBufferDesc, m_DecodeBitstreamBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create decode bitstream buffer"; + return false; + } + + m_Ready = true; + m_Status = std::string(GetCodecName(m_Config.codec)) + " decoder initialized"; + return true; +} + +bool Decoder::WriteAnnexBEndOfStream(std::vector& annexBEndOfStream) { + annexBEndOfStream.clear(); + if (m_Config.codec == SampleCodec::AV1) + return true; + + nri::VideoInterface& video = *m_Context.video; + nri::VideoAnnexBEndOfStreamDesc annexBDesc = {}; + annexBDesc.codec = GetNriCodec(m_Config.codec); + if (video.WriteVideoAnnexBEndOfStream(annexBDesc) != nri::Result::SUCCESS || annexBDesc.writtenSize == 0) { + m_Status = std::string("Failed to query ") + GetCodecName(m_Config.codec) + " Annex-B end-of-stream size"; + return false; + } + + annexBEndOfStream.resize((size_t)annexBDesc.writtenSize); + annexBDesc.dst = annexBEndOfStream.data(); + annexBDesc.dstSize = annexBEndOfStream.size(); + if (video.WriteVideoAnnexBEndOfStream(annexBDesc) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to build ") + GetCodecName(m_Config.codec) + " Annex-B end-of-stream marker"; + return false; + } + + return true; +} + +bool Decoder::BuildDecodeBitstream(const EncodedFrame& frame, uint64_t& decodeBitstreamRange, uint32_t& pictureOffset) { + NRIInterface& nri = *m_Context.nri; + + std::vector annexBHeaders; + if (!frame.hasAv1DecodeInfo) { + nri::VideoInterface& video = *m_Context.video; + nri::VideoAnnexBParameterSetsDesc annexBDesc = {}; + annexBDesc.codec = GetNriCodec(m_Config.codec); + annexBDesc.h264Sps = &m_CodecParameters.h264Sps; + annexBDesc.h264Pps = &m_CodecParameters.h264Pps; + annexBDesc.h265Vps = &m_CodecParameters.h265Vps; + annexBDesc.h265Sps = &m_CodecParameters.h265Sps; + annexBDesc.h265Pps = &m_CodecParameters.h265Pps; + if (video.WriteVideoAnnexBParameterSets(annexBDesc) != nri::Result::SUCCESS || annexBDesc.writtenSize == 0 || annexBDesc.writtenSize >= ENCODED_SLICE_OFFSET) { + m_Status = std::string("Failed to query ") + GetCodecName(m_Config.codec) + " Annex-B parameter-set size"; + return false; + } + annexBHeaders.resize((size_t)annexBDesc.writtenSize); + annexBDesc.dst = annexBHeaders.data(); + annexBDesc.dstSize = annexBHeaders.size(); + if (video.WriteVideoAnnexBParameterSets(annexBDesc) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to build ") + GetCodecName(m_Config.codec) + " Annex-B parameter sets"; + return false; + } + } + + std::vector annexBEndOfStream; + if (!WriteAnnexBEndOfStream(annexBEndOfStream)) + return false; + if (m_Context.graphicsAPI == nri::GraphicsAPI::VK) + annexBEndOfStream.clear(); + + const nri::VideoAV1EncodeDecodeInfo* av1DecodeInfo = frame.hasAv1DecodeInfo ? &frame.av1DecodeInfo : nullptr; + const uint64_t encodedPayloadSkip = av1DecodeInfo ? av1DecodeInfo->bitstreamOffset : 0; + const uint64_t encodedPayloadBytes = av1DecodeInfo ? av1DecodeInfo->bitstreamSize : frame.payload.size() - encodedPayloadSkip; + const uint64_t decodeSliceOffset = annexBHeaders.size(); + pictureOffset = (uint32_t)decodeSliceOffset; + const uint64_t decodeBitstreamSize = AlignUp(decodeSliceOffset + encodedPayloadBytes + annexBEndOfStream.size(), m_Size.decodeBitstreamSizeAlignment); + if (encodedPayloadSkip + encodedPayloadBytes > frame.payload.size() || decodeBitstreamSize > m_Size.bitstreamSize) { + m_Status = std::string("Encoded ") + GetCodecName(m_Config.codec) + " bitstream exceeded decode buffer size"; + return false; + } + + uint8_t* decodeBitstream = (uint8_t*)nri.MapBuffer(*m_DecodeBitstreamBuffer, 0, decodeBitstreamSize); + if (!decodeBitstream) { + m_Status = std::string("Failed to map exact ") + GetCodecName(m_Config.codec) + " decode bitstream"; + return false; + } + std::memset(decodeBitstream, 0, (size_t)decodeBitstreamSize); + if (!annexBHeaders.empty()) + std::memcpy(decodeBitstream, annexBHeaders.data(), annexBHeaders.size()); + std::memcpy(decodeBitstream + decodeSliceOffset, frame.payload.data() + encodedPayloadSkip, (size_t)encodedPayloadBytes); + if (!annexBEndOfStream.empty()) + std::memcpy(decodeBitstream + decodeSliceOffset + encodedPayloadBytes, annexBEndOfStream.data(), annexBEndOfStream.size()); + decodeBitstreamRange = decodeBitstreamSize; + nri.UnmapBuffer(*m_DecodeBitstreamBuffer); + return true; +} + +bool Decoder::Decode(const DecodeRequest& request, DecodedFrame& decodedFrame) { + if (!m_Ready || !request.frame || !request.nv12ReadbackBuffer || !request.nv12Layout) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " decoder is not ready"; + return false; + } + + const EncodedFrame& frame = *request.frame; + const FramePlan& plan = frame.plan; + const nri::VideoAV1EncodeDecodeInfo* av1DecodeInfo = frame.hasAv1DecodeInfo ? &frame.av1DecodeInfo : nullptr; + const bool isKeyFrame = plan.type == nri::VideoFrameType::IDR; + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + + uint64_t decodeBitstreamRange = 0; + uint32_t pictureOffset = 0; + if (!BuildDecodeBitstream(frame, decodeBitstreamRange, pictureOffset)) + return false; + + // Distinct output: in distinct mode, or for pictures applying film grain + const bool appliesFilmGrain = av1DecodeInfo && (av1DecodeInfo->picture.flags & nri::VideoAV1PictureBits::APPLY_GRAIN); + const bool isDistinct = m_IsDistinct || (m_IsFilmGrainOutputOnly && appliesFilmGrain); + PictureSlot& setup = m_Dpb[plan.setupSlot]; + PictureSlot& output = isDistinct ? m_Output : setup; + const uint32_t pictureOffsets[] = {pictureOffset}; + + // References, in the order of the plan (reversed on odd H.265 pictures to test RPS ordering) + PlanReference orderedReferences[MAX_REFERENCE_NUM] = {}; + nri::VideoReference references[MAX_REFERENCE_NUM] = {}; + nri::VideoH264DecodeReferenceDesc h264References[MAX_REFERENCE_NUM] = {}; + nri::VideoH265ReferenceDesc h265References[MAX_REFERENCE_NUM] = {}; + for (uint32_t i = 0; i < plan.referenceNum; i++) + orderedReferences[i] = plan.references[plan.reverseDecodeReferenceOrder ? plan.referenceNum - 1 - i : i]; + for (uint32_t i = 0; i < plan.referenceNum; i++) { + const PlanReference& reference = orderedReferences[i]; + references[i] = {m_Dpb[reference.slot].picture, reference.slot}; + h264References[i] = {nri::VideoH264DecodeReferenceBits::TOP_FIELD | nri::VideoH264DecodeReferenceBits::BOTTOM_FIELD, (uint16_t)reference.frameNum, reference.slot, reference.poc, reference.poc}; + h265References[i] = {reference.slot, reference.poc, 0, reference.type, 0, reference.listIndex}; + } + + nri::VideoH264DecodePictureDesc h264DecodePicture = {}; + h264DecodePicture.flags = nri::VideoH264DecodePictureBits::NONE; + if (isKeyFrame) + h264DecodePicture.flags |= nri::VideoH264DecodePictureBits::IDR | nri::VideoH264DecodePictureBits::INTRA; + if (plan.isReference) + h264DecodePicture.flags |= nri::VideoH264DecodePictureBits::REFERENCE; + h264DecodePicture.sequenceParameterSetId = m_CodecParameters.h264Sps.sequenceParameterSetId; + h264DecodePicture.pictureParameterSetId = m_CodecParameters.h264Pps.pictureParameterSetId; + h264DecodePicture.frameNum = (uint16_t)plan.frameNum; + h264DecodePicture.idrPictureId = (uint16_t)plan.idrPictureId; + h264DecodePicture.topFieldOrderCount = plan.poc; + h264DecodePicture.bottomFieldOrderCount = plan.poc; + h264DecodePicture.sliceOffsets = pictureOffsets; + h264DecodePicture.sliceOffsetNum = helper::GetCountOf(pictureOffsets); + h264DecodePicture.references = plan.referenceNum ? h264References : nullptr; + h264DecodePicture.referenceNum = plan.referenceNum; + + nri::VideoH265DecodePictureDesc h265DecodePicture = {}; + h265DecodePicture.flags = nri::VideoH265DecodePictureBits::NONE; + if (isKeyFrame) + h265DecodePicture.flags |= nri::VideoH265DecodePictureBits::IRAP | nri::VideoH265DecodePictureBits::IDR; + if (plan.isReference) + h265DecodePicture.flags |= nri::VideoH265DecodePictureBits::REFERENCE; + h265DecodePicture.videoParameterSetId = m_CodecParameters.h265Vps.videoParameterSetId; + h265DecodePicture.sequenceParameterSetId = m_CodecParameters.h265Sps.sequenceParameterSetId; + h265DecodePicture.pictureParameterSetId = m_CodecParameters.h265Pps.pictureParameterSetId; + h265DecodePicture.pictureOrderCount = plan.poc; + h265DecodePicture.sliceSegmentOffsets = pictureOffsets; + h265DecodePicture.sliceSegmentOffsetNum = helper::GetCountOf(pictureOffsets); + h265DecodePicture.references = plan.referenceNum ? h265References : nullptr; + h265DecodePicture.referenceNum = plan.referenceNum; + + nri::VideoAV1EncodeDecodeInfo av1Info = {}; + uint8_t av1DecodeOrderHints[8] = {}; + if (av1DecodeInfo) { + av1Info = *av1DecodeInfo; + av1Info.picture.tiles = av1Info.tiles; + av1Info.picture.tileLayout = &av1Info.tileLayout; + av1Info.picture.quantization = &av1Info.quantization; + av1Info.picture.loopFilter = &av1Info.loopFilter; + av1Info.picture.cdef = &av1Info.cdef; + av1Info.picture.segmentation = av1DecodeInfo->picture.segmentation ? &av1Info.segmentation : nullptr; + av1Info.picture.loopRestoration = &av1Info.loopRestoration; + av1Info.picture.globalMotion = &av1Info.globalMotion; + av1Info.tileLayout.miColumnStarts = av1Info.miColumnStarts; + av1Info.tileLayout.miRowStarts = av1Info.miRowStarts; + av1Info.tileLayout.widthInSuperblocksMinus1 = av1Info.widthInSuperblocksMinus1; + av1Info.tileLayout.heightInSuperblocksMinus1 = av1Info.heightInSuperblocksMinus1; + if (av1Info.picture.references && av1Info.picture.referenceNum) + av1Info.picture.references = av1Info.references; + if (!isKeyFrame) { + av1DecodeOrderHints[0] = frame.hasAv1SavedOrderHints ? av1Info.picture.orderHint : 0; + av1Info.picture.orderHints = av1DecodeOrderHints; + for (uint32_t i = 0; i < av1Info.picture.referenceNum && i < helper::GetCountOf(av1Info.references); i++) + av1Info.references[i].savedOrderHints = frame.hasAv1SavedOrderHints ? frame.av1SavedOrderHints[av1Info.references[i].slot % MAX_DPB_SLOT_NUM] : av1DecodeOrderHints; + } + } + + nri::VideoDecodeDesc decodeDesc = {}; + decodeDesc.session = m_Session; + decodeDesc.parameters = m_Parameters; + decodeDesc.bitstream.buffer = m_DecodeBitstreamBuffer; + decodeDesc.bitstream.size = decodeBitstreamRange; + decodeDesc.dstPicture = output.picture; + decodeDesc.setupPicture = isDistinct ? setup.picture : nullptr; + decodeDesc.references = plan.referenceNum ? references : nullptr; + decodeDesc.referenceNum = plan.referenceNum; + decodeDesc.dstSlot = plan.setupSlot; + decodeDesc.h264PictureDesc = m_Config.codec == SampleCodec::H264 ? &h264DecodePicture : nullptr; + decodeDesc.h265PictureDesc = m_Config.codec == SampleCodec::H265 ? &h265DecodePicture : nullptr; + decodeDesc.av1PictureDesc = av1DecodeInfo ? &av1Info.picture : nullptr; + + // Picture states + PictureSlot* pictures[2 + MAX_REFERENCE_NUM] = {}; + nri::VideoPictureState states[2 + MAX_REFERENCE_NUM] = {}; + uint32_t pictureNum = 0; + bool statesOk = true; + auto addPicture = [&](PictureSlot* slot, nri::VideoPictureRole role) { + statesOk = statesOk && video.GetVideoPictureState(*slot->picture, role, states[pictureNum]) == nri::Result::SUCCESS; + pictures[pictureNum++] = slot; + }; + if (isDistinct) { + addPicture(&m_Output, nri::VideoPictureRole::DECODE_OUTPUT); + addPicture(&setup, nri::VideoPictureRole::DECODE_SETUP); + } else + addPicture(&setup, nri::VideoPictureRole::DECODE_OUTPUT_AND_SETUP); + for (uint32_t i = 0; i < plan.referenceNum; i++) + addPicture(&m_Dpb[plan.references[i].slot], nri::VideoPictureRole::DECODE_REFERENCE); + if (!statesOk) { + m_Status = "Failed to query video decode picture states"; + return false; + } + + if (!SubmitOneTime(nri, *m_Context.decodeQueue, [&](nri::CommandBuffer& commandBuffer) { + nri::BufferBarrierDesc bufferBarrier = {}; + bufferBarrier.buffer = m_DecodeBitstreamBuffer; + bufferBarrier.before = {nri::AccessBits::NONE, nri::StageBits::NONE}; + bufferBarrier.after = {nri::AccessBits::VIDEO_DECODE_READ, nri::StageBits::VIDEO_DECODE}; + + nri::TextureBarrierDesc textureBarriers[2 + MAX_REFERENCE_NUM] = {}; + for (uint32_t i = 0; i < pictureNum; i++) + textureBarriers[i] = MakePictureBarrier(*pictures[i], pictures[i]->state, states[i].required); + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = m_Context.graphicsAPI == nri::GraphicsAPI::D3D12 ? nullptr : &bufferBarrier; + barrierDesc.bufferNum = m_Context.graphicsAPI == nri::GraphicsAPI::D3D12 ? 0 : 1; + barrierDesc.textures = textureBarriers; + barrierDesc.textureNum = pictureNum; + nri.CmdBarrier(commandBuffer, barrierDesc); + + video.CmdDecodeVideo(commandBuffer, decodeDesc); + + uint32_t postTextureNum = 0; + for (uint32_t i = 0; i < pictureNum; i++) { + if (!states[i].transitionOnVideoQueue) + continue; + textureBarriers[postTextureNum++] = MakePictureBarrier(*pictures[i], states[i].required, states[i].videoQueueAfter); + } + barrierDesc.buffers = nullptr; + barrierDesc.bufferNum = 0; + barrierDesc.textureNum = postTextureNum; + nri.CmdBarrier(commandBuffer, barrierDesc); + })) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " decode submission failed"; + return false; + } + for (uint32_t i = 0; i < pictureNum; i++) + ApplyVideoPictureState(*pictures[i], states[i]); + + // Copy NV12 into the readback buffer + if (!SubmitOneTime(nri, *m_Context.graphicsQueue, [&](nri::CommandBuffer& commandBuffer) { + nri::TextureBarrierDesc textureBarrier = MakePictureBarrier(output, output.consumerState, {nri::AccessBits::COPY_SOURCE, nri::Layout::COPY_SOURCE, nri::StageBits::COPY}); + + nri::BufferBarrierDesc nv12BufferBarrier = {}; + nv12BufferBarrier.buffer = request.nv12ReadbackBuffer; + nv12BufferBarrier.before = {nri::AccessBits::NONE, nri::StageBits::NONE}; + nv12BufferBarrier.after = {nri::AccessBits::COPY_DESTINATION, nri::StageBits::COPY}; + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = &nv12BufferBarrier; + barrierDesc.bufferNum = 1; + barrierDesc.textures = &textureBarrier; + barrierDesc.textureNum = 1; + nri.CmdBarrier(commandBuffer, barrierDesc); + + nri::TextureRegionDesc lumaRegion = {}; + lumaRegion.width = (nri::Dim_t)m_Size.videoWidth; + lumaRegion.height = (nri::Dim_t)m_Size.videoHeight; + lumaRegion.depth = 1; + lumaRegion.layerOffset = (nri::Dim_t)output.layer; + lumaRegion.planes = nri::PlaneBits::PLANE_0; + + nri::TextureDataLayoutDesc lumaLayout = {}; + lumaLayout.rowPitch = request.nv12Layout->yRowPitchBytes; + lumaLayout.slicePitch = request.nv12Layout->ySlicePitchBytes; + nri.CmdReadbackTextureToBuffer(commandBuffer, *request.nv12ReadbackBuffer, lumaLayout, *output.texture, lumaRegion); + + nri::TextureRegionDesc chromaRegion = lumaRegion; + chromaRegion.planes = nri::PlaneBits::PLANE_1; + + nri::TextureDataLayoutDesc chromaLayout = {}; + chromaLayout.offset = request.nv12Layout->uvOffsetBytes; + chromaLayout.rowPitch = request.nv12Layout->uvRowPitchBytes; + chromaLayout.slicePitch = request.nv12Layout->uvSlicePitchBytes; + nri.CmdReadbackTextureToBuffer(commandBuffer, *request.nv12ReadbackBuffer, chromaLayout, *output.texture, chromaRegion); + + nv12BufferBarrier.before = nv12BufferBarrier.after; + nv12BufferBarrier.after = {nri::AccessBits::NONE, nri::StageBits::NONE}; + textureBarrier.before = textureBarrier.after; + textureBarrier.after = {nri::AccessBits::NONE, nri::Layout::GENERAL, nri::StageBits::NONE}; + nri.CmdBarrier(commandBuffer, barrierDesc); + output.state = textureBarrier.after; + output.consumerState = textureBarrier.after; + })) { + m_Status = "Failed to copy decoded NV12"; + return false; + } + + decodedFrame = {}; + decodedFrame.displayIndex = plan.displayIndex; + decodedFrame.isDisplay = plan.isDisplay; + + char message[128] = {}; + std::snprintf(message, sizeof(message), "%s decode complete, encoded %llu bytes", GetCodecName(m_Config.codec), (unsigned long long)frame.feedback.encodedBitstreamWrittenBytes); + m_Status = message; + return true; +} + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Decoder.h b/Source/VideoEncodeDecode/Decoder.h new file mode 100644 index 0000000..6da5b55 --- /dev/null +++ b/Source/VideoEncodeDecode/Decoder.h @@ -0,0 +1,72 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#include "Shared.h" + +namespace video_sample { + +struct DecodeRequest { + const EncodedFrame* frame = nullptr; + nri::Buffer* nv12ReadbackBuffer = nullptr; + const Nv12BufferLayout* nv12Layout = nullptr; +}; + +class Decoder { +public: + Decoder() = default; + ~Decoder(); + + Decoder(const Decoder&) = delete; + Decoder& operator=(const Decoder&) = delete; + + bool Initialize(const VideoContext& context, const VideoConfig& config, const VideoSize& size, const CodecParameters& codecParameters); + bool Decode(const DecodeRequest& request, DecodedFrame& decodedFrame); + + bool IsReady() const { + return m_Ready; + } + + bool IsUnsupported() const { + return m_Unsupported; + } + + bool IsDistinct() const { + return m_IsDistinct; + } + + const nri::VideoCapabilities& GetCapabilities() const { + return m_Capabilities; + } + + const std::string& GetStatus() const { + return m_Status; + } + +private: + bool WriteAnnexBEndOfStream(std::vector& annexBEndOfStream); + bool BuildDecodeBitstream(const EncodedFrame& frame, uint64_t& decodeBitstreamRange, uint32_t& pictureOffset); + +private: + VideoContext m_Context = {}; + VideoConfig m_Config = {}; + VideoSize m_Size = {}; + CodecParameters m_CodecParameters = {}; + nri::VideoCapabilities m_Capabilities = {}; + std::string m_Status = "Initializing decoder"; + + nri::VideoSession* m_Session = nullptr; + nri::VideoSessionParameters* m_Parameters = nullptr; + std::vector m_Textures; + PictureSlot m_Dpb[MAX_DPB_SLOT_NUM] = {}; + PictureSlot m_Output = {}; // distinct mode, or film grain without distinct mode + uint32_t m_DpbSlotNum = 0; + nri::Buffer* m_DecodeBitstreamBuffer = nullptr; + + bool m_Ready = false; + bool m_Unsupported = false; + bool m_IsDistinct = false; + bool m_IsFilmGrainOutputOnly = false; // only pictures applying film grain use the distinct "m_Output" +}; + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Encoder.cpp b/Source/VideoEncodeDecode/Encoder.cpp new file mode 100644 index 0000000..f8b5593 --- /dev/null +++ b/Source/VideoEncodeDecode/Encoder.cpp @@ -0,0 +1,705 @@ +// © 2021 NVIDIA Corporation + +#include "Encoder.h" + +#include +#include + +namespace video_sample { + +static const nri::VideoAV1ReferenceName AV1_REFERENCE_NAMES[] = { + nri::VideoAV1ReferenceName::LAST, + nri::VideoAV1ReferenceName::LAST2, + nri::VideoAV1ReferenceName::LAST3, + nri::VideoAV1ReferenceName::GOLDEN, + nri::VideoAV1ReferenceName::BWDREF, + nri::VideoAV1ReferenceName::ALTREF2, + nri::VideoAV1ReferenceName::ALTREF, +}; + +Encoder::~Encoder() { + if (!m_Context.nri) + return; + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + + if (video.DestroyVideoPicture) { + for (PictureSlot& slot : m_Dpb) { + if (slot.picture) + video.DestroyVideoPicture(slot.picture); + } + if (m_Input.picture) + video.DestroyVideoPicture(m_Input.picture); + if (m_Parameters) + video.DestroyVideoSessionParameters(m_Parameters); + if (m_Session) + video.DestroyVideoSession(m_Session); + } + + if (m_ResolvedMetadataReadbackBuffer && m_ResolvedMetadataReadbackBuffer != m_ResolvedMetadataBuffer) + nri.DestroyBuffer(m_ResolvedMetadataReadbackBuffer); + if (m_ResolvedMetadataBuffer) + nri.DestroyBuffer(m_ResolvedMetadataBuffer); + if (m_MetadataBuffer) + nri.DestroyBuffer(m_MetadataBuffer); + if (m_BitstreamBuffer) + nri.DestroyBuffer(m_BitstreamBuffer); + if (m_BitstreamHeaderUploadBuffer) + nri.DestroyBuffer(m_BitstreamHeaderUploadBuffer); + for (nri::Texture* texture : m_Textures) + nri.DestroyTexture(texture); +} + +bool Encoder::Initialize(const VideoContext& context, const VideoConfig& config, const VideoSize& size, const CodecParameters& codecParameters) { + m_Context = context; + m_Config = config; + m_Size = size; + m_CodecParameters = codecParameters; + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + + nri::VideoSessionDesc sessionDesc = {}; + sessionDesc.type = nri::VideoSessionType::ENCODE; + sessionDesc.codec = GetNriCodec(m_Config.codec); + sessionDesc.format = nri::Format::NV12_UNORM; + sessionDesc.width = m_Size.codedWidth; + sessionDesc.height = m_Size.codedHeight; + sessionDesc.maxReferenceNum = m_Config.referenceNum; + + if (video.GetVideoCapabilities(*m_Context.device, sessionDesc, m_Capabilities) != nri::Result::SUCCESS || m_Config.referenceNum > m_Capabilities.maxReferenceNum) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " encode with " + std::to_string(m_Config.referenceNum) + " reference(s) is unsupported"; + m_Unsupported = true; + return false; + } + + m_UseFeedback = m_Config.encodeFeedback && m_Capabilities.encodeFeedbackSupported; + const bool useArray = m_Config.dpbLayout == DpbLayout::ARRAY || (m_Config.dpbLayout == DpbLayout::AUTO && m_Capabilities.dpbTextureArrayRequired); + if (m_Capabilities.dpbTextureArrayRequired && !useArray) { + m_Status = "The backend requires DPB texture arrays"; + m_Unsupported = true; + return false; + } + + if (video.CreateVideoSession(*m_Context.device, sessionDesc, m_Session) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to create ") + GetCodecName(m_Config.codec) + " encode session"; + return false; + } + + nri::VideoH264SessionParametersDesc h264Parameters = {}; + h264Parameters.sequenceParameterSets = &m_CodecParameters.h264Sps; + h264Parameters.sequenceParameterSetNum = 1; + h264Parameters.pictureParameterSets = &m_CodecParameters.h264Pps; + h264Parameters.pictureParameterSetNum = 1; + h264Parameters.maxSequenceParameterSetNum = 1; + h264Parameters.maxPictureParameterSetNum = 1; + + nri::VideoH265SessionParametersDesc h265Parameters = {}; + h265Parameters.videoParameterSets = &m_CodecParameters.h265Vps; + h265Parameters.videoParameterSetNum = 1; + h265Parameters.sequenceParameterSets = &m_CodecParameters.h265Sps; + h265Parameters.sequenceParameterSetNum = 1; + h265Parameters.pictureParameterSets = &m_CodecParameters.h265Pps; + h265Parameters.pictureParameterSetNum = 1; + h265Parameters.maxVideoParameterSetNum = 1; + h265Parameters.maxSequenceParameterSetNum = 1; + h265Parameters.maxPictureParameterSetNum = 1; + + nri::VideoAV1SessionParametersDesc av1Parameters = {}; + av1Parameters.sequence = m_CodecParameters.av1Sequence; + + nri::VideoSessionParametersDesc parametersDesc = {}; + parametersDesc.session = m_Session; + parametersDesc.h264Parameters = m_Config.codec == SampleCodec::H264 ? &h264Parameters : nullptr; + parametersDesc.h265Parameters = (m_Config.codec == SampleCodec::H265 && !m_Config.h265DefaultParameters) ? &h265Parameters : nullptr; + parametersDesc.av1Parameters = m_Config.codec == SampleCodec::AV1 ? &av1Parameters : nullptr; + + const nri::Result parametersResult = video.CreateVideoSessionParameters(*m_Context.device, parametersDesc, m_Parameters); + if (parametersResult != nri::Result::SUCCESS) { + m_Status = std::string("Failed to create ") + GetCodecName(m_Config.codec) + " encode parameters"; + m_Unsupported = parametersResult == nri::Result::UNSUPPORTED; + return false; + } + + // Source + nri::TextureDesc textureDesc = {}; + textureDesc.type = nri::TextureType::TEXTURE_2D; + textureDesc.usage = nri::TextureUsageBits::VIDEO_ENCODE; + if (m_Config.encodeInputOutputOnly) + textureDesc.usage |= nri::TextureUsageBits::VIDEO_OUTPUT_ONLY; + textureDesc.format = nri::Format::NV12_UNORM; + textureDesc.width = (nri::Dim_t)m_Size.codedWidth; + textureDesc.height = (nri::Dim_t)m_Size.codedHeight; + textureDesc.mipNum = 1; + textureDesc.layerNum = 1; + textureDesc.videoCodec = GetNriCodec(m_Config.codec); + + if (!CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::ENCODE_INPUT, false, 1, "VideoEncodeInput", &m_Input, m_Textures)) { + m_Status = "Failed to create NV12 encode source"; + return false; + } + + // Reconstructed pictures (DPB) + textureDesc.usage = nri::TextureUsageBits::VIDEO_ENCODE | nri::TextureUsageBits::VIDEO_REFERENCE_ONLY; + m_DpbSlotNum = std::max(m_Config.referenceNum + 1, useArray ? m_Capabilities.dpbTextureArrayMinLayerNum : 0u); + m_DpbSlotNum = std::min(m_DpbSlotNum, MAX_DPB_SLOT_NUM); + if (!CreatePictureSlots(nri, video, *m_Context.device, textureDesc, nri::VideoPictureUsage::ENCODE_REFERENCE, useArray, m_DpbSlotNum, "VideoEncodeDpb", m_Dpb, m_Textures)) { + m_Status = "Failed to create NV12 reconstructed pictures"; + return false; + } + + if (!InitializePictureLayouts(nri, *m_Context.graphicsQueue, m_Textures)) { + m_Status = "Failed to initialize encode texture layouts"; + return false; + } + + // Buffers + nri::BufferDesc bitstreamHeaderUploadBufferDesc = {}; + bitstreamHeaderUploadBufferDesc.size = ENCODED_SLICE_OFFSET; + + nri::BufferDesc bitstreamBufferDesc = {}; + bitstreamBufferDesc.size = m_Size.bitstreamSize; + bitstreamBufferDesc.usage = nri::BufferUsageBits::VIDEO_ENCODE; + + nri::BufferDesc metadataBufferDesc = {}; + metadataBufferDesc.size = std::max(m_Capabilities.metadataSize, 4096); + metadataBufferDesc.usage = nri::BufferUsageBits::VIDEO_ENCODE; + + nri::BufferDesc resolvedMetadataBufferDesc = {}; + resolvedMetadataBufferDesc.size = std::max(m_Capabilities.resolvedMetadataSize, RESOLVED_METADATA_SIZE); + resolvedMetadataBufferDesc.usage = nri::BufferUsageBits::VIDEO_ENCODE; + + if (nri.CreateCommittedBuffer(*m_Context.device, nri::MemoryLocation::HOST_UPLOAD, 0.0f, bitstreamHeaderUploadBufferDesc, m_BitstreamHeaderUploadBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create bitstream header upload buffer"; + return false; + } + if (CreateEncodeBitstreamBuffer(nri, *m_Context.device, 0.0f, bitstreamBufferDesc, m_BitstreamBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create encode bitstream buffer"; + return false; + } + if (m_Capabilities.metadataSize && nri.CreateCommittedBuffer(*m_Context.device, nri::MemoryLocation::DEVICE, 0.0f, metadataBufferDesc, m_MetadataBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create encode metadata buffer"; + return false; + } + { + // VK: the query index is recorded in the host-visible buffer. D3D12: resolved on the device, then copied + if (m_Context.graphicsAPI == nri::GraphicsAPI::VK) { + if (nri.CreateCommittedBuffer(*m_Context.device, nri::MemoryLocation::HOST_READBACK, 0.0f, resolvedMetadataBufferDesc, m_ResolvedMetadataBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create resolved encode metadata buffer"; + return false; + } + m_ResolvedMetadataReadbackBuffer = m_ResolvedMetadataBuffer; + } else { + nri::BufferDesc readbackDesc = {}; + readbackDesc.size = resolvedMetadataBufferDesc.size; + if (nri.CreateCommittedBuffer(*m_Context.device, nri::MemoryLocation::DEVICE, 0.0f, resolvedMetadataBufferDesc, m_ResolvedMetadataBuffer) != nri::Result::SUCCESS || nri.CreateCommittedBuffer(*m_Context.device, nri::MemoryLocation::HOST_READBACK, 0.0f, readbackDesc, m_ResolvedMetadataReadbackBuffer) != nri::Result::SUCCESS) { + m_Status = "Failed to create resolved encode metadata buffers"; + return false; + } + } + + if (m_UseFeedback && m_Capabilities.encodeFeedbackResolveRequired && nri.GetQueue(*m_Context.device, m_Capabilities.resolvedMetadataQueueType, 0, m_ResolveQueue) != nri::Result::SUCCESS) { + m_Status = "The resolved metadata queue is unavailable"; + m_Unsupported = true; + return false; + } + } + + m_Ready = true; + m_Status = std::string(GetCodecName(m_Config.codec)) + " encoder initialized"; + return true; +} + +bool Encoder::UploadHeaders(const FramePlan& plan, std::vector& headers) { + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + const bool isKeyFrame = plan.type == nri::VideoFrameType::IDR; + + headers.clear(); + + if (m_Config.codec == SampleCodec::AV1) { + // Temporal delimiter, sequence header on key frames. Not written into the buffer, "VideoEncodeDesc::bitstreamMetadataSize" bytes are skipped + if (isKeyFrame) { + nri::VideoAV1ObuHeadersDesc obuDesc = {}; + obuDesc.sequence = m_CodecParameters.av1Sequence; + if (video.WriteVideoAV1ObuHeaders(obuDesc) != nri::Result::SUCCESS || !obuDesc.writtenSize) { + m_Status = "Failed to query AV1 OBU headers size"; + return false; + } + headers.resize((size_t)obuDesc.writtenSize); + obuDesc.dst = headers.data(); + obuDesc.dstSize = headers.size(); + if (video.WriteVideoAV1ObuHeaders(obuDesc) != nri::Result::SUCCESS) { + m_Status = "Failed to build AV1 OBU headers"; + return false; + } + } else + headers = {0x12, 0x00}; + + void* headerPtr = nri.MapBuffer(*m_BitstreamHeaderUploadBuffer, 0, ENCODED_SLICE_OFFSET); + if (!headerPtr) { + m_Status = "Failed to map bitstream header upload buffer"; + return false; + } + std::memset(headerPtr, 0, (size_t)ENCODED_SLICE_OFFSET); + nri.UnmapBuffer(*m_BitstreamHeaderUploadBuffer); + return true; + } + + nri::VideoAnnexBParameterSetsDesc annexBDesc = {}; + annexBDesc.codec = GetNriCodec(m_Config.codec); + annexBDesc.h264Sps = &m_CodecParameters.h264Sps; + annexBDesc.h264Pps = &m_CodecParameters.h264Pps; + annexBDesc.h265Vps = &m_CodecParameters.h265Vps; + annexBDesc.h265Sps = &m_CodecParameters.h265Sps; + annexBDesc.h265Pps = &m_CodecParameters.h265Pps; + + std::vector annexBHeaders; + if (video.WriteVideoAnnexBParameterSets(annexBDesc) != nri::Result::SUCCESS || annexBDesc.writtenSize == 0 || annexBDesc.writtenSize >= ENCODED_SLICE_OFFSET) { + m_Status = std::string("Failed to query ") + GetCodecName(m_Config.codec) + " Annex-B parameter-set size"; + return false; + } + + annexBHeaders.resize((size_t)annexBDesc.writtenSize); + annexBDesc.dst = annexBHeaders.data(); + annexBDesc.dstSize = annexBHeaders.size(); + if (video.WriteVideoAnnexBParameterSets(annexBDesc) != nri::Result::SUCCESS) { + m_Status = std::string("Failed to build ") + GetCodecName(m_Config.codec) + " Annex-B parameter sets"; + return false; + } + + void* headerPtr = nri.MapBuffer(*m_BitstreamHeaderUploadBuffer, 0, ENCODED_SLICE_OFFSET); + if (!headerPtr) { + m_Status = "Failed to map bitstream header upload buffer"; + return false; + } + std::memset(headerPtr, 0, (size_t)ENCODED_SLICE_OFFSET); + std::memcpy(headerPtr, annexBHeaders.data(), annexBHeaders.size()); + nri.UnmapBuffer(*m_BitstreamHeaderUploadBuffer); + + if (isKeyFrame) + headers = annexBHeaders; + return true; +} + +bool Encoder::ResolveFeedback(nri::VideoEncodeFeedback& feedback, bool& feedbackResolved) { + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + feedbackResolved = false; + + if (m_Capabilities.encodeFeedbackResolveRequired) { + const bool onEncodeQueue = m_Capabilities.resolvedMetadataQueueType == nri::QueueType::VIDEO_ENCODE; + if (!SubmitOneTime(nri, *m_ResolveQueue, [&](nri::CommandBuffer& commandBuffer) { + nri::BufferBarrierDesc bufferBarriers[2] = {}; + uint32_t bufferBarrierNum = 0; + bufferBarriers[bufferBarrierNum].buffer = m_ResolvedMetadataBuffer; + bufferBarriers[bufferBarrierNum++].after = m_Capabilities.resolvedMetadataState; + if (onEncodeQueue && m_MetadataBuffer) { + bufferBarriers[bufferBarrierNum].buffer = m_MetadataBuffer; + bufferBarriers[bufferBarrierNum++].after = {nri::AccessBits::VIDEO_ENCODE_READ, nri::StageBits::VIDEO_ENCODE}; + } + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = bufferBarriers; + barrierDesc.bufferNum = bufferBarrierNum; + nri.CmdBarrier(commandBuffer, barrierDesc); + m_Context.video->CmdResolveVideoEncodeFeedback(commandBuffer, *m_Session, *m_ResolvedMetadataBuffer, 0); + for (uint32_t i = 0; i < bufferBarrierNum; i++) { + bufferBarriers[i].before = bufferBarriers[i].after; + bufferBarriers[i].after = {}; + } + nri.CmdBarrier(commandBuffer, barrierDesc); + })) { + m_Status = "Encode feedback resolve submission failed"; + return false; + } + } + + // D3D12: the resolved metadata lives on the device (written by the encode or by the resolve), copy it to the readback buffer + { + if (m_ResolvedMetadataReadbackBuffer != m_ResolvedMetadataBuffer) { + if (!SubmitOneTime(nri, *m_Context.graphicsQueue, [&](nri::CommandBuffer& commandBuffer) { + nri::BufferBarrierDesc bufferBarriers[2] = {}; + bufferBarriers[0].buffer = m_ResolvedMetadataBuffer; + bufferBarriers[0].after = {nri::AccessBits::COPY_SOURCE, nri::StageBits::COPY}; + bufferBarriers[1].buffer = m_ResolvedMetadataReadbackBuffer; + bufferBarriers[1].after = {nri::AccessBits::COPY_DESTINATION, nri::StageBits::COPY}; + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = bufferBarriers; + barrierDesc.bufferNum = helper::GetCountOf(bufferBarriers); + nri.CmdBarrier(commandBuffer, barrierDesc); + nri.CmdCopyBuffer(commandBuffer, *m_ResolvedMetadataReadbackBuffer, 0, *m_ResolvedMetadataBuffer, 0, nri.GetBufferDesc(*m_ResolvedMetadataBuffer).size); + for (nri::BufferBarrierDesc& bufferBarrier : bufferBarriers) { + bufferBarrier.before = bufferBarrier.after; + bufferBarrier.after = {}; + } + nri.CmdBarrier(commandBuffer, barrierDesc); + })) { + m_Status = "Encode feedback readback submission failed"; + return false; + } + } + } + + const nri::Result result = video.GetVideoEncodeFeedback(*m_Session, *m_ResolvedMetadataReadbackBuffer, 0, feedback); + if (result != nri::Result::SUCCESS) { + m_Status = result == nri::Result::UNSUPPORTED ? std::string(GetCodecName(m_Config.codec)) + " encode metadata feedback is unsupported" : "Failed to read resolved encode metadata"; + return false; + } + + feedbackResolved = true; + return true; +} + +// No feedback: the bitstream buffer is zeroed before each frame, so the payload ends at the last non-zero byte +bool Encoder::ScanFeedback(nri::VideoEncodeFeedback& feedback) { + NRIInterface& nri = *m_Context.nri; + const uint8_t* bitstream = (const uint8_t*)nri.MapBuffer(*m_BitstreamBuffer, ENCODED_SLICE_OFFSET, m_Size.bitstreamSize - ENCODED_SLICE_OFFSET); + if (!bitstream) { + m_Status = "Failed to map the encode bitstream"; + return false; + } + + uint64_t size = m_Size.bitstreamSize - ENCODED_SLICE_OFFSET; + while (size && !bitstream[size - 1]) + size--; + nri.UnmapBuffer(*m_BitstreamBuffer); + + feedback = {}; + feedback.encodedBitstreamWrittenBytes = size; + feedback.writtenSubregionNum = 1; + return true; +} + +bool Encoder::BuildAv1DecodeInfo(EncodedFrame& frame, const nri::VideoEncodePictureDesc& pictureDesc, const nri::VideoAV1EncodePictureDesc& av1PictureDesc, const nri::VideoAV1ReferenceDesc* av1References, uint32_t av1ReferenceNum) { + nri::VideoInterface& video = *m_Context.video; + + nri::VideoAV1EncodeDecodeInfoDesc av1InfoDesc = {}; + av1InfoDesc.feedback = &frame.feedback; + av1InfoDesc.sequence = &m_CodecParameters.av1Sequence; + av1InfoDesc.references = av1References; + av1InfoDesc.referenceNum = av1ReferenceNum; + av1InfoDesc.pictureDesc = &pictureDesc; + av1InfoDesc.av1PictureDesc = &av1PictureDesc; + + Av1InfoMode mode = m_Config.av1Info; + if (mode == Av1InfoMode::AUTO) + mode = m_Context.graphicsAPI == nri::GraphicsAPI::VK ? Av1InfoMode::HEADER : Av1InfoMode::METADATA; + + // The resolved metadata requires encode feedback + nri::Result result = nri::Result::UNSUPPORTED; + nri::Result metadataResult = nri::Result::UNSUPPORTED; + if (mode == Av1InfoMode::METADATA && m_UseFeedback) { + // Submitted descriptions only, no payload header + metadataResult = video.GetVideoAV1EncodeDecodeInfo(*m_Session, *m_ResolvedMetadataReadbackBuffer, 0, av1InfoDesc, frame.av1DecodeInfo); + result = metadataResult; + if (result == nri::Result::UNSUPPORTED) + frame.av1MetadataUnsupported = true; + } + + if (result != nri::Result::SUCCESS) { + av1InfoDesc.encodedPayloadHeader = frame.payload.data(); + av1InfoDesc.encodedPayloadHeaderSize = frame.payload.size(); + result = video.GetVideoAV1EncodeDecodeInfo(*m_Session, *m_ResolvedMetadataReadbackBuffer, 0, av1InfoDesc, frame.av1DecodeInfo); + } + + if (result != nri::Result::SUCCESS) { + // Unsupported only if no path can work (e.g. D3D12 without encode feedback: the payload has no frame header to parse). A failing + // metadata path stays a failure, even if the payload header fallback is unsupported + m_Unsupported = result == nri::Result::UNSUPPORTED && metadataResult == nri::Result::UNSUPPORTED; + m_Status = m_Unsupported ? "AV1 decode metadata is unsupported for this configuration" : "Failed to prepare AV1 decode metadata"; + return false; + } + + frame.hasAv1DecodeInfo = true; + return true; +} + +bool Encoder::Encode(const EncodeRequest& request, EncodedFrame& frame) { + if (!m_Ready || !request.nv12Buffer || !request.nv12Layout) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " encoder is not ready"; + return false; + } + + NRIInterface& nri = *m_Context.nri; + nri::VideoInterface& video = *m_Context.video; + const FramePlan& plan = request.plan; + const bool isH26 = m_Config.codec != SampleCodec::AV1; + const bool isKeyFrame = plan.type == nri::VideoFrameType::IDR; + const uint32_t minQ = m_Config.codec == SampleCodec::AV1 ? 1 : 0; + + frame = {}; + frame.plan = plan; + + // Source + if (!CopyNv12BufferToTexture(nri, *m_Context.graphicsQueue, *request.nv12Layout, *request.nv12Buffer, request.nv12BufferState, m_Input, request.nv12Width, request.nv12Height)) { + m_Status = "Failed to upload NV12 source to video texture"; + return false; + } + + if (!UploadHeaders(plan, frame.headers)) + return false; + + if (!SubmitOneTime(nri, *m_Context.graphicsQueue, [&](nri::CommandBuffer& commandBuffer) { + nri.CmdZeroBuffer(commandBuffer, *m_BitstreamBuffer, 0, m_Size.bitstreamSize); + nri.CmdCopyBuffer(commandBuffer, *m_BitstreamBuffer, 0, *m_BitstreamHeaderUploadBuffer, 0, ENCODED_SLICE_OFFSET); + })) { + m_Status = std::string("Failed to upload ") + GetCodecName(m_Config.codec) + " Annex-B parameter sets"; + return false; + } + + // References, in the order of the plan (reversed on odd H.265 pictures to test RPS ordering) + nri::VideoReference references[MAX_REFERENCE_NUM] = {}; + nri::VideoH264EncodeReferenceDesc h264References[MAX_REFERENCE_NUM] = {}; + nri::VideoH265ReferenceDesc h265References[MAX_REFERENCE_NUM] = {}; + PlanReference orderedReferences[MAX_REFERENCE_NUM] = {}; + for (uint32_t i = 0; i < plan.referenceNum; i++) + orderedReferences[i] = plan.references[plan.reverseReferenceOrder ? plan.referenceNum - 1 - i : i]; + for (uint32_t i = 0; i < plan.referenceNum; i++) { + const PlanReference& reference = orderedReferences[i]; + references[i] = {m_Dpb[reference.slot].picture, reference.slot}; + h264References[i] = {reference.type, 0, reference.listIndex, 0, reference.frameNum, reference.poc, reference.slot, 0, 0}; + h265References[i] = {reference.slot, reference.poc, 0, reference.type, 0, reference.listIndex}; + } + + nri::VideoEncodePictureDesc pictureDesc = {}; + pictureDesc.frameType = plan.type; + pictureDesc.frameIndex = plan.frameNum; + pictureDesc.pictureOrderCount = plan.poc; + pictureDesc.idrPictureId = (uint16_t)plan.idrPictureId; + + nri::VideoH264EncodePictureDesc h264PictureDesc = {}; + h264PictureDesc.sequenceParameterSetId = m_CodecParameters.h264Sps.sequenceParameterSetId; + h264PictureDesc.pictureParameterSetId = m_CodecParameters.h264Pps.pictureParameterSetId; + h264PictureDesc.references = plan.referenceNum ? h264References : nullptr; + h264PictureDesc.referenceNum = plan.referenceNum; + + nri::VideoH265EncodePictureDesc h265PictureDesc = {}; + h265PictureDesc.videoParameterSetId = m_CodecParameters.h265Vps.videoParameterSetId; + h265PictureDesc.sequenceParameterSetId = m_CodecParameters.h265Sps.sequenceParameterSetId; + h265PictureDesc.pictureParameterSetId = m_CodecParameters.h265Pps.pictureParameterSetId; + + // AV1: all reference names map to the latest reference picture (DPB slots alternate, "refFrameIndex" 0 is always the latest) + nri::VideoAV1ReferenceDesc av1References[8] = {}; + uint32_t av1ReferenceNum = 0; + if (m_Config.codec == SampleCodec::AV1 && plan.referenceNum) { + const PlanReference& reference = plan.references[0]; + for (nri::VideoAV1ReferenceName name : AV1_REFERENCE_NAMES) { + nri::VideoAV1ReferenceDesc& av1Reference = av1References[av1ReferenceNum++]; + av1Reference.name = name; + av1Reference.refFrameIndex = 0; + av1Reference.frameType = reference.type; + av1Reference.orderHint = reference.orderHint; + av1Reference.frameId = reference.frameId; + av1Reference.slot = reference.slot; + } + } + + uint16_t av1MiColumnStarts[] = {0, (uint16_t)(2 * ((m_Size.codedWidth + 7) >> 3))}; + uint16_t av1MiRowStarts[] = {0, (uint16_t)(2 * ((m_Size.codedHeight + 7) >> 3))}; + uint16_t av1WidthInSuperblocksMinus1[] = {(uint16_t)(((m_Size.codedWidth + 63) / 64) - 1)}; + uint16_t av1HeightInSuperblocksMinus1[] = {(uint16_t)(((m_Size.codedHeight + 63) / 64) - 1)}; + nri::VideoAV1TileLayoutDesc av1TileLayout = {}; + av1TileLayout.columnNum = 1; + av1TileLayout.rowNum = 1; + av1TileLayout.tileSizeBytesMinus1 = 3; + av1TileLayout.uniformSpacing = 1; + av1TileLayout.miColumnStarts = av1MiColumnStarts; + av1TileLayout.miRowStarts = av1MiRowStarts; + av1TileLayout.widthInSuperblocksMinus1 = av1WidthInSuperblocksMinus1; + av1TileLayout.heightInSuperblocksMinus1 = av1HeightInSuperblocksMinus1; + nri::VideoAV1LoopFilterDesc av1LoopFilter = {}; + av1LoopFilter.refDeltas[0] = 1; + av1LoopFilter.refDeltas[4] = -1; + av1LoopFilter.refDeltas[6] = -1; + av1LoopFilter.refDeltas[7] = -1; + nri::VideoAV1CdefDesc av1Cdef = {}; + nri::VideoAV1LoopRestorationDesc av1LoopRestoration = {}; + nri::VideoAV1GlobalMotionDesc av1GlobalMotion = {}; + for (auto& params : av1GlobalMotion.params) { + params[2] = 1 << 16; + params[5] = 1 << 16; + } + + const bool isVK = m_Context.graphicsAPI == nri::GraphicsAPI::VK; + const bool av1LosslessFallback = m_Config.codec == SampleCodec::AV1 && request.quality.lossless; + nri::VideoAV1PictureBits av1CommonPictureFlags = nri::VideoAV1PictureBits::SHOW_FRAME; + if (m_Context.graphicsAPI == nri::GraphicsAPI::D3D12) + av1CommonPictureFlags |= nri::VideoAV1PictureBits::SEGMENTATION_ENABLED; + + nri::VideoAV1EncodePictureDesc av1PictureDesc = {}; + av1PictureDesc.currentFrameId = plan.frameNum; + av1PictureDesc.orderHint = plan.av1OrderHint; + av1PictureDesc.refreshFrameFlags = plan.av1RefreshFrameFlags; + av1PictureDesc.primaryReferenceName = isKeyFrame ? nri::VideoAV1ReferenceName::NONE : nri::VideoAV1ReferenceName::LAST; + av1PictureDesc.flags = isKeyFrame ? av1CommonPictureFlags | nri::VideoAV1PictureBits::ERROR_RESILIENT_MODE : av1CommonPictureFlags; + av1PictureDesc.renderWidthMinus1 = (uint16_t)((isVK ? m_Size.codedWidth : m_Size.videoWidth) - 1); + av1PictureDesc.renderHeightMinus1 = (uint16_t)((isVK ? m_Size.codedHeight : m_Size.videoHeight) - 1); + av1PictureDesc.baseQIndex = (uint8_t)(request.quality.lossless ? 1 : std::max(request.quality.av1BaseQIndex, minQ)); + av1PictureDesc.interpolationFilter = 0; + av1PictureDesc.txMode = 2; + av1PictureDesc.cdefDampingMinus3 = 3; + av1PictureDesc.tileLayout = isVK ? nullptr : &av1TileLayout; + av1PictureDesc.loopFilter = isVK ? nullptr : &av1LoopFilter; + av1PictureDesc.cdef = isVK ? nullptr : &av1Cdef; + av1PictureDesc.loopRestoration = isVK ? nullptr : &av1LoopRestoration; + av1PictureDesc.globalMotion = isVK ? nullptr : &av1GlobalMotion; + av1PictureDesc.references = av1ReferenceNum ? av1References : nullptr; + av1PictureDesc.referenceNum = av1ReferenceNum; + + // Rate control + const RateControlSetting& rateControl = request.quality.rateControl; + auto getQp = [&](uint32_t qp) { + return (uint8_t)(request.quality.lossless ? (av1LosslessFallback ? 1 : 0) : std::max(qp, minQ)); + }; + nri::VideoEncodeRateControlDesc rateControlDesc = {}; + rateControlDesc.mode = rateControl.kind == RateControlKind::CBR ? nri::VideoEncodeRateControlMode::CBR : (rateControl.kind == RateControlKind::VBR ? nri::VideoEncodeRateControlMode::VBR : nri::VideoEncodeRateControlMode::CQP); + rateControlDesc.qpI = getQp(request.quality.qpI); + rateControlDesc.qpP = getQp(request.quality.qpP); + rateControlDesc.qpB = getQp(request.quality.qpB); + rateControlDesc.frameRateNumerator = 30; + rateControlDesc.frameRateDenominator = 1; + if (rateControl.kind != RateControlKind::CQP) { + rateControlDesc.targetBitrate = uint64_t(rateControl.bitrateKbps) * 1000; + rateControlDesc.maxBitrate = uint64_t(rateControl.maxBitrateKbps ? rateControl.maxBitrateKbps : rateControl.bitrateKbps) * 1000; + rateControlDesc.qpMin = (uint8_t)rateControl.qpMin; + rateControlDesc.qpMax = (uint8_t)rateControl.qpMax; + rateControlDesc.maxFrameBitSize = rateControl.maxFrameBits; + rateControlDesc.virtualBufferSizeMs = rateControl.vbvMs; + rateControlDesc.initialVirtualBufferSizeMs = rateControl.vbvInitialMs; + } + + // Encode + // Non-reference pictures (B frames, AV1 "refreshFrameFlags = 0") still write the setup slot + PictureSlot* reconstructed = &m_Dpb[plan.setupSlot]; + + nri::VideoEncodeDesc encodeDesc = {}; + encodeDesc.session = m_Session; + encodeDesc.parameters = m_Parameters; + encodeDesc.srcPicture = m_Input.picture; + encodeDesc.dstBitstream.buffer = m_BitstreamBuffer; + encodeDesc.dstBitstream.offset = ENCODED_SLICE_OFFSET; + encodeDesc.dstBitstream.size = m_Size.bitstreamSize - ENCODED_SLICE_OFFSET; + encodeDesc.bitstreamMetadataSize = ENCODED_SLICE_OFFSET; + encodeDesc.pictureDesc = &pictureDesc; + encodeDesc.rateControlDesc = &rateControlDesc; + encodeDesc.reconstructedPicture = reconstructed ? reconstructed->picture : nullptr; + encodeDesc.reconstructedSlot = plan.setupSlot; + encodeDesc.references = plan.referenceNum ? references : nullptr; + encodeDesc.referenceNum = plan.referenceNum; + encodeDesc.metadata = m_MetadataBuffer; + encodeDesc.resolvedMetadata = m_UseFeedback ? m_ResolvedMetadataBuffer : nullptr; + encodeDesc.h264PictureDesc = m_Config.codec == SampleCodec::H264 ? &h264PictureDesc : nullptr; + encodeDesc.h265PictureDesc = m_Config.codec == SampleCodec::H265 ? &h265PictureDesc : nullptr; + encodeDesc.h265ReferenceDescs = (m_Config.codec == SampleCodec::H265 && plan.referenceNum) ? h265References : nullptr; + encodeDesc.av1PictureDesc = m_Config.codec == SampleCodec::AV1 ? &av1PictureDesc : nullptr; + + // Picture states + PictureSlot* pictures[2 + MAX_REFERENCE_NUM] = {}; + nri::VideoPictureState states[2 + MAX_REFERENCE_NUM] = {}; + uint32_t pictureNum = 0; + bool statesOk = true; + auto addPicture = [&](PictureSlot* slot, nri::VideoPictureRole role) { + statesOk = statesOk && video.GetVideoPictureState(*slot->picture, role, states[pictureNum]) == nri::Result::SUCCESS; + pictures[pictureNum++] = slot; + }; + addPicture(&m_Input, nri::VideoPictureRole::ENCODE_INPUT); + if (reconstructed) + addPicture(reconstructed, nri::VideoPictureRole::ENCODE_RECONSTRUCTED); + for (uint32_t i = 0; i < plan.referenceNum; i++) + addPicture(&m_Dpb[plan.references[i].slot], nri::VideoPictureRole::ENCODE_REFERENCE); + if (!statesOk) { + m_Status = "Failed to query video encode picture states"; + return false; + } + + if (!SubmitOneTime(nri, *m_Context.encodeQueue, [&](nri::CommandBuffer& commandBuffer) { + // D3D12 resolves the metadata inside the encode: the resolved buffer is written in the advertised state + const bool resolveInEncode = m_UseFeedback && !m_Capabilities.encodeFeedbackResolveRequired && m_ResolvedMetadataReadbackBuffer != m_ResolvedMetadataBuffer; + + nri::BufferBarrierDesc bufferBarriers[2] = {}; + uint32_t bufferBarrierNum = 0; + if (m_MetadataBuffer) { + bufferBarriers[bufferBarrierNum].buffer = m_MetadataBuffer; + bufferBarriers[bufferBarrierNum++].after = {nri::AccessBits::VIDEO_ENCODE_WRITE, nri::StageBits::VIDEO_ENCODE}; + } + if (resolveInEncode) { + bufferBarriers[bufferBarrierNum].buffer = m_ResolvedMetadataBuffer; + bufferBarriers[bufferBarrierNum++].after = m_Capabilities.resolvedMetadataState; + } + + nri::TextureBarrierDesc textureBarriers[2 + MAX_REFERENCE_NUM] = {}; + for (uint32_t i = 0; i < pictureNum; i++) + textureBarriers[i] = MakePictureBarrier(*pictures[i], pictures[i]->state, states[i].required); + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = bufferBarriers; + barrierDesc.bufferNum = bufferBarrierNum; + barrierDesc.textures = textureBarriers; + barrierDesc.textureNum = pictureNum; + nri.CmdBarrier(commandBuffer, barrierDesc); + + video.CmdEncodeVideo(commandBuffer, encodeDesc); + + for (uint32_t i = 0; i < bufferBarrierNum; i++) { + bufferBarriers[i].before = bufferBarriers[i].after; + bufferBarriers[i].after = {}; + } + uint32_t postTextureNum = 0; + for (uint32_t i = 0; i < pictureNum; i++) { + if (!states[i].transitionOnVideoQueue) + continue; + textureBarriers[postTextureNum++] = MakePictureBarrier(*pictures[i], states[i].required, states[i].videoQueueAfter); + } + barrierDesc.textureNum = postTextureNum; + nri.CmdBarrier(commandBuffer, barrierDesc); + })) { + m_Status = std::string(GetCodecName(m_Config.codec)) + " encode submission failed"; + return false; + } + for (uint32_t i = 0; i < pictureNum; i++) + ApplyVideoPictureState(*pictures[i], states[i]); + + // Feedback + if (m_UseFeedback) { + if (!ResolveFeedback(frame.feedback, frame.feedbackResolved)) + return false; + } else if (!ScanFeedback(frame.feedback)) + return false; + + if (frame.feedback.errorFlags || !frame.feedback.encodedBitstreamWrittenBytes) { + char message[160] = {}; + std::snprintf(message, sizeof(message), "Encoder returned errorFlags=0x%llX bytes=%llu", + (unsigned long long)frame.feedback.errorFlags, (unsigned long long)frame.feedback.encodedBitstreamWrittenBytes); + m_Status = message; + return false; + } + + // Payload + const uint64_t payloadOffset = ENCODED_SLICE_OFFSET + frame.feedback.encodedBitstreamOffset; + const uint64_t payloadSize = frame.feedback.encodedBitstreamWrittenBytes; + if (payloadOffset > m_Size.bitstreamSize || payloadSize > m_Size.bitstreamSize - payloadOffset) { + m_Status = "Encoded bitstream range exceeds the bitstream buffer"; + return false; + } + const uint8_t* payload = (const uint8_t*)nri.MapBuffer(*m_BitstreamBuffer, payloadOffset, payloadSize); + if (!payload) { + m_Status = "Failed to map the encode bitstream"; + return false; + } + frame.payload.assign(payload, payload + payloadSize); + nri.UnmapBuffer(*m_BitstreamBuffer); + + if (m_Config.codec == SampleCodec::AV1) { + if (!BuildAv1DecodeInfo(frame, pictureDesc, av1PictureDesc, av1ReferenceNum ? av1References : nullptr, av1ReferenceNum)) + return false; + } + (void)isH26; + + m_Status = std::string(GetCodecName(m_Config.codec)) + " encode complete"; + return true; +} + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Encoder.h b/Source/VideoEncodeDecode/Encoder.h new file mode 100644 index 0000000..b33b469 --- /dev/null +++ b/Source/VideoEncodeDecode/Encoder.h @@ -0,0 +1,79 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#include "Shared.h" + +namespace video_sample { + +struct EncodeRequest { + nri::Buffer* nv12Buffer = nullptr; + nri::AccessStage nv12BufferState = {}; + const Nv12BufferLayout* nv12Layout = nullptr; + uint32_t nv12Width = 0; + uint32_t nv12Height = 0; + VideoQuality quality = {}; + FramePlan plan = {}; +}; + +class Encoder { +public: + Encoder() = default; + ~Encoder(); + + Encoder(const Encoder&) = delete; + Encoder& operator=(const Encoder&) = delete; + + bool Initialize(const VideoContext& context, const VideoConfig& config, const VideoSize& size, const CodecParameters& codecParameters); + bool Encode(const EncodeRequest& request, EncodedFrame& encodedFrame); + + bool IsReady() const { + return m_Ready; + } + + bool IsUnsupported() const { + return m_Unsupported; + } + + const nri::VideoCapabilities& GetCapabilities() const { + return m_Capabilities; + } + + const std::string& GetStatus() const { + return m_Status; + } + +private: + bool UploadHeaders(const FramePlan& plan, std::vector& headers); + bool ResolveFeedback(nri::VideoEncodeFeedback& feedback, bool& feedbackResolved); + bool ScanFeedback(nri::VideoEncodeFeedback& feedback); + bool BuildAv1DecodeInfo(EncodedFrame& frame, const nri::VideoEncodePictureDesc& pictureDesc, const nri::VideoAV1EncodePictureDesc& av1PictureDesc, const nri::VideoAV1ReferenceDesc* av1References, uint32_t av1ReferenceNum); + +private: + VideoContext m_Context = {}; + VideoConfig m_Config = {}; + VideoSize m_Size = {}; + CodecParameters m_CodecParameters = {}; + nri::VideoCapabilities m_Capabilities = {}; + std::string m_Status = "Initializing encoder"; + + nri::VideoSession* m_Session = nullptr; + nri::VideoSessionParameters* m_Parameters = nullptr; + std::vector m_Textures; + PictureSlot m_Input = {}; + PictureSlot m_Dpb[MAX_DPB_SLOT_NUM] = {}; + uint32_t m_DpbSlotNum = 0; + nri::Buffer* m_BitstreamHeaderUploadBuffer = nullptr; + nri::Buffer* m_BitstreamBuffer = nullptr; + nri::Buffer* m_MetadataBuffer = nullptr; + nri::Buffer* m_ResolvedMetadataBuffer = nullptr; // VK: the readback buffer + nri::Buffer* m_ResolvedMetadataReadbackBuffer = nullptr; + nri::Queue* m_ResolveQueue = nullptr; + + bool m_Ready = false; + bool m_Unsupported = false; + bool m_UseFeedback = false; + std::vector m_Headers; +}; + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Shared.h b/Source/VideoEncodeDecode/Shared.h new file mode 100644 index 0000000..b7d0e2b --- /dev/null +++ b/Source/VideoEncodeDecode/Shared.h @@ -0,0 +1,668 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#if defined(_WIN32) +# include +#endif + +#include "NRIFramework.h" + +#include "Extensions/NRIVideo.h" + +#include +#include +#include +#include +#include +#include + +namespace video_sample { + +constexpr uint32_t DEFAULT_VIDEO_WIDTH = 1920; +constexpr uint32_t DEFAULT_VIDEO_HEIGHT = 1080; +constexpr double ROUND_TRIP_INTERVAL_SEC = 1.0 / 60.0; +constexpr uint64_t ENCODED_SLICE_OFFSET = 4096; +constexpr uint64_t RESOLVED_METADATA_SIZE = 4096; +constexpr uint32_t MAX_REFERENCE_NUM = 8; +constexpr uint32_t MAX_DPB_SLOT_NUM = MAX_REFERENCE_NUM + 1; // references + one setup slot + +enum PatternOperation : uint32_t { + OP_GENERATE_PATTERN = 0, + OP_NV12_TO_PREVIEW = 1, +}; + +enum class SampleCodec : uint8_t { + H264, + H265, + AV1, +}; + +enum class VisualFrameMode : uint8_t { + IDR, + P, + B, +}; + +enum class RateControlKind : uint8_t { + CQP, + CBR, + VBR, +}; + +enum class DecodeDpbMode : uint8_t { + AUTO, // coincide if supported + COINCIDE, // decode output is the DPB setup picture + DISTINCT, // decode output ("VIDEO_OUTPUT_ONLY") differs from the DPB setup picture +}; + +enum class DpbLayout : uint8_t { + AUTO, // texture array if the backend requires it, otherwise separate textures + ARRAY, // one texture array, one layer per DPB slot + SEPARATE, // one texture per DPB slot +}; + +enum class Av1InfoMode : uint8_t { + AUTO, // VK: payload header, D3D12: metadata only + HEADER, // "encodedPayloadHeader" + METADATA, // submitted picture descriptions only +}; + +struct Av1SequenceOptions { + bool enableCdef = true; + bool enableRestoration = true; + uint8_t seqForceScreenContentTools = 2; +}; + +struct QueuedFrame { + nri::CommandAllocator* commandAllocator = nullptr; + nri::CommandBuffer* commandBuffer = nullptr; +}; + +struct PatternConstants { + uint32_t width = DEFAULT_VIDEO_WIDTH; + uint32_t height = DEFAULT_VIDEO_HEIGHT; + uint32_t yOffsetBytes = 0; + uint32_t yRowPitchBytes = 0; + uint32_t uvRowPitchBytes = 0; + uint32_t uvOffsetBytes = 0; + uint32_t operation = OP_GENERATE_PATTERN; + float time = 0.0f; + uint32_t _padding = 0; + uint32_t _padding1 = 0; +}; + +struct Nv12BufferLayout { + uint32_t yRowPitchBytes = DEFAULT_VIDEO_WIDTH; + uint32_t ySlicePitchBytes = DEFAULT_VIDEO_WIDTH * DEFAULT_VIDEO_HEIGHT; + uint64_t uvOffsetBytes = uint64_t(DEFAULT_VIDEO_WIDTH) * DEFAULT_VIDEO_HEIGHT; + uint32_t uvRowPitchBytes = DEFAULT_VIDEO_WIDTH; + uint32_t uvSlicePitchBytes = DEFAULT_VIDEO_WIDTH * DEFAULT_VIDEO_HEIGHT / 2; + uint64_t totalSizeBytes = uint64_t(DEFAULT_VIDEO_WIDTH) * DEFAULT_VIDEO_HEIGHT * 3 / 2; +}; + +struct VideoConfig { + SampleCodec codec = SampleCodec::H264; + uint32_t videoWidth = DEFAULT_VIDEO_WIDTH; + uint32_t videoHeight = DEFAULT_VIDEO_HEIGHT; + bool av1PFrameVisual = false; + VisualFrameMode h26FrameMode = VisualFrameMode::IDR; + + // Stream configuration + uint32_t referenceNum = 1; // "VideoSessionDesc::maxReferenceNum" of both sessions, DPB has "referenceNum + 1" slots + bool hasBFrames = false; + uint32_t reorderNum = 0; // SPS max_num_reorder_pics, from the frame plan ("GetReorderNum") + DecodeDpbMode decodeDpb = DecodeDpbMode::AUTO; + bool av1FilmGrain = false; // AV1 decode session that applies film grain (the output is distinct from the DPB picture) + DpbLayout dpbLayout = DpbLayout::AUTO; + bool encodeInputOutputOnly = true; // "VIDEO_OUTPUT_ONLY" encode source + bool h265ListsModification = true; // PPS lists_modification_present_flag + bool reverseDecodeReferences = true; // H.265: pass the decode references of every second picture in the opposite POC order, also without list modification + bool reverseReferences = true; // H.265: pass the references of every second picture in the opposite POC order (the backend sorts them) + bool encodeFeedback = true; // "CmdResolveVideoEncodeFeedback" + "GetVideoEncodeFeedback", otherwise the bitstream is scanned + Av1InfoMode av1Info = Av1InfoMode::AUTO; + bool h265DefaultParameters = false; // encode session parameters are created by the backend (decode and Annex-B headers mirror them) + bool decodePictureAtVideoSize = false; // decode pictures cover the video size (external streams) instead of the coded texture size + bool h264TransformBypass = false; // SPS qpprime_y_zero_transform_bypass_flag (lossless with QP 0), not allowed by the High profile + uint32_t codedAlignment = 1; // minimum alignment of the coded size, e.g. 16 (macroblocks) for drivers that code aligned pictures + uint8_t h264SpsId = 0; + uint8_t h264PpsRefIdxL0DefaultActiveMinus1 = 0; // PPS num_ref_idx_l0_default_active_minus1 + uint8_t h264PpsId = 0; + uint8_t h265VpsId = 0; + uint8_t h265SpsId = 0; + uint8_t h265PpsId = 0; +}; + +struct RateControlSetting { + RateControlKind kind = RateControlKind::CQP; + uint32_t bitrateKbps = 4000; + uint32_t maxBitrateKbps = 0; // VBR peak, 0 = target + uint32_t qpMin = 0; // CBR/VBR QP range, 0 = backend default + uint32_t qpMax = 0; + uint32_t maxFrameBits = 0; // 0 = unlimited + uint32_t vbvMs = 0; // virtual buffer size, 0 = backend default + uint32_t vbvInitialMs = 0; +}; + +struct VideoQuality { + uint32_t qpI = 20; + uint32_t qpP = 22; + uint32_t qpB = 24; + uint32_t av1BaseQIndex = 20; + bool lossless = false; + RateControlSetting rateControl = {}; +}; + +struct VideoSize { + uint32_t videoWidth = DEFAULT_VIDEO_WIDTH; + uint32_t videoHeight = DEFAULT_VIDEO_HEIGHT; + uint32_t codedWidth = DEFAULT_VIDEO_WIDTH; + uint32_t codedHeight = DEFAULT_VIDEO_HEIGHT; + uint32_t decodeBitstreamSizeAlignment = 256; + uint32_t bitstreamOffsetAlignment = 1; + uint32_t bitstreamSizeAlignment = 1; + uint64_t bitstreamSize = 2 * 1024 * 1024; +}; + +struct VideoContext { + NRIInterface* nri = nullptr; + nri::VideoInterface* video = nullptr; + nri::Device* device = nullptr; + nri::Queue* graphicsQueue = nullptr; + nri::Queue* encodeQueue = nullptr; + nri::Queue* decodeQueue = nullptr; + nri::GraphicsAPI graphicsAPI = nri::GraphicsAPI::NONE; +}; + +struct CodecParameters { + nri::VideoH264SequenceParameterSetDesc h264Sps = {}; + nri::VideoH264PictureParameterSetDesc h264Pps = {}; + nri::VideoH265VideoParameterSetDesc h265Vps = {}; + nri::VideoH265SequenceParameterSetDesc h265Sps = {}; + nri::VideoH265PictureParameterSetDesc h265Pps = {}; + nri::VideoAV1SequenceDesc av1Sequence = {}; +}; + +// One coded picture in decode order +struct PlanReference { + uint32_t slot = 0; + int32_t poc = 0; + uint32_t frameNum = 0; + uint32_t frameId = 0; // AV1 + uint8_t orderHint = 0; + nri::VideoFrameType type = nri::VideoFrameType::IDR; + uint8_t listIndex = 0; // H.264/H.265: 0 - List0 (past), 1 - List1 (future) +}; + +struct FramePlan { + nri::VideoFrameType type = nri::VideoFrameType::IDR; + uint32_t codingIndex = 0; + uint32_t displayIndex = 0; + int32_t poc = 0; + uint32_t frameNum = 0; // H.264 "frame_num", AV1 frame id + uint32_t idrPictureId = 0; + uint32_t setupSlot = 0; // always allocated, a non-reference picture takes a free slot + bool isReference = true; + bool isDisplay = true; // interactive: the last picture of a cycle + bool reverseReferenceOrder = false; // H.265 RPS order independence (references are passed in POC-unsorted order) + bool reverseDecodeReferenceOrder = false; // the same for the decode only (encode lists are order dependent without "lists_modification_present_flag") + uint8_t av1RefreshFrameFlags = 0xFF; + uint8_t av1OrderHint = 0; + uint32_t referenceNum = 0; + PlanReference references[MAX_REFERENCE_NUM] = {}; +}; + +struct EncodedFrame { + FramePlan plan = {}; + nri::VideoEncodeFeedback feedback = {}; + std::vector headers; // Annex-B parameter sets, AV1: temporal delimiter + sequence header (key frames only) + std::vector payload; + nri::VideoAV1EncodeDecodeInfo av1DecodeInfo = {}; + bool hasAv1DecodeInfo = false; + bool feedbackResolved = false; + bool av1MetadataUnsupported = false; + bool hasAv1SavedOrderHints = false; // external stream decode: "SavedOrderHints" of the DPB pictures (indexed by DPB slot) instead of zeros + uint8_t av1SavedOrderHints[MAX_DPB_SLOT_NUM][8] = {}; +}; + +struct DecodedFrame { + uint32_t displayIndex = 0; + bool isDisplay = true; +}; + +// Video picture (texture layer) with the state tracked between operations +struct PictureSlot { + nri::Texture* texture = nullptr; + nri::VideoPicture* picture = nullptr; + uint32_t layer = 0; + nri::AccessLayoutStage state = {nri::AccessBits::NONE, nri::Layout::GENERAL, nri::StageBits::NONE}; // source of the next barrier on the same queue + nri::AccessLayoutStage consumerState = {nri::AccessBits::NONE, nri::Layout::GENERAL, nri::StageBits::NONE}; // source of a barrier on another queue +}; + +inline const char* GetCodecName(SampleCodec codec) { + switch (codec) { + case SampleCodec::H265: + return "H.265"; + case SampleCodec::AV1: + return "AV1"; + case SampleCodec::H264: + default: + return "H.264"; + } +} + +inline nri::VideoCodec GetNriCodec(SampleCodec codec) { + switch (codec) { + case SampleCodec::H265: + return nri::VideoCodec::H265; + case SampleCodec::AV1: + return nri::VideoCodec::AV1; + case SampleCodec::H264: + default: + return nri::VideoCodec::H264; + } +} + +inline uint64_t AlignUp(uint64_t value, uint64_t alignment) { + return alignment == 0 ? value : ((value + alignment - 1) / alignment) * alignment; +} + +inline uint64_t AlignDown(uint64_t value, uint64_t alignment) { + return alignment == 0 ? value : (value / alignment) * alignment; +} + +inline uint8_t GetAv1FrameSizeBitsMinus1(uint32_t value) { + uint32_t bits = 0; + uint32_t maxValue = value ? value - 1 : 0; + do { + bits++; + maxValue >>= 1; + } while (maxValue); + return (uint8_t)(bits - 1); +} + +inline nri::VideoAV1SequenceDesc MakeAV1SequenceDesc(uint32_t width, uint32_t height, const Av1SequenceOptions& options) { + nri::VideoAV1SequenceDesc desc = {}; + desc.flags = nri::VideoAV1SequenceBits::ENABLE_ORDER_HINT | nri::VideoAV1SequenceBits::COLOR_DESCRIPTION_PRESENT; + if (options.enableCdef) + desc.flags |= nri::VideoAV1SequenceBits::ENABLE_CDEF; + if (options.enableRestoration) + desc.flags |= nri::VideoAV1SequenceBits::ENABLE_RESTORATION; + desc.bitDepth = 8; + desc.subsamplingX = 1; + desc.subsamplingY = 1; + desc.maxFrameWidthMinus1 = (uint16_t)(width - 1); + desc.maxFrameHeightMinus1 = (uint16_t)(height - 1); + desc.frameWidthBitsMinus1 = GetAv1FrameSizeBitsMinus1(width); + desc.frameHeightBitsMinus1 = GetAv1FrameSizeBitsMinus1(height); + desc.orderHintBitsMinus1 = 7; + desc.seqForceIntegerMv = 2; + desc.seqForceScreenContentTools = options.seqForceScreenContentTools; + desc.colorPrimaries = 1; + desc.transferCharacteristics = 1; + desc.matrixCoefficients = 1; + desc.chromaSamplePosition = 1; + return desc; +} + +inline Nv12BufferLayout MakeNv12BufferLayout(const nri::DeviceDesc& deviceDesc, uint32_t width, uint32_t height) { + const uint32_t rowAlignment = std::max(deviceDesc.memoryAlignment.uploadBufferTextureRow, 1u); + const uint32_t sliceAlignment = std::max(deviceDesc.memoryAlignment.uploadBufferTextureSlice, 1u); + + Nv12BufferLayout layout = {}; + layout.yRowPitchBytes = (uint32_t)AlignUp(width, rowAlignment); + layout.ySlicePitchBytes = (uint32_t)AlignUp(uint64_t(layout.yRowPitchBytes) * height, sliceAlignment); + layout.uvOffsetBytes = layout.ySlicePitchBytes; + layout.uvRowPitchBytes = (uint32_t)AlignUp(width, rowAlignment); + layout.uvSlicePitchBytes = (uint32_t)AlignUp(uint64_t(layout.uvRowPitchBytes) * (height / 2), sliceAlignment); + layout.totalSizeBytes = layout.uvOffsetBytes + layout.uvSlicePitchBytes; + return layout; +} + +// "general_level_idc" is 30 times the level number +inline uint8_t GetH265GeneralLevelIdc(uint32_t width, uint32_t height) { + struct Level { + uint8_t generalLevelIdc; + uint64_t maxLumaPs; + }; + + static const Level levels[] = {{93, 983040}, {123, 2228224}, {153, 8912896}, {183, 35651584}}; + const uint64_t samples = uint64_t(width) * height; + for (const Level& level : levels) { + if (samples <= level.maxLumaPs) + return level.generalLevelIdc; + } + return levels[3].generalLevelIdc; +} + +inline uint8_t GetH264LevelIdc(uint32_t width, uint32_t height) { + const uint64_t macroblockNum = uint64_t((width + 15) / 16) * ((height + 15) / 16); + if (macroblockNum <= 8704) + return 42; + if (macroblockNum <= 36864) + return 51; + return 62; +} + +// Mirrors the parameters the Vulkan backend creates for an H.265 encode session without "h265Parameters" +inline void MakeH265DefaultParameters(CodecParameters& params, uint32_t codedWidth, uint32_t codedHeight, uint32_t maxReferenceNum) { + params.h265Vps = {}; + params.h265Sps = {}; + params.h265Pps = {}; + + params.h265Vps.flags = nri::VideoH265VideoParameterSetBits::TEMPORAL_ID_NESTING; + params.h265Vps.profileTierLevel.generalProfileIdc = 1; + params.h265Vps.profileTierLevel.generalLevelIdc = GetH265GeneralLevelIdc(codedWidth, codedHeight); + params.h265Vps.decPicBufMgr.maxDecPicBufferingMinus1[0] = (uint8_t)std::min(maxReferenceNum ? maxReferenceNum : 1u, 15u); + params.h265Vps.decPicBufMgr.maxNumReorderPics[0] = maxReferenceNum > 1 ? 1 : 0; + + params.h265Sps.flags = nri::VideoH265SequenceParameterSetBits::TEMPORAL_ID_NESTING | nri::VideoH265SequenceParameterSetBits::SAMPLE_ADAPTIVE_OFFSET_ENABLED | nri::VideoH265SequenceParameterSetBits::STRONG_INTRA_SMOOTHING_ENABLED; + params.h265Sps.chromaFormatIdc = 1; + params.h265Sps.pictureWidthInLumaSamples = codedWidth; + params.h265Sps.pictureHeightInLumaSamples = codedHeight; + params.h265Sps.log2MaxPictureOrderCountLsbMinus4 = 4; + params.h265Sps.log2MinLumaCodingBlockSizeMinus3 = 0; + params.h265Sps.log2DiffMaxMinLumaCodingBlockSize = 2; + params.h265Sps.log2MinLumaTransformBlockSizeMinus2 = 0; + params.h265Sps.log2DiffMaxMinLumaTransformBlockSize = 2; + params.h265Sps.maxTransformHierarchyDepthInter = 2; + params.h265Sps.maxTransformHierarchyDepthIntra = 2; + params.h265Sps.profileTierLevel = params.h265Vps.profileTierLevel; + params.h265Sps.decPicBufMgr = params.h265Vps.decPicBufMgr; + + params.h265Pps.flags = nri::VideoH265PictureParameterSetBits::LOOP_FILTER_ACROSS_SLICES_ENABLED | nri::VideoH265PictureParameterSetBits::LISTS_MODIFICATION_PRESENT; + params.h265Pps.log2ParallelMergeLevelMinus2 = 2; +} + +inline CodecParameters MakeCodecParameters(nri::GraphicsAPI graphicsAPI, const VideoConfig& config, uint32_t codedWidth, uint32_t codedHeight) { + CodecParameters params = {}; + + const bool isCropped = codedWidth != config.videoWidth || codedHeight != config.videoHeight; + const uint32_t referenceNum = std::max(config.referenceNum, 1u); + + // H.264 + params.h264Sps.flags = nri::VideoH264SequenceParameterSetBits::DIRECT_8X8_INFERENCE | nri::VideoH264SequenceParameterSetBits::FRAME_MBS_ONLY; + if (config.h264TransformBypass) + params.h264Sps.flags |= nri::VideoH264SequenceParameterSetBits::QPPRIME_Y_ZERO_TRANSFORM_BYPASS; + params.h264Sps.profileIdc = 100; + params.h264Sps.levelIdc = GetH264LevelIdc(codedWidth, codedHeight); + params.h264Sps.chromaFormatIdc = 1; + params.h264Sps.sequenceParameterSetId = config.h264SpsId; + params.h264Sps.log2MaxFrameNumMinus4 = 4; + params.h264Sps.pictureOrderCountType = 0; + params.h264Sps.log2MaxPictureOrderCountLsbMinus4 = 4; + params.h264Sps.referenceFrameNum = (uint8_t)referenceNum; + params.h264Sps.pictureWidthInMbsMinus1 = (uint16_t)((codedWidth + 15) / 16 - 1); + params.h264Sps.pictureHeightInMapUnitsMinus1 = (uint16_t)((codedHeight + 15) / 16 - 1); + // The coded size can be smaller than the macroblock-aligned picture (D3D12 codes the video size) + const uint32_t h264AlignedWidth = (codedWidth + 15) & ~15u; + const uint32_t h264AlignedHeight = (codedHeight + 15) & ~15u; + if (h264AlignedWidth != config.videoWidth || h264AlignedHeight != config.videoHeight) { + // CropUnitX/Y are 2 luma samples (4:2:0, frame_mbs_only) + params.h264Sps.flags |= nri::VideoH264SequenceParameterSetBits::FRAME_CROPPING; + params.h264Sps.frameCropRightOffset = (uint16_t)((h264AlignedWidth - config.videoWidth) / 2); + params.h264Sps.frameCropBottomOffset = (uint16_t)((h264AlignedHeight - config.videoHeight) / 2); + } + + params.h264Pps.flags = nri::VideoH264PictureParameterSetBits::DEBLOCKING_FILTER_CONTROL_PRESENT; + params.h264Pps.sequenceParameterSetId = config.h264SpsId; + params.h264Pps.pictureParameterSetId = config.h264PpsId; + params.h264Pps.refIndexL0DefaultActiveMinus1 = config.h264PpsRefIdxL0DefaultActiveMinus1; + params.h264Pps.refIndexL1DefaultActiveMinus1 = 0; + + // H.265 + if (config.h265DefaultParameters) + MakeH265DefaultParameters(params, codedWidth, codedHeight, referenceNum); + else { + params.h265Vps.flags = nri::VideoH265VideoParameterSetBits::TEMPORAL_ID_NESTING; + params.h265Vps.maxSubLayersMinus1 = 0; + params.h265Vps.profileTierLevel.flags = nri::VideoH265ProfileTierLevelBits::FRAME_ONLY_CONSTRAINT; + params.h265Vps.profileTierLevel.generalProfileIdc = 1; + params.h265Vps.profileTierLevel.generalLevelIdc = GetH265GeneralLevelIdc(codedWidth, codedHeight); + params.h265Vps.decPicBufMgr.maxDecPicBufferingMinus1[0] = (uint8_t)std::min(referenceNum + 1, 15u); + params.h265Vps.decPicBufMgr.maxNumReorderPics[0] = (uint8_t)std::min(config.reorderNum, params.h265Vps.decPicBufMgr.maxDecPicBufferingMinus1[0]); + + params.h265Sps.flags = nri::VideoH265SequenceParameterSetBits::TEMPORAL_ID_NESTING | nri::VideoH265SequenceParameterSetBits::AMP_ENABLED | nri::VideoH265SequenceParameterSetBits::SAMPLE_ADAPTIVE_OFFSET_ENABLED; + params.h265Sps.maxSubLayersMinus1 = params.h265Vps.maxSubLayersMinus1; + params.h265Sps.chromaFormatIdc = 1; + params.h265Sps.pictureWidthInLumaSamples = codedWidth; + params.h265Sps.pictureHeightInLumaSamples = codedHeight; + params.h265Sps.log2MaxPictureOrderCountLsbMinus4 = 3; + params.h265Sps.log2MinLumaCodingBlockSizeMinus3 = 0; + params.h265Sps.log2DiffMaxMinLumaCodingBlockSize = 2; + params.h265Sps.log2MinLumaTransformBlockSizeMinus2 = 0; + params.h265Sps.log2DiffMaxMinLumaTransformBlockSize = 3; + params.h265Sps.maxTransformHierarchyDepthInter = 3; + params.h265Sps.maxTransformHierarchyDepthIntra = 3; + params.h265Sps.profileTierLevel = params.h265Vps.profileTierLevel; + params.h265Sps.decPicBufMgr = params.h265Vps.decPicBufMgr; + + params.h265Pps.flags = nri::VideoH265PictureParameterSetBits::CABAC_INIT_PRESENT | nri::VideoH265PictureParameterSetBits::TRANSFORM_SKIP_ENABLED | nri::VideoH265PictureParameterSetBits::CU_QP_DELTA_ENABLED | nri::VideoH265PictureParameterSetBits::SLICE_CHROMA_QP_OFFSETS_PRESENT | nri::VideoH265PictureParameterSetBits::DEBLOCKING_FILTER_CONTROL_PRESENT; + if (config.h265ListsModification) + params.h265Pps.flags |= nri::VideoH265PictureParameterSetBits::LISTS_MODIFICATION_PRESENT; + } + params.h265Vps.videoParameterSetId = config.h265VpsId; + params.h265Sps.videoParameterSetId = config.h265VpsId; + params.h265Sps.sequenceParameterSetId = config.h265SpsId; + params.h265Pps.videoParameterSetId = config.h265VpsId; + params.h265Pps.sequenceParameterSetId = config.h265SpsId; + params.h265Pps.pictureParameterSetId = config.h265PpsId; + if (isCropped) { + // Conformance window offsets are in chroma sample units (2 luma samples) + params.h265Sps.flags |= nri::VideoH265SequenceParameterSetBits::CONFORMANCE_WINDOW; + params.h265Sps.confWinRightOffset = (codedWidth - config.videoWidth) / 2; + params.h265Sps.confWinBottomOffset = (codedHeight - config.videoHeight) / 2; + } + + // AV1 + Av1SequenceOptions av1SequenceOptions = {}; + if (graphicsAPI == nri::GraphicsAPI::VK) { + av1SequenceOptions.enableCdef = false; + av1SequenceOptions.enableRestoration = false; + av1SequenceOptions.seqForceScreenContentTools = 0; + } + params.av1Sequence = MakeAV1SequenceDesc(codedWidth, codedHeight, av1SequenceOptions); + return params; +} + +template +bool SubmitOneTime(nri::CoreInterface& core, nri::Queue& queue, Record&& record) { + nri::CommandAllocator* allocator = nullptr; + nri::CommandBuffer* commandBuffer = nullptr; + bool ok = core.CreateCommandAllocator(queue, allocator) == nri::Result::SUCCESS && allocator && core.CreateCommandBuffer(*allocator, commandBuffer) == nri::Result::SUCCESS && commandBuffer && core.BeginCommandBuffer(*commandBuffer, nullptr) == nri::Result::SUCCESS; + if (ok) { + std::forward(record)(*commandBuffer); + ok = core.EndCommandBuffer(*commandBuffer) == nri::Result::SUCCESS; + } + if (ok) { + const nri::CommandBuffer* commandBuffers[] = {commandBuffer}; + nri::QueueSubmitDesc submit = {}; + submit.commandBuffers = commandBuffers; + submit.commandBufferNum = 1; + ok = core.QueueSubmit(queue, submit) == nri::Result::SUCCESS && core.QueueWaitIdle(&queue) == nri::Result::SUCCESS; + } + if (commandBuffer) + core.DestroyCommandBuffer(commandBuffer); + if (allocator) + core.DestroyCommandAllocator(allocator); + return ok; +} + +template +bool SubmitOneTime(nri::CoreInterface& core, nri::Queue& queue, nri::DescriptorPool* descriptorPool, Record&& record) { + nri::CommandAllocator* allocator = nullptr; + nri::CommandBuffer* commandBuffer = nullptr; + bool ok = core.CreateCommandAllocator(queue, allocator) == nri::Result::SUCCESS && allocator && core.CreateCommandBuffer(*allocator, commandBuffer) == nri::Result::SUCCESS && commandBuffer && core.BeginCommandBuffer(*commandBuffer, descriptorPool) == nri::Result::SUCCESS; + if (ok) { + std::forward(record)(*commandBuffer); + ok = core.EndCommandBuffer(*commandBuffer) == nri::Result::SUCCESS; + } + if (ok) { + const nri::CommandBuffer* commandBuffers[] = {commandBuffer}; + nri::QueueSubmitDesc submit = {}; + submit.commandBuffers = commandBuffers; + submit.commandBufferNum = 1; + ok = core.QueueSubmit(queue, submit) == nri::Result::SUCCESS && core.QueueWaitIdle(&queue) == nri::Result::SUCCESS; + } + if (commandBuffer) + core.DestroyCommandBuffer(commandBuffer); + if (allocator) + core.DestroyCommandAllocator(allocator); + return ok; +} + +// "src" is in "srcState" before and after the copy +inline bool CopyNv12BufferToTexture(nri::CoreInterface& core, nri::Queue& queue, const Nv12BufferLayout& layout, nri::Buffer& src, nri::AccessStage srcState, PictureSlot& dst, uint32_t width, uint32_t height) { + return SubmitOneTime(core, queue, [&](nri::CommandBuffer& commandBuffer) { + nri::BufferBarrierDesc bufferBarrier = {}; + bufferBarrier.buffer = &src; + bufferBarrier.before = srcState; + bufferBarrier.after = {nri::AccessBits::COPY_SOURCE, nri::StageBits::COPY}; + + nri::TextureBarrierDesc textureBarrier = {}; + textureBarrier.texture = dst.texture; + textureBarrier.before = dst.state; + textureBarrier.after = {nri::AccessBits::COPY_DESTINATION, nri::Layout::COPY_DESTINATION, nri::StageBits::COPY}; + textureBarrier.layerOffset = (nri::Dim_t)dst.layer; + textureBarrier.layerNum = 1; + textureBarrier.mipNum = 1; + textureBarrier.planes = nri::PlaneBits::ALL; + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.buffers = &bufferBarrier; + barrierDesc.bufferNum = 1; + barrierDesc.textures = &textureBarrier; + barrierDesc.textureNum = 1; + core.CmdBarrier(commandBuffer, barrierDesc); + + nri::TextureRegionDesc lumaRegion = {}; + lumaRegion.width = (nri::Dim_t)width; + lumaRegion.height = (nri::Dim_t)height; + lumaRegion.depth = 1; + lumaRegion.layerOffset = (nri::Dim_t)dst.layer; + lumaRegion.planes = nri::PlaneBits::PLANE_0; + + nri::TextureDataLayoutDesc lumaLayout = {}; + lumaLayout.rowPitch = layout.yRowPitchBytes; + lumaLayout.slicePitch = layout.ySlicePitchBytes; + core.CmdUploadBufferToTexture(commandBuffer, *dst.texture, lumaRegion, src, lumaLayout); + + nri::TextureRegionDesc chromaRegion = {}; + chromaRegion.width = (nri::Dim_t)width; + chromaRegion.height = (nri::Dim_t)height; + chromaRegion.depth = 1; + chromaRegion.layerOffset = (nri::Dim_t)dst.layer; + chromaRegion.planes = nri::PlaneBits::PLANE_1; + + nri::TextureDataLayoutDesc chromaLayout = {}; + chromaLayout.offset = layout.uvOffsetBytes; + chromaLayout.rowPitch = layout.uvRowPitchBytes; + chromaLayout.slicePitch = layout.uvSlicePitchBytes; + core.CmdUploadBufferToTexture(commandBuffer, *dst.texture, chromaRegion, src, chromaLayout); + + textureBarrier.before = textureBarrier.after; + textureBarrier.after = {nri::AccessBits::NONE, nri::Layout::GENERAL, nri::StageBits::NONE}; + bufferBarrier.before = bufferBarrier.after; + bufferBarrier.after = srcState; + core.CmdBarrier(commandBuffer, barrierDesc); + dst.state = textureBarrier.after; + dst.consumerState = textureBarrier.after; + }); +} + +inline nri::Result CreateEncodeBitstreamBuffer(nri::CoreInterface& core, nri::Device& device, float priority, const nri::BufferDesc& bufferDesc, nri::Buffer*& buffer) { + return core.CreateCommittedBuffer(device, nri::MemoryLocation::HOST_READBACK, priority, bufferDesc, buffer); +} + +inline nri::Result CreateDecodeBitstreamBuffer(nri::CoreInterface& core, nri::Device& device, float priority, const nri::BufferDesc& bufferDesc, nri::Buffer*& buffer) { + return core.CreateCommittedBuffer(device, nri::MemoryLocation::HOST_UPLOAD, priority, bufferDesc, buffer); +} + +// Creates "slotNum" DPB pictures: layers of one texture or separate textures +inline bool CreatePictureSlots(NRIInterface& nri, nri::VideoInterface& video, nri::Device& device, const nri::TextureDesc& textureDesc, nri::VideoPictureUsage usage, bool useArray, uint32_t slotNum, const char* name, PictureSlot* slots, std::vector& textures, uint32_t pictureWidth = 0, uint32_t pictureHeight = 0) { + nri::TextureDesc desc = textureDesc; + nri::Texture* arrayTexture = nullptr; + if (useArray) { + desc.layerNum = (nri::Dim_t)slotNum; + nri::Texture* texture = nullptr; + if (nri.CreateCommittedTexture(device, nri::MemoryLocation::DEVICE, 0.0f, desc, texture) != nri::Result::SUCCESS) + return false; + nri.SetDebugName(texture, name); + textures.push_back(texture); + arrayTexture = texture; + } + + for (uint32_t i = 0; i < slotNum; i++) { + PictureSlot& slot = slots[i]; + if (useArray) { + slot.texture = arrayTexture; + slot.layer = i; + } else { + desc.layerNum = 1; + if (nri.CreateCommittedTexture(device, nri::MemoryLocation::DEVICE, 0.0f, desc, slot.texture) != nri::Result::SUCCESS) + return false; + nri.SetDebugName(slot.texture, name); + textures.push_back(slot.texture); + slot.layer = 0; + } + + nri::VideoPictureDesc pictureDesc = {}; + pictureDesc.texture = slot.texture; + pictureDesc.usage = usage; + pictureDesc.width = (nri::Dim_t)(pictureWidth ? pictureWidth : textureDesc.width); + pictureDesc.height = (nri::Dim_t)(pictureHeight ? pictureHeight : textureDesc.height); + pictureDesc.layer = (nri::Dim_t)slot.layer; + if (video.CreateVideoPicture(device, pictureDesc, slot.picture) != nri::Result::SUCCESS) + return false; + } + return true; +} + +// Moves new textures from "UNDEFINED" to the resting state +inline bool InitializePictureLayouts(nri::CoreInterface& core, nri::Queue& queue, const std::vector& textures) { + return SubmitOneTime(core, queue, [&](nri::CommandBuffer& commandBuffer) { + std::vector barriers(textures.size()); + for (size_t i = 0; i < textures.size(); i++) { + barriers[i] = {}; + barriers[i].texture = textures[i]; + barriers[i].before = {nri::AccessBits::NONE, nri::Layout::UNDEFINED, nri::StageBits::ALL}; + barriers[i].after = {nri::AccessBits::NONE, nri::Layout::GENERAL, nri::StageBits::NONE}; + barriers[i].mipNum = nri::REMAINING; + barriers[i].layerNum = nri::REMAINING; + barriers[i].planes = nri::PlaneBits::ALL; + } + + nri::BarrierDesc barrierDesc = {}; + barrierDesc.textures = barriers.data(); + barrierDesc.textureNum = (uint32_t)barriers.size(); + core.CmdBarrier(commandBuffer, barrierDesc); + }); +} + +// "ALL" by default; "COLOR" and "PLANE_0 | PLANE_1" cover the other ways to address both planes of an NV12 picture +inline nri::PlaneBits g_PicturePlanes = nri::PlaneBits::ALL; + +inline nri::TextureBarrierDesc MakePictureBarrier(const PictureSlot& slot, nri::AccessLayoutStage before, nri::AccessLayoutStage after) { + nri::TextureBarrierDesc barrier = {}; + barrier.texture = slot.texture; + barrier.before = before; + barrier.after = after; + barrier.layerOffset = (nri::Dim_t)slot.layer; + barrier.layerNum = 1; + barrier.mipNum = 1; + barrier.planes = g_PicturePlanes; + return barrier; +} + +// Updates the tracked state after an operation recorded on a video queue +inline void ApplyVideoPictureState(PictureSlot& slot, const nri::VideoPictureState& state) { + if (state.transitionOnVideoQueue) { + slot.state = state.videoQueueAfter; + slot.consumerState = state.consumerQueueBefore; + } else { + slot.state = state.required; + slot.consumerState = state.consumerQueueBefore; + } +} + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Stream.cpp b/Source/VideoEncodeDecode/Stream.cpp new file mode 100644 index 0000000..75e4241 --- /dev/null +++ b/Source/VideoEncodeDecode/Stream.cpp @@ -0,0 +1,1481 @@ +// © 2021 NVIDIA Corporation + +#include "Stream.h" + +#include "Decoder.h" +#include "Encoder.h" + +// Header-only AV1 frame header parser of NRI (the public "GetVideoAV1EncodeDecodeInfo" needs an AV1 encode session) +#include "SharedVideo.h" + +#include +#include +#include +#include +#include + +namespace video_sample { + +//================================================================================================== +// Test pattern +//================================================================================================== + +void GenerateNv12Pattern(uint8_t* dst, const Nv12BufferLayout& layout, uint32_t width, uint32_t height, uint32_t patternWidth, uint32_t patternHeight, uint32_t frame) { + const int32_t pw = (int32_t)patternWidth; + const int32_t ph = (int32_t)patternHeight; + const int32_t radius = std::max(ph / 8, 8); + const int32_t boxX = (int32_t)((frame * 13u) % (uint32_t)pw); + const int32_t boxY = ph / 3 + (int32_t)((frame * 5u) % (uint32_t)std::max(ph / 3, 1)); + + for (uint32_t y = 0; y < height; y++) { + uint8_t* row = dst + uint64_t(y) * layout.yRowPitchBytes; + for (uint32_t x = 0; x < width; x++) { + int32_t v = 32 + (int32_t)(((x + frame * 3u) % (uint32_t)pw) * 160u / (uint32_t)pw) + (int32_t)(y * 48u / (uint32_t)ph); + v += (((x >> 3) ^ (y >> 3)) & 1) ? 12 : -12; + const int32_t dx = (int32_t)x - boxX; + const int32_t dy = (int32_t)y - boxY; + if (dx * dx + dy * dy < radius * radius) + v = 220 - ((dx * dx + dy * dy) * 60) / (radius * radius); + const uint32_t hash = (x * 73856093u) ^ (y * 19349663u) ^ (frame * 83492791u); + v += (int32_t)((hash >> 13) & 7) - 3; + row[x] = (uint8_t)std::clamp(v, 16, 235); + } + } + + for (uint32_t y = 0; y < height / 2; y++) { + uint8_t* row = dst + layout.uvOffsetBytes + uint64_t(y) * layout.uvRowPitchBytes; + for (uint32_t x = 0; x < width / 2; x++) { + const int32_t fx = (int32_t)x * 2; + const int32_t fy = (int32_t)y * 2; + int32_t u = 128 + (int32_t)(((uint32_t)fx * 50u) / (uint32_t)pw) - 25; + int32_t v = 128 + (int32_t)(((uint32_t)fy * 50u) / (uint32_t)ph) - 25; + const int32_t dx = fx - boxX; + const int32_t dy = fy - boxY; + if (dx * dx + dy * dy < radius * radius) { + u = 90; + v = 200; + } + row[2 * x] = (uint8_t)std::clamp(u, 16, 240); + row[2 * x + 1] = (uint8_t)std::clamp(v, 16, 240); + } + } +} + +//================================================================================================== +// Frame plans +//================================================================================================== + +struct DpbEntry { + uint32_t slot = 0; + int32_t poc = 0; + uint32_t frameNum = 0; + uint32_t frameId = 0; + uint8_t orderHint = 0; + nri::VideoFrameType type = nri::VideoFrameType::IDR; +}; + +// SPS max_num_reorder_pics: the most pictures that precede a picture in decode order and follow it in output order +uint32_t GetReorderNum(const std::vector& plans) { + uint32_t reorderNum = 0; + for (size_t i = 0; i < plans.size(); i++) { + uint32_t num = 0; + for (size_t j = 0; j < i; j++) + num += plans[j].displayIndex > plans[i].displayIndex; + reorderNum = std::max(reorderNum, num); + } + return reorderNum; +} + +std::vector BuildFramePlans(const VideoConfig& config, const std::string& gop, uint32_t frameNum, uint32_t idrPeriod) { + const uint32_t referenceNum = std::clamp(config.referenceNum, 1u, MAX_REFERENCE_NUM); + const bool isAv1 = config.codec == SampleCodec::AV1; + const uint32_t maxFrameNum = 256; // H.264 SPS: log2_max_frame_num = 8 + + std::vector plans; + std::vector dpb; // oldest first + std::vector pendingB; + uint32_t lastReferenceFrameNum = 0; + uint32_t idrDisplayIndex = 0; + uint32_t idrCount = 0; + uint32_t codingIndex = 0; + + const char nonReferenceP = isAv1 ? 'p' : 'P'; + + auto getKind = [&](uint32_t displayIndex) { + if (displayIndex == 0 || (idrPeriod && (displayIndex % idrPeriod) == 0)) + return 'I'; + if (gop.empty()) + return 'P'; + char kind = gop[(displayIndex - 1) % gop.size()]; + if (kind == 'B' && isAv1) + kind = 'p'; + if (kind == 'p' && !isAv1) + kind = 'P'; // H.264/H.265: only B pictures are non-reference (the backend marks them by the frame type) + return kind; + }; + + auto emit = [&](uint32_t displayIndex, char kind) { + FramePlan plan = {}; + plan.codingIndex = codingIndex++; + plan.displayIndex = displayIndex; + plan.type = kind == 'I' ? nri::VideoFrameType::IDR : (kind == 'B' ? nri::VideoFrameType::B : nri::VideoFrameType::P); + plan.isReference = kind == 'I' || kind == 'P'; + + if (kind == 'I') { + dpb.clear(); + idrDisplayIndex = displayIndex; + plan.idrPictureId = idrCount++ & 0xFFFF; + } + + plan.poc = (int32_t)(displayIndex - idrDisplayIndex); + plan.frameNum = kind == 'I' ? 0 : (lastReferenceFrameNum + 1) % maxFrameNum; + plan.av1OrderHint = (uint8_t)(displayIndex & 0xFF); + plan.av1RefreshFrameFlags = kind == 'I' ? 0xFF : (plan.isReference ? 0x1 : 0x0); + if (isAv1) + plan.frameNum = plan.codingIndex; // frame id + + auto toReference = [&](const DpbEntry& entry, uint8_t listIndex) { + PlanReference reference = {}; + reference.slot = entry.slot; + reference.poc = entry.poc; + reference.frameNum = entry.frameNum; + reference.frameId = entry.frameId; + reference.orderHint = entry.orderHint; + reference.type = entry.type; + reference.listIndex = listIndex; + return reference; + }; + + if (kind == 'P' || kind == 'p') { + // The most recent reference first (initial List0 order) + const uint32_t count = isAv1 ? 1u : (uint32_t)std::min(dpb.size(), referenceNum); + for (uint32_t i = 0; i < count && i < dpb.size(); i++) + plan.references[plan.referenceNum++] = toReference(dpb[dpb.size() - 1 - i], 0); + } else if (kind == 'B') { + std::vector past; + std::vector future; + for (const DpbEntry& entry : dpb) + (entry.poc < plan.poc ? past : future).push_back(entry); + std::sort(past.begin(), past.end(), [](const DpbEntry& a, const DpbEntry& b) { return a.poc > b.poc; }); + std::sort(future.begin(), future.end(), [](const DpbEntry& a, const DpbEntry& b) { return a.poc < b.poc; }); + + // The H.265 B picture List0 limit is not exposed by NRI (NVIDIA: 1), H.264 takes the DPB size + const uint32_t pastMax = config.codec == SampleCodec::H265 ? 1u : std::max(referenceNum, 2u) - 1; + const uint32_t pastNum = (uint32_t)std::min(past.size(), pastMax); + for (uint32_t i = 0; i < pastNum; i++) + plan.references[plan.referenceNum++] = toReference(past[i], 0); + if (!future.empty()) + plan.references[plan.referenceNum++] = toReference(future[0], 1); + } + + // A free slot, never one of the DPB pictures + for (uint32_t slot = 0; slot <= referenceNum; slot++) { + bool isUsed = false; + for (const DpbEntry& entry : dpb) + isUsed = isUsed || entry.slot == slot; + if (!isUsed) { + plan.setupSlot = slot; + break; + } + } + + // The H.265 RPS of a picture only lists its own references (NRI cannot keep other DPB pictures), a decoder drops the rest + if (kind == 'B' && config.codec == SampleCodec::H265) { + dpb.erase(std::remove_if(dpb.begin(), dpb.end(), [&](const DpbEntry& entry) { + for (uint32_t i = 0; i < plan.referenceNum; i++) { + if (plan.references[i].slot == entry.slot) + return false; + } + return true; + }), + dpb.end()); + } + + plan.reverseReferenceOrder = config.reverseReferences && config.codec == SampleCodec::H265 && plan.referenceNum > 1 && (plan.codingIndex & 1); + plan.reverseDecodeReferenceOrder = config.reverseDecodeReferences && config.codec == SampleCodec::H265 && plan.referenceNum > 1 && (plan.codingIndex & 1); + + if (plan.isReference) { + DpbEntry entry = {}; + entry.slot = plan.setupSlot; + entry.poc = plan.poc; + entry.frameNum = plan.frameNum; + entry.frameId = plan.codingIndex; + entry.orderHint = plan.av1OrderHint; + entry.type = plan.type; + dpb.push_back(entry); + if (dpb.size() > referenceNum) + dpb.erase(dpb.begin()); + lastReferenceFrameNum = plan.frameNum; + } + + plans.push_back(plan); + }; + + for (uint32_t displayIndex = 0; displayIndex < frameNum; displayIndex++) { + const char kind = getKind(displayIndex); + + if (kind == 'B') { + pendingB.push_back(displayIndex); + continue; + } + + if (kind == 'I') { + // B pictures can't reference across an IDR + for (uint32_t pending : pendingB) + emit(pending, nonReferenceP); + pendingB.clear(); + emit(displayIndex, kind); + continue; + } + + emit(displayIndex, kind); + for (uint32_t pending : pendingB) + emit(pending, 'B'); + pendingB.clear(); + } + + // Trailing B pictures have no future reference + for (uint32_t pending : pendingB) + emit(pending, nonReferenceP); + + return plans; +} + +//================================================================================================== +// Video size +//================================================================================================== + +bool QueryVideoSize(const VideoContext& context, const VideoConfig& config, VideoSize& size, bool& isUnsupported, std::string& status) { + nri::VideoInterface& video = *context.video; + isUnsupported = true; + + nri::VideoSessionDesc encodeSessionDesc = {}; + encodeSessionDesc.type = nri::VideoSessionType::ENCODE; + encodeSessionDesc.codec = GetNriCodec(config.codec); + encodeSessionDesc.format = nri::Format::NV12_UNORM; + // NVIDIA D3D12 H.265 encode corrupts the bottom partial CTB row (driver 617.42, 360, 368, 376 and 400 lines at 32x32 CTBs): code multiples of 32 lines and crop + const uint32_t widthAlignment = config.codedAlignment; + const uint32_t heightAlignment = (context.graphicsAPI == nri::GraphicsAPI::D3D12 && config.codec == SampleCodec::H265) ? std::max(config.codedAlignment, 32u) : config.codedAlignment; + encodeSessionDesc.width = (uint32_t)AlignUp(config.videoWidth, widthAlignment); // the backends that echo the extents need the aligned size + encodeSessionDesc.height = (uint32_t)AlignUp(config.videoHeight, heightAlignment); + encodeSessionDesc.maxReferenceNum = config.referenceNum; + + nri::VideoSessionDesc decodeSessionDesc = encodeSessionDesc; + decodeSessionDesc.type = nri::VideoSessionType::DECODE; + + nri::VideoCapabilities encodeCapabilities = {}; + nri::VideoCapabilities decodeCapabilities = {}; + video.GetVideoCapabilities(*context.device, encodeSessionDesc, encodeCapabilities); + video.GetVideoCapabilities(*context.device, decodeSessionDesc, decodeCapabilities); + if (!encodeCapabilities.pictureAccessGranularityWidth || !encodeCapabilities.pictureAccessGranularityHeight || !decodeCapabilities.pictureAccessGranularityWidth || !decodeCapabilities.pictureAccessGranularityHeight) { + status = std::string(GetCodecName(config.codec)) + " encode or decode is unsupported"; + return false; + } + + const uint32_t codedWidthAlignment = std::max({encodeCapabilities.pictureAccessGranularityWidth, decodeCapabilities.pictureAccessGranularityWidth, widthAlignment}); + const uint32_t codedHeightAlignment = std::max({encodeCapabilities.pictureAccessGranularityHeight, decodeCapabilities.pictureAccessGranularityHeight, heightAlignment}); + const uint32_t codedWidth = (uint32_t)AlignUp(std::max({config.videoWidth, encodeCapabilities.widthMin, decodeCapabilities.widthMin}), codedWidthAlignment); + const uint32_t codedHeight = (uint32_t)AlignUp(std::max({config.videoHeight, encodeCapabilities.heightMin, decodeCapabilities.heightMin}), codedHeightAlignment); + if ((encodeCapabilities.widthMax && codedWidth > encodeCapabilities.widthMax) || (decodeCapabilities.widthMax && codedWidth > decodeCapabilities.widthMax) || (encodeCapabilities.heightMax && codedHeight > encodeCapabilities.heightMax) || (decodeCapabilities.heightMax && codedHeight > decodeCapabilities.heightMax)) { + status = std::string(GetCodecName(config.codec)) + " coded video size " + std::to_string(codedWidth) + "x" + std::to_string(codedHeight) + " exceeds backend capabilities"; + return false; + } + + encodeSessionDesc.width = codedWidth; + encodeSessionDesc.height = codedHeight; + decodeSessionDesc.width = codedWidth; + decodeSessionDesc.height = codedHeight; + if (video.GetVideoCapabilities(*context.device, encodeSessionDesc, encodeCapabilities) != nri::Result::SUCCESS || video.GetVideoCapabilities(*context.device, decodeSessionDesc, decodeCapabilities) != nri::Result::SUCCESS) { + status = std::string(GetCodecName(config.codec)) + " coded video size " + std::to_string(codedWidth) + "x" + std::to_string(codedHeight) + " is unsupported"; + return false; + } + + size = {}; + size.videoWidth = config.videoWidth; + size.videoHeight = config.videoHeight; + size.codedWidth = codedWidth; + size.codedHeight = codedHeight; + size.decodeBitstreamSizeAlignment = std::max(decodeCapabilities.bitstreamSizeAlignment, 1u); + size.bitstreamOffsetAlignment = std::max(encodeCapabilities.bitstreamOffsetAlignment, 1u); + size.bitstreamSizeAlignment = std::max(encodeCapabilities.bitstreamSizeAlignment, 1u); + size.bitstreamSize = AlignUp(std::max(2 * 1024 * 1024, uint64_t(codedWidth) * codedHeight), 1024 * 1024); + + if ((ENCODED_SLICE_OFFSET % size.bitstreamOffsetAlignment) != 0 || ((size.bitstreamSize - ENCODED_SLICE_OFFSET) % size.bitstreamSizeAlignment) != 0) { + status = "Encode bitstream alignment is not satisfiable"; + return false; + } + + isUnsupported = false; + return true; +} + +//================================================================================================== +// Stream run +//================================================================================================== + +namespace { + +struct MessageStats { + uint32_t errorNum = 0; + uint32_t warningNum = 0; + std::vector errors; +}; + +void NRI_CALL MessageCallback(nri::Message messageType, const char* file, uint32_t line, const char* message, void* userArg) { + MessageStats& stats = *(MessageStats*)userArg; + const char* name = messageType == nri::Message::ERROR ? "ERROR" : (messageType == nri::Message::WARNING ? "WARNING" : "INFO"); + + if (messageType == nri::Message::ERROR) { + stats.errorNum++; + if (stats.errors.size() < 4) + stats.errors.push_back(message); + } else if (messageType == nri::Message::WARNING) + stats.warningNum++; + + if (messageType != nri::Message::INFO) + std::fprintf(stderr, "[NRI %s] %s (%s:%u)\n", name, message, file, line); +} + +void NRI_CALL AbortCallback(void*) { + // Errors are counted, the run continues +} + +struct DeviceHolder { + ~DeviceHolder() { + if (device) + nri::nriDestroyDevice(device); + } + + nri::Device* device = nullptr; +}; + +double GetPsnr(double squaredErrorSum, uint64_t sampleNum) { + if (!sampleNum || squaredErrorSum <= 0.0) + return 99.0; + return std::min(99.0, 10.0 * std::log10(255.0 * 255.0 * double(sampleNum) / squaredErrorSum)); +} + +void ComputeSquaredError(const uint8_t* a, const uint8_t* b, uint64_t size, double& sum) { + uint64_t total = 0; + for (uint64_t i = 0; i < size; i++) { + const int32_t d = (int32_t)a[i] - (int32_t)b[i]; + total += uint64_t(d * d); + } + sum += double(total); +} + +const char* GetStreamExtension(SampleCodec codec) { + return codec == SampleCodec::H265 ? "h265" : (codec == SampleCodec::AV1 ? "obu" : "h264"); +} + +bool WriteFile(const std::filesystem::path& path, const std::vector& data) { + FILE* file = std::fopen(path.string().c_str(), "wb"); + if (!file) + return false; + const bool ok = data.empty() || std::fwrite(data.data(), 1, data.size(), file) == data.size(); + std::fclose(file); + return ok; +} + +const char* GetFrameTypeName(nri::VideoFrameType type) { + switch (type) { + case nri::VideoFrameType::IDR: + return "IDR"; + case nri::VideoFrameType::I: + return "I"; + case nri::VideoFrameType::P: + return "P"; + case nri::VideoFrameType::B: + default: + return "B"; + } +} + +} // namespace + +const char* GetStreamStatusName(StreamStatus status) { + switch (status) { + case StreamStatus::PASS: + return "PASS"; + case StreamStatus::UNSUPPORTED: + return "SKIP"; + case StreamStatus::FAIL: + default: + return "FAIL"; + } +} + +StreamResult RunStream(const RunEnvironment& environment, const StreamOptions& options) { + StreamResult result = {}; + MessageStats stats; + VideoConfig config = options.config; + const bool hasB = options.gop.find('B') != std::string::npos && config.codec != SampleCodec::AV1; + config.hasBFrames = hasB; + if (hasB) + config.referenceNum = std::max(config.referenceNum, 2u); + if (config.codec == SampleCodec::AV1) + config.referenceNum = 1; // the AV1 picture layout uses the latest reference only + config.referenceNum = std::clamp(config.referenceNum, 1u, MAX_REFERENCE_NUM); + + auto finish = [&](StreamStatus status, const std::string& message) { + result.status = status; + result.message = message; + result.nriErrorNum = stats.errorNum; + result.nriWarningNum = stats.warningNum; + if (status == StreamStatus::PASS && stats.errorNum) { + result.status = StreamStatus::FAIL; + result.message = "NRI reported " + std::to_string(stats.errorNum) + " error(s): " + (stats.errors.empty() ? "" : stats.errors[0]); + } + return result; + }; + + // Device + nri::AdapterDesc adapters[8] = {}; + uint32_t adapterNum = helper::GetCountOf(adapters); + if (nri::nriEnumerateAdapters(adapters, adapterNum) != nri::Result::SUCCESS || !adapterNum) + return finish(StreamStatus::UNSUPPORTED, "No graphics adapters"); + + // Adapters of the requested API (the list also contains the NONE adapter) + uint32_t apiAdapterNum = 0; + for (uint32_t i = 0; i < adapterNum; i++) { + if (adapters[i].supportedGraphicsAPIs & environment.graphicsAPI) + adapters[apiAdapterNum++] = adapters[i]; + } + if (!apiAdapterNum) + return finish(StreamStatus::UNSUPPORTED, "No adapters support the requested graphics API"); + const nri::AdapterDesc& adapter = adapters[std::min(environment.adapterIndex, apiAdapterNum - 1)]; + result.adapterName = adapter.name; + if (environment.graphicsAPI == nri::GraphicsAPI::D3D11 || !adapter.queueNum[(uint32_t)nri::QueueType::VIDEO_ENCODE] || !adapter.queueNum[(uint32_t)nri::QueueType::VIDEO_DECODE]) + return finish(StreamStatus::UNSUPPORTED, "The adapter has no NRI video encode and decode queues"); + + nri::QueueFamilyDesc queueFamilies[3] = {}; + queueFamilies[0].queueNum = 1; + queueFamilies[0].queueType = nri::QueueType::GRAPHICS; + queueFamilies[1].queueNum = 1; + queueFamilies[1].queueType = nri::QueueType::VIDEO_ENCODE; + queueFamilies[2].queueNum = 1; + queueFamilies[2].queueType = nri::QueueType::VIDEO_DECODE; + + nri::DeviceCreationDesc deviceCreationDesc = {}; + deviceCreationDesc.graphicsAPI = environment.graphicsAPI; + deviceCreationDesc.enableGraphicsAPIValidation = environment.debugAPI; + deviceCreationDesc.enableNRIValidation = environment.debugNRI; + deviceCreationDesc.vkBindingOffsets = VK_BINDING_OFFSETS; + deviceCreationDesc.disableD3D12EnhancedBarriers = environment.graphicsAPI == nri::GraphicsAPI::D3D12 && !environment.enhancedBarriers; // legacy barriers by default + deviceCreationDesc.adapterDesc = &adapter; + deviceCreationDesc.queueFamilies = queueFamilies; + deviceCreationDesc.queueFamilyNum = helper::GetCountOf(queueFamilies); + deviceCreationDesc.callbackInterface.MessageCallback = MessageCallback; + deviceCreationDesc.callbackInterface.AbortExecution = AbortCallback; + deviceCreationDesc.callbackInterface.userArg = &stats; + + DeviceHolder deviceHolder; + if (nri::nriCreateDevice(deviceCreationDesc, deviceHolder.device) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to create the device"); + nri::Device& device = *deviceHolder.device; + + NRIInterface NRI = {}; + nri::VideoInterface Video = {}; + if (nri::nriGetInterface(device, NRI_INTERFACE(nri::CoreInterface), (nri::CoreInterface*)&NRI) != nri::Result::SUCCESS || nri::nriGetInterface(device, NRI_INTERFACE(nri::HelperInterface), (nri::HelperInterface*)&NRI) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to get NRI interfaces"); + if (nri::nriGetInterface(device, NRI_INTERFACE(nri::VideoInterface), &Video) != nri::Result::SUCCESS || !Video.CreateVideoSession) + return finish(StreamStatus::UNSUPPORTED, "NRI video interface is unavailable"); + + VideoContext context = {}; + context.nri = &NRI; + context.video = &Video; + context.device = &device; + context.graphicsAPI = environment.graphicsAPI; + if (NRI.GetQueue(device, nri::QueueType::GRAPHICS, 0, context.graphicsQueue) != nri::Result::SUCCESS || NRI.GetQueue(device, nri::QueueType::VIDEO_ENCODE, 0, context.encodeQueue) != nri::Result::SUCCESS || NRI.GetQueue(device, nri::QueueType::VIDEO_DECODE, 0, context.decodeQueue) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to get queues"); + + VideoSize size = {}; + bool isUnsupported = false; + std::string status; + if (!QueryVideoSize(context, config, size, isUnsupported, status)) + return finish(isUnsupported ? StreamStatus::UNSUPPORTED : StreamStatus::FAIL, status); + + std::vector plans = BuildFramePlans(config, options.gop, options.frameNum, options.idrPeriod); + config.reorderNum = GetReorderNum(plans); + CodecParameters codecParameters = MakeCodecParameters(environment.graphicsAPI, config, size.codedWidth, size.codedHeight); + + if (plans.empty()) + return finish(StreamStatus::FAIL, "Empty frame plan"); + + // Objects (the encoder and decoder must be destroyed before the device) + auto encoder = std::make_unique(); + auto decoder = std::make_unique(); + nri::Buffer* sourceBuffer = nullptr; + nri::Buffer* readbackBuffer = nullptr; + auto cleanup = [&]() { + NRI.DeviceWaitIdle(&device); + decoder.reset(); + encoder.reset(); + if (sourceBuffer) + NRI.DestroyBuffer(sourceBuffer); + if (readbackBuffer) + NRI.DestroyBuffer(readbackBuffer); + }; + + if (!encoder->Initialize(context, config, size, codecParameters)) { + const bool isEncoderUnsupported = encoder->IsUnsupported(); + const std::string message = encoder->GetStatus(); + cleanup(); + return finish(isEncoderUnsupported ? StreamStatus::UNSUPPORTED : StreamStatus::FAIL, message); + } + if (!options.encodeOnly && !decoder->Initialize(context, config, size, codecParameters)) { + const bool isDecoderUnsupported = decoder->IsUnsupported(); + const std::string message = decoder->GetStatus(); + cleanup(); + return finish(isDecoderUnsupported ? StreamStatus::UNSUPPORTED : StreamStatus::FAIL, message); + } + + if (options.verbose) { + const nri::VideoCapabilities& e = encoder->GetCapabilities(); + std::fprintf(stderr, "[%s] encode caps: maxRef=%u extent=%ux%u-%ux%u granularity=%ux%u bitstreamAlign=%u/%u dpbArray=%d(min %u) feedback=%d resolve=%d resolveQueue=%u metadata=%llu resolved=%llu rangeSize=%d\n", options.name.c_str(), e.maxReferenceNum, e.widthMin, e.heightMin, e.widthMax, e.heightMax, e.pictureAccessGranularityWidth, e.pictureAccessGranularityHeight, e.bitstreamOffsetAlignment, e.bitstreamSizeAlignment, e.dpbTextureArrayRequired, e.dpbTextureArrayMinLayerNum, e.encodeFeedbackSupported, e.encodeFeedbackResolveRequired, (uint32_t)e.resolvedMetadataQueueType, (unsigned long long)e.metadataSize, (unsigned long long)e.resolvedMetadataSize, e.encodeBitstreamRangeSizeSupported); + if (!options.encodeOnly) { + const nri::VideoCapabilities& d = decoder->GetCapabilities(); + std::fprintf(stderr, "[%s] decode caps: maxRef=%u extent=%ux%u-%ux%u bitstreamAlign=%u/%u coincide=%d distinct=%d dpbArray=%d(min %u) sources=%u\n", options.name.c_str(), d.maxReferenceNum, d.widthMin, d.heightMin, d.widthMax, d.heightMax, d.bitstreamOffsetAlignment, d.bitstreamSizeAlignment, d.decodeDpbAndOutputCoincide, d.decodeDpbAndOutputDistinct, d.dpbTextureArrayRequired, d.dpbTextureArrayMinLayerNum, (uint32_t)d.decodeBitstreamSourceMask); + } + } + + const nri::DeviceDesc& deviceDesc = NRI.GetDeviceDesc(device); + const Nv12BufferLayout sourceLayout = MakeNv12BufferLayout(deviceDesc, size.codedWidth, size.codedHeight); + const Nv12BufferLayout readbackLayout = MakeNv12BufferLayout(deviceDesc, size.videoWidth, size.videoHeight); + + nri::BufferDesc sourceBufferDesc = {}; + sourceBufferDesc.size = sourceLayout.totalSizeBytes; + nri::BufferDesc readbackBufferDesc = {}; + readbackBufferDesc.size = readbackLayout.totalSizeBytes; + if (NRI.CreateCommittedBuffer(device, nri::MemoryLocation::HOST_UPLOAD, 0.0f, sourceBufferDesc, sourceBuffer) != nri::Result::SUCCESS || NRI.CreateCommittedBuffer(device, nri::MemoryLocation::HOST_READBACK, 0.0f, readbackBufferDesc, readbackBuffer) != nri::Result::SUCCESS) { + cleanup(); + return finish(StreamStatus::FAIL, "Failed to create the NV12 buffers"); + } + + // Round trip + const uint32_t width = size.videoWidth; + const uint32_t height = size.videoHeight; + const uint64_t lumaSize = uint64_t(width) * height; + const uint64_t chromaSize = lumaSize / 2; + Nv12BufferLayout tightLayout = {}; + tightLayout.yRowPitchBytes = width; + tightLayout.ySlicePitchBytes = (uint32_t)lumaSize; + tightLayout.uvOffsetBytes = lumaSize; + tightLayout.uvRowPitchBytes = width; + tightLayout.uvSlicePitchBytes = (uint32_t)chromaSize; + tightLayout.totalSizeBytes = lumaSize + chromaSize; + + std::vector> decodedFrames(options.frameNum); + std::vector sourceReference(tightLayout.totalSizeBytes); + std::vector streamBytes; + std::vector frameLines; + std::vector psnrs; + double psnrSum = 0.0; + double psnrMin = 99.0; + uint32_t av1MetadataUnsupportedNum = 0; + uint32_t feedbackNum = 0; + uint64_t byteNum = 0; + std::string failure; + bool isFailureUnsupported = false; + + for (const FramePlan& plan : plans) { + // Source + uint8_t* source = (uint8_t*)NRI.MapBuffer(*sourceBuffer, 0, sourceLayout.totalSizeBytes); + if (!source) { + failure = "Failed to map the source buffer"; + break; + } + GenerateNv12Pattern(source, sourceLayout, size.codedWidth, size.codedHeight, width, height, plan.displayIndex); + NRI.UnmapBuffer(*sourceBuffer); + + EncodeRequest encodeRequest = {}; + encodeRequest.nv12Buffer = sourceBuffer; + encodeRequest.nv12BufferState = {nri::AccessBits::NONE, nri::StageBits::NONE}; + encodeRequest.nv12Layout = &sourceLayout; + encodeRequest.nv12Width = size.codedWidth; + encodeRequest.nv12Height = size.codedHeight; + encodeRequest.quality = options.quality; + encodeRequest.plan = plan; + if (options.rateControlChangeFrame >= 0 && plan.codingIndex >= (uint32_t)options.rateControlChangeFrame) + encodeRequest.quality.rateControl = options.rateControlB; + + if (options.verbose) { + std::fprintf(stderr, "[%s] picture %u: %s display=%u poc=%d frameNum=%u setupSlot=%u reference=%d refs:", options.name.c_str(), plan.codingIndex, GetFrameTypeName(plan.type), plan.displayIndex, plan.poc, plan.frameNum, plan.setupSlot, plan.isReference ? 1 : 0); + for (uint32_t i = 0; i < plan.referenceNum; i++) + std::fprintf(stderr, " [slot=%u poc=%d list=%u]", plan.references[i].slot, plan.references[i].poc, plan.references[i].listIndex); + std::fprintf(stderr, "\n"); + } + + EncodedFrame encodedFrame = {}; + if (!encoder->Encode(encodeRequest, encodedFrame)) { + failure = "Frame " + std::to_string(plan.codingIndex) + ": " + encoder->GetStatus(); + isFailureUnsupported = encoder->IsUnsupported(); + break; + } + byteNum += encodedFrame.payload.size(); + feedbackNum += encodedFrame.feedbackResolved ? 1 : 0; + av1MetadataUnsupportedNum += encodedFrame.av1MetadataUnsupported ? 1 : 0; + streamBytes.insert(streamBytes.end(), encodedFrame.headers.begin(), encodedFrame.headers.end()); + streamBytes.insert(streamBytes.end(), encodedFrame.payload.begin(), encodedFrame.payload.end()); + + if (options.encodeOnly) { + psnrs.push_back(99.0); + frameLines.push_back(std::to_string(plan.codingIndex) + "," + GetFrameTypeName(plan.type) + "," + std::to_string(plan.displayIndex) + "," + std::to_string(plan.poc) + "," + std::to_string(plan.setupSlot) + "," + std::to_string(encodedFrame.payload.size())); + continue; + } + + DecodeRequest decodeRequest = {}; + decodeRequest.frame = &encodedFrame; + decodeRequest.nv12ReadbackBuffer = readbackBuffer; + decodeRequest.nv12Layout = &readbackLayout; + DecodedFrame decodedFrame = {}; + if (!decoder->Decode(decodeRequest, decodedFrame)) { + failure = "Frame " + std::to_string(plan.codingIndex) + ": " + decoder->GetStatus(); + break; + } + + // Compare + const uint8_t* readback = (const uint8_t*)NRI.MapBuffer(*readbackBuffer, 0, readbackLayout.totalSizeBytes); + if (!readback) { + failure = "Failed to map the readback buffer"; + break; + } + std::vector& decoded = decodedFrames[plan.displayIndex]; + decoded.resize(tightLayout.totalSizeBytes); + for (uint32_t y = 0; y < height; y++) + std::memcpy(decoded.data() + uint64_t(y) * width, readback + uint64_t(y) * readbackLayout.yRowPitchBytes, width); + for (uint32_t y = 0; y < height / 2; y++) + std::memcpy(decoded.data() + lumaSize + uint64_t(y) * width, readback + readbackLayout.uvOffsetBytes + uint64_t(y) * readbackLayout.uvRowPitchBytes, width); + NRI.UnmapBuffer(*readbackBuffer); + + GenerateNv12Pattern(sourceReference.data(), tightLayout, width, height, width, height, plan.displayIndex); + double lumaError = 0.0; + double chromaError = 0.0; + ComputeSquaredError(sourceReference.data(), decoded.data(), lumaSize, lumaError); + ComputeSquaredError(sourceReference.data() + lumaSize, decoded.data() + lumaSize, chromaSize, chromaError); + const double psnr = GetPsnr(lumaError, lumaSize); + psnrSum += psnr; + psnrMin = std::min(psnrMin, psnr); + psnrs.push_back(psnr); + + char line[256] = {}; + std::snprintf(line, sizeof(line), "%u,%s,%u,%d,%u,%zu,%llu,%.2f,%.2f", plan.codingIndex, GetFrameTypeName(plan.type), plan.displayIndex, plan.poc, plan.setupSlot, encodedFrame.payload.size(), (unsigned long long)encodedFrame.feedback.averageQp, psnr, GetPsnr(chromaError, chromaSize)); + frameLines.push_back(line); + } + + const bool wasDistinct = !options.encodeOnly && decoder->IsDistinct(); + + // Dump + if (!options.dumpDir.empty()) { + const std::filesystem::path directory = std::filesystem::path(options.dumpDir) / options.name; + std::error_code errorCode; + std::filesystem::create_directories(directory, errorCode); + + WriteFile(directory / (std::string("stream.") + GetStreamExtension(config.codec)), streamBytes); + + std::vector decodedBytes; + std::vector sourceBytes; + for (uint32_t i = 0; i < options.frameNum; i++) { + if (decodedFrames[i].empty() && !options.encodeOnly) + continue; + decodedBytes.insert(decodedBytes.end(), decodedFrames[i].begin(), decodedFrames[i].end()); + GenerateNv12Pattern(sourceReference.data(), tightLayout, width, height, width, height, i); + sourceBytes.insert(sourceBytes.end(), sourceReference.begin(), sourceReference.end()); + } + char info[512] = {}; + std::snprintf(info, sizeof(info), "codec=%s\nvideo=%ux%u\ncoded=%ux%u\nframes=%u\nencodeOnly=%d\n", GetCodecName(config.codec), size.videoWidth, size.videoHeight, size.codedWidth, size.codedHeight, (uint32_t)plans.size(), options.encodeOnly ? 1 : 0); + WriteFile(directory / "info.txt", std::vector(info, info + std::strlen(info))); + WriteFile(directory / "decoded.yuv", decodedBytes); + WriteFile(directory / "source.yuv", sourceBytes); + + std::string csv = "coding,type,display,poc,setupSlot,bytes,averageQp,psnrY,psnrUV\n"; + for (const std::string& line : frameLines) + csv += line + "\n"; + WriteFile(directory / "frames.csv", std::vector(csv.begin(), csv.end())); + } + + cleanup(); + + result.frameNum = (uint32_t)psnrs.size(); + result.byteNum = byteNum; + result.psnrMin = psnrs.empty() ? 0.0 : psnrMin; + result.psnrAvg = psnrs.empty() ? 0.0 : psnrSum / double(psnrs.size()); + + char notes[256] = {}; + std::snprintf(notes, sizeof(notes), "coded=%ux%u refs=%u dpb=%s%s feedback=%u/%u%s", size.codedWidth, size.codedHeight, config.referenceNum, wasDistinct ? "distinct" : "coincide", config.av1Info == Av1InfoMode::METADATA && config.codec == SampleCodec::AV1 ? "" : "", feedbackNum, (uint32_t)plans.size(), + av1MetadataUnsupportedNum ? " av1-metadata=UNSUPPORTED(fallback to payload header)" : ""); + result.notes = notes; + + if (!failure.empty()) + return finish(isFailureUnsupported ? StreamStatus::UNSUPPORTED : StreamStatus::FAIL, failure); + if (result.psnrMin < options.minPsnr) { + char message[128] = {}; + std::snprintf(message, sizeof(message), "PSNR %.2f dB is below %.2f dB", result.psnrMin, options.minPsnr); + return finish(StreamStatus::FAIL, message); + } + + return finish(StreamStatus::PASS, ""); +} + +//================================================================================================== +// Matrix +//================================================================================================== + +std::vector MakeMatrixCases(const StreamOptions& base) { + std::vector cases; + + for (SampleCodec codec : {SampleCodec::H264, SampleCodec::H265, SampleCodec::AV1}) { + std::string prefix = codec == SampleCodec::H265 ? "h265" : (codec == SampleCodec::AV1 ? "av1" : "h264"); + + auto add = [&](const char* name, auto&& configure) { + StreamOptions options = base; + options.name = prefix + "-" + name; + options.config.codec = codec; + configure(options); + cases.push_back(options); + }; + auto setRate = [](StreamOptions& options, RateControlKind kind, uint32_t kbps, uint32_t maxKbps) { + options.quality.rateControl = {kind, kbps, maxKbps}; + options.minPsnr = 25.0; + }; + + add("idr", [](StreamOptions& o) { o.gop = "I"; }); + add("p", [](StreamOptions& o) { o.gop = "P"; }); + add("nonref", [](StreamOptions& o) { o.gop = "pP"; }); + add("dpb-coincide", [](StreamOptions& o) { o.config.decodeDpb = DecodeDpbMode::COINCIDE; }); + add("dpb-distinct", [](StreamOptions& o) { o.config.decodeDpb = DecodeDpbMode::DISTINCT; }); + add("dpb-array", [](StreamOptions& o) { o.config.dpbLayout = DpbLayout::ARRAY; }); + add("dpb-separate", [](StreamOptions& o) { o.config.dpbLayout = DpbLayout::SEPARATE; }); + add("input-plain", [](StreamOptions& o) { o.config.encodeInputOutputOnly = false; }); + add("cbr", [&](StreamOptions& o) { setRate(o, RateControlKind::CBR, 4000, 0); }); + add("vbr", [&](StreamOptions& o) { setRate(o, RateControlKind::VBR, 3000, 6000); }); + add("rc-change", [&](StreamOptions& o) { + setRate(o, RateControlKind::CBR, 6000, 0); + o.rateControlChangeFrame = 4; + o.rateControlB = {RateControlKind::VBR, 2000, 4000}; + }); + add("rc-change-cqp", [&](StreamOptions& o) { + o.rateControlChangeFrame = 4; + o.rateControlB = {RateControlKind::CBR, 3000, 0}; + o.minPsnr = 25.0; + }); + // Rate control limits: D3D12 enables them by flags, VK by the CBR/VBR structures + add("cbr-qp-range", [&](StreamOptions& o) { + setRate(o, RateControlKind::CBR, 4000, 0); + o.quality.rateControl.qpMin = 30; + o.quality.rateControl.qpMax = 30; + }); + add("cbr-max-frame", [&](StreamOptions& o) { + setRate(o, RateControlKind::CBR, 4000, 0); + o.quality.rateControl.maxFrameBits = 120000; + }); + add("vbr-vbv", [&](StreamOptions& o) { + setRate(o, RateControlKind::VBR, 3000, 6000); + o.quality.rateControl.vbvMs = 200; + o.quality.rateControl.vbvInitialMs = 100; + }); + add("no-feedback", [](StreamOptions& o) { o.config.encodeFeedback = false; }); + add("1080p", [](StreamOptions& o) { + o.config.videoWidth = 1920; + o.config.videoHeight = 1080; + o.frameNum = 4; + }); + add("4k", [](StreamOptions& o) { + o.config.videoWidth = 3840; + o.config.videoHeight = 2160; + o.frameNum = 3; + }); + add("long", [](StreamOptions& o) { + o.frameNum = 40; + o.idrPeriod = 17; + }); + + if (codec != SampleCodec::AV1) { + add("refs3", [](StreamOptions& o) { + o.config.referenceNum = 3; + o.frameNum = 12; + }); + add("refs3-nonref", [](StreamOptions& o) { + o.config.referenceNum = 3; + o.gop = "PpP"; + o.frameNum = 12; + }); + add("b", [](StreamOptions& o) { + o.gop = "BP"; + o.config.referenceNum = 2; + }); + add("bb", [](StreamOptions& o) { + o.gop = "BBP"; + o.config.referenceNum = 3; + o.frameNum = 13; + }); + add("b-distinct", [](StreamOptions& o) { + o.gop = "BP"; + o.config.referenceNum = 2; + o.config.decodeDpb = DecodeDpbMode::DISTINCT; + }); + } + + if (codec == SampleCodec::H264) { + add("ids", [](StreamOptions& o) { + o.config.h264SpsId = 3; + o.config.h264PpsId = 5; + o.config.referenceNum = 2; + }); + } + + if (codec == SampleCodec::H265) { + add("ids-nolistmod", [](StreamOptions& o) { + o.config.h265VpsId = 3; + o.config.h265SpsId = 5; + o.config.h265PpsId = 7; + o.config.referenceNum = 2; + o.config.h265ListsModification = false; + o.config.reverseReferences = false; + }); + add("b-nolistmod", [](StreamOptions& o) { + o.gop = "BP"; + o.config.referenceNum = 2; + o.config.h265ListsModification = false; + o.config.reverseReferences = false; + o.frameNum = 8; + }); + add("ids", [](StreamOptions& o) { + o.config.h265VpsId = 3; + o.config.h265SpsId = 5; + o.config.h265PpsId = 7; + o.config.referenceNum = 2; + }); + // The same without lists_modification_present_flag (no list modification syntax in the slice headers) + add("refs3-nolistmod", [](StreamOptions& o) { + o.config.referenceNum = 3; + o.config.h265ListsModification = false; + o.config.reverseReferences = false; + o.frameNum = 12; + }); + add("bb-nolistmod", [](StreamOptions& o) { + o.gop = "BBP"; + o.config.referenceNum = 3; + o.config.h265ListsModification = false; + o.config.reverseReferences = false; + o.frameNum = 13; + }); + // The backend writes its own parameter sets, they are not available through NRI: encode only + add("default-params", [](StreamOptions& o) { + o.config.h265DefaultParameters = true; + o.encodeOnly = true; + }); + add("4k-default-params", [](StreamOptions& o) { + o.config.h265DefaultParameters = true; + o.encodeOnly = true; + o.config.videoWidth = 3840; + o.config.videoHeight = 2160; + o.frameNum = 3; + }); + } + + if (codec == SampleCodec::AV1) { + add("metadata", [](StreamOptions& o) { o.config.av1Info = Av1InfoMode::METADATA; }); + add("header", [](StreamOptions& o) { o.config.av1Info = Av1InfoMode::HEADER; }); + } + } + + return cases; +} + + +//================================================================================================== +// Decode of an external AV1 stream (OBU file, e.g. "ffmpeg -c:v libaom-av1 -f obu") +//================================================================================================== + +namespace { + +struct BitReader { + const uint8_t* data = nullptr; + size_t size = 0; + size_t pos = 0; + bool ok = true; + + uint32_t Bits(uint32_t n) { + uint64_t v = 0; + for (uint32_t i = 0; i < n; i++) { + uint32_t bit = 0; + if (pos < size * 8) + bit = (data[pos >> 3] >> (7 - (pos & 7))) & 1; + else + ok = false; + pos++; + v = (v << 1) | bit; + } + return (uint32_t)v; + } + + uint32_t Uvlc() { + uint32_t zeros = 0; + while (ok && !Bits(1)) { + if (++zeros >= 32) + return UINT32_MAX; + } + return Bits(zeros) + ((1u << zeros) - 1u); + } +}; + +struct ObuSpan { + uint8_t type = 0; + size_t begin = 0; // OBU header + size_t payload = 0; // first payload byte + size_t end = 0; +}; + +bool ReadObus(const std::vector& data, std::vector& obus) { + size_t pos = 0; + while (pos < data.size()) { + const uint8_t header = data[pos]; + const bool hasExtension = (header >> 2) & 1; + const bool hasSize = (header >> 1) & 1; + if ((header >> 7) || !hasSize) + return false; + + size_t p = pos + 1 + (hasExtension ? 1 : 0); + uint64_t size = 0; + for (uint32_t i = 0; i < 8; i++) { + if (p >= data.size()) + return false; + const uint8_t byte = data[p++]; + size |= uint64_t(byte & 0x7F) << (7 * i); + if (!(byte & 0x80)) + break; + } + if (p + size > data.size()) + return false; + + obus.push_back({(uint8_t)((header >> 3) & 15), pos, p, (size_t)(p + size)}); + pos = (size_t)(p + size); + } + + return true; +} + +// Sequence header OBU payload -> neutral description (AV1 5.5) +bool ParseSequenceHeader(const uint8_t* data, size_t size, nri::VideoAV1SequenceDesc& desc) { + BitReader r = {data, size}; + desc = {}; + auto flag = [&](nri::VideoAV1SequenceBits bit) { + if (r.Bits(1)) + desc.flags |= bit; + }; + + desc.seqProfile = (uint8_t)r.Bits(3); + flag(nri::VideoAV1SequenceBits::STILL_PICTURE); + if (r.Bits(1)) + return false; // reduced_still_picture_header + if (r.Bits(1)) { // timing_info_present_flag + desc.flags |= nri::VideoAV1SequenceBits::TIMING_INFO_PRESENT; + desc.numUnitsInDisplayTick = r.Bits(32); + desc.timeScale = r.Bits(32); + if (r.Bits(1)) + desc.numTicksPerPictureMinus1 = r.Uvlc(); + if (r.Bits(1)) + return false; // decoder_model_info_present_flag + } + const bool initialDisplayDelayPresent = r.Bits(1); + if (initialDisplayDelayPresent) + desc.flags |= nri::VideoAV1SequenceBits::INITIAL_DISPLAY_DELAY_PRESENT; + const uint32_t operatingPointNum = r.Bits(5) + 1; + for (uint32_t i = 0; i < operatingPointNum; i++) { + r.Bits(12); // operating_point_idc + const uint32_t level = r.Bits(5); + if (i == 0) + desc.level = (uint8_t)level; + if (level > 7) + r.Bits(1); // seq_tier + if (initialDisplayDelayPresent && r.Bits(1)) + r.Bits(4); + } + desc.frameWidthBitsMinus1 = (uint8_t)r.Bits(4); + desc.frameHeightBitsMinus1 = (uint8_t)r.Bits(4); + desc.maxFrameWidthMinus1 = (uint16_t)r.Bits(desc.frameWidthBitsMinus1 + 1); + desc.maxFrameHeightMinus1 = (uint16_t)r.Bits(desc.frameHeightBitsMinus1 + 1); + if (r.Bits(1)) { // frame_id_numbers_present_flag + desc.flags |= nri::VideoAV1SequenceBits::FRAME_ID_NUMBERS_PRESENT; + desc.deltaFrameIdLengthMinus2 = (uint8_t)r.Bits(4); + desc.additionalFrameIdLengthMinus1 = (uint8_t)r.Bits(3); + } + flag(nri::VideoAV1SequenceBits::USE_128X128_SUPERBLOCK); + flag(nri::VideoAV1SequenceBits::ENABLE_FILTER_INTRA); + flag(nri::VideoAV1SequenceBits::ENABLE_INTRA_EDGE_FILTER); + flag(nri::VideoAV1SequenceBits::ENABLE_INTERINTRA_COMPOUND); + flag(nri::VideoAV1SequenceBits::ENABLE_MASKED_COMPOUND); + flag(nri::VideoAV1SequenceBits::ENABLE_WARPED_MOTION); + flag(nri::VideoAV1SequenceBits::ENABLE_DUAL_FILTER); + const bool enableOrderHint = r.Bits(1); + if (enableOrderHint) { + desc.flags |= nri::VideoAV1SequenceBits::ENABLE_ORDER_HINT; + flag(nri::VideoAV1SequenceBits::ENABLE_JNT_COMP); + flag(nri::VideoAV1SequenceBits::ENABLE_REF_FRAME_MVS); + } + desc.seqForceScreenContentTools = r.Bits(1) ? 2 : (uint8_t)r.Bits(1); + desc.seqForceIntegerMv = 2; + if (desc.seqForceScreenContentTools > 0) + desc.seqForceIntegerMv = r.Bits(1) ? 2 : (uint8_t)r.Bits(1); + if (enableOrderHint) + desc.orderHintBitsMinus1 = (uint8_t)r.Bits(3); + flag(nri::VideoAV1SequenceBits::ENABLE_SUPERRES); + flag(nri::VideoAV1SequenceBits::ENABLE_CDEF); + flag(nri::VideoAV1SequenceBits::ENABLE_RESTORATION); + + // color_config() + const bool highBitDepth = r.Bits(1); + desc.bitDepth = highBitDepth ? 10 : 8; + if (desc.seqProfile == 2 && highBitDepth && r.Bits(1)) + desc.bitDepth = 12; + const bool monochrome = desc.seqProfile == 1 ? false : r.Bits(1); + if (monochrome) + desc.flags |= nri::VideoAV1SequenceBits::MONO_CHROME; + uint32_t colorPrimaries = 2, transfer = 2, matrix = 2; + if (r.Bits(1)) { + desc.flags |= nri::VideoAV1SequenceBits::COLOR_DESCRIPTION_PRESENT; + colorPrimaries = r.Bits(8); + transfer = r.Bits(8); + matrix = r.Bits(8); + } + desc.colorPrimaries = (uint8_t)colorPrimaries; + desc.transferCharacteristics = (uint8_t)transfer; + desc.matrixCoefficients = (uint8_t)matrix; + if (monochrome) { + flag(nri::VideoAV1SequenceBits::COLOR_RANGE); + desc.subsamplingX = desc.subsamplingY = 1; + } else if (colorPrimaries == 1 && transfer == 13 && matrix == 0) { + desc.flags |= nri::VideoAV1SequenceBits::COLOR_RANGE; + } else { + flag(nri::VideoAV1SequenceBits::COLOR_RANGE); + if (desc.seqProfile == 0) + desc.subsamplingX = desc.subsamplingY = 1; + else if (desc.seqProfile == 1) + desc.subsamplingX = desc.subsamplingY = 0; + else if (desc.bitDepth == 12) { + desc.subsamplingX = (uint8_t)r.Bits(1); + desc.subsamplingY = desc.subsamplingX ? (uint8_t)r.Bits(1) : 0; + } else { + desc.subsamplingX = 1; + desc.subsamplingY = 0; + } + if (desc.subsamplingX && desc.subsamplingY) + desc.chromaSamplePosition = (uint8_t)r.Bits(2); + } + if (!monochrome) + flag(nri::VideoAV1SequenceBits::SEPARATE_UV_DELTA_Q); + flag(nri::VideoAV1SequenceBits::FILM_GRAIN_PARAMS_PRESENT); + + return r.ok; +} + +} // namespace + +StreamResult RunDecodeFile(const RunEnvironment& environment, const std::string& path, const std::string& refYuvPath, const std::string& name, const std::string& dumpDir, bool verbose) { + StreamResult result = {}; + MessageStats stats; + + auto finish = [&](StreamStatus status, const std::string& message) { + result.status = status; + result.message = message; + result.nriErrorNum = stats.errorNum; + result.nriWarningNum = stats.warningNum; + if (status == StreamStatus::PASS && stats.errorNum) { + result.status = StreamStatus::FAIL; + result.message = "NRI reported " + std::to_string(stats.errorNum) + " error(s): " + (stats.errors.empty() ? "" : stats.errors[0]); + } + return result; + }; + + auto readFile = [](const std::string& filePath, std::vector& bytes) { + FILE* file = std::fopen(filePath.c_str(), "rb"); + if (!file) + return false; + std::fseek(file, 0, SEEK_END); + const long size = std::ftell(file); + std::fseek(file, 0, SEEK_SET); + bytes.resize(size > 0 ? (size_t)size : 0); + const bool ok = bytes.empty() || std::fread(bytes.data(), 1, bytes.size(), file) == bytes.size(); + std::fclose(file); + return ok; + }; + + std::vector fileBytes; + std::vector refBytes; + const bool hasReference = !refYuvPath.empty(); + if (!readFile(path, fileBytes)) + return finish(StreamStatus::FAIL, "Failed to read " + path); + if (hasReference && (!readFile(refYuvPath, refBytes) || refBytes.empty())) + return finish(StreamStatus::FAIL, "Failed to read or empty reference " + refYuvPath); + + std::vector obus; + if (!ReadObus(fileBytes, obus)) + return finish(StreamStatus::FAIL, "Not a low-overhead OBU stream (every OBU needs obu_size)"); + + nri::VideoAV1SequenceDesc sequence = {}; + bool hasSequence = false; + for (const ObuSpan& obu : obus) { + if (obu.type == 1 && !hasSequence) { + if (!ParseSequenceHeader(fileBytes.data() + obu.payload, obu.end - obu.payload, sequence)) + return finish(StreamStatus::FAIL, "Unsupported AV1 sequence header"); + hasSequence = true; + } + } + if (!hasSequence) + return finish(StreamStatus::FAIL, "No AV1 sequence header"); + + if (verbose) + std::fprintf(stderr, "[%s] sequence: flags=0x%X profile=%u bitDepth=%u ss=%u%u size=%ux%u bits=%u/%u orderHintBitsMinus1=%u sct=%u imv=%u level=%u cp=%u tc=%u mc=%u csp=%u\n", name.c_str(), (uint32_t)sequence.flags, sequence.seqProfile, sequence.bitDepth, sequence.subsamplingX, sequence.subsamplingY, sequence.maxFrameWidthMinus1 + 1u, sequence.maxFrameHeightMinus1 + 1u, sequence.frameWidthBitsMinus1, sequence.frameHeightBitsMinus1, sequence.orderHintBitsMinus1, sequence.seqForceScreenContentTools, sequence.seqForceIntegerMv, sequence.level, sequence.colorPrimaries, sequence.transferCharacteristics, sequence.matrixCoefficients, sequence.chromaSamplePosition); + + VideoConfig config = {}; + config.codec = SampleCodec::AV1; + config.videoWidth = sequence.maxFrameWidthMinus1 + 1u; + config.videoHeight = sequence.maxFrameHeightMinus1 + 1u; + config.referenceNum = 8; + config.decodePictureAtVideoSize = true; // the AV1 frame size is the picture extent (not the texture size) + config.av1FilmGrain = !!(sequence.flags & nri::VideoAV1SequenceBits::FILM_GRAIN_PARAMS_PRESENT); + + // Device + nri::AdapterDesc adapters[8] = {}; + uint32_t adapterNum = helper::GetCountOf(adapters); + if (nri::nriEnumerateAdapters(adapters, adapterNum) != nri::Result::SUCCESS || !adapterNum) + return finish(StreamStatus::UNSUPPORTED, "No graphics adapters"); + uint32_t apiAdapterNum = 0; + for (uint32_t i = 0; i < adapterNum; i++) { + if (adapters[i].supportedGraphicsAPIs & environment.graphicsAPI) + adapters[apiAdapterNum++] = adapters[i]; + } + if (!apiAdapterNum) + return finish(StreamStatus::UNSUPPORTED, "No adapters support the requested graphics API"); + const nri::AdapterDesc& adapter = adapters[std::min(environment.adapterIndex, apiAdapterNum - 1)]; + result.adapterName = adapter.name; + if (!adapter.queueNum[(uint32_t)nri::QueueType::VIDEO_DECODE]) + return finish(StreamStatus::UNSUPPORTED, "The adapter has no NRI video decode queue"); + + nri::QueueFamilyDesc queueFamilies[2] = {}; + queueFamilies[0].queueNum = 1; + queueFamilies[0].queueType = nri::QueueType::GRAPHICS; + queueFamilies[1].queueNum = 1; + queueFamilies[1].queueType = nri::QueueType::VIDEO_DECODE; + + nri::DeviceCreationDesc deviceCreationDesc = {}; + deviceCreationDesc.graphicsAPI = environment.graphicsAPI; + deviceCreationDesc.enableGraphicsAPIValidation = environment.debugAPI; + deviceCreationDesc.disableD3D12EnhancedBarriers = environment.graphicsAPI == nri::GraphicsAPI::D3D12 && !environment.enhancedBarriers; // legacy barriers by default + deviceCreationDesc.enableNRIValidation = environment.debugNRI; + deviceCreationDesc.vkBindingOffsets = VK_BINDING_OFFSETS; + deviceCreationDesc.adapterDesc = &adapter; + deviceCreationDesc.queueFamilies = queueFamilies; + deviceCreationDesc.queueFamilyNum = helper::GetCountOf(queueFamilies); + deviceCreationDesc.callbackInterface.MessageCallback = MessageCallback; + deviceCreationDesc.callbackInterface.AbortExecution = AbortCallback; + deviceCreationDesc.callbackInterface.userArg = &stats; + + DeviceHolder deviceHolder; + if (nri::nriCreateDevice(deviceCreationDesc, deviceHolder.device) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to create the device"); + nri::Device& device = *deviceHolder.device; + + NRIInterface NRI = {}; + nri::VideoInterface Video = {}; + if (nri::nriGetInterface(device, NRI_INTERFACE(nri::CoreInterface), (nri::CoreInterface*)&NRI) != nri::Result::SUCCESS || nri::nriGetInterface(device, NRI_INTERFACE(nri::HelperInterface), (nri::HelperInterface*)&NRI) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to get NRI interfaces"); + if (nri::nriGetInterface(device, NRI_INTERFACE(nri::VideoInterface), &Video) != nri::Result::SUCCESS || !Video.CreateVideoSession) + return finish(StreamStatus::UNSUPPORTED, "NRI video interface is unavailable"); + + VideoContext context = {}; + context.nri = &NRI; + context.video = &Video; + context.device = &device; + context.graphicsAPI = environment.graphicsAPI; + if (NRI.GetQueue(device, nri::QueueType::GRAPHICS, 0, context.graphicsQueue) != nri::Result::SUCCESS || NRI.GetQueue(device, nri::QueueType::VIDEO_DECODE, 0, context.decodeQueue) != nri::Result::SUCCESS) + return finish(StreamStatus::FAIL, "Failed to get queues"); + + // Decode-only video size + nri::VideoSessionDesc sessionDesc = {}; + sessionDesc.type = nri::VideoSessionType::DECODE; + sessionDesc.codec = nri::VideoCodec::AV1; + sessionDesc.format = nri::Format::NV12_UNORM; + sessionDesc.width = config.videoWidth; + sessionDesc.height = config.videoHeight; + sessionDesc.maxReferenceNum = config.referenceNum; + sessionDesc.av1FilmGrain = config.av1FilmGrain; + nri::VideoCapabilities capabilities = {}; + Video.GetVideoCapabilities(device, sessionDesc, capabilities); + if (!capabilities.pictureAccessGranularityWidth || !capabilities.pictureAccessGranularityHeight) + return finish(StreamStatus::UNSUPPORTED, config.av1FilmGrain ? "AV1 film grain decode is unsupported" : "AV1 decode is unsupported"); + VideoSize size = {}; + size.videoWidth = config.videoWidth; + size.videoHeight = config.videoHeight; + size.codedWidth = (uint32_t)AlignUp(std::max(config.videoWidth, capabilities.widthMin), capabilities.pictureAccessGranularityWidth); + size.codedHeight = (uint32_t)AlignUp(std::max(config.videoHeight, capabilities.heightMin), capabilities.pictureAccessGranularityHeight); + size.decodeBitstreamSizeAlignment = std::max(capabilities.bitstreamSizeAlignment, 1u); + size.bitstreamSize = AlignUp(std::max(2 * 1024 * 1024, uint64_t(size.codedWidth) * size.codedHeight), 1024 * 1024); + + CodecParameters codecParameters = {}; + codecParameters.av1Sequence = sequence; + + auto decoder = std::make_unique(); + nri::Buffer* readbackBuffer = nullptr; + auto cleanup = [&]() { + NRI.DeviceWaitIdle(&device); + decoder.reset(); + if (readbackBuffer) + NRI.DestroyBuffer(readbackBuffer); + }; + + if (!decoder->Initialize(context, config, size, codecParameters)) { + const bool isUnsupported = decoder->IsUnsupported(); + const std::string message = decoder->GetStatus(); + cleanup(); + return finish(isUnsupported ? StreamStatus::UNSUPPORTED : StreamStatus::FAIL, message); + } + + const nri::DeviceDesc& deviceDesc = NRI.GetDeviceDesc(device); + const Nv12BufferLayout readbackLayout = MakeNv12BufferLayout(deviceDesc, size.videoWidth, size.videoHeight); + nri::BufferDesc readbackBufferDesc = {}; + readbackBufferDesc.size = readbackLayout.totalSizeBytes; + if (NRI.CreateCommittedBuffer(device, nri::MemoryLocation::HOST_READBACK, 0.0f, readbackBufferDesc, readbackBuffer) != nri::Result::SUCCESS) { + cleanup(); + return finish(StreamStatus::FAIL, "Failed to create the readback buffer"); + } + + const uint32_t width = size.videoWidth; + const uint32_t height = size.videoHeight; + const uint64_t lumaSize = uint64_t(width) * height; + const uint64_t frameSize = lumaSize * 3 / 2; + + struct RefSlot { + bool valid = false; + uint32_t dpbSlot = 0; + nri::VideoFrameType type = nri::VideoFrameType::IDR; + uint8_t orderHint = 0; + uint32_t frameId = 0; + uint8_t saved[8] = {}; + }; + RefSlot refs[8] = {}; + nri::VideoAV1SavedFrameState savedFrameStates[8] = {}; // state of the frames in the reference slots for headers that inherit it + + std::vector decodedBytes; + std::vector frameLines; + double psnrMin = 99.0; + double psnrSum = 0.0; + uint32_t outputNum = 0; + uint32_t codingIndex = 0; + uint64_t byteNum = 0; + std::string failure; + + for (const ObuSpan& obu : obus) { + if (obu.type != 6) { + if (obu.type == 3 || obu.type == 4 || obu.type == 8) { + failure = "Unsupported OBU layout (OBU_FRAME_HEADER / OBU_TILE_GROUP): use a single OBU_FRAME per picture"; + break; + } + continue; + } + + EncodedFrame frame = {}; + frame.payload.assign(fileBytes.begin() + obu.begin, fileBytes.begin() + obu.end); + frame.feedback.encodedBitstreamWrittenBytes = frame.payload.size(); + byteNum += frame.payload.size(); + + nri::VideoAV1ReferenceDesc snapshot[8] = {}; + for (uint32_t j = 0; j < 8; j++) { + snapshot[j].name = nri::VideoAV1ReferenceName::NONE; + snapshot[j].refFrameIndex = (uint8_t)j; + snapshot[j].frameType = refs[j].type; + snapshot[j].orderHint = refs[j].orderHint; + snapshot[j].frameId = refs[j].frameId; + snapshot[j].slot = refs[j].dpbSlot; + snapshot[j].savedOrderHints = refs[j].saved; + } + const bool hasReferences = refs[0].valid; + + nri::VideoAV1EncodeDecodeInfoDesc infoDesc = {}; + infoDesc.feedback = &frame.feedback; + infoDesc.sequence = &sequence; + infoDesc.encodedPayloadHeader = frame.payload.data(); + infoDesc.encodedPayloadHeaderSize = frame.payload.size(); + infoDesc.references = hasReferences ? snapshot : nullptr; + infoDesc.referenceNum = hasReferences ? 8 : 0; + infoDesc.savedFrameStates = savedFrameStates; + const nri::Result infoResult = nri::video::av1::GetEncodeDecodeInfoFromHeader(infoDesc, frame.av1DecodeInfo); + if (infoResult != nri::Result::SUCCESS) { + failure = "Picture " + std::to_string(codingIndex) + ": the AV1 frame header is not supported by the NRI parser"; + break; + } + frame.hasAv1DecodeInfo = true; + + const nri::VideoAV1DecodePictureDesc& picture = frame.av1DecodeInfo.picture; + const bool isKey = picture.frameType == nri::VideoFrameType::IDR; + + FramePlan& plan = frame.plan; + plan.type = isKey ? nri::VideoFrameType::IDR : nri::VideoFrameType::P; + plan.codingIndex = codingIndex; + plan.displayIndex = outputNum; + plan.isReference = picture.refreshFrameFlags != 0; + plan.isDisplay = true; + + bool used[MAX_DPB_SLOT_NUM] = {}; + for (const RefSlot& ref : refs) + used[ref.dpbSlot] = used[ref.dpbSlot] || ref.valid; + plan.setupSlot = MAX_DPB_SLOT_NUM; + for (uint32_t slot = 0; slot < MAX_DPB_SLOT_NUM; slot++) { + if (!used[slot]) { + plan.setupSlot = slot; + break; + } + } + if (plan.setupSlot == MAX_DPB_SLOT_NUM) { + failure = "No free DPB slot"; + break; + } + + // Distinct DPB slots referenced by the picture + if (!isKey) { + for (uint32_t i = 0; i < picture.referenceNum; i++) { + const uint32_t slot = picture.references[i].slot; + bool found = false; + for (uint32_t k = 0; k < plan.referenceNum; k++) + found = found || plan.references[k].slot == slot; + if (!found && plan.referenceNum < MAX_REFERENCE_NUM) { + PlanReference& reference = plan.references[plan.referenceNum++]; + reference.slot = slot; + reference.type = picture.references[i].frameType; + reference.orderHint = picture.references[i].orderHint; + reference.frameId = picture.references[i].frameId; + } + } + } + + // "SavedOrderHints" of this picture (AV1 7.20): OrderHints[] indexed by reference name + uint8_t savedOrderHints[8] = {}; + savedOrderHints[0] = picture.orderHint; + if (isKey) { + for (uint8_t& hint : savedOrderHints) + hint = picture.orderHint; + } else { + for (uint32_t i = 0; i < picture.referenceNum; i++) { + const uint8_t nameIndex = nri::video::av1::GetReferenceNameIndex(picture.references[i].name); + if (nameIndex < 7) + savedOrderHints[1 + nameIndex] = picture.references[i].orderHint; + } + } + frame.hasAv1SavedOrderHints = true; + for (const RefSlot& ref : refs) { + if (ref.valid) + std::memcpy(frame.av1SavedOrderHints[ref.dpbSlot], ref.saved, sizeof(ref.saved)); + } + + if (verbose) { + std::fprintf(stderr, "[%s] picture %u: %s orderHint=%u refresh=0x%02X setupSlot=%u refs:", name.c_str(), codingIndex, isKey ? "KEY" : "INTER", picture.orderHint, picture.refreshFrameFlags, plan.setupSlot); + for (uint32_t i = 0; i < picture.referenceNum; i++) + std::fprintf(stderr, " [name=%u idx=%u slot=%u hint=%u]", (uint32_t)picture.references[i].name, picture.references[i].refFrameIndex, picture.references[i].slot, picture.references[i].orderHint); + std::fprintf(stderr, "\n payload=%zu bitstreamOffset=%llu bitstreamSize=%llu tileNum=%u", frame.payload.size(), (unsigned long long)frame.av1DecodeInfo.bitstreamOffset, (unsigned long long)frame.av1DecodeInfo.bitstreamSize, picture.tileNum); + for (uint32_t i = 0; i < picture.tileNum && i < 4; i++) + std::fprintf(stderr, " tile%u=[off=%u size=%u r=%u c=%u]", i, picture.tiles[i].offset, picture.tiles[i].size, picture.tiles[i].row, picture.tiles[i].column); + std::fprintf(stderr, "\n flags=0x%X baseQ=%u txMode=%u interp=%u cdefBits=%u frameHeaderOffset=%u lr=[%u %u %u]", (uint32_t)picture.flags, picture.baseQIndex, picture.txMode, picture.interpolationFilter, picture.cdefBits, picture.frameHeaderOffset, picture.loopRestoration ? picture.loopRestoration->frameRestorationType[0] : 9, picture.loopRestoration ? picture.loopRestoration->frameRestorationType[1] : 9, picture.loopRestoration ? picture.loopRestoration->frameRestorationType[2] : 9); + std::fprintf(stderr, " skipMode=%d [%u %u]\n", !!(picture.flags & nri::VideoAV1PictureBits::SKIP_MODE_PRESENT), (uint32_t)picture.skipModeFrames[0], (uint32_t)picture.skipModeFrames[1]); + } + + DecodeRequest decodeRequest = {}; + decodeRequest.frame = &frame; + decodeRequest.nv12ReadbackBuffer = readbackBuffer; + decodeRequest.nv12Layout = &readbackLayout; + DecodedFrame decodedFrame = {}; + if (!decoder->Decode(decodeRequest, decodedFrame)) { + failure = "Picture " + std::to_string(codingIndex) + ": " + decoder->GetStatus(); + break; + } + + // Shown pictures only (the first frame header bits: show_existing_frame, frame_type, show_frame) + const bool isShown = !!(picture.flags & nri::VideoAV1PictureBits::SHOW_FRAME); + if (isShown) { + const uint8_t* readback = (const uint8_t*)NRI.MapBuffer(*readbackBuffer, 0, readbackLayout.totalSizeBytes); + if (!readback) { + failure = "Failed to map the readback buffer"; + break; + } + const size_t offset = decodedBytes.size(); + decodedBytes.resize(offset + frameSize); + for (uint32_t y = 0; y < height; y++) + std::memcpy(decodedBytes.data() + offset + uint64_t(y) * width, readback + uint64_t(y) * readbackLayout.yRowPitchBytes, width); + for (uint32_t y = 0; y < height / 2; y++) + std::memcpy(decodedBytes.data() + offset + lumaSize + uint64_t(y) * width, readback + readbackLayout.uvOffsetBytes + uint64_t(y) * readbackLayout.uvRowPitchBytes, width); + NRI.UnmapBuffer(*readbackBuffer); + + double psnr = 99.0; + if (hasReference) { + if (offset + frameSize > refBytes.size()) { + failure = "Reference has fewer frames"; + break; + } + double lumaError = 0.0; + ComputeSquaredError(refBytes.data() + offset, decodedBytes.data() + offset, lumaSize, lumaError); + double chromaError = 0.0; + ComputeSquaredError(refBytes.data() + offset + lumaSize, decodedBytes.data() + offset + lumaSize, lumaSize / 2, chromaError); + psnr = (lumaError == 0.0 && chromaError == 0.0) ? 99.0 : std::min(98.0, GetPsnr(lumaError + chromaError, lumaSize * 3 / 2)); + } + psnrMin = std::min(psnrMin, psnr); + psnrSum += psnr; + outputNum++; + char line[128] = {}; + std::snprintf(line, sizeof(line), "%u,%s,%u,%u,%u,%zu,0,%.2f,0", codingIndex, isKey ? "IDR" : "P", plan.displayIndex, picture.orderHint, plan.setupSlot, frame.payload.size(), psnr); + frameLines.push_back(line); + } + + // Reference update (AV1 7.20) + for (uint32_t j = 0; j < 8; j++) { + if (picture.refreshFrameFlags & (1u << j)) { + refs[j].valid = true; + refs[j].dpbSlot = plan.setupSlot; + refs[j].type = plan.type; + refs[j].orderHint = picture.orderHint; + refs[j].frameId = picture.currentFrameId; + std::memcpy(refs[j].saved, savedOrderHints, sizeof(savedOrderHints)); + savedFrameStates[j] = frame.av1DecodeInfo.savedFrameState; + } + } + codingIndex++; + } + + cleanup(); + + if (!dumpDir.empty()) { + const std::filesystem::path directory = std::filesystem::path(dumpDir) / name; + std::error_code errorCode; + std::filesystem::create_directories(directory, errorCode); + WriteFile(directory / "stream.obu", fileBytes); + WriteFile(directory / "decoded.yuv", decodedBytes); + if (hasReference) + WriteFile(directory / "source.yuv", refBytes); + char info[256] = {}; + std::snprintf(info, sizeof(info), "codec=AV1\nvideo=%ux%u\ncoded=%ux%u\nframes=%u\nencodeOnly=0\n", width, height, size.codedWidth, size.codedHeight, outputNum); + WriteFile(directory / "info.txt", std::vector(info, info + std::strlen(info))); + std::string csv = "coding,type,display,poc,setupSlot,bytes,averageQp,psnrY,psnrUV\n"; + for (const std::string& line : frameLines) + csv += line + "\n"; + WriteFile(directory / "frames.csv", std::vector(csv.begin(), csv.end())); + } + + result.frameNum = outputNum; + result.byteNum = byteNum; + result.psnrMin = outputNum ? psnrMin : 0.0; + result.psnrAvg = outputNum ? psnrSum / outputNum : 0.0; + result.notes = "coded=" + std::to_string(size.codedWidth) + "x" + std::to_string(size.codedHeight) + " refs=8 external-av1" + (hasReference ? " (bit-exact vs reference required)" : " (no reference)"); + + if (!failure.empty()) + return finish(StreamStatus::FAIL, failure); + if (!outputNum) + return finish(StreamStatus::FAIL, "No picture was decoded"); + if (hasReference && (outputNum * frameSize != refBytes.size() || result.psnrMin < 99.0)) { + char message[128] = {}; + std::snprintf(message, sizeof(message), "decoded %u frames, reference has %llu; min PSNR vs reference %.2f dB (bit-exact is 99)", outputNum, (unsigned long long)(refBytes.size() / frameSize), result.psnrMin); + return finish(StreamStatus::FAIL, message); + } + + return finish(StreamStatus::PASS, ""); +} + +} // namespace video_sample diff --git a/Source/VideoEncodeDecode/Stream.h b/Source/VideoEncodeDecode/Stream.h new file mode 100644 index 0000000..88e55b3 --- /dev/null +++ b/Source/VideoEncodeDecode/Stream.h @@ -0,0 +1,68 @@ +// © 2021 NVIDIA Corporation + +#pragma once + +#include "Shared.h" + +namespace video_sample { + +// Headless encode -> decode stream runs ("--stream" / "--matrix") +struct StreamOptions { + std::string name = "stream"; + VideoConfig config = {}; + VideoQuality quality = {}; + uint32_t frameNum = 8; + std::string gop = "P"; // display-order kinds of the frames after the first IDR, repeated: I (IDR), P, p (non-reference P), B (non-reference bi-predicted) + uint32_t idrPeriod = 0; // 0 - only the first frame is IDR + int32_t rateControlChangeFrame = -1; // coding index where "rateControlB" replaces "quality.rateControl" + RateControlSetting rateControlB = {}; + bool verbose = false; // log every picture before it is submitted + bool encodeOnly = false; // skip the decoder (the stream is still dumped) + double minPsnr = 30.0; + std::string dumpDir; // writes //{stream,decoded.yuv,source.yuv,frames.csv} +}; + +struct RunEnvironment { + nri::GraphicsAPI graphicsAPI = nri::GraphicsAPI::VK; + uint32_t adapterIndex = 0; + bool debugAPI = false; + bool debugNRI = false; + bool enhancedBarriers = false; // D3D12 +}; + +enum class StreamStatus : uint8_t { + PASS, + FAIL, + UNSUPPORTED, +}; + +struct StreamResult { + StreamStatus status = StreamStatus::FAIL; + std::string message; + std::string adapterName; + uint32_t frameNum = 0; + uint64_t byteNum = 0; + double psnrMin = 0.0; + double psnrAvg = 0.0; + uint32_t nriErrorNum = 0; + uint32_t nriWarningNum = 0; + std::string notes; +}; + +// Display-order test pattern, "patternWidth/Height" define the content, "width/height" the generated area +void GenerateNv12Pattern(uint8_t* dst, const Nv12BufferLayout& layout, uint32_t width, uint32_t height, uint32_t patternWidth, uint32_t patternHeight, uint32_t frame); + +// Frame plans in decode order +uint32_t GetReorderNum(const std::vector& plans); +std::vector BuildFramePlans(const VideoConfig& config, const std::string& gop, uint32_t frameNum, uint32_t idrPeriod); + +// Query capabilities, derive the coded size and bitstream limits +bool QueryVideoSize(const VideoContext& context, const VideoConfig& config, VideoSize& size, bool& isUnsupported, std::string& status); + +StreamResult RunStream(const RunEnvironment& environment, const StreamOptions& options); +// Decode an external AV1 OBU stream (one OBU_FRAME per picture), optionally compared bit-exactly with an NV12 reference of the shown pictures +StreamResult RunDecodeFile(const RunEnvironment& environment, const std::string& path, const std::string& refYuvPath, const std::string& name, const std::string& dumpDir, bool verbose); +std::vector MakeMatrixCases(const StreamOptions& base); +const char* GetStreamStatusName(StreamStatus status); + +} // namespace video_sample