diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 630b714..908b94b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -36,6 +36,9 @@ jobs: - uses: ilammy/msvc-dev-cmd@v1 with: arch: x64 + - name: Ensure Media Foundation is installed + shell: pwsh + run: ./build/EnsureMediaFoundation.ps1 - name: Restore, build, ABI tests, pack, and consume packages shell: pwsh run: ./build.ps1 -Configuration ${{ matrix.configuration }} @@ -85,6 +88,10 @@ jobs: env: DXSHARP_FLEET_EVIDENCE: artifacts/sample-results/fleet-system.ppm run: ./build/VerifyInterop.ps1 -Configuration Release -RuntimeMajor ${{ matrix.runtime }} -PublishAot + - name: Ensure Media Foundation is installed + if: runner.os == 'Windows' + shell: pwsh + run: ./build/EnsureMediaFoundation.ps1 - name: WARP sample qualification if: runner.os == 'Windows' shell: pwsh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9b86f74..084a6e3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,6 +45,9 @@ jobs: - uses: ilammy/msvc-dev-cmd@v1 with: arch: x64 + - name: Ensure Media Foundation is installed + shell: pwsh + run: ./build/EnsureMediaFoundation.ps1 - name: Check the requested version and source branch id: version shell: pwsh diff --git a/DXSharp.sln b/DXSharp.sln index f1b38c7..ac71797 100644 --- a/DXSharp.sln +++ b/DXSharp.sln @@ -170,6 +170,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DXSharp.Framework.WinUI", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CharacterLab.WinUI", "samples\CharacterLab.WinUI\CharacterLab.WinUI.csproj", "{0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DXSharp.Media", "src\DXSharp.Media\DXSharp.Media.csproj", "{CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VideoPlayer", "samples\VideoPlayer\VideoPlayer.csproj", "{87FBB6E0-0B1E-4616-BD9E-B547832286F3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -538,6 +542,30 @@ Global {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x64.Build.0 = Release|x64 {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x86.ActiveCfg = Release|x64 {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x86.Build.0 = Release|x64 + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|x64.ActiveCfg = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|x64.Build.0 = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|x86.ActiveCfg = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Debug|x86.Build.0 = Debug|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|Any CPU.Build.0 = Release|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|x64.ActiveCfg = Release|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|x64.Build.0 = Release|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|x86.ActiveCfg = Release|Any CPU + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF}.Release|x86.Build.0 = Release|Any CPU + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|Any CPU.ActiveCfg = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|Any CPU.Build.0 = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|x64.ActiveCfg = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|x64.Build.0 = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|x86.ActiveCfg = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Debug|x86.Build.0 = Debug|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|Any CPU.ActiveCfg = Release|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|Any CPU.Build.0 = Release|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|x64.ActiveCfg = Release|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|x64.Build.0 = Release|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|x86.ActiveCfg = Release|x64 + {87FBB6E0-0B1E-4616-BD9E-B547832286F3}.Release|x86.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -586,6 +614,8 @@ Global {CA095DE4-9BC3-49E4-A764-D4406AA4D795} = {29411031-4490-4542-B2D1-02D223BFD605} {A466B395-6AE2-4EA8-8AE7-576F60182FC0} = {29411031-4490-4542-B2D1-02D223BFD605} {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} + {CAED65E0-B5AD-4AB3-BB4B-A35AFC8152FF} = {29411031-4490-4542-B2D1-02D223BFD605} + {87FBB6E0-0B1E-4616-BD9E-B547832286F3} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7C4990EC-248E-49D5-A254-EA8AD214C338} diff --git a/README.md b/README.md index a18c399..4b77405 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ The first command presents four frames and exits. The second verifies GPU comput | `DXSharp.Assets` | Static glTF/GLB models, materials, transforms, and decoded textures | | `DXSharp.Core` | D3D12, DXGI, DXC, and generated COM interop | | `DXSharp.Framework.Desktop` | WinForms presentation loop, swap-chain resize, and frame-slot retirement | +| `DXSharp.Media` | Media Foundation frame-server playback and precompiled D3D12 video-texture rendering; [media contract](doc/Media-Playback.md) | | `DXSharp.Framework.WinUI` | Optional WinUI 3 composition viewport and XAML overlays; [hosting contract](doc/WinUI-Hosting.md) | | `DXSharp.Framework.Wpf` | Optional WPF child-HWND viewport using the shared frame renderer; [hosting contract](doc/Wpf-Hosting.md) | | `DXSharp.DirectML` | Device and operator ownership, tensor binding, and DirectML execution | diff --git a/build/EnsureMediaFoundation.ps1 b/build/EnsureMediaFoundation.ps1 new file mode 100644 index 0000000..b95873e --- /dev/null +++ b/build/EnsureMediaFoundation.ps1 @@ -0,0 +1,11 @@ +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +if (-not $IsWindows) { return } +if (Get-Command Get-WindowsFeature -ErrorAction SilentlyContinue) { + $feature = Get-WindowsFeature -Name Server-Media-Foundation + if ($feature -and -not $feature.Installed) { + $result = Install-WindowsFeature -Name Server-Media-Foundation + if (-not $result.Success -or $result.RestartNeeded -eq 'Yes') { throw 'Media Foundation installation did not complete without a reboot.' } + } +} diff --git a/build/VerifyPackages.ps1 b/build/VerifyPackages.ps1 index 28fd3ee..09b46ba 100644 --- a/build/VerifyPackages.ps1 +++ b/build/VerifyPackages.ps1 @@ -17,7 +17,7 @@ try { if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($version)) { throw 'Unable to evaluate the package version.' } - foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Native', 'DXSharp.Assets', 'DXSharp.Core', 'DXSharp.DirectML')) { + foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Media', 'DXSharp.Native', 'DXSharp.Assets', 'DXSharp.Core', 'DXSharp.DirectML')) { $path = Join-Path $packageDirectory "$name.$version.nupkg" if (-not (Test-Path $path)) { throw "Missing package: $path" } $archive = [System.IO.Compression.ZipFile]::OpenRead($path) @@ -32,13 +32,13 @@ try { ('Microsoft.WindowsDesktop.App.WPF' -notin $frameworkReferences -or 'Microsoft.WindowsDesktop.App.WindowsForms' -in $frameworkReferences)) { throw 'The WPF package must declare WPF without acquiring Windows Forms.' } - if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.Framework', 'DXSharp.Assets') -and + if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.Framework', 'DXSharp.Assets', 'DXSharp.Media') -and @($frameworkReferences | Where-Object { $_ -like 'Microsoft.WindowsDesktop*' }).Count -gt 0) { throw "Optional desktop framework leaked into $name." } $assemblies = @($archive.Entries | Where-Object FullName -CLike "lib/*/$name.dll") if ($assemblies.Count -eq 0) { throw "No library assembly found in $path" } - if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.DirectML', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Assets', 'DXSharp.Framework')) { + if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.DirectML', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Assets', 'DXSharp.Framework', 'DXSharp.Media')) { foreach ($major in '10', '11') { # NuGet normalizes the trailing zero of the Windows platform version. $framework = if ($name -eq 'DXSharp.Assets') { "net$major.0" } else { "net$major.0-windows10.0.26100" } diff --git a/build/VerifySamples.ps1 b/build/VerifySamples.ps1 index 5f8dc62..a6d9485 100644 --- a/build/VerifySamples.ps1 +++ b/build/VerifySamples.ps1 @@ -24,6 +24,7 @@ try { Invoke-Sample 'CharacterLab-wpf-host' @('run', '--project', 'samples/CharacterLab.Wpf', '-c', 'Debug', '--', '--warp', '--host-test') Invoke-Sample 'CharacterLab-winui' @('run', '--project', 'samples/CharacterLab.WinUI', '-c', 'Debug', '--', '--warp', '--frames=9') Invoke-Sample 'CharacterLab-winui-host' @('run', '--project', 'samples/CharacterLab.WinUI', '-c', 'Debug', '--', '--warp', '--host-test') + Invoke-Sample 'VideoPlayer' @('run', '--project', 'samples/VideoPlayer', '-c', 'Debug', '--', '--warp', '--test') Invoke-Sample 'DepthStencil' @('run', '--project', 'samples/DepthStencil', '-c', 'Debug', '--', '--warp') Invoke-Sample 'ModernTriangle' @('run', '--project', 'samples/ModernTriangle', '-c', 'Debug', '--', diff --git a/build/release_packages.py b/build/release_packages.py index 993e07f..f7e3197 100644 --- a/build/release_packages.py +++ b/build/release_packages.py @@ -9,7 +9,7 @@ import xml.etree.ElementTree as ET from zipfile import ZipFile -PACKAGE_IDS = ("DXSharp.Native", "DXSharp.Assets", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Tools.Builds") +PACKAGE_IDS = ("DXSharp.Native", "DXSharp.Assets", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Media", "DXSharp.Tools.Builds") PREVIEW = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-(?:net10-)?preview\.[1-9][0-9]*") diff --git a/build/verify_sample_packages.py b/build/verify_sample_packages.py index 7e80029..f9f2151 100644 --- a/build/verify_sample_packages.py +++ b/build/verify_sample_packages.py @@ -9,7 +9,7 @@ import tempfile import xml.etree.ElementTree as ET -SDK_PACKAGES = ("DXSharp.Native", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Assets", "DXSharp.Framework") +SDK_PACKAGES = ("DXSharp.Native", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Assets", "DXSharp.Framework", "DXSharp.Media") EXCLUDED = {"bin", "obj", "artifacts", ".vs"} @@ -134,6 +134,12 @@ def qualify(configuration, runtime_major): raise RuntimeError(f'WinUI precompiled consumer deployed {name}') run([str(winui), '--warp', '--frames=9'], consumer, evidence / 'character-winui-runtime.log', executable=True) run([str(winui), '--warp', '--host-test'], consumer, evidence / 'character-winui-host.log', executable=True) + media_project = consumer / 'samples/VideoPlayer/VideoPlayer.csproj' + media = Path(subprocess.check_output(['dotnet', 'msbuild', str(media_project), f'-p:Configuration={configuration}', '-p:Platform=Any CPU', '-getProperty:TargetPath', '-nologo'], cwd=consumer, text=True).strip()).with_suffix('.exe') + for name in ('dxcompiler.dll', 'dxil.dll'): + if (media.parent / name).exists(): + raise RuntimeError(f'Media precompiled consumer deployed {name}') + run([str(media), '--warp', '--test'], consumer, evidence / 'video-player.log', executable=True) (evidence / "samples.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") print(f"PASS: all {len(manifest)} runnable samples consume packaged SDK {version} outside the checkout.") diff --git a/doc/API-Coverage.md b/doc/API-Coverage.md index fe7e907..29ef8ed 100644 --- a/doc/API-Coverage.md +++ b/doc/API-Coverage.md @@ -24,6 +24,7 @@ ApiCoverage reads the pinned WinMD and built assembly with System.Reflection.Met | Direct2D | 359 / 359 | 1600 / 1600 | | DirectWrite | 207 / 207 | 1287 / 1287 | | WIC | 139 / 139 | 948 / 948 | +| Media Foundation, including pinned D3D12 video declarations | 1650 / 1650 | 8484 / 8484 | | Audio, including XAudio2 and DirectSound | 474 / 474 | 3647 / 3647 | | Raw input | 20 / 20 | 91 / 91 | | DirectInput and HID | 141 / 141 | 5546 / 5546 | diff --git a/doc/Media-Playback.md b/doc/Media-Playback.md new file mode 100644 index 0000000..62f65eb --- /dev/null +++ b/doc/Media-Playback.md @@ -0,0 +1,39 @@ +# Media playback + +Preview 4 development adds the optional `DXSharp.Media` assembly and one `samples/VideoPlayer` application. The application reuses the existing WinUI composition host. CharacterLab remains the shared host-regression scene; media functionality is implemented in a reusable library. + +## Native declarations and ownership + +DXSharp.Native projects the complete pinned `Windows.Win32.Media.MediaFoundation` namespace. The name/member/IID gate measures 1,650 top-level types and 8,484 member names against Win32Metadata 71.0.45-preview and the selected Agility metadata. This includes the pinned Direct3D 12 video interfaces located in that namespace. Declaration coverage does not establish every ABI shape, driver capability, codec or video-queue workflow. + +`MediaNative` supplies raw owned-output overloads for MF attribute creation, in-process COM activation and writable WIC section bitmaps. Each successful output transfers one native reference. Media uses Core's `NativeInterface` leases and a source-generated factory shim so output references and private projections are deterministically released. Media Engine callbacks use a generated managed COM class; native callback threads record errors, while the application thread owns playback, presentation and disposal. + +## Playback contract + +Create `MediaPlayer` on the application thread, call `Open` with an existing local file, then `Play`. Pause, seek, volume, mute and looping are exposed. Media Engine supplies the native playback pipeline, audio output and A/V presentation clock. No custom decode thread or unbounded managed frame queue is created. + +`TryGetFrame` polls `OnVideoStreamTick` and transfers one due frame through an explicitly writable WIC bitmap. It returns borrowed tightly packed BGRA bytes, native video PTS and a source/seek generation. The bytes remain valid until the next frame transfer, Open or Dispose on that player. Copy them if retaining them. Missing frames and in-progress seeks return false. Open and Seek invalidate the renderer's old-generation display. Source and display aspect ratios remain distinct. + +This initial backend is **Media Foundation → WIC BGRA → CPU staging → D3D12 upload**. It supplies SDR 8-bit presentation and does not claim zero-copy interop, HDR handling, or direct D3D12 decoding. Hardware acceleration is reported as unmeasured, not inferred from successful playback. Codec availability depends on installed Windows media components. Network/protected sources are outside the local-file wrapper. + +`VideoTextureRenderer.Draw(RenderFrame)` uses persistent per-slot textures and the shared upload ring. The host must retire the supplied frame slot before reuse. Every slot receives the newest CPU frame before it is sampled, avoiding alternating stale frames when display and video rates differ. The source display aspect is fitted to the target with letterboxing. Shaders are precompiled and embedded in Media; the sample excludes runtime DXC DLLs. + +Stop and await the viewport, dispose the video renderer, then dispose the player and device. MediaPlayer shuts down the engine before releasing its interfaces, callback owner, bitmap and mapping, and balances MF/COM initialization on the creating thread. Dispose is idempotent; other calls after disposal fail. The sample uses explicit WinUI dispatcher shutdown so asynchronous cleanup and post-close checks complete before the message loop exits. + +## Sample and evidence + +Run: + +```powershell +dotnet run --project samples/VideoPlayer -c Release +dotnet run --project samples/VideoPlayer -c Release -- --file="C:\Media\clip.mp4" +dotnet run --project samples/VideoPlayer -c Release -- --warp --test +``` + +The sample provides local file selection, seek, play/pause/restart, loop, volume/mute and transfer diagnostics. The default original H.264/AAC fixture contains a color/motion pattern, white flashes and synchronized 880 Hz pulses. `Assets/generate_fixture.py` records the reproducible FFmpeg source and updates SHA-256 hashes. FFmpeg is a development-only fixture-generation tool, not a runtime/package dependency. + +The `--test` fixture has no audio stream so hosted Windows machines without audio endpoints can execute the real video decoder and playback clock. Add `--diagnostics` when investigating the reported hardware startup crash; lifecycle/HRESULT logs are written under `%LOCALAPPDATA%/DXSharp/logs`. The bounded tests check BGRA colors/geometry, duration, pause, seek generation, video PTS/clock offset, resize bursts, end-of-stream, looping, reopening, missing paths, repeated engine creation/disposal and post-close callback inactivity. They join source and isolated package consumption on .NET 10/11. Windows Server CI installs its Media Foundation feature if absent. + +The displayed PTS-minus-clock offset is not a measurement of physical speaker latency or independent A/V drift. Audible synchronization, endpoint/device changes and actual hardware decode behavior need separate workstation review using the audio-bearing fixture. A silent CI pass does not qualify audible output. Media JIT playback is the first runtime target; NativeAOT media callbacks need a dedicated playback qualification before an AOT media claim. SDK COM ownership/AOT gates remain independent. + +References: [Media Engine](https://learn.microsoft.com/windows/win32/api/mfmediaengine/nn-mfmediaengine-imfmediaengine), [frame transfer](https://learn.microsoft.com/windows/win32/api/mfmediaengine/nf-mfmediaengine-imfmediaengine-transfervideoframe), [frame-server ticks](https://learn.microsoft.com/windows/win32/api/mfmediaengine/nf-mfmediaengine-imfmediaengine-onvideostreamtick), [D3D12 video](https://learn.microsoft.com/windows/win32/medfound/direct3d-12-video-overview). diff --git a/doc/Preview4-Candidate.md b/doc/Preview4-Candidate.md new file mode 100644 index 0000000..343db91 --- /dev/null +++ b/doc/Preview4-Candidate.md @@ -0,0 +1,17 @@ +# Preview 4 candidate cutoff + +The intended package version is `0.4.0-preview.4`. The feature cutoff combines the modern Framework/character workload, texture transfers, shader build tooling, native/WinForms/WPF/WinUI hosts and the first reusable Media Foundation playback path. CharacterLab variants remain shared host regression tests. DirectStorage, current GameInput, X3DAudio and the visual DXR scene continue in later bounded iterations. + +The release manifest contains ten modern package IDs, including the optional `DXSharp.Media`, for twenty package/symbol archives. Public release preparation must retain the exact qualifying commit and archive hashes. Legacy packages remain separate compatibility artifacts. + +Before publication: + +- Complete Windows Debug/Release source and isolated package qualification on .NET 10/11, including VideoPlayer. +- Pass native COM JIT/NativeAOT gates, native API coverage and shader package checks. +- Retest both WinUI samples on affected hardware: no VideoPlayer `0xC000027B` startup/activation failure, no CharacterLab move/resize freeze, successful repeated close/reopen and monitor DPI changes. Preserve diagnostic logs for any recurrence. +- Review Media Lab on hardware with its audio-bearing fixture: play/pause/seek/loop, correct audio/video alignment, resize and repeated open/close. Record actual decoder/transfer behavior and unsupported cases. +- Document Framework's breaking migration and the JIT-only qualification of optional desktop/media workloads. +- Finalize matching versioned release notes only when the candidate is approved for publication; merging a versioned release-note file triggers the release workflow. +- Qualify and publish the immutable candidate, then verify every public NuGet package with a fresh public-feed consumer. + +The generated Media Foundation/D3D12 video inventory is distinct from runtime-qualified playback. Direct D3D12 video commands, zero-copy video transfer and independently measured audio-output latency are not claims of this candidate. diff --git a/doc/Publishing-Previews.md b/doc/Publishing-Previews.md index f4aa81e..01762a6 100644 --- a/doc/Publishing-Previews.md +++ b/doc/Publishing-Previews.md @@ -1,6 +1,6 @@ # Publishing DXSharp previews -Preview 3 shipped five modern package IDs. Preview 4 development adds Framework, the DXC build tool and the optional WPF and WinUI hosts. The candidate set is defined in `build/release_packages.py`: `DXSharp.Native`, `DXSharp.Assets`, `DXSharp.Core`, `DXSharp.DirectML`, `DXSharp.Framework.Desktop`, `DXSharp.Framework`, `DXSharp.Framework.Wpf`, `DXSharp.Framework.WinUI` and `DXSharp.Tools.Builds`. Library assets target .NET 10/11 for Windows x64 (Assets is portable; the build tool targets netstandard2.0). Legacy compatibility projects remain independently buildable CI artifacts. Published versions remain immutable. +Preview 3 shipped five modern package IDs. Preview 4 development adds Framework, the DXC build tool the optional WPF and WinUI hosts, and Media playback. The candidate set is defined in `build/release_packages.py`: `DXSharp.Native`, `DXSharp.Assets`, `DXSharp.Core`, `DXSharp.DirectML`, `DXSharp.Framework.Desktop`, `DXSharp.Framework`, `DXSharp.Framework.Wpf`, `DXSharp.Framework.WinUI`, `DXSharp.Media` and `DXSharp.Tools.Builds`. Library assets target .NET 10/11 for Windows x64 (Assets is portable; the build tool targets netstandard2.0). Legacy compatibility projects remain independently buildable CI artifacts. Published versions remain immutable. ## One-time configuration diff --git a/doc/SDK-Architecture.md b/doc/SDK-Architecture.md index 5822457..406f98a 100644 --- a/doc/SDK-Architecture.md +++ b/doc/SDK-Architecture.md @@ -28,6 +28,7 @@ flowchart TD | `DXSharp.Core` | Device and queue ownership, buffers and resource states, descriptors, pipelines, HWND swap chains, DXC, and a bounded DXR surface | | `DXSharp.DirectML` | Same-device tensor binding and synchronous compiled Add and GEMM execution with optional fused ReLU | | `DXSharp.Framework.Desktop` | A WinForms-owned STA loop, one or two fenced frame slots, resize, depth target, and presentation | +| `DXSharp.Media` | Optional Media Foundation playback and reusable D3D12 video-texture rendering | | `DXSharp.Framework.WinUI` | Optional WinUI 3 SwapChainPanel composition over the shared frame renderer | | `DXSharp.Framework.Wpf` | Optional WPF dispatcher scheduling and a child-HWND viewport over the shared frame renderer | | `DXSharp`, `DXSharp.Dxc`, `DXSharp.Framework` | Compatibility types, RCWs, older wrappers and framework. The compatibility tests still exercise this path. BasicSample uses the current desktop host. | diff --git a/doc/Support-Matrix.md b/doc/Support-Matrix.md index 5fb8b75..493249c 100644 --- a/doc/Support-Matrix.md +++ b/doc/Support-Matrix.md @@ -30,7 +30,8 @@ Samples default to .NET 10. Select the newer runtime with `-p:DXSharpRuntimeMajo | D2D/DirectWrite/WIC/composition | Pinned declarations | Native escape hatch | Family-specific end-to-end qualification remains | | Audio/input | Pinned audio, Raw Input, DirectInput/HID, XInput and older GameInput | Selected sample-local behavior | Current GameInput, X3DAudio and reusable audio/input integrations remain | | DirectStorage | Missing separate metadata source | None | Explicitly unsupported/unqualified | -| Media Foundation/D3D12 video | Not projected | None | Separate binding and workload qualification remains | +| Media Foundation | Pinned namespace projected and name/IID coverage checked | Optional Media Engine frame-server playback; WIC/CPU transfer and D3D12 texture rendering | Fixture playback, colors, clock/seek/loop and shutdown; audible A/V sync remains hardware qualification | +| D3D12 video | Pinned declarations under Media.MediaFoundation | Native escape hatch; no owned decode/encode workflow | Direct video-command-queue workloads remain unqualified | | Advanced D3D12 features | Availability varies by pinned interface | Selected native recording paths | Query interface/features and qualify each claimed workflow | CI validates only the matrix recorded for its exact commit. A skipped hardware capability is not a pass, compilation is not execution, and a name/IID gate is not a complete ABI proof. Retain adapter/driver/runtime details with hardware results. See [qualification](SDK-Release-Qualification.md), [coverage and migration notes](API-Coverage.md), and [the parity roadmap](Competitive-Parity-Roadmap.md). diff --git a/doc/WinUI-Hosting.md b/doc/WinUI-Hosting.md index b494397..07774cb 100644 --- a/doc/WinUI-Hosting.md +++ b/doc/WinUI-Hosting.md @@ -16,7 +16,7 @@ viewport.Start( device, new WindowRenderOptions { }, frame => scene.Draw( frame ), owner: window ); ``` -The device and scene remain caller-owned. `Start` may precede loading. Calls, rendering callbacks, panel attachment and disposal belong to the creating UI thread, with the normal WinUI dispatcher synchronization context. Pass the owning window to pause presentation while minimized; use `IsSuspended` for other application visibility policies. Loading schedules frames through `CompositionTarget.Rendering`. Unloading drains and detaches presentation resources; reloading resumes the active session. +The device and scene remain caller-owned. `Start` may precede loading. Calls, rendering callbacks, panel attachment and disposal belong to the creating UI thread, with the normal WinUI dispatcher synchronization context. Pass the owning window to pause presentation while minimized; use `IsSuspended` for other application visibility policies. Loading uses `CompositionTarget.Rendering` only to enqueue one dispatcher render turn; drawing and subscriber layout changes run after the XAML composition callback returns. Frame-slot completion is polled with `CommandQueue.TryWait`; busy DXGI presentation is retried with `SwapChain.TryPresent` before another recording. A resize drains on a worker while the UI continues dispatching, then recreates back buffers and calls `SetSwapChain` again on the UI thread. Unloading drains and detaches presentation resources; reloading resumes the active session. Panel layout is in XAML units. Back buffers use `ceil(ActualWidth * CompositionScaleX)` and the corresponding height. `RenderFrame.Size` and `PixelSize` are physical pixels. The swap-chain matrix applies the inverse composition scale, including after resizing, so scaling is applied once. `Panel` exposes the underlying panel for layout/transform configuration; callers must not replace its swap chain. Ordinary XAML overlays can appear above it, unlike the WPF child-HWND adapter. Overlays that should pass pointer input through must set `IsHitTestVisible=false`. @@ -32,6 +32,12 @@ The code-created application explicitly provides WinUI XAML type metadata and in The same CharacterScene and OrbitCamera sources serve WinForms, native Win32, WPF and WinUI. WinUI playback controls, a text editor and an overlaid XAML badge demonstrate composition without a second renderer. Shaders remain precompiled, and runtime DXC binaries are excluded. -`--warp --frames=9` bounds presentation. `--warp --host-test` exercises physical resize, nonuniform XAML scale, focus, tab navigation and window activation isolation, suspension, minimize/restore, unload/reload, intentional render failure, restart and close from a presentation callback. Source and isolated package consumers join Windows CI on .NET 10 and 11. The qualification target is Windows x64 JIT; the separate native COM NativeAOT fixture does not establish WinUI NativeAOT support. Hardware pacing and monitor-to-monitor DPI transitions need interactive hardware review. +`--warp --frames=9` bounds presentation. `--warp --host-test` exercises rapid move/resize bursts with dispatcher responsiveness checks, physical resize, nonuniform XAML scale, focus, tab navigation and window activation isolation, suspension, minimize/restore, unload/reload, intentional render failure, restart and close from a presentation callback. Source and isolated package consumers join Windows CI on .NET 10 and 11. The qualification target is Windows x64 JIT; the separate native COM NativeAOT fixture does not establish WinUI NativeAOT support. Hardware pacing and monitor-to-monitor DPI transitions need interactive hardware review. References: [composition swap-chain creation](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgifactory2-createswapchainforcomposition), [WinUI native panel attachment](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/win32/microsoft.ui.xaml.media.dxinterop/nf-microsoft-ui-xaml-media-dxinterop-iswapchainpanelnative-setswapchain), [SwapChainPanel](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swapchainpanel), and [self-contained Windows App SDK deployment](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/self-contained-deploy/deploy-self-contained-apps). + +## Hardware crash investigation + +Both unpackaged WinUI samples write lifecycle stages, exception HRESULTs and stacks to `%LOCALAPPDATA%/DXSharp/logs`; the exact file is printed at startup. Add `--diagnostics` to capture the first 200 managed first-chance exceptions as well. Qualification modes have an independent 120-second process watchdog so a blocked UI/native call fails CI rather than hanging indefinitely. Ordinary interactive runs have no watchdog deadline. + +The reported VideoPlayer `0xC000027B` stowed exception and CharacterLab.WinUI move/resize freeze require hardware retesting. The dispatcher/presentation changes address identified blocking/reentrancy risks; they do not establish the cause of a native stowed exception without its originating exception record. Hosted WARP checks cannot substitute for interactive move/resize, monitor DPI transitions and audible playback on the affected workstation. diff --git a/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj b/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj index 478665e..408f7a3 100644 --- a/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj +++ b/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj @@ -7,6 +7,7 @@ app.manifestfalse + diff --git a/samples/CharacterLab.WinUI/CharacterWindow.cs b/samples/CharacterLab.WinUI/CharacterWindow.cs index 506ec1e..d9aac75 100644 --- a/samples/CharacterLab.WinUI/CharacterWindow.cs +++ b/samples/CharacterLab.WinUI/CharacterWindow.cs @@ -1,3 +1,4 @@ +using DXSharp.Samples; using DXSharp.Framework.Hosting; using DXSharp.Framework.WinUI; using DXSharp.Graphics; @@ -56,7 +57,10 @@ internal CharacterWindow( GraphicsDevice device, CharacterScene scene, int limit scene.Camera.InputEnabled = ( ) => Viewport.HasInputFocus; scene.Camera.PointerEnabled = ( ) => Viewport.AcceptsPointerInput; Viewport.WheelScrolled += delta => scene.Camera.Zoom( -delta / 120f * .3f ); - Viewport.RenderFailed += error => { Failure = error; if ( !testing ) CloseOrderly( ); }; + Viewport.RenderFailed += error => { + if ( !testing || error is not ApplicationException { Message: "intentional WinUI render failure" } ) WinUISampleDiagnostics.Error( error ); + Failure = error; if ( !testing ) CloseOrderly( ); + }; Viewport.FramePresented += statistics => { if ( scene.UpdateTitle( statistics.Frames ) is { } title ) Title = title; if ( statistics.Frames == 1 || statistics.Frames % 30 == 0 ) { diff --git a/samples/CharacterLab.WinUI/Program.cs b/samples/CharacterLab.WinUI/Program.cs index 74e06bb..00eb6e3 100644 --- a/samples/CharacterLab.WinUI/Program.cs +++ b/samples/CharacterLab.WinUI/Program.cs @@ -1,3 +1,4 @@ +using DXSharp.Samples; using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Markup; @@ -11,6 +12,7 @@ internal static class Program { internal static bool HadUnhandledException; [STAThread] private static int Main( string[] args ) { + WinUISampleDiagnostics.Initialize( "CharacterLab.WinUI", args ); try { Console.WriteLine( "Host: WinUI 3 composition; unpackaged apphost." ); WinRT.ComWrappersSupport.InitializeComWrappers( ); @@ -19,7 +21,8 @@ private static int Main( string[] args ) { _ = new CharacterApplication( args ); } ); return ExitCode; - } catch ( Exception error ) { Console.Error.WriteLine( error ); return 1; } + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); return 1; } + finally { WinUISampleDiagnostics.Shutdown( ); } } } @@ -34,12 +37,13 @@ internal sealed class CharacterApplication : Application, IXamlMetadataProvider internal CharacterApplication( string[] arguments ) { _arguments = arguments; this.DispatcherShutdownMode = Microsoft.UI.Xaml.DispatcherShutdownMode.OnExplicitShutdown; - UnhandledException += ( _, args ) => { Console.Error.WriteLine( args.Exception ); Program.ExitCode = 1; Program.HadUnhandledException = true; args.Handled = true; _window?.CloseOrderly( ); }; + UnhandledException += ( _, args ) => { WinUISampleDiagnostics.Error( args.Exception, args.Message ); Program.ExitCode = 1; Program.HadUnhandledException = true; args.Handled = true; _window?.CloseOrderly( ); }; } protected override async void OnLaunched( LaunchActivatedEventArgs args ) { GraphicsDevice? device = null; CharacterScene? scene = null; try { + WinUISampleDiagnostics.Stage( "initialize XAML resources" ); XamlControlsXamlMetaDataProvider.Initialize( ); Resources.MergedDictionaries.Add( new Microsoft.UI.Xaml.Controls.XamlControlsResources( ) ); int limit = int.Parse( _arguments.FirstOrDefault( a => a.StartsWith( "--frames=" ) )?[9..] ?? "0" ); @@ -49,9 +53,13 @@ protected override async void OnLaunched( LaunchActivatedEventArgs args ) { #else bool debug = false; #endif + WinUISampleDiagnostics.Stage( "create D3D12 device" ); device = GraphicsDevice.Create( new( ) { UseWarp = _arguments.Contains( "--warp" ), UseAgility = !_arguments.Contains( "--system-runtime" ), EnableDebugLayer = debug } ); + WinUISampleDiagnostics.Stage( "create character scene" ); scene = new( device, model, limit > 0 || _arguments.Contains( "--host-test" ) ); - _window = new( device, scene, limit, _arguments.Contains( "--host-test" ) ); _window.Activate( ); + WinUISampleDiagnostics.Stage( "construct window and controls" ); + _window = new( device, scene, limit, _arguments.Contains( "--host-test" ) ); + WinUISampleDiagnostics.Stage( "activate window and start presentation" ); _window.Activate( ); if ( _arguments.Contains( "--host-test" ) ) await WinUIHostQualification.Run( _window, device, scene ); await _window.Completion; if ( _window.Failure is { } failure ) throw new InvalidOperationException( "WinUI rendering stopped.", failure ); @@ -63,12 +71,13 @@ protected override async void OnLaunched( LaunchActivatedEventArgs args ) { throw new InvalidOperationException( "WinUI sample loaded another desktop UI framework." ); Console.WriteLine( $"PASS: WinUI CharacterLab presented {scene.Frames} GPU-skinned frames through composition; mean CPU recording {scene.MeanRecordingMilliseconds:F2} ms." ); Program.ExitCode = 0; - } catch ( Exception error ) { Console.Error.WriteLine( error ); Program.ExitCode = 1; } + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); Program.ExitCode = 1; } finally { + WinUISampleDiagnostics.Stage( "drain viewport and dispose scene/device" ); try { try { if ( _window is not null ) await _window.StopAsync( ); } finally { try { scene?.Dispose( ); } finally { device?.Dispose( ); } } - } catch ( Exception error ) { Console.Error.WriteLine( error ); Program.ExitCode = 1; } + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); Program.ExitCode = 1; } finally { Exit( ); } } } diff --git a/samples/CharacterLab.WinUI/WinUIHostQualification.cs b/samples/CharacterLab.WinUI/WinUIHostQualification.cs index 3aa4450..44fb21c 100644 --- a/samples/CharacterLab.WinUI/WinUIHostQualification.cs +++ b/samples/CharacterLab.WinUI/WinUIHostQualification.cs @@ -21,6 +21,19 @@ internal static async Task Run( CharacterWindow window, GraphicsDevice device, C window.AppWindow.Resize( new SizeInt32( 1000, 700 ) ); await Frames( viewport, viewport.Statistics.Frames + 3 ); Require( viewport.PixelSize != original && viewport.Statistics.Resizes > 0 && rendered == viewport.PixelSize, "WinUI resize did not reach the physical back buffers." ); + // Coalesced resize/move bursts must keep the dispatcher alive and ultimately render the latest physical size. + var turn = System.Diagnostics.Stopwatch.StartNew( ); + for ( int i = 0; i < 24; ++i ) { + var rectangle = window.AppWindow.Position; + window.AppWindow.MoveAndResize( new RectInt32( rectangle.X + (i % 2 == 0 ? 1 : -1), rectangle.Y, + 920 + i % 4 * 23, 640 + i % 3 * 17 ) ); + await Task.Delay( 15 ); + Require( turn.Elapsed < TimeSpan.FromSeconds( 5 ), "WinUI dispatcher stalled during move/resize." ); turn.Restart( ); + } + int before = viewport.Statistics.Frames; + await Frames( viewport, before + 4 ); + Require( rendered == viewport.PixelSize, "Resize burst did not settle on the latest physical dimensions." ); + Console.WriteLine( "PASS: WinUI move/resize burst kept dispatching and settled on the final back-buffer size." ); Require( viewport.Focus( FocusState.Programmatic ) && viewport.HasInputFocus, "Cannot focus the WinUI viewport." ); window.Editor.Focus( FocusState.Programmatic ); Require( !viewport.HasInputFocus && Equals( FocusManager.GetFocusedElement( viewport.XamlRoot ), window.Editor ), "Viewport stole text editor focus." ); diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props index 4fec25d..8e683e3 100644 --- a/samples/Directory.Build.props +++ b/samples/Directory.Build.props @@ -8,6 +8,7 @@ DXSharp - $(MSBuildProjectName) DXSharp Samples Copyright (c) Arkaen Solutions and DXSharp contributors + Media Foundation video/audio playback through DXSharp D3D12 textures. GPU-skinned CharacterLab hosted in a WinUI 3 composition panel. Advanced DXSharp graphics techniques. A minimal Direct3D 12 renderer built with DXSharp. diff --git a/samples/README.md b/samples/README.md index 8234c15..1017cc8 100644 --- a/samples/README.md +++ b/samples/README.md @@ -28,3 +28,5 @@ CharacterLab adds persistent GPU skinning, animation playback and material maps; `CharacterLab.WinUI` shares the scene through the optional WinUI 3 composition viewport, with playback controls, independent text input and a genuine XAML overlay. The unpackaged app bundles its Windows App SDK runtime. `--warp --host-test` checks scale, resize, focus, suspension, unload/reload, restart and teardown. See [WinUI hosting](../doc/WinUI-Hosting.md). See the [visual showcase and optional UI host plan](../doc/Sample-Showcase-Plan.md) for WPF/WinUI adapters and the upcoming media, spatial audio, DirectStorage and interactive DXR samples. The media, storage and interactive DXR showcases remain planned. + +`VideoPlayer` demonstrates Media Foundation frame-server playback through DXSharp D3D12 textures, with WinUI open/play/pause/seek/loop/volume controls and live transfer diagnostics. The original generated test clip includes synchronized flashes and audio pulses. Run `dotnet run --project samples/VideoPlayer -c Release`; use `-- --file="C:\Media\clip.mp4"` for a local file or `-- --warp --test` for bounded CI checks. See [media playback](../doc/Media-Playback.md). diff --git a/samples/Shared/WinUISampleDiagnostics.cs b/samples/Shared/WinUISampleDiagnostics.cs new file mode 100644 index 0000000..cdce2cc --- /dev/null +++ b/samples/Shared/WinUISampleDiagnostics.cs @@ -0,0 +1,52 @@ +using System.Runtime.ExceptionServices; + +namespace DXSharp.Samples; + +// Shared by the unpackaged WinUI samples; no additional desktop framework is loaded. +internal static class WinUISampleDiagnostics { + private static readonly object Gate = new( ); + private static string? _path; + private static string _stage = "bootstrap"; + private static int _firstChanceCount; + [ThreadStatic] private static bool _writing; + private static Timer? _watchdog; + + internal static void Initialize( string name, string[] arguments ) { + try { + string directory = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ), "DXSharp", "logs" ); + Directory.CreateDirectory( directory ); + _path = Path.Combine( directory, $"{name}-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Environment.ProcessId}.log" ); + Console.WriteLine( $"Diagnostic log: {_path}" ); + } catch ( Exception error ) { Console.Error.WriteLine( $"Cannot create diagnostic log: {error.Message}" ); } + Stage( $"bootstrap; .NET {Environment.Version}; OS {Environment.OSVersion}; {RuntimeInformation()}" ); + AppDomain.CurrentDomain.UnhandledException += ( _, args ) => Error( args.ExceptionObject as Exception ?? new Exception( args.ExceptionObject.ToString( ) ) ); + if ( arguments.Contains( "--diagnostics" ) ) AppDomain.CurrentDomain.FirstChanceException += FirstChance; + if ( arguments.Contains( "--host-test" ) || arguments.Contains( "--test" ) ) { + _watchdog = new Timer( _ => { + Write( "FAIL: qualification exceeded 120 seconds; UI/native call may be blocked." ); + Environment.Exit( 124 ); + }, null, TimeSpan.FromSeconds( 120 ), Timeout.InfiniteTimeSpan ); + } + } + private static string RuntimeInformation( ) => System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString( ); + internal static void Stage( string stage ) { Volatile.Write( ref _stage, stage ); Write( stage ); } + internal static void Error( Exception error, string? context = null ) => Write( $"FAIL at {Volatile.Read( ref _stage )}; HRESULT 0x{error.HResult:X8}; {context}\n{error}" ); + internal static void Shutdown( ) { _watchdog?.Dispose( ); _watchdog = null; } + private static void FirstChance( object? sender, FirstChanceExceptionEventArgs args ) { + if ( Interlocked.Increment( ref _firstChanceCount ) <= 200 ) Write( $"First-chance HRESULT 0x{args.Exception.HResult:X8}: {args.Exception}" ); + } + private static void Write( string message ) { + if ( _writing ) return; + _writing = true; + try { + string line = $"{DateTime.UtcNow:O} [thread {Environment.CurrentManagedThreadId}] {message}"; + try { Console.Error.WriteLine( line ); } catch ( IOException ) { } + lock ( Gate ) { + if ( _path is null ) return; + try { File.AppendAllText( _path, line + Environment.NewLine ); } + catch ( IOException ) { _path = null; } + catch ( UnauthorizedAccessException ) { _path = null; } + } + } finally { _writing = false; } + } +} diff --git a/samples/VideoPlayer/Assets/generate_fixture.py b/samples/VideoPlayer/Assets/generate_fixture.py new file mode 100644 index 0000000..9b1a50c --- /dev/null +++ b/samples/VideoPlayer/Assets/generate_fixture.py @@ -0,0 +1,14 @@ +"""Regenerate original DXSharp test media with FFmpeg; no external footage is used.""" +from pathlib import Path +import hashlib, json, subprocess +root = Path(__file__).resolve().parent +video = "testsrc2=size=320x180:rate=24:duration=6,drawbox=x=280:y=8:w=32:h=32:color=white:t=fill:enable='lt(mod(t,1),0.1)'" +audio = "sine=frequency=880:sample_rate=48000:duration=6" +subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','lavfi','-i',video,'-f','lavfi','-i',audio, + '-vf','format=yuv420p','-af',"volume='0.3*lt(mod(t,1),0.1)':eval=frame",'-c:v','libx264','-preset','slow','-crf','23', + '-c:a','aac','-b:a','64k','-movflags','+faststart','-map_metadata','-1',str(root/'test-av.mp4')],check=True) +subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-i',str(root/'test-av.mp4'),'-an','-c:v','copy', + '-map_metadata','-1',str(root/'test-video.mp4')],check=True) +(root/'manifest.json').write_text(json.dumps({'origin':'Original FFmpeg-generated DXSharp test pattern; MIT licensed with this repository.', + 'width':320,'height':180,'framesPerSecond':24,'durationSeconds':6,'audio':'880 Hz pulses synchronized to the white flash; 48 kHz AAC stereo/mono as encoded', + 'files':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in root.glob('*.mp4')}},indent=2)+'\n') diff --git a/samples/VideoPlayer/Assets/manifest.json b/samples/VideoPlayer/Assets/manifest.json new file mode 100644 index 0000000..ffc02b3 --- /dev/null +++ b/samples/VideoPlayer/Assets/manifest.json @@ -0,0 +1,12 @@ +{ + "origin": "Original FFmpeg-generated DXSharp test pattern; MIT licensed with this repository.", + "width": 320, + "height": 180, + "framesPerSecond": 24, + "durationSeconds": 6, + "audio": "880 Hz pulses synchronized to the white flash; 48 kHz AAC stereo/mono as encoded", + "files": { + "test-av.mp4": "def5fc5bf10be167ddde071087c71dfbca644a046f6e3e3b5e64acdb650a6cef", + "test-video.mp4": "4a741edddd69fecb2405b454a5d64abffcdd1c9d1969830823cb695ddac2c962" + } +} diff --git a/samples/VideoPlayer/Assets/test-av.mp4 b/samples/VideoPlayer/Assets/test-av.mp4 new file mode 100644 index 0000000..b25ac98 Binary files /dev/null and b/samples/VideoPlayer/Assets/test-av.mp4 differ diff --git a/samples/VideoPlayer/Assets/test-video.mp4 b/samples/VideoPlayer/Assets/test-video.mp4 new file mode 100644 index 0000000..8d9f7c2 Binary files /dev/null and b/samples/VideoPlayer/Assets/test-video.mp4 differ diff --git a/samples/VideoPlayer/PlaybackQualification.cs b/samples/VideoPlayer/PlaybackQualification.cs new file mode 100644 index 0000000..5cfd280 --- /dev/null +++ b/samples/VideoPlayer/PlaybackQualification.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using DXSharp.Media; +using Windows.Graphics; + +namespace DXSharp.VideoPlayer; + +internal static class PlaybackQualification { + internal static async Task Run(PlayerWindow window, string source) { + var player = window.Player; + await Until(() => player.IsReady && window.VideoFrames >= 3,player); + Require(Math.Abs(player.Duration.TotalSeconds - 6) < .2 && player.HasVideo,"Fixture duration/video stream is incorrect."); + var frame = window.LatestFrame; Require(frame.Width == 320 && frame.Height == 180 && frame.RowPitch == 1280,"Incorrect BGRA frame geometry."); + int colored = 0; var pixels = frame.Pixels.ToArray(); + for (int i=0;i 70) ++colored; + Require(colored > 5000,"Decoded color pattern is missing or channel data are blank."); + player.Pause(); await Task.Delay(80); var paused = player.Position; await Task.Delay(180); + Require(player.IsPaused && Math.Abs((player.Position-paused).TotalMilliseconds)<50,"Paused presentation clock advanced."); + Console.WriteLine("PASS: decoded BGRA pattern, fixture duration and paused presentation clock."); + player.Volume=.25; player.Muted=true; Require(player.Muted && Math.Abs(player.Volume-.25)<.001,"Volume/mute state failed."); player.Muted=false; + long generation=player.Generation; player.Seek(TimeSpan.FromSeconds(2)); + await Until(() => !player.IsSeeking && Math.Abs(player.Position.TotalSeconds-2)<.2,player); + Require(player.Generation>generation,"Seek did not invalidate old frame generation."); + player.Play(); long count=window.VideoFrames; + await Until(() => window.VideoFrames>count+2 && window.LatestFrame.Generation==player.Generation,player); + Require(Math.Abs(player.Statistics.PresentationOffset.TotalSeconds)<.5,"Video PTS is far from Media Engine clock."); + window.AppWindow.Resize(new SizeInt32(840,660)); await Until(() => window.Statistics.Resizes>0,player); + Require(window.Viewport.PixelSize.Width>0,"Resize lost the presentation surface."); + for (int i=0;i<12;++i) { window.AppWindow.Resize(new SizeInt32(840+i%3*32,660+i%2*24)); await Task.Delay(20); } + int resizedFrames=window.Statistics.Frames; + await Until(() => window.Statistics.Frames>resizedFrames+3,player); + Require(window.Viewport.Failure is null,"Video viewport failed during resize burst."); + player.Loop=false; player.Seek(player.Duration-TimeSpan.FromMilliseconds(150)); player.Play(); await Until(() => player.IsEnded,player); + player.Loop=true; player.Seek(player.Duration-TimeSpan.FromMilliseconds(120)); player.Play(); await Until(() => player.Position.TotalSeconds<1 && !player.IsSeeking,player); + Require(!player.IsEnded,"Loop did not restart playback."); + for (int i=0;i<3;++i) { + generation=player.Generation; window.Open(source); + await Until(() => player.IsReady && window.LatestFrame.Generation>generation,player); + } + bool missing=false; try { player.Open(Path.Combine(Path.GetDirectoryName(source)!,"missing-file.mp4")); } catch(FileNotFoundException) { missing=true; } + Require(missing,"Missing media path was accepted."); + Console.WriteLine("PASS: Media Foundation BGRA colors/duration, presentation clock, pause, seek/generation, mute/volume, resize, end-of-stream, loop, repeated open and missing file."); + window.CloseOrderly(); await window.Completion.WaitAsync(TimeSpan.FromSeconds(20)); + int presented=window.Statistics.Frames; await Task.Delay(120); Require(presented==window.Statistics.Frames,"Closed player retained presentation callbacks."); + for (int i=0;i<2;++i) { + using var reopened = new MediaPlayer(); reopened.Open(source); reopened.Play(); + await Until(() => reopened.TryGetFrame(out _),reopened); + } + player.Dispose(); bool disposed=false; + try { player.Play(); } catch(ObjectDisposedException) { disposed=true; } + Require(disposed,"Disposed player accepted playback."); player.Dispose(); + Console.WriteLine("PASS: video player drained shutdown and inert post-close callbacks. Audio-less CI fixture; audible A/V synchronization requires hardware review."); + } + private static async Task Until(Func predicate,MediaPlayer player, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(predicate))] string condition = "") { + var watch=Stopwatch.StartNew(); + while(!predicate()) { player.ThrowIfFailed(); if(watch.Elapsed>TimeSpan.FromSeconds(20)) throw new TimeoutException($"Media qualification timed out: {condition}; position={player.Position.TotalSeconds:F3}, duration={player.Duration.TotalSeconds:F3}, ready={player.IsReady}, seeking={player.IsSeeking}, paused={player.IsPaused}, ended={player.IsEnded}."); await Task.Delay(10); } + } + private static void Require(bool condition,string message) { if(!condition) throw new InvalidOperationException(message); } +} diff --git a/samples/VideoPlayer/PlayerWindow.cs b/samples/VideoPlayer/PlayerWindow.cs new file mode 100644 index 0000000..0bcb5e8 --- /dev/null +++ b/samples/VideoPlayer/PlayerWindow.cs @@ -0,0 +1,92 @@ +using DXSharp.Samples; +using DXSharp.Framework.Hosting; +using DXSharp.Framework.WinUI; +using DXSharp.Graphics; +using DXSharp.Media; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Windows.Graphics; +using Windows.Storage.Pickers; +using System.Runtime.InteropServices; + +namespace DXSharp.VideoPlayer; + +internal sealed class PlayerWindow : Window { + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly VideoTextureRenderer _renderer; + private readonly TextBlock _status = new() { TextWrapping = TextWrapping.Wrap, FontSize = 12 }; + private readonly TextBlock _source = new() { TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 14 }; + private readonly Slider _timeline = new() { Minimum = 0, Maximum = 1, HorizontalAlignment = HorizontalAlignment.Stretch }; + private readonly int _limit; + private bool _updating, _closing, _closed, _mediaError; + internal D3D12Viewport Viewport { get; } = new(); + internal MediaPlayer Player { get; } + internal Task Completion => _completion.Task; + internal RenderStatistics Statistics => Viewport.Statistics; + internal long VideoFrames => _renderer.FramesTransferred; + internal VideoFrame LatestFrame => _renderer.LatestFrame; + internal Exception? Failure { get; private set; } + + internal PlayerWindow(GraphicsDevice device, MediaPlayer player, string file, int limit) { + Player = player; _limit = limit; _renderer = new(device, player); + Title = "DXSharp · Media Lab"; + var root = new Grid { Padding = new(20), RowSpacing = 12, RequestedTheme = ElementTheme.Dark, Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255,10,16,26)) }; + root.RowDefinitions.Add(new() { Height = GridLength.Auto }); root.RowDefinitions.Add(new()); + root.RowDefinitions.Add(new() { Height = GridLength.Auto }); root.RowDefinitions.Add(new() { Height = GridLength.Auto }); root.RowDefinitions.Add(new() { Height = GridLength.Auto }); + var title = new StackPanel { Spacing = 4 }; + title.Children.Add(new TextBlock { Text = "ARKAEN / DXSHARP · MEDIA LAB", FontSize = 24 }); title.Children.Add(_source); root.Children.Add(title); + var scene = new Grid(); scene.Children.Add(Viewport); Grid.SetRow(scene,1); root.Children.Add(scene); + var badge = new Border { IsHitTestVisible = false, Background = new SolidColorBrush(Windows.UI.Color.FromArgb(220,12,30,40)), Padding = new(10), Margin = new(12), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, + Child = new TextBlock { Text = "MEDIA FOUNDATION → DXSHARP D3D12\nFrame-server playback · precompiled shaders", FontSize = 12 } }; scene.Children.Add(badge); + Grid.SetRow(_timeline,2); root.Children.Add(_timeline); + _timeline.ValueChanged += (_,e) => { if (!_updating && Player.IsReady) TryAction(() => Player.Seek(TimeSpan.FromSeconds(e.NewValue))); }; + var commands = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; + var open = new Button { Content = "Open file…" }; open.Click += async (_,_) => { + try { + var picker = new FileOpenPicker(); WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(this)); + foreach (string extension in new[] { ".mp4", ".wmv", ".avi", ".mov", ".mp3", ".wav" }) picker.FileTypeFilter.Add(extension); + var selected = await picker.PickSingleFileAsync(); if (selected is not null && !_closing) Open(selected.Path); + } catch (Exception error) { _status.Text = error.Message; } + }; commands.Children.Add(open); + var play = new Button { Content = "Play / pause" }; play.Click += (_,_) => TryAction(() => { if (Player.IsPaused) Player.Play(); else Player.Pause(); }); commands.Children.Add(play); + var restart = new Button { Content = "Restart" }; restart.Click += (_,_) => TryAction(() => { Player.Seek(TimeSpan.Zero); Player.Play(); }); commands.Children.Add(restart); + var loop = new CheckBox { Content = "Loop" }; loop.Checked += (_,_) => TryAction(() => Player.Loop = true); loop.Unchecked += (_,_) => TryAction(() => Player.Loop = false); commands.Children.Add(loop); + var mute = new CheckBox { Content = "Mute" }; mute.Checked += (_,_) => TryAction(() => Player.Muted = true); mute.Unchecked += (_,_) => TryAction(() => Player.Muted = false); commands.Children.Add(mute); + var volume = new Slider { Minimum = 0, Maximum = 1, Value = .65, Width = 130 }; volume.ValueChanged += (_,e) => TryAction(() => Player.Volume = e.NewValue); + commands.Children.Add(new TextBlock { Text = "Volume", VerticalAlignment = VerticalAlignment.Center }); commands.Children.Add(volume); + var controlScroll = new ScrollViewer { Content = commands, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollMode = ScrollMode.Enabled, VerticalScrollMode = ScrollMode.Disabled }; + Grid.SetRow(controlScroll,3); root.Children.Add(controlScroll); Grid.SetRow(_status,4); root.Children.Add(_status); + Content = root; AppWindow.Resize(new SizeInt32(1180,780)); + Open(file); Player.Volume = .65; + Viewport.RenderFailed += error => { WinUISampleDiagnostics.Error( error ); Failure = error; CloseOrderly(); }; + Viewport.FramePresented += stats => { + if (stats.Frames % 12 == 0 && !_mediaError) { + _updating = true; + try { _timeline.Maximum = Math.Max(1,Player.Duration.TotalSeconds); _timeline.Value = Math.Min(_timeline.Maximum,Player.Position.TotalSeconds); } + finally { _updating = false; } + var s = Player.Statistics; var f = LatestFrame; + _status.Text = $"{Player.Position:mm\\:ss\\.fff} / {Player.Duration:mm\\:ss} · {(Player.IsEnded ? "ENDED" : Player.IsPaused ? "PAUSED" : "PLAYING")} · {f.Width}×{f.Height} · audio {(Player.HasAudio ? "present" : "none")}\n" + + $"Transferred {s.FramesTransferred} · dropped {s.FramesDropped?.ToString() ?? "unavailable"} · video PTS − A/V clock {s.PresentationOffset.TotalMilliseconds:+0.0;-0.0;0.0} ms · hardware decode unmeasured\n{s.TransferPath}"; + } + if (_limit > 0 && stats.Frames >= _limit && VideoFrames > 1) CloseOrderly(); + }; + Viewport.Start(device,new() { FramesInFlight = 2 },frame => { + if (_mediaError) return; + try { _renderer.Draw(frame); } + catch (COMException error) { _mediaError = true; WinUISampleDiagnostics.Error(error); _status.Text = $"Playback error: {error.Message}"; Failure = error; } + },this); + AppWindow.Closing += (_,e) => { if (!_closed) { e.Cancel = true; CloseOrderly(); } }; + Closed += (_,_) => _completion.TrySetResult(); + VisibilityChanged += (_,e) => Viewport.IsSuspended = !e.Visible; + } + private void TryAction(Action action) { try { action(); } catch (Exception error) { _status.Text = error.Message; } } + internal void Open(string path) { Player.Open(path); Failure = null; _mediaError = false; _source.Text = path; Player.Play(); } + internal async Task StopAsync() { await Viewport.StopAsync(); Viewport.Dispose(); _renderer.Dispose(); } + internal async void CloseOrderly() { + if (_closing) return; _closing = true; + try { await StopAsync(); } + catch (Exception error) { Failure ??= error; } + finally { _closed = true; Close(); _completion.TrySetResult(); } + } +} diff --git a/samples/VideoPlayer/Program.cs b/samples/VideoPlayer/Program.cs new file mode 100644 index 0000000..51192a6 --- /dev/null +++ b/samples/VideoPlayer/Program.cs @@ -0,0 +1,85 @@ +using DXSharp.Samples; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Markup; +using Microsoft.UI.Xaml.XamlTypeInfo; +using DXSharp.Graphics; + +namespace DXSharp.VideoPlayer; + +internal static class Program { + internal static int ExitCode = 1; + internal static bool HadUnhandledException; + [STAThread] + private static int Main( string[] args ) { + WinUISampleDiagnostics.Initialize( "VideoPlayer", args ); + try { + Console.WriteLine( "Host: DXSharp Media Foundation video player; WinUI 3 composition." ); + WinRT.ComWrappersSupport.InitializeComWrappers( ); + Application.Start( parameters => { + SynchronizationContext.SetSynchronizationContext( new DispatcherQueueSynchronizationContext( DispatcherQueue.GetForCurrentThread( ) ) ); + _ = new VideoApplication( args ); + } ); + return ExitCode; + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); return 1; } + finally { WinUISampleDiagnostics.Shutdown( ); } + } +} + +internal sealed class VideoApplication : Application, IXamlMetadataProvider { + private XamlControlsXamlMetaDataProvider? _metadata; + private XamlControlsXamlMetaDataProvider Metadata => _metadata ??= new( ); + IXamlType IXamlMetadataProvider.GetXamlType( Type type ) => Metadata.GetXamlType( type ); + IXamlType IXamlMetadataProvider.GetXamlType( string name ) => Metadata.GetXamlType( name ); + XmlnsDefinition[] IXamlMetadataProvider.GetXmlnsDefinitions( ) => Metadata.GetXmlnsDefinitions( ); + private readonly string[] _arguments; + private PlayerWindow? _window; + internal VideoApplication( string[] arguments ) { + _arguments = arguments; + this.DispatcherShutdownMode = Microsoft.UI.Xaml.DispatcherShutdownMode.OnExplicitShutdown; + UnhandledException += ( _, args ) => { WinUISampleDiagnostics.Error( args.Exception, args.Message ); Program.ExitCode = 1; Program.HadUnhandledException = true; args.Handled = true; _window?.CloseOrderly( ); }; + } + protected override async void OnLaunched( LaunchActivatedEventArgs args ) { + GraphicsDevice? device = null; + DXSharp.Media.MediaPlayer? scene = null; + try { + WinUISampleDiagnostics.Stage( "initialize XAML resources" ); + XamlControlsXamlMetaDataProvider.Initialize( ); + Resources.MergedDictionaries.Add( new Microsoft.UI.Xaml.Controls.XamlControlsResources( ) ); + bool testing = _arguments.Contains( "--test" ); + int limit = int.Parse( _arguments.FirstOrDefault( a => a.StartsWith( "--frames=" ) )?[9..] ?? "0" ); + string source = _arguments.FirstOrDefault( a => a.StartsWith( "--file=" ) )?[7..] ?? System.IO.Path.Combine( AppContext.BaseDirectory, "Assets", testing || _arguments.Contains( "--silent-fixture" ) ? "test-video.mp4" : "test-av.mp4" ); +#if DEBUG + bool debug = !_arguments.Contains( "--no-debug" ); +#else + bool debug = false; +#endif + WinUISampleDiagnostics.Stage( "create D3D12 device" ); + device = GraphicsDevice.Create( new( ) { UseWarp = _arguments.Contains( "--warp" ), UseAgility = !_arguments.Contains( "--system-runtime" ), EnableDebugLayer = debug } ); + WinUISampleDiagnostics.Stage( "create media engine" ); + scene = new( ); + WinUISampleDiagnostics.Stage( "construct window and controls" ); + _window = new( device, scene, source, limit ); + WinUISampleDiagnostics.Stage( "activate window and start presentation" ); _window.Activate( ); + if ( testing ) await PlaybackQualification.Run( _window, source ); + await _window.Completion; + if ( _window.Failure is { } failure ) throw new InvalidOperationException( "Video rendering stopped.", failure ); + if ( limit > 0 && _window.Statistics.Frames < limit ) throw new InvalidOperationException( "Video frame limit was not reached." ); + var diagnostics = device.GetDiagnostics( ); + foreach ( var message in diagnostics.Messages ) Console.WriteLine( message ); + if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( m => m.Contains( "SEVERITY_ERROR" ) || m.Contains( "SEVERITY_CORRUPTION" ) ) || Program.HadUnhandledException ) throw new InvalidOperationException( "WinUI qualification reported a device or unhandled UI failure." ); + if ( AppDomain.CurrentDomain.GetAssemblies( ).Any( a => a.GetName( ).Name is "System.Windows.Forms" or "PresentationFramework" ) ) + throw new InvalidOperationException( "WinUI sample loaded another desktop UI framework." ); + Console.WriteLine( $"PASS: VideoPlayer presented {_window.Statistics.Frames} frames; media frames transferred {_window.VideoFrames}." ); + Program.ExitCode = 0; + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); Program.ExitCode = 1; } + finally { + WinUISampleDiagnostics.Stage( "drain viewport and dispose scene/device" ); + try { + try { if ( _window is not null ) await _window.StopAsync( ); } + finally { try { scene?.Dispose( ); } finally { device?.Dispose( ); } } + } catch ( Exception error ) { WinUISampleDiagnostics.Error( error ); Program.ExitCode = 1; } + finally { Exit( ); } + } + } +} diff --git a/samples/VideoPlayer/VideoPlayer.csproj b/samples/VideoPlayer/VideoPlayer.csproj new file mode 100644 index 0000000..deadca9 --- /dev/null +++ b/samples/VideoPlayer/VideoPlayer.csproj @@ -0,0 +1,15 @@ + + + Exe$(DotNetTargets) + truefalseNone + truex64x64 + win-x64false + app.manifestfalse + + + + + + + + diff --git a/samples/VideoPlayer/app.manifest b/samples/VideoPlayer/app.manifest new file mode 100644 index 0000000..4ab17df --- /dev/null +++ b/samples/VideoPlayer/app.manifest @@ -0,0 +1,11 @@ + + + + + PerMonitorV2 + true + + + + + diff --git a/samples/VideoPlayer/packages.lock.json b/samples/VideoPlayer/packages.lock.json new file mode 100644 index 0000000..28e20a8 --- /dev/null +++ b/samples/VideoPlayer/packages.lock.json @@ -0,0 +1,138 @@ +{ + "version": 2, + "dependencies": { + "net10.0-windows10.0.26100": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.framework.winui": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )", + "Microsoft.WindowsAppSDK.WinUI": "[2.7.0, 2.7.0]" + } + }, + "dxsharp.media": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "Microsoft.WindowsAppSDK.WinUI": { + "type": "CentralTransitive", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net10.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + } + } +} \ No newline at end of file diff --git a/samples/VideoPlayer/packages.net11.lock.json b/samples/VideoPlayer/packages.net11.lock.json new file mode 100644 index 0000000..7140a51 --- /dev/null +++ b/samples/VideoPlayer/packages.net11.lock.json @@ -0,0 +1,138 @@ +{ + "version": 2, + "dependencies": { + "net11.0-windows10.0.26100": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.framework.winui": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )", + "Microsoft.WindowsAppSDK.WinUI": "[2.7.0, 2.7.0]" + } + }, + "dxsharp.media": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "Microsoft.WindowsAppSDK.WinUI": { + "type": "CentralTransitive", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net11.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + } + } +} \ No newline at end of file diff --git a/src/DXSharp.Core/Graphics/Commands.cs b/src/DXSharp.Core/Graphics/Commands.cs index 9272196..68e0335 100644 --- a/src/DXSharp.Core/Graphics/Commands.cs +++ b/src/DXSharp.Core/Graphics/Commands.cs @@ -362,6 +362,19 @@ public ulong Submit( GraphicsCommandList commands ) { return value; } } + /// Polls a submitted fence without waiting for the GPU or a busy queue. Completed submissions release their retained resources. + public bool TryWait( ulong value ) { + if ( !Monitor.TryEnter( _gate ) ) return false; + try { + ObjectDisposedException.ThrowIf( IsDisposed, this ); + if ( value > _nextValue ) throw new ArgumentOutOfRangeException( nameof(value) ); + foreach ( var pending in _pending ) + if ( pending.Value <= value && pending.SignalFailure < 0 ) throw new GraphicsException( "CommandQueue.Signal", pending.SignalFailure ); + ulong completed = _fence.Interface.GetCompletedValue( ); + if ( completed == ulong.MaxValue ) throw new GraphicsException( "Fence/device removed", _device.Interface.GetDeviceRemovedReason( ).Value ); + RetireThrough( completed ); return completed >= value; + } finally { Monitor.Exit( _gate ); } + } /// Waits for a submitted value. A timeout retains pending resources and prevents premature reuse. public void Wait( ulong value, TimeSpan? timeout = null ) { lock ( _gate ) { diff --git a/src/DXSharp.Core/Graphics/Pipelines.cs b/src/DXSharp.Core/Graphics/Pipelines.cs index 437adf2..709ac36 100644 --- a/src/DXSharp.Core/Graphics/Pipelines.cs +++ b/src/DXSharp.Core/Graphics/Pipelines.cs @@ -59,7 +59,13 @@ public RootSignature CreateRootSignature( uint computeBufferCount, uint computeC /// Number of inline DWORDs. Zero omits the constant parameter. /// Uses a linear repeat sampler at s0 when true and point clamp when false. /// The owning root signature. Bind the texture at parameter one when constants are present. - public RootSignature CreateTextureRootSignature( uint constantCount, bool linearWrap ) { + public RootSignature CreateTextureRootSignature( uint constantCount, bool linearWrap ) => CreateTextureRootSignature( constantCount, linearWrap, linearWrap ); + + /// Creates a texture signature with independent filtering and address-mode choices. + /// Inline DWORD constants at b0, or zero. + /// True for linear filtering, false for point filtering. + /// True for repeating UV coordinates, false for clamping to texture edges. + public RootSignature CreateTextureRootSignature( uint constantCount, bool linearFiltering, bool wrap ) { if ( constantCount > 63 ) throw new ArgumentOutOfRangeException( nameof(constantCount) ); D3D12_DESCRIPTOR_RANGE range = new( ) { RangeType = D3D12_DESCRIPTOR_RANGE_TYPE.D3D12_DESCRIPTOR_RANGE_TYPE_SRV, NumDescriptors = 1 }; D3D12_ROOT_PARAMETER parameter = new( ) { @@ -71,10 +77,10 @@ public RootSignature CreateTextureRootSignature( uint constantCount, bool linear int textureSlot = constantCount == 0 ? 0 : 1; if ( constantCount != 0 ) parameters[0] = InlineConstants( constantCount ); parameters[textureSlot] = parameter; - var address = linearWrap ? D3D12_TEXTURE_ADDRESS_MODE.D3D12_TEXTURE_ADDRESS_MODE_WRAP + var address = wrap ? D3D12_TEXTURE_ADDRESS_MODE.D3D12_TEXTURE_ADDRESS_MODE_WRAP : D3D12_TEXTURE_ADDRESS_MODE.D3D12_TEXTURE_ADDRESS_MODE_CLAMP; D3D12_STATIC_SAMPLER_DESC sampler = new( ) { - Filter = linearWrap ? D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_LINEAR : D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_POINT, + Filter = linearFiltering ? D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_LINEAR : D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU = address, AddressV = address, AddressW = address, MaxAnisotropy = 1, MaxLOD = float.MaxValue, ComparisonFunc = D3D12_COMPARISON_FUNC.D3D12_COMPARISON_FUNC_ALWAYS, diff --git a/src/DXSharp.Core/Graphics/SwapChain.cs b/src/DXSharp.Core/Graphics/SwapChain.cs index be79b30..f5fcdc6 100644 --- a/src/DXSharp.Core/Graphics/SwapChain.cs +++ b/src/DXSharp.Core/Graphics/SwapChain.cs @@ -35,6 +35,13 @@ public int Present( uint syncInterval = 1 ) { if ( syncInterval > 4 ) throw new ArgumentOutOfRangeException( nameof(syncInterval) ); int hr = _native.Interface.Present( syncInterval, 0 ); Results.Check( hr, "SwapChain.Present" ); return hr; } + /// Attempts presentation without waiting for DXGI dependencies. False means retry the same frame before recording another back buffer. + public bool TryPresent( uint syncInterval = 1 ) { + if ( syncInterval > 4 ) throw new ArgumentOutOfRangeException( nameof(syncInterval) ); + int hr = _native.Interface.Present( syncInterval, DXGI_PRESENT.DXGI_PRESENT_DO_NOT_WAIT ); + if ( hr == unchecked((int)0x887A000A) ) return false; // DXGI_ERROR_WAS_STILL_DRAWING + Results.Check( hr, "SwapChain.Present(nonblocking)" ); return true; + } /// Resizes after the caller drains the presentation queue with /// and releases all back-buffer references. public void Resize( uint width, uint height ) { diff --git a/src/DXSharp.Framework.WinUI/D3D12Viewport.cs b/src/DXSharp.Framework.WinUI/D3D12Viewport.cs index 051f06d..7ac9965 100644 --- a/src/DXSharp.Framework.WinUI/D3D12Viewport.cs +++ b/src/DXSharp.Framework.WinUI/D3D12Viewport.cs @@ -22,6 +22,7 @@ public sealed class D3D12Viewport : UserControl, IDisposable { private readonly int _thread = Environment.CurrentManagedThreadId; private readonly SwapChainPanel _panel = new( ); private readonly Stopwatch _clock = new( ); + private readonly Action _record; private GraphicsDevice? _device; private WindowRenderOptions? _options; private Action? _draw; @@ -33,11 +34,11 @@ public sealed class D3D12Viewport : UserControl, IDisposable { private TimeSpan _previous; private Vector2 _appliedScale; private nint _ownerWindow; - private bool _started, _subscribed, _drawing, _disposed, _inside, _captured, _suspended; + private bool _started, _subscribed, _drawing, _disposed, _inside, _captured, _suspended, _scheduled; /// Creates a viewport usable as ordinary composed WinUI content. public D3D12Viewport( ) { - Content = _panel; IsTabStop = true; + _record = Record; Content = _panel; IsTabStop = true; Loaded += OnLoaded; Unloaded += OnUnloaded; PointerEntered += ( _, _ ) => _inside = true; PointerExited += ( _, _ ) => _inside = false; @@ -142,12 +143,28 @@ private void CreateRenderer( Size size ) { var scale = CompositionScale; renderer.SetCompositionScale( scale.X, scale.Y ); Marshal.ThrowExceptionForHR( panel.Interface.SetSwapChain( chain.Pointer ) ); _renderer = renderer; _panelNative = panel; _chainNative = chain; _appliedScale = scale; + renderer.SurfaceResized += ReattachSwapChain; } catch { if ( panel is not null ) panel.Interface.SetSwapChain( 0 ); chain?.Dispose( ); panel?.Dispose( ); renderer.Dispose( ); throw; } } + private void ReattachSwapChain( ) => Marshal.ThrowExceptionForHR( _panelNative!.Interface.SetSwapChain( _chainNative!.Pointer ) ); private void OnRendering( object? sender, object args ) { + if ( _scheduled || !_started || _disposed ) return; + _scheduled = true; + // Leave the XAML composition callback before recording or notifying subscribers that may mutate layout. + if ( !DispatcherQueue.TryEnqueue( RenderTurn ) ) _scheduled = false; + } + private void RenderTurn( ) { + try { RenderOnce( ); } + finally { _scheduled = false; } + } + private void Record( RenderFrame frame ) { + // Accumulate time across skipped GPU-busy turns; animation must not slow down when frames are unavailable. + _previous = _clock.Elapsed; _draw!( frame ); + } + private void RenderOnce( ) { if ( !_started || _disposed || _drawing || _stop is { IsCompleted: false } ) return; var now = _clock.Elapsed; if ( _suspended || !IsLoaded || Visibility != Visibility.Visible || @@ -160,9 +177,8 @@ private void OnRendering( object? sender, object args ) { if ( scale != _appliedScale ) { _renderer!.SetCompositionScale( scale.X, scale.Y ); _appliedScale = scale; } bool presented; _drawing = true; - try { presented = _renderer!.Render( size, now - _previous, _draw! ); } + try { presented = _renderer!.RenderAvailable( size, now - _previous, _record ); } finally { _drawing = false; } - _previous = now; if ( presented ) { var statistics = Statistics; FramePresented?.Invoke( statistics ); if ( _options!.FrameLimit > 0 && statistics.Frames >= _options.FrameLimit ) _ = FinishAsync( ); @@ -178,7 +194,7 @@ private async Task FinishAsync( Exception? error = null ) { private async Task RetireAsync( ) { var renderer = _renderer; if ( renderer is null ) return; - _retired = Statistics; _renderer = null; + _retired = Statistics; _renderer = null; renderer.SurfaceResized -= ReattachSwapChain; try { await renderer.BeginDrain( ); } finally { try { if ( _panelNative is not null ) Marshal.ThrowExceptionForHR( _panelNative.Interface.SetSwapChain( 0 ) ); } diff --git a/src/DXSharp.Framework/Hosting/FrameRenderer.cs b/src/DXSharp.Framework/Hosting/FrameRenderer.cs index fe3fd3a..b02123b 100644 --- a/src/DXSharp.Framework/Hosting/FrameRenderer.cs +++ b/src/DXSharp.Framework/Hosting/FrameRenderer.cs @@ -40,7 +40,10 @@ public sealed class FrameRenderer : IDisposable { private DepthTarget? _depth; private Size _size; private bool _rendering, _disposed; - private Task? _drain; + private Task? _drain, _resizeDrain; + private bool _pendingPresent; + /// Raised on the owning thread after back buffers are resized, before recording/presentation. Composition hosts reattach their panel here. + public event Action? SurfaceResized; /// Current presentation totals. public RenderStatistics Statistics { get; private set; } @@ -78,19 +81,33 @@ private FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions o } /// Records and presents one frame. Zero-sized/minimized surfaces are skipped. Nested calls return false. - public bool Render( Size size, TimeSpan elapsed, Action draw ) { + public bool Render( Size size, TimeSpan elapsed, Action draw ) => RenderCore( size, elapsed, draw, false ); + /// Attempts a frame without waiting for GPU fences or DXGI presentation. Resize draining runs on a worker; false means retry on a later UI turn. + /// A submitted frame whose presentation is busy is retained and retried before any new recording. Draw is called only for retired frame slots. + public bool RenderAvailable( Size size, TimeSpan elapsed, Action draw ) => RenderCore( size, elapsed, draw, true ); + private bool RenderCore( Size size, TimeSpan elapsed, Action draw, bool nonblocking ) { CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); ArgumentNullException.ThrowIfNull( draw ); if ( _drain is not null ) throw new InvalidOperationException( "Presentation is draining." ); if ( _rendering || size.Width <= 0 || size.Height <= 0 ) return false; _rendering = true; try { - if ( size != _size ) { - _queue.WaitIdle( ); ReleaseBuffers( ); - _swap.Resize( (uint)size.Width, (uint)size.Height ); _size = size; AcquireBuffers( ); - Statistics = Statistics with { Resizes = Statistics.Resizes + 1 }; + if ( _pendingPresent ) { + if ( !_swap.TryPresent( ) ) return false; + _pendingPresent = false; Statistics = Statistics with { Frames = Statistics.Frames + 1 }; return true; + } + if ( _resizeDrain is not null ) { + if ( !_resizeDrain.IsCompleted ) return false; + _resizeDrain.GetAwaiter( ).GetResult( ); _resizeDrain = null; + Resize( size ); + } else if ( size != _size ) { + if ( nonblocking ) { _resizeDrain = Task.Run( _queue.WaitIdle ); return false; } + _queue.WaitIdle( ); Resize( size ); } int slotIndex = Statistics.Frames % _slots.Length; var slot = _slots[slotIndex]; - if ( slot.Completion != 0 ) _queue.Wait( slot.Completion ); + if ( slot.Completion != 0 ) { + if ( nonblocking ) { if ( !_queue.TryWait( slot.Completion ) ) return false; } + else _queue.Wait( slot.Completion ); + } var commands = slot.Begin( ); uint index = _swap.CurrentBackBufferIndex; var buffer = _buffers[index]!; var target = _targets[index]; commands.Transition( buffer, ResourceState.Present, ResourceState.RenderTarget ); @@ -100,15 +117,30 @@ public bool Render( Size size, TimeSpan elapsed, Action draw ) { draw( new( commands, target, size, elapsed, slotIndex ) ); commands.Transition( buffer, ResourceState.RenderTarget, ResourceState.Present ); commands.Close( ); slot.Completion = _queue.Submit( commands ); - if ( _slots.Length == 1 ) _queue.Wait( slot.Completion ); - _swap.Present( ); Statistics = Statistics with { Frames = Statistics.Frames + 1 }; return true; + if ( nonblocking ) { + _pendingPresent = !_swap.TryPresent( ); + if ( _pendingPresent ) return false; + } else { + if ( _slots.Length == 1 ) _queue.Wait( slot.Completion ); + _swap.Present( ); + } + Statistics = Statistics with { Frames = Statistics.Frames + 1 }; return true; } finally { _rendering = false; } } + private void Resize( Size size ) { + // The drain has completed and retired the command recordings' back-buffer leases. + ReleaseBuffers( ); _swap.Resize( (uint)size.Width, (uint)size.Height ); _size = size; AcquireBuffers( ); + Statistics = Statistics with { Resizes = Statistics.Resizes + 1 }; SurfaceResized?.Invoke( ); + } /// Starts draining on a worker so the UI host can continue dispatching messages until completion. public Task BeginDrain( ) { CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); if ( _rendering ) throw new InvalidOperationException( "Cannot drain during recording or presentation." ); - return _drain ??= Task.Run( _queue.WaitIdle ); + return _drain ??= DrainAsync( ); + } + private async Task DrainAsync( ) { + try { if ( _resizeDrain is not null ) await _resizeDrain.ConfigureAwait( false ); } + finally { await Task.Run( _queue.WaitIdle ).ConfigureAwait( false ); } } private void CheckThread( ) { if ( Environment.CurrentManagedThreadId != _thread ) throw new InvalidOperationException( "The frame renderer is owned by another thread." ); } private void AcquireBuffers( ) { diff --git a/src/DXSharp.Media/DXSharp.Media.csproj b/src/DXSharp.Media/DXSharp.Media.csproj new file mode 100644 index 0000000..e352ed2 --- /dev/null +++ b/src/DXSharp.Media/DXSharp.Media.csproj @@ -0,0 +1,20 @@ + + + $(DXSharpTargetFrameworks) + true + Owned Media Foundation frame-server playback and D3D12 video-texture presentation for DXSharp. + $(WarningsAsErrors);CS1591 + + + + + + + + + false + $(RepoRootPath)artifacts/bin/DXSharp.Tools.Builds/$(Configuration)/netstandard2.0/DXSharp.Tools.Builds.dll + + + + diff --git a/src/DXSharp.Media/MediaPlayer.cs b/src/DXSharp.Media/MediaPlayer.cs new file mode 100644 index 0000000..a5ee9bb --- /dev/null +++ b/src/DXSharp.Media/MediaPlayer.cs @@ -0,0 +1,184 @@ +using System.IO.MemoryMappedFiles; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using DXSharp.Interop; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.Graphics.Imaging; +using Windows.Win32.Media.MediaFoundation; +using Windows.Win32.System.Com; +using Windows.Win32.System.Variant; + +namespace DXSharp.Media; + +/// A borrowed BGRA video frame. Pixels are valid until the next frame transfer, Open or Dispose on this player. +/// Physical width.Physical height.Bytes per row. +/// Borrowed tightly packed BGRA bytes.Media presentation timestamp.Source/seek generation. +public readonly record struct VideoFrame(uint Width, uint Height, uint RowPitch, ReadOnlyMemory Pixels, TimeSpan Timestamp, long Generation); + +/// Playback and transfer telemetry. Presentation offset is video PTS minus the engine's A/V clock, not independently measured speaker latency. +/// Frames copied into caller-visible CPU storage.Engine-reported dropped frames, or null if unavailable. +/// Engine-reported FPS, or null if unavailable.Most recent video PTS minus playback clock. +/// Actual transfer backend.Null when decoder acceleration has not been established. +public readonly record struct PlaybackStatistics(long FramesTransferred, long? FramesDropped, double? FramesPerSecond, TimeSpan PresentationOffset, string TransferPath, bool? HardwareDecoding); + +/// Thread-owned local-file Media Foundation playback. Media Engine owns audio output and A/V scheduling; frames are exposed for application rendering. +/// Create, call and dispose on one COM-capable application thread. Dispose before that thread exits. No UI framework dependency is acquired. +/// This baseline transfers through a writable WIC bitmap into bounded CPU storage; it does not claim direct D3D12 decoding or zero-copy interop. +public sealed class MediaPlayer : IDisposable { + private readonly int _thread = Environment.CurrentManagedThreadId; + private readonly EngineNotify _notify = new(); + private NativeInterface? _engine; + private NativeInterface? _extended; + private NativeInterface? _bitmap; + private MemoryMappedFile? _section; + private MemoryMappedViewAccessor? _view; + private byte[] _pixels = []; + private uint _width, _height; + private long _frames, _generation; + private TimeSpan _offset; + private bool _com, _mf, _disposed, _opened; + private IMFMediaEngine Engine { get { Check(); return _engine!.Interface; } } + + /// Initializes COM/MF and creates an independent frame-server engine. Playback starts only after Open and Play. + public unsafe MediaPlayer() { + try { + int hr = (int)PInvoke.CoInitializeEx(null, COINIT.COINIT_MULTITHREADED); + if (hr < 0 && hr != unchecked((int)0x80010106)) CheckResult(hr); + _com = hr >= 0; + CheckResult((int)PInvoke.MFStartup(0x20070, 0)); _mf = true; + CheckResult(MediaNative.CreateAttributes(out nint attributes, 3)); + using var store = NativeInterface.Adopt(attributes); + Guid callback = PInvoke.MF_MEDIA_ENGINE_CALLBACK, output = PInvoke.MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT; + CheckResult((int)store.Interface.SetUnknown(&callback, _notify)); + CheckResult((int)store.Interface.SetUINT32(&output, 87)); // DXGI_FORMAT_B8G8R8A8_UNORM + CheckResult(MediaNative.CreateInstance(PInvoke.CLSID_MFMediaEngineClassFactory, 0, 1, typeof(IEngineFactoryRaw).GUID, out nint factory)); + using var ownedFactory = NativeInterface.Adopt(factory); + CheckResult(ownedFactory.Interface.CreateInstance(0, store.Pointer, out nint engine)); + _engine = NativeInterface.Adopt(engine); + Guid extended = typeof(IMFMediaEngineEx).GUID; + if (Marshal.QueryInterface(engine, in extended, out nint pointer) >= 0) _extended = NativeInterface.Adopt(pointer); + } catch { Dispose(); throw; } + } + private void Check() { if (Environment.CurrentManagedThreadId != _thread) throw new InvalidOperationException("MediaPlayer belongs to its creating thread."); ObjectDisposedException.ThrowIf(_disposed, this); } + internal static void CheckResult(int result) { if (result < 0) Marshal.ThrowExceptionForHR(result); } + /// Opens an existing local media file. Network URLs and protected playback are outside this API. + public unsafe void Open(string path) { + Check(); string file = Path.GetFullPath(path); if (!File.Exists(file)) throw new FileNotFoundException("Media file not found.", file); + if (_opened) CheckResult((int)Engine.Pause()); _opened = false; _notify.Clear(); ReleaseBitmap(); _frames = 0; _offset = default; ++_generation; + nint text = Marshal.StringToBSTR(new Uri(file).AbsoluteUri); + try { CheckResult((int)Engine.SetSource(new BSTR((char*)text))); CheckResult((int)Engine.Load()); _opened = true; } + finally { Marshal.FreeBSTR(text); } + } + /// Starts/resumes the current source. + public void Play() { RequireSource(); CheckResult((int)Engine.Play()); } + /// Pauses the presentation clock. + public void Pause() { RequireSource(); CheckResult((int)Engine.Pause()); } + /// Seeks within the finite source duration. Frames from the old seek generation are invalidated. + public void Seek(TimeSpan position) { + RequireSource(); double seconds = position.TotalSeconds; + if (seconds < 0 || !double.IsFinite(seconds) || !double.IsFinite(Engine.GetDuration()) || seconds > Engine.GetDuration()) throw new ArgumentOutOfRangeException(nameof(position)); + ++_generation; _offset = default; CheckResult((int)(_extended is null ? Engine.SetCurrentTime(seconds) : _extended.Interface.SetCurrentTimeEx(seconds, MF_MEDIA_ENGINE_SEEK_MODE.MF_MEDIA_ENGINE_SEEK_MODE_NORMAL))); + } + private void RequireSource() { Check(); if (!_opened) throw new InvalidOperationException("Open a media source first."); ThrowIfFailed(); } + /// Monotonically increasing source/seek generation for invalidating borrowed frames. + public long Generation { get { Check(); return _generation; } } + /// Display aspect ratio reported by the source, including pixel aspect ratio. + public unsafe double DisplayAspectRatio { get { uint x = 0, y = 0; CheckResult((int)Engine.GetVideoAspectRatio(&x, &y)); return y == 0 ? 0 : x / (double)y; } } + /// Current media time. + public TimeSpan Position => Time(Engine.GetCurrentTime()); + /// Finite duration, or zero until metadata becomes available. + public TimeSpan Duration => Time(Engine.GetDuration()); + /// Whether metadata and current playback data are available. + public bool IsReady => Engine.GetReadyState() >= 2; + /// Whether playback is paused. + public bool IsPaused => Engine.IsPaused(); + /// Whether a seek is in progress. + public bool IsSeeking => Engine.IsSeeking(); + /// Whether the current non-looping source reached end-of-stream. + public bool IsEnded => Engine.IsEnded(); + /// Whether the source has an audio stream, once metadata is loaded. + public bool HasAudio => Engine.HasAudio(); + /// Whether the source has a video stream. + public bool HasVideo => Engine.HasVideo(); + /// Linear volume in [0,1]. + public double Volume { get => Engine.GetVolume(); set { if (!double.IsFinite(value) || value < 0 || value > 1) throw new ArgumentOutOfRangeException(nameof(value)); CheckResult((int)Engine.SetVolume(value)); } } + /// Audio muting without changing playback time. + public bool Muted { get => Engine.GetMuted(); set => CheckResult((int)Engine.SetMuted(value)); } + /// Native end-of-stream looping. + public bool Loop { get => Engine.GetLoop(); set => CheckResult((int)Engine.SetLoop(value)); } + /// Throws a reported asynchronous media/decoder/output error on the application thread. + public void ThrowIfFailed() { Check(); int error = Volatile.Read(ref _notify.Error); if (error != 0) throw new COMException($"Media Engine reported error {Volatile.Read(ref _notify.ErrorCode)} (HRESULT 0x{error:X8}).", error); } + /// Returns one due frame. Poll on the render thread; S_FALSE, seeking and audio-only sources return false without allocation. + public unsafe bool TryGetFrame(out VideoFrame frame) { + RequireSource(); frame = default; + if (!IsReady || !HasVideo) return false; + uint width = 0, height = 0; CheckResult((int)Engine.GetNativeVideoSize(&width, &height)); + if (width == 0 || height == 0) return false; + if (width != _width || height != _height) CreateBitmap(width, height); + int result = (int)Engine.OnVideoStreamTick(out long ticks); CheckResult(result); if (result != 0) return false; + RECT destination = new(0, 0, checked((int)width), checked((int)height)); MFARGB border = new() { rgbAlpha = 255 }; + CheckResult((int)Engine.TransferVideoFrame(_bitmap!.Interface, null, &destination, &border)); + // Continue ticking/transferring while seeking so the native frame-server can complete its presentation transition. + // Suppress publication of the old seek generation until the engine reports completion. + if (IsSeeking) return false; + _view!.ReadArray(0, _pixels, 0, _pixels.Length); + var time = TimeSpan.FromTicks(ticks); _offset = time - Position; ++_frames; + frame = new(width, height, width * 4, _pixels, time, _generation); return true; + } + private void CreateBitmap(uint width, uint height) { + if (width > 8192 || height > 8192) throw new NotSupportedException("The CPU-transfer backend accepts video up to 8192 pixels per dimension."); + int bytes = checked((int)((ulong)width * height * 4)); + ReleaseBitmap(); + try { + _section = MemoryMappedFile.CreateNew(null, bytes, MemoryMappedFileAccess.ReadWrite); + _view = _section.CreateViewAccessor(0, bytes, MemoryMappedFileAccess.ReadWrite); + CheckResult(MediaNative.CreateBitmap(width, height, PInvoke.GUID_WICPixelFormat32bppBGRA, _section.SafeMemoryMappedFileHandle.DangerousGetHandle(), width * 4, 0, 3, out nint bitmap)); + _bitmap = NativeInterface.Adopt(bitmap); _pixels = new byte[bytes]; _width = width; _height = height; + } catch { ReleaseBitmap(); throw; } + } + /// Snapshot of timing, dropped-frame and transfer-path diagnostics. Decoder acceleration is explicitly unmeasured. + public PlaybackStatistics Statistics { get { Check(); return new(_frames, Statistic(MF_MEDIA_ENGINE_STATISTIC.MF_MEDIA_ENGINE_STATISTIC_FRAMES_DROPPED) is { } drops ? (long)drops : null, + Statistic(MF_MEDIA_ENGINE_STATISTIC.MF_MEDIA_ENGINE_STATISTIC_FRAMES_PER_SECOND), _offset, "Media Foundation → WIC BGRA → CPU staging → D3D12 upload", null); } } + private double? Statistic(MF_MEDIA_ENGINE_STATISTIC statistic) { + if (_extended is null || (int)_extended.Interface.GetStatistics(statistic, out var value) < 0) return null; + try { return value.vt switch { VARENUM.VT_UI4 => value.ulVal, VARENUM.VT_UI8 => value.uhVal, VARENUM.VT_R8 => value.dblVal, VARENUM.VT_R4 => value.fltVal, _ => null }; } + finally { PInvoke.PropVariantClear(ref value); } + } + private static TimeSpan Time(double seconds) => double.IsFinite(seconds) && seconds >= 0 && seconds <= TimeSpan.MaxValue.TotalSeconds ? TimeSpan.FromSeconds(seconds) : TimeSpan.Zero; + private void ReleaseBitmap() { _bitmap?.Dispose(); _bitmap = null; _view?.Dispose(); _view = null; _section?.Dispose(); _section = null; _pixels = []; _width = _height = 0; } + /// Shuts down the engine before releasing callback, frame mapping and MF/COM initialization. Idempotent on the creating thread. + public void Dispose() { + if (_disposed) return; Check(); _disposed = true; + try { if (_engine is not null) CheckResult((int)_engine.Interface.Shutdown()); } + finally { + _extended?.Dispose(); _extended = null; _engine?.Dispose(); _engine = null; _notify.Close(); ReleaseBitmap(); + try { if (_mf) CheckResult((int)PInvoke.MFShutdown()); } + finally { _mf = false; if (_com) PInvoke.CoUninitialize(); _com = false; } + } + } +} + +[GeneratedComInterface(Options = ComInterfaceOptions.ComObjectWrapper)] +[Guid("4D645ACE-26AA-4688-9BE1-DF3516990B93")] +internal partial interface IEngineFactoryRaw { + [PreserveSig] int CreateInstance(uint flags, nint attributes, out nint engine); + [PreserveSig] int CreateTimeRange(out nint range); + [PreserveSig] int CreateError(out nint error); +} + +[GeneratedComClass] +internal sealed partial class EngineNotify : IMFMediaEngineNotify { + internal int Error, ErrorCode; + private int _closed; + internal void Clear() { Volatile.Write(ref Error, 0); Volatile.Write(ref ErrorCode, 0); } + internal void Close() => Volatile.Write(ref _closed, 1); + public HRESULT EventNotify(uint @event, nuint param1, uint param2) { + if (@event == (uint)MF_MEDIA_ENGINE_EVENT.MF_MEDIA_ENGINE_EVENT_NOTIFYSTABLESTATE) { PInvoke.SetEvent(new HANDLE((nint)param1)); return new(0); } + if (Volatile.Read(ref _closed) != 0) return new(0); + if (@event is (uint)MF_MEDIA_ENGINE_EVENT.MF_MEDIA_ENGINE_EVENT_ERROR or (uint)MF_MEDIA_ENGINE_EVENT.MF_MEDIA_ENGINE_EVENT_STREAMRENDERINGERROR) { + Volatile.Write(ref ErrorCode, unchecked((int)param1)); Volatile.Write(ref Error, unchecked((int)param2) < 0 ? unchecked((int)param2) : unchecked((int)0x80004005)); + } + return new(0); + } +} diff --git a/src/DXSharp.Media/Video.hlsl b/src/DXSharp.Media/Video.hlsl new file mode 100644 index 0000000..467951a --- /dev/null +++ b/src/DXSharp.Media/Video.hlsl @@ -0,0 +1,9 @@ +cbuffer Fit : register(b0) { float2 Scale; }; +Texture2D Video : register(t0); +SamplerState LinearClamp : register(s0); +struct Vertex { float4 Position : SV_Position; float2 UV : TEXCOORD; }; +Vertex VS(uint id : SV_VertexID) { + const float2 points[6] = { float2(-1,1),float2(1,1),float2(-1,-1),float2(-1,-1),float2(1,1),float2(1,-1) }; + Vertex result; float2 p = points[id]; result.Position = float4(p * Scale,0,1); result.UV = float2(p.x*.5+.5,.5-p.y*.5); return result; +} +float4 PS(Vertex input) : SV_Target { return float4(Video.Sample(LinearClamp,input.UV).rgb,1); } diff --git a/src/DXSharp.Media/VideoTextureRenderer.cs b/src/DXSharp.Media/VideoTextureRenderer.cs new file mode 100644 index 0000000..161e6a5 --- /dev/null +++ b/src/DXSharp.Media/VideoTextureRenderer.cs @@ -0,0 +1,77 @@ +using System.Numerics; +using DXSharp.Framework.Hosting; +using DXSharp.Graphics; +using DXSharp.Shaders; +using Windows.Win32.Graphics.Dxgi.Common; + +namespace DXSharp.Media; + +/// Aspect-correct D3D12 presentation of a MediaPlayer's BGRA frames using persistent frame-slot textures and fence-retired uploads. +/// Call Draw only with a retired frame slot supplied by FrameRenderer. The device, player and renderer share the application thread. +/// Dispose after stopping the host. Precompiled shaders are embedded; runtime DXC is unnecessary. +public sealed class VideoTextureRenderer : IDisposable { + private readonly GraphicsDevice _device; + private readonly MediaPlayer _player; + private readonly DescriptorPool _descriptors; + private readonly Texture2D?[] _textures; + private readonly long[] _versions; + private readonly RootSignature _root; + private readonly PipelineState _pipeline; + private readonly TextureSubresourceData[] _data = new TextureSubresourceData[1]; + private UploadRing? _uploads; + private ulong _capacity; + private VideoFrame _latest; + private long _version, _generation; + private bool _disposed; + /// Constructs the renderer for the host's one to three frame slots. + public VideoTextureRenderer(GraphicsDevice device, MediaPlayer player, int frameSlots = 2) { + ArgumentNullException.ThrowIfNull(device); ArgumentNullException.ThrowIfNull(player); + if (frameSlots is < 1 or > 3) throw new ArgumentOutOfRangeException(nameof(frameSlots)); + _device = device; _player = player; _textures = new Texture2D[frameSlots]; _versions = new long[frameSlots]; + _descriptors = device.CreateDescriptorPool((uint)frameSlots * 2); + _root = device.CreateTextureRootSignature(2, linearFiltering: true, wrap: false); + try { _pipeline = device.CreateGraphicsPipeline(_root, Shader("VS"), Shader("PS")); } + catch { _root.Dispose(); _descriptors.Dispose(); throw; } + } + private static ShaderBytecode Shader(string entry) { + using var input = typeof(VideoTextureRenderer).Assembly.GetManifestResourceStream($"DXSharp.Media.Video.{entry}.dxil") ?? throw new InvalidOperationException("Missing precompiled media shader."); + using var output = new MemoryStream(); input.CopyTo(output); return ShaderBytecode.CopyFrom(output.ToArray()); + } + /// Number of due frames obtained from the player. + public long FramesTransferred => _version; + /// Most recently obtained frame; pixels remain borrowed from the player. + public VideoFrame LatestFrame => _latest; + /// Transfers at most one due frame, updates the retired slot if needed, and draws a letterboxed quad. + public void Draw(RenderFrame frame) { + ObjectDisposedException.ThrowIf(_disposed, this); + if ((uint)frame.FrameSlotIndex >= _textures.Length) throw new ArgumentOutOfRangeException(nameof(frame)); + if (_generation != _player.Generation) { _latest = default; _generation = _player.Generation; } + if (_player.TryGetFrame(out var video)) { _latest = video; ++_version; } + if (_latest.Pixels.IsEmpty) return; + int slot = frame.FrameSlotIndex; + var texture = _textures[slot]; bool fresh = texture is null || texture.Description.Width != _latest.Width || texture.Description.Height != _latest.Height; + if (fresh) { + texture?.Dispose(); _textures[slot] = texture = _device.CreateTexture2D(new(_latest.Width, _latest.Height, DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM), _descriptors); + } + if (fresh || _versions[slot] != _version) { + ulong size = checked((((ulong)_latest.Width * 4 + 255) & ~255UL) * _latest.Height + 512); + ulong capacity = size * (ulong)_textures.Length; + if (_uploads is null || capacity > _capacity) { _uploads?.Dispose(); _uploads = _device.CreateUploadRing(capacity); _capacity = capacity; } + if (!fresh) frame.Commands.Transition(texture!, ResourceState.PixelShaderResource, ResourceState.CopyDestination); + _data[0] = new(_latest.Pixels, _latest.RowPitch); frame.Commands.UploadTexture(texture!, _uploads, _data); + frame.Commands.Transition(texture!, ResourceState.CopyDestination, ResourceState.PixelShaderResource); _versions[slot] = _version; + } + float videoAspect = (float)_player.DisplayAspectRatio; + if (!(videoAspect > 0)) videoAspect = _latest.Width / (float)_latest.Height; + float targetAspect = frame.Size.Width / (float)Math.Max(1, frame.Size.Height); + float x = Math.Min(1, videoAspect / targetAspect), y = Math.Min(1, targetAspect / videoAspect); + frame.Commands.SetGraphicsPipeline(_pipeline); frame.Commands.SetGraphicsConstants([BitConverter.SingleToUInt32Bits(x), BitConverter.SingleToUInt32Bits(y)]); + frame.Commands.SetGraphicsTexture(texture!, 1); frame.Commands.Draw(6); + } + /// Releases the renderer owners after host shutdown. Recorded native resources retain their submission leases. + public void Dispose() { + if (_disposed) return; _disposed = true; + foreach (var texture in _textures) texture?.Dispose(); + _uploads?.Dispose(); _pipeline.Dispose(); _root.Dispose(); _descriptors.Dispose(); + } +} diff --git a/src/DXSharp.Media/packages.lock.json b/src/DXSharp.Media/packages.lock.json new file mode 100644 index 0000000..2e2d102 --- /dev/null +++ b/src/DXSharp.Media/packages.lock.json @@ -0,0 +1,107 @@ +{ + "version": 2, + "dependencies": { + "net10.0-windows10.0.26100": { + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net11.0-windows10.0.26100": { + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + } + } +} \ No newline at end of file diff --git a/src/DXSharp.Native/MediaNative.cs b/src/DXSharp.Native/MediaNative.cs new file mode 100644 index 0000000..8f839f7 --- /dev/null +++ b/src/DXSharp.Native/MediaNative.cs @@ -0,0 +1,17 @@ +using System.Runtime.InteropServices; + +namespace DXSharp.Interop; + +/// Raw owned-output entry points for deterministic Media Foundation and WIC interface leases. +/// Successful outputs each transfer one native COM reference to the caller. Adopt with NativeInterface in Core. +public static partial class MediaNative { + /// Creates an attribute store and transfers one native IMFAttributes reference. + [LibraryImport("mfplat.dll", EntryPoint = "MFCreateAttributes")] + public static partial int CreateAttributes(out nint attributes, uint capacity); + /// Creates a writable section-backed IWICBitmap and transfers one reference. Keep the section alive through bitmap disposal. + [LibraryImport("windowscodecs.dll", EntryPoint = "WICCreateBitmapFromSectionEx")] + public static partial int CreateBitmap(uint width, uint height, in Guid format, nint section, uint stride, uint offset, uint access, out nint bitmap); + /// Activates an in-process COM class and transfers one reference of the requested interface. + [LibraryImport("ole32.dll", EntryPoint = "CoCreateInstance")] + public static partial int CreateInstance(in Guid classId, nint outer, uint context, in Guid interfaceId, out nint instance); +} diff --git a/src/DXSharp.Native/NativeMethods.txt b/src/DXSharp.Native/NativeMethods.txt index 2cc4fbc..774d61f 100644 --- a/src/DXSharp.Native/NativeMethods.txt +++ b/src/DXSharp.Native/NativeMethods.txt @@ -22,6 +22,7 @@ Windows.Win32.Graphics.Dxgi Windows.Win32.Graphics.Dxgi.Common Windows.Win32.Graphics.Imaging Windows.Win32.Graphics.Imaging.D2D +Windows.Win32.Media.MediaFoundation Windows.Win32.Media.Audio Windows.Win32.Media.Audio.Apo Windows.Win32.Media.Audio.DirectMusic @@ -41,3 +42,7 @@ GetCursorPos Windows.Win32.UI.WindowsAndMessaging Windows.Win32.UI.HiDpi Windows.Win32.UI.Input.KeyboardAndMouse +CoInitializeEx +CoUninitialize +PropVariantClear +SetEvent diff --git a/tests/InteropQualification/GpuAllocationQualification.cs b/tests/InteropQualification/GpuAllocationQualification.cs index ef950ad..a4f25b2 100644 --- a/tests/InteropQualification/GpuAllocationQualification.cs +++ b/tests/InteropQualification/GpuAllocationQualification.cs @@ -49,6 +49,8 @@ internal static void Run( GraphicsDevice device ) { Results.Check( queueB.Native.Interface.Wait( gate.Interface, 2 ), "QueueB.Wait(allocation gate)" ); try { ulong a = queueA.Submit( commandsA ), b = queueB.Submit( commandsB ); + Check( !queueA.TryWait( a ) && !queueB.TryWait( b ), "nonblocking polls retain GPU-gated submissions" ); + Invalid( ( ) => queueA.TryWait( ulong.MaxValue ) ); slice.Dispose( ); range.Dispose( ); Check( ring.AvailableBytes == 0 && descriptors.AvailableCount == 0, "early owner disposal preserves submitted ranges" ); Invalid( ( ) => slice.Write( [0] ) ); @@ -56,6 +58,7 @@ internal static void Run( GraphicsDevice device ) { Check( !ring.TryAllocate( 256, out _ ), "timed-out waits retain slices" ); Results.Check( gate.Interface.Signal( 1 ), "Signal(first allocation gate)" ); queueA.Wait( a ); + Check( queueA.TryWait( a ), "nonblocking poll observes the completed submission" ); Check( ring.AvailableBytes == 0 && descriptors.AvailableCount == 0, "first queue retirement cannot reclaim second queue's use" ); Results.Check( gate.Interface.Signal( 2 ), "Signal(second allocation gate)" ); queueB.Wait( b ); diff --git a/tools/ApiCoverage/Program.cs b/tools/ApiCoverage/Program.cs index e2ddff0..4ba784c 100644 --- a/tools/ApiCoverage/Program.cs +++ b/tools/ApiCoverage/Program.cs @@ -53,6 +53,7 @@ "Windows.Win32.Graphics.DirectWrite", "Windows.Win32.Graphics.Imaging", "Windows.Win32.Media.Audio", + "Windows.Win32.Media.MediaFoundation", "Windows.Win32.UI.Input", "Windows.Win32.Devices.HumanInterfaceDevice", "Windows.Win32.UI.Animation",