From e59cf4450a82369365c18496d4c4c352a3cc9fb0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 27 May 2026 16:36:19 +0100 Subject: [PATCH] Decode compressed camera frames on GPU --- config/mimir-runtime.ks-camera.example.json | 15 + docs/implementation-plan.md | 9 + native/camera_capture/CMakeLists.txt | 14 + .../camera_capture/mimir_mf_gpu_capture.cpp | 524 ++++++++++++++++++ notes/current-system-map.md | 8 + notes/fresh-workspace-handoff.md | 10 +- src/Mimir.BufferSmoke/Program.cs | 66 +++ ...mirMediaFoundationGpuVideoCaptureDriver.cs | 183 ++++++ .../MimirRuntimeConfiguration.cs | 26 + state/evidence.jsonl | 1 + state/map.yaml | 10 +- 11 files changed, 863 insertions(+), 3 deletions(-) create mode 100644 native/camera_capture/mimir_mf_gpu_capture.cpp create mode 100644 src/Mimir.Runtime/Synchronization/MimirMediaFoundationGpuVideoCaptureDriver.cs diff --git a/config/mimir-runtime.ks-camera.example.json b/config/mimir-runtime.ks-camera.example.json index b7ce5f3..6e0f8f1 100644 --- a/config/mimir-runtime.ks-camera.example.json +++ b/config/mimir-runtime.ks-camera.example.json @@ -57,6 +57,21 @@ "minimumFramesPerSecond": 25.0, "queueDepth": 8 }, + { + "sourceId": "kiyo-pro-mf-gpu", + "displayName": "Kiyo Pro MF GPU decode", + "kind": "Video", + "origin": "LocalDevice", + "enabled": false, + "adapter": "mf-gpu", + "command": "../native/camera_capture/build/Release/mimir_mf_gpu_capture.dll", + "pathNeedle": "vid_1532&pid_0e05", + "width": 1920, + "height": 1080, + "inputFormat": "MJPG", + "outputFormat": "RGB32", + "minimumFramesPerSecond": 25.0 + }, { "sourceId": "kiyo-yuy2", "displayName": "Kiyo YUY2", diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 9e8c163..76ed5c8 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -215,6 +215,15 @@ a named invariant that the native runtime cannot protect yet. Current direct-driver smokes prove real-frame upload for LeapUVC 640x240 YUY2, both PS3 Eyes at 320x240 Bayer8, Kiyo Pro 1920x1080 YUY2, and regular Kiyo 640x480 YUY2. Regular Kiyo 1280x720 YUY2 did not open. + `MimirMediaFoundationGpuVideoCaptureDriver` is the first compressed camera + path: `native/camera_capture/mimir_mf_gpu_capture.dll` uses Media Foundation + SourceReader with a D3D11 device manager, selects MJPG/H264 camera modes, + decodes on the GPU, copies the decoded GPU surface into a shared BGRA D3D11 + texture, and publishes only a `shared-d3d11-texture` handle. Live payload + bytes stay empty. Kiyo Pro 1920x1080 MJPG->RGB32 and H264->RGB32 smokes both + produced GPU handles and valid Fensalir camera resources. NV12 sharing was + rejected by D3D11 in this path, so planar NV12 remains future plane-aware + interop or GPU bridge-copy work. Fensalir can still resolve imported shared `Texture2D` resources by native D3D12 handle and accepts Mimir video format names. `Mimir.BufferSmoke --fensalir-camera-observation-smoke` verifies the split, diff --git a/native/camera_capture/CMakeLists.txt b/native/camera_capture/CMakeLists.txt index 35fb87a..bbb87f3 100644 --- a/native/camera_capture/CMakeLists.txt +++ b/native/camera_capture/CMakeLists.txt @@ -54,3 +54,17 @@ target_compile_definitions(mimir_ps3eye_capture PRIVATE NOMINMAX) target_include_directories(mimir_ps3eye_capture PRIVATE ${PS3EYE_ROOT}/src) target_link_libraries(mimir_ps3eye_capture PRIVATE mimir_ps3eye_vendor) + +add_library(mimir_mf_gpu_capture SHARED + mimir_mf_gpu_capture.cpp) +target_compile_features(mimir_mf_gpu_capture PRIVATE cxx_std_20) +target_compile_definitions(mimir_mf_gpu_capture PRIVATE + WIN32_LEAN_AND_MEAN + NOMINMAX) +target_link_libraries(mimir_mf_gpu_capture PRIVATE + d3d11 + dxgi + mf + mfplat + mfreadwrite + mfuuid) diff --git a/native/camera_capture/mimir_mf_gpu_capture.cpp b/native/camera_capture/mimir_mf_gpu_capture.cpp new file mode 100644 index 0000000..b5002c1 --- /dev/null +++ b/native/camera_capture/mimir_mf_gpu_capture.cpp @@ -0,0 +1,524 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace +{ +struct MimirMfGpuCapture +{ + ComPtr source; + ComPtr reader; + ComPtr device; + ComPtr context; + ComPtr deviceManager; + ComPtr sharedTexture; + HANDLE sharedHandle = nullptr; + int width = 0; + int height = 0; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + std::uint64_t sequence = 0; +}; + +bool debugEnabled() +{ + return GetEnvironmentVariableA("MIMIR_MF_GPU_DEBUG", nullptr, 0) > 0; +} + +void debugLog(const char* format, ...) +{ + if (!debugEnabled()) + { + return; + } + + std::fprintf(stderr, "mimir-mf-gpu: "); + va_list args; + va_start(args, format); + std::vfprintf(stderr, format, args); + va_end(args); + std::fprintf(stderr, "\n"); +} + +std::wstring widen(const char* value) +{ + if (!value) + { + return {}; + } + + const int chars = MultiByteToWideChar(CP_UTF8, 0, value, -1, nullptr, 0); + if (chars <= 1) + { + return {}; + } + + std::wstring result(static_cast(chars - 1), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, value, -1, result.data(), chars); + return result; +} + +std::wstring lowercase(std::wstring value) +{ + std::transform(value.begin(), value.end(), value.begin(), [](wchar_t c) { + return static_cast(towlower(c)); + }); + return value; +} + +GUID subtypeFromText(const char* text) +{ + const std::string value = text ? text : ""; + std::string upper; + upper.resize(value.size()); + std::transform(value.begin(), value.end(), upper.begin(), [](unsigned char c) { + return static_cast(std::toupper(c)); + }); + + if (upper == "MJPG") return MFVideoFormat_MJPG; + if (upper == "H264") return MFVideoFormat_H264; + if (upper == "NV12") return MFVideoFormat_NV12; + if (upper == "YUY2") return MFVideoFormat_YUY2; + if (upper == "RGB32" || upper == "BGRA") return MFVideoFormat_RGB32; + return GUID_NULL; +} + +DXGI_FORMAT dxgiFormatForSubtype(const GUID& subtype) +{ + if (subtype == MFVideoFormat_NV12) return DXGI_FORMAT_NV12; + if (subtype == MFVideoFormat_RGB32) return DXGI_FORMAT_B8G8R8A8_UNORM; + if (subtype == MFVideoFormat_YUY2) return DXGI_FORMAT_YUY2; + return DXGI_FORMAT_UNKNOWN; +} + +const char* textForSubtype(const GUID& subtype) +{ + if (subtype == MFVideoFormat_NV12) return "NV12"; + if (subtype == MFVideoFormat_RGB32) return "Bgra8"; + if (subtype == MFVideoFormat_YUY2) return "YUY2"; + return "Unknown"; +} + +bool findVideoSource(const wchar_t* needle, IMFMediaSource** mediaSource) +{ + *mediaSource = nullptr; + ComPtr attributes; + if (FAILED(MFCreateAttributes(&attributes, 2))) + { + debugLog("MFCreateAttributes for devices failed"); + return false; + } + + attributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID); + IMFActivate** rawDevices = nullptr; + UINT32 count = 0; + if (FAILED(MFEnumDeviceSources(attributes.Get(), &rawDevices, &count))) + { + debugLog("MFEnumDeviceSources failed"); + return false; + } + + debugLog("device sources=%u", count); + + const std::wstring target = lowercase(needle ? needle : L""); + bool found = false; + for (UINT32 index = 0; index < count; ++index) + { + ComPtr activate(rawDevices[index]); + rawDevices[index] = nullptr; + WCHAR* symbolicLink = nullptr; + UINT32 symbolicLength = 0; + activate->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &symbolicLink, &symbolicLength); + const std::wstring link = lowercase(symbolicLink ? symbolicLink : L""); + if (debugEnabled()) + { + std::fwprintf(stderr, L"mimir-mf-gpu: source[%u]=%ls\n", index, link.c_str()); + } + CoTaskMemFree(symbolicLink); + if (!target.empty() && link.find(target) == std::wstring::npos) + { + continue; + } + + if (SUCCEEDED(activate->ActivateObject(IID_PPV_ARGS(mediaSource)))) + { + debugLog("activated source index=%u", index); + found = true; + break; + } + } + + for (UINT32 index = 0; index < count; ++index) + { + if (rawDevices[index]) + { + rawDevices[index]->Release(); + } + } + CoTaskMemFree(rawDevices); + return found; +} + +bool mediaTypeMatches(IMFMediaType* type, int width, int height, const GUID& subtype, double minFps) +{ + GUID actualSubtype{}; + UINT32 actualWidth = 0; + UINT32 actualHeight = 0; + UINT32 fpsNumerator = 0; + UINT32 fpsDenominator = 0; + if (FAILED(type->GetGUID(MF_MT_SUBTYPE, &actualSubtype)) || + actualSubtype != subtype || + FAILED(MFGetAttributeSize(type, MF_MT_FRAME_SIZE, &actualWidth, &actualHeight)) || + static_cast(actualWidth) != width || + static_cast(actualHeight) != height) + { + return false; + } + + if (SUCCEEDED(MFGetAttributeRatio(type, MF_MT_FRAME_RATE, &fpsNumerator, &fpsDenominator)) && + fpsDenominator != 0) + { + return static_cast(fpsNumerator) / fpsDenominator >= minFps; + } + + return minFps <= 0.0; +} + +bool setInputType(IMFSourceReader* reader, int width, int height, const GUID& subtype, double minFps) +{ + for (DWORD index = 0;; ++index) + { + ComPtr type; + const HRESULT hr = reader->GetNativeMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, index, &type); + if (hr == MF_E_NO_MORE_TYPES) + { + debugLog("no input type matched %dx%d minFps=%.3f", width, height, minFps); + return false; + } + + if (FAILED(hr)) + { + debugLog("GetNativeMediaType failed index=%lu hr=0x%08lx", index, static_cast(hr)); + return false; + } + + if (debugEnabled()) + { + GUID actualSubtype{}; + UINT32 actualWidth = 0; + UINT32 actualHeight = 0; + UINT32 fpsNumerator = 0; + UINT32 fpsDenominator = 0; + type->GetGUID(MF_MT_SUBTYPE, &actualSubtype); + MFGetAttributeSize(type.Get(), MF_MT_FRAME_SIZE, &actualWidth, &actualHeight); + MFGetAttributeRatio(type.Get(), MF_MT_FRAME_RATE, &fpsNumerator, &fpsDenominator); + debugLog( + "nativeType[%lu] %ux%u subtype=%08lx fps=%u/%u", + index, + actualWidth, + actualHeight, + static_cast(actualSubtype.Data1), + fpsNumerator, + fpsDenominator); + } + + if (mediaTypeMatches(type.Get(), width, height, subtype, minFps)) + { + const HRESULT setHr = reader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, nullptr, type.Get()); + debugLog("SetCurrentMediaType input index=%lu hr=0x%08lx", index, static_cast(setHr)); + return SUCCEEDED(setHr); + } + } +} + +bool setOutputType(IMFSourceReader* reader, const GUID& subtype) +{ + ComPtr output; + if (FAILED(MFCreateMediaType(&output))) + { + return false; + } + + output->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); + output->SetGUID(MF_MT_SUBTYPE, subtype); + const HRESULT hr = reader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, nullptr, output.Get()); + debugLog("SetCurrentMediaType output hr=0x%08lx", static_cast(hr)); + return SUCCEEDED(hr); +} + +bool createSharedTexture(MimirMfGpuCapture& capture, const GUID& outputSubtype) +{ + ComPtr current; + if (FAILED(capture.reader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, ¤t))) + { + debugLog("GetCurrentMediaType output failed"); + return false; + } + + UINT32 width = 0; + UINT32 height = 0; + GUID subtype{}; + if (FAILED(MFGetAttributeSize(current.Get(), MF_MT_FRAME_SIZE, &width, &height)) || + FAILED(current->GetGUID(MF_MT_SUBTYPE, &subtype))) + { + return false; + } + + const auto format = dxgiFormatForSubtype(subtype); + if (format == DXGI_FORMAT_UNKNOWN || subtype != outputSubtype) + { + debugLog("output texture subtype/format unsupported subtype=%08lx", static_cast(subtype.Data1)); + return false; + } + + D3D11_TEXTURE2D_DESC desc{}; + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; + + const HRESULT textureHr = capture.device->CreateTexture2D(&desc, nullptr, &capture.sharedTexture); + if (FAILED(textureHr)) + { + debugLog("CreateTexture2D shared NT failed hr=0x%08lx; retrying legacy shared", static_cast(textureHr)); + desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; + const HRESULT legacyTextureHr = capture.device->CreateTexture2D(&desc, nullptr, &capture.sharedTexture); + if (FAILED(legacyTextureHr)) + { + debugLog("CreateTexture2D legacy shared failed hr=0x%08lx", static_cast(legacyTextureHr)); + return false; + } + } + + ComPtr dxgiResource; + const HRESULT asHr = capture.sharedTexture.As(&dxgiResource); + const HRESULT handleHr = SUCCEEDED(asHr) + ? dxgiResource->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &capture.sharedHandle) + : asHr; + if (FAILED(asHr) || FAILED(handleHr)) + { + ComPtr legacyResource; + const HRESULT legacyAsHr = capture.sharedTexture.As(&legacyResource); + const HRESULT legacyHandleHr = SUCCEEDED(legacyAsHr) + ? legacyResource->GetSharedHandle(&capture.sharedHandle) + : legacyAsHr; + if (FAILED(legacyAsHr) || FAILED(legacyHandleHr)) + { + debugLog( + "CreateSharedHandle failed as=0x%08lx handle=0x%08lx legacyAs=0x%08lx legacyHandle=0x%08lx", + static_cast(asHr), + static_cast(handleHr), + static_cast(legacyAsHr), + static_cast(legacyHandleHr)); + return false; + } + } + + capture.width = static_cast(width); + capture.height = static_cast(height); + capture.format = format; + return true; +} + +} // namespace + +extern "C" +{ +__declspec(dllexport) MimirMfGpuCapture* mimir_mf_gpu_create( + const char* pathNeedle, + int width, + int height, + const char* inputSubtypeText, + const char* outputSubtypeText, + double minFps) +{ + CoInitializeEx(nullptr, COINIT_MULTITHREADED); + if (FAILED(MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET))) + { + debugLog("MFStartup failed"); + return nullptr; + } + + auto capture = new MimirMfGpuCapture(); + const UINT deviceFlags = D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT; + D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; + D3D_FEATURE_LEVEL featureLevel{}; + const HRESULT deviceHr = D3D11CreateDevice( + nullptr, + D3D_DRIVER_TYPE_HARDWARE, + nullptr, + deviceFlags, + featureLevels, + ARRAYSIZE(featureLevels), + D3D11_SDK_VERSION, + &capture->device, + &featureLevel, + &capture->context); + if (FAILED(deviceHr)) + { + debugLog("D3D11CreateDevice failed hr=0x%08lx", static_cast(deviceHr)); + delete capture; + return nullptr; + } + + ComPtr multithread; + if (SUCCEEDED(capture->device.As(&multithread))) + { + multithread->SetMultithreadProtected(TRUE); + } + + UINT resetToken = 0; + if (FAILED(MFCreateDXGIDeviceManager(&resetToken, &capture->deviceManager)) || + FAILED(capture->deviceManager->ResetDevice(capture->device.Get(), resetToken))) + { + debugLog("DXGI device manager setup failed"); + delete capture; + return nullptr; + } + + const auto needle = widen(pathNeedle); + if (!findVideoSource(needle.c_str(), &capture->source)) + { + debugLog("no source matched needle"); + delete capture; + return nullptr; + } + + ComPtr readerAttributes; + if (FAILED(MFCreateAttributes(&readerAttributes, 4))) + { + debugLog("MFCreateAttributes reader failed"); + delete capture; + return nullptr; + } + + readerAttributes->SetUnknown(MF_SOURCE_READER_D3D_MANAGER, capture->deviceManager.Get()); + readerAttributes->SetUINT32(MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, TRUE); + readerAttributes->SetUINT32(MF_LOW_LATENCY, TRUE); + readerAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, TRUE); + + const HRESULT readerHr = MFCreateSourceReaderFromMediaSource(capture->source.Get(), readerAttributes.Get(), &capture->reader); + if (FAILED(readerHr)) + { + debugLog("MFCreateSourceReaderFromMediaSource failed hr=0x%08lx", static_cast(readerHr)); + delete capture; + return nullptr; + } + + const auto inputSubtype = subtypeFromText(inputSubtypeText); + const auto outputSubtype = subtypeFromText(outputSubtypeText && outputSubtypeText[0] ? outputSubtypeText : "NV12"); + if (inputSubtype == GUID_NULL || + outputSubtype == GUID_NULL || + !setInputType(capture->reader.Get(), width, height, inputSubtype, minFps) || + !setOutputType(capture->reader.Get(), outputSubtype) || + !createSharedTexture(*capture, outputSubtype)) + { + debugLog("create failed input=%s output=%s", inputSubtypeText ? inputSubtypeText : "", outputSubtypeText ? outputSubtypeText : ""); + delete capture; + return nullptr; + } + + return capture; +} + +__declspec(dllexport) int mimir_mf_gpu_read( + MimirMfGpuCapture* capture, + HANDLE* sharedHandle, + int* width, + int* height, + char* format, + int formatCapacity, + std::int64_t* timestampNs, + std::uint64_t* sequence) +{ + if (!capture || !capture->reader || !capture->sharedTexture || !sharedHandle) + { + return 0; + } + + DWORD streamIndex = 0; + DWORD flags = 0; + LONGLONG timestamp = 0; + ComPtr sample; + const HRESULT hr = capture->reader->ReadSample( + MF_SOURCE_READER_FIRST_VIDEO_STREAM, + 0, + &streamIndex, + &flags, + ×tamp, + &sample); + if (FAILED(hr) || !sample || (flags & MF_SOURCE_READERF_STREAMTICK) != 0) + { + return 0; + } + + ComPtr buffer; + ComPtr dxgiBuffer; + ComPtr decodedTexture; + UINT subresource = 0; + if (FAILED(sample->GetBufferByIndex(0, &buffer)) || + FAILED(buffer.As(&dxgiBuffer)) || + FAILED(dxgiBuffer->GetResource(IID_PPV_ARGS(&decodedTexture))) || + FAILED(dxgiBuffer->GetSubresourceIndex(&subresource))) + { + return 0; + } + + capture->context->CopySubresourceRegion(capture->sharedTexture.Get(), 0, 0, 0, 0, decodedTexture.Get(), subresource, nullptr); + capture->context->Flush(); + *sharedHandle = capture->sharedHandle; + if (width) *width = capture->width; + if (height) *height = capture->height; + if (format && formatCapacity > 0) + { + const char* text = capture->format == DXGI_FORMAT_NV12 + ? textForSubtype(MFVideoFormat_NV12) + : capture->format == DXGI_FORMAT_B8G8R8A8_UNORM + ? textForSubtype(MFVideoFormat_RGB32) + : textForSubtype(MFVideoFormat_YUY2); + std::snprintf(format, static_cast(formatCapacity), "%s", text); + } + if (timestampNs) *timestampNs = timestamp * 100; + if (sequence) *sequence = ++capture->sequence; + return 1; +} + +__declspec(dllexport) void mimir_mf_gpu_destroy(MimirMfGpuCapture* capture) +{ + if (!capture) + { + return; + } + + if (capture->sharedHandle) + { + CloseHandle(capture->sharedHandle); + } + if (capture->source) + { + capture->source->Shutdown(); + } + delete capture; + MFShutdown(); + CoUninitialize(); +} +} diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 4ced503..1692e84 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -355,6 +355,14 @@ WinUSB/libusb capture, emitting Bayer8 frames through the common upload lane. Driver smokes have pulled and uploaded real frames for LeapUVC 640x240 YUY2, both PS3 Eyes at 320x240 Bayer8, Kiyo Pro 1920x1080 YUY2, and regular Kiyo 640x480 YUY2. Regular Kiyo 1280x720 YUY2 did not open. +`MimirMediaFoundationGpuVideoCaptureDriver` plus +`native/camera_capture/mimir_mf_gpu_capture.dll` is the compressed camera path: +Media Foundation SourceReader runs with a D3D11 device manager, decodes MJPG or +H264 camera frames on the GPU, copies the decoded GPU surface into a shared BGRA +D3D11 texture, and publishes a `shared-d3d11-texture` handle with no live CPU +payload bytes. Kiyo Pro 1920x1080 MJPG->RGB32 and H264->RGB32 smokes both +produced valid GPU handles/resources. Direct NV12 shared texture creation +failed in D3D11, so NV12 needs plane-aware interop or a GPU bridge-copy cut. Metadata-only cadence frames do not create camera surface intents or fake payload requests. The old direct `AquariumGpuSensorFrame` bridge proof has been removed from Mimir's active proof path. Camera image claims currently defer diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 6a415ef..3f48781 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -63,8 +63,14 @@ Get-Content .\state\evidence.jsonl -Tail 8 Fresh driver smokes pulled and uploaded real frames for LeapUVC 640x240 YUY2, both PS3 Eyes at 320x240 Bayer8, Kiyo Pro 1920x1080 YUY2, and regular Kiyo 640x480 YUY2. Regular Kiyo 1280x720 YUY2 did not open. - Compressed MJPG/H264 still need a device/GPU decode producer, not this raw - upload lane. + Compressed Kiyo Pro MJPG/H264 now have a first GPU-resident path: + `MimirMediaFoundationGpuVideoCaptureDriver` uses + `native/camera_capture/mimir_mf_gpu_capture.dll` to decode through Media + Foundation with a D3D11 device manager, copy into a shared BGRA D3D11 texture, + and publish `shared-d3d11-texture` with zero live CPU payload bytes. + 1920x1080 MJPG->RGB32 and H264->RGB32 smokes passed. Direct shared NV12 + texture creation failed, so NV12 remains future plane-aware interop or + GPU bridge-copy work. Foreign shared texture handles are import edges, not the primary hot path. - The current Mimir/Fensalir rendering teardown map is [[docs/fensalir-rendering-rebuild-migration|Fensalir Rendering Rebuild diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index b1c83e9..4b4368e 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -123,6 +123,11 @@ if (args.Any(arg => string.Equals(arg, "--ps3eye-driver-smoke", StringComparison return RunPs3EyeDriverSmoke(args); } +if (args.Any(arg => string.Equals(arg, "--mf-gpu-driver-smoke", StringComparison.OrdinalIgnoreCase))) +{ + return RunMfGpuDriverSmoke(args); +} + if (args.Any(arg => string.Equals(arg, "--mimir-spectrum-upload-smoke", StringComparison.OrdinalIgnoreCase))) { return RunMimirSpectrumUploadSmoke(); @@ -927,6 +932,67 @@ static int RunPs3EyeDriverSmoke(string[] args) return 1; } +static int RunMfGpuDriverSmoke(string[] args) +{ + var library = ParseStringOption(args, "--native-library", Path.GetFullPath("native/camera_capture/build/Release/mimir_mf_gpu_capture.dll")); + var sourceId = ParseStringOption(args, "--source-id", "kiyo-pro-mf-gpu"); + var pathNeedle = ParseStringOption(args, "--path-needle", "vid_1532&pid_0e05"); + var width = ParseIntOption(args, "--width", 1920); + var height = ParseIntOption(args, "--height", 1080); + var inputFormat = ParseStringOption(args, "--input-format", "MJPG"); + var outputFormat = ParseStringOption(args, "--output-format", "NV12"); + var minFps = ParseDoubleOption(args, "--min-fps", 25.0); + var timeoutMs = ParseIntOption(args, "--timeout-ms", 3000); + + using var driver = new MimirMediaFoundationGpuVideoCaptureDriver(new MimirMediaFoundationGpuVideoCaptureDriverOptions( + library, + sourceId, + pathNeedle, + width, + height, + inputFormat, + outputFormat, + minFps)); + using var source = new MimirVideoCaptureDriverSource( + new MimirStreamDescriptor(sourceId, MimirStreamKind.Video, MimirStreamOrigin.LocalDevice), + driver, + static () => StopwatchTicksToNs(Stopwatch.GetTimestamp())); + + var deadline = Stopwatch.GetTimestamp() + (long)(timeoutMs / 1000.0 * Stopwatch.Frequency); + while (Stopwatch.GetTimestamp() < deadline) + { + if (!source.TryRead(out var sample)) + { + Thread.Sleep(1); + continue; + } + + var frame = sample.VideoFrame; + var buffer = new MimirRollingStreamBuffer( + new MimirStreamDescriptor(sourceId, MimirStreamKind.Video, MimirStreamOrigin.LocalDevice), + TimeSpan.FromSeconds(5)); + buffer.Append(sample); + var evidence = new MimirFensalirFieldLowering().BuildCameraObservationFrame([buffer]); + var validation = AquariumFieldEvidenceValidator.Validate(evidence); + Console.WriteLine( + $"mf-gpu-driver-smoke source={sample.SourceId} {frame?.Width}x{frame?.Height} format={frame?.PixelFormat} liveBytes={sample.ByteLength} handle=0x{frame?.NativeHandle:x} kind={frame?.NativeHandleKind} resources={evidence.Resources.Count} errors={validation.HasErrors}"); + return frame != null && + frame.Width == width && + frame.Height == height && + frame.NativeHandle != 0 && + frame.NativeHandleKind == "shared-d3d11-texture" && + sample.ByteLength == 0 && + evidence.Resources.Count == 1 && + evidence.Resources[0].Residency == AquariumFieldResourceResidency.SharedGpu && + !validation.HasErrors + ? 0 + : 1; + } + + Console.WriteLine($"mf-gpu-driver-smoke timeout source={sourceId} pathNeedle={pathNeedle} {width}x{height} {inputFormat}->{outputFormat}"); + return 1; +} + static long StopwatchTicksToNs(long ticks) { return checked((long)(ticks * (1_000_000_000.0 / Stopwatch.Frequency))); diff --git a/src/Mimir.Runtime/Synchronization/MimirMediaFoundationGpuVideoCaptureDriver.cs b/src/Mimir.Runtime/Synchronization/MimirMediaFoundationGpuVideoCaptureDriver.cs new file mode 100644 index 0000000..ac28d64 --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirMediaFoundationGpuVideoCaptureDriver.cs @@ -0,0 +1,183 @@ +using System.Runtime.InteropServices; + +namespace Mimir.Runtime.Synchronization; + +public sealed record MimirMediaFoundationGpuVideoCaptureDriverOptions( + string NativeLibraryPath, + string SourceId, + string PathNeedle, + int Width, + int Height, + string InputFormat, + string OutputFormat = "Nv12", + double MinimumFramesPerSecond = 0.0); + +public sealed unsafe class MimirMediaFoundationGpuVideoCaptureDriver : IMimirVideoCaptureDriver +{ + private readonly Native native; + private readonly nint capture; + private readonly string sourceId; + private bool disposed; + + public MimirMediaFoundationGpuVideoCaptureDriver(MimirMediaFoundationGpuVideoCaptureDriverOptions options) + { + if (string.IsNullOrWhiteSpace(options.NativeLibraryPath)) + { + throw new ArgumentException("Media Foundation GPU capture requires a native library path.", nameof(options)); + } + + if (string.IsNullOrWhiteSpace(options.SourceId)) + { + throw new ArgumentException("Media Foundation GPU capture requires a source id.", nameof(options)); + } + + native = Native.Load(options.NativeLibraryPath); + sourceId = options.SourceId; + capture = native.Create( + options.PathNeedle, + options.Width, + options.Height, + options.InputFormat, + options.OutputFormat, + options.MinimumFramesPerSecond); + if (capture == 0) + { + throw new InvalidOperationException($"Media Foundation GPU capture could not open {options.PathNeedle} {options.Width}x{options.Height} {options.InputFormat}->{options.OutputFormat}."); + } + } + + public string DriverName => "media-foundation-gpu-decode"; + + public bool TryCapture(out MimirVideoFrameDescriptor frame, out ReadOnlyMemory data) + { + Span formatBytes = stackalloc byte[16]; + if (!native.Read( + capture, + out var sharedHandle, + out var width, + out var height, + formatBytes, + out var timestampNs, + out var sequence) || + sharedHandle == 0) + { + frame = default!; + data = default; + return false; + } + + var pixelFormat = PixelFormatFromText(FourCcFromBytes(formatBytes)); + frame = new MimirVideoFrameDescriptor( + width, + height, + pixelFormat, + StrideBytesFor(pixelFormat, width), + timestampNs, + NativeHandle: unchecked((ulong)sharedHandle), + NativeHandleKind: "shared-d3d11-texture", + ResourceKey: MimirFensalirTextureLeaseClient.ResourceKeyForSource(sourceId), + ProducerFenceValue: sequence); + data = default; + return true; + } + + public void Dispose() + { + if (disposed) + { + return; + } + + disposed = true; + native.Destroy(capture); + native.Dispose(); + } + + private static int StrideBytesFor(MimirVideoPixelFormat format, int width) => + format switch + { + MimirVideoPixelFormat.Nv12 => width, + MimirVideoPixelFormat.Yuy2 => checked(width * 2), + MimirVideoPixelFormat.Bgra8 => checked(width * 4), + _ => Math.Max(1, width), + }; + + private static MimirVideoPixelFormat PixelFormatFromText(string value) => + value.Trim().ToUpperInvariant() switch + { + "NV12" => MimirVideoPixelFormat.Nv12, + "YUY2" => MimirVideoPixelFormat.Yuy2, + "BGRA8" or "BGRA" or "RGB32" => MimirVideoPixelFormat.Bgra8, + _ => MimirVideoPixelFormat.Unknown, + }; + + private static string FourCcFromBytes(ReadOnlySpan bytes) + { + var length = bytes.IndexOf((byte)0); + if (length < 0) + { + length = bytes.Length; + } + + return System.Text.Encoding.ASCII.GetString(bytes[..length]); + } + + private sealed class Native : IDisposable + { + private readonly nint library; + private readonly delegate* unmanaged[Stdcall] create; + private readonly delegate* unmanaged[Stdcall] read; + private readonly delegate* unmanaged[Stdcall] destroy; + + private Native(nint library) + { + this.library = library; + create = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_mf_gpu_create"); + read = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_mf_gpu_read"); + destroy = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_mf_gpu_destroy"); + } + + public static Native Load(string path) => new(NativeLibrary.Load(path)); + + public nint Create(string pathNeedle, int width, int height, string inputFormat, string outputFormat, double minFps) + { + var pathNeedleBytes = System.Text.Encoding.UTF8.GetBytes(pathNeedle + "\0"); + var inputBytes = System.Text.Encoding.UTF8.GetBytes(inputFormat + "\0"); + var outputBytes = System.Text.Encoding.UTF8.GetBytes(outputFormat + "\0"); + fixed (byte* pathNeedlePointer = pathNeedleBytes) + fixed (byte* inputPointer = inputBytes) + fixed (byte* outputPointer = outputBytes) + { + return create(pathNeedlePointer, width, height, inputPointer, outputPointer, minFps); + } + } + + public bool Read( + nint capture, + out nint sharedHandle, + out int width, + out int height, + Span format, + out long timestampNs, + out ulong sequence) + { + fixed (byte* formatPointer = format) + { + return read(capture, out sharedHandle, out width, out height, formatPointer, format.Length, out timestampNs, out sequence) != 0; + } + } + + public void Destroy(nint capture) + { + if (capture != 0) + { + destroy(capture); + } + } + + public void Dispose() + { + NativeLibrary.Free(library); + } + } +} diff --git a/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs b/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs index bb03b78..49440ed 100644 --- a/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs +++ b/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs @@ -192,6 +192,28 @@ public sealed class MimirRuntimeConfiguration static () => StopwatchTicksToNs(System.Diagnostics.Stopwatch.GetTimestamp()))); } + if (string.Equals(stream.Adapter, "mf-gpu", StringComparison.OrdinalIgnoreCase) + || string.Equals(stream.Adapter, "media-foundation-gpu", StringComparison.OrdinalIgnoreCase)) + { + if (!OperatingSystem.IsWindows()) + { + throw new PlatformNotSupportedException("The Mimir Media Foundation GPU source requires Windows."); + } + + return new MimirStreamSourceFactory(descriptor, () => new MimirVideoCaptureDriverSource( + descriptor, + new MimirMediaFoundationGpuVideoCaptureDriver(new MimirMediaFoundationGpuVideoCaptureDriverOptions( + ResolveCommand(stream.Command, configDirectory), + stream.SourceId, + stream.PathNeedle, + stream.Width, + stream.Height, + stream.InputFormat, + stream.OutputFormat, + stream.MinimumFramesPerSecond)), + static () => StopwatchTicksToNs(System.Diagnostics.Stopwatch.GetTimestamp()))); + } + if (string.Equals(stream.Adapter, "frame-events", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Adapter, "json-lines", StringComparison.OrdinalIgnoreCase)) { @@ -368,6 +390,10 @@ public sealed class MimirStreamConfig public string PixelFormat { get; set; } = ""; + public string InputFormat { get; set; } = ""; + + public string OutputFormat { get; set; } = "Nv12"; + public double MinimumFramesPerSecond { get; set; } public int QueueDepth { get; set; } = 8; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 853739a..07a99df 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -180,3 +180,4 @@ {"ts": "2026-05-27T14:21:26+01:00", "type": "decision", "status": "ok", "note": "Mimir now has a production-shaped in-process KS/UVC camera driver. native/camera_capture builds mimir_camera_capture.dll, which opens a Kernel Streaming capture pin and queues uncompressed UVC frames; MimirKsVideoCaptureDriver feeds those frames through IMimirVideoCaptureDriver so MimirVideoCaptureDriverSource can upload single-plane raw pixels into Fensalir texture leases and count the unavoidable copy. MJPG/H264 remain future device/GPU decode producer work."} {"ts": "2026-05-27T14:25:26+01:00", "type": "verification", "status": "ok", "note": "The new in-process KS/UVC driver pulled a real LeapUVC 640x240 YUY2 frame through native/camera_capture, MimirKsVideoCaptureDriver, and MimirVideoCaptureDriverSource, then uploaded 307200 bytes into the Fensalir texture lease for mimir:resource:camera:leap-stereo-ir:texture2d with UnavoidableCopyCount=1. Managed live payload bytes were cleared after upload."} {"ts": "2026-05-27T14:31:40+01:00", "type": "verification", "status": "ok", "note": "Direct camera driver smokes pulled and uploaded real camera pixels into Fensalir texture leases: LeapUVC 640x240 YUY2 uploaded 307200 bytes, PS3 Eye 0 and 1 each uploaded 320x240 Bayer8 / 76800 bytes, Kiyo Pro uploaded 1920x1080 YUY2 / 4147200 bytes, and regular Kiyo uploaded 640x480 YUY2 / 614400 bytes. All successful paths cleared live managed payload bytes after upload and reported UnavoidableCopyCount=1. Regular Kiyo 1280x720 YUY2 did not open; compressed MJPG/H264 still require a device/GPU decode producer."} +{"ts": "2026-05-27T16:35:32+01:00", "type": "verification", "status": "ok", "note": "Media Foundation GPU decode is now a Mimir-owned producer path. native/camera_capture/mimir_mf_gpu_capture.dll runs SourceReader with a D3D11 device manager, selects Kiyo Pro compressed modes, decodes MJPG/H264 on the GPU, copies the decoded GPU surface into a shared BGRA D3D11 texture, and MimirMediaFoundationGpuVideoCaptureDriver publishes a shared-d3d11-texture handle with empty live CPU payload bytes. Kiyo Pro 1920x1080 MJPG->RGB32 and H264->RGB32 smokes passed and lowered to valid Fensalir camera resources. Direct shared NV12 texture creation failed with E_INVALIDARG, so planar NV12 remains future plane-aware interop or GPU bridge-copy work."} diff --git a/state/map.yaml b/state/map.yaml index 89d965d..dc1b754 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -336,7 +336,15 @@ accepted_design: Fresh direct-driver smokes uploaded real frames for LeapUVC 640x240 YUY2, PS3 Eye 0/1 320x240 Bayer8, Kiyo Pro 1920x1080 YUY2, and regular Kiyo 640x480 YUY2. Regular Kiyo 1280x720 YUY2 did not open; compressed - MJPG/H264 remain device/GPU decode producer work. + Kiyo Pro MJPG/H264 now have a first GPU-resident producer: + `MimirMediaFoundationGpuVideoCaptureDriver` uses + `native/camera_capture/mimir_mf_gpu_capture.dll` to run Media Foundation + SourceReader with a D3D11 device manager, decode MJPG/H264 on the GPU, copy + the decoded GPU surface into a shared BGRA D3D11 texture, and publish a + `shared-d3d11-texture` handle with zero live CPU payload bytes. Kiyo Pro + 1920x1080 MJPG->RGB32 and H264->RGB32 smokes passed. Direct shared NV12 + texture creation failed in D3D11, so NV12 remains future plane-aware interop + or GPU bridge-copy work. `Mimir.BufferSmoke --fensalir-camera-observation-smoke` verifies the split, and `--fensalir-texture-lease-smoke` verifies the engine-owned lease path. Camera image claims currently defer until Fensalir