diff --git a/config/mimir-runtime.ks-camera.example.json b/config/mimir-runtime.ks-camera.example.json new file mode 100644 index 0000000..0a35e3c --- /dev/null +++ b/config/mimir-runtime.ks-camera.example.json @@ -0,0 +1,20 @@ +{ + "bufferSeconds": 5.0, + "streams": [ + { + "sourceId": "leap-stereo-ir", + "displayName": "LeapUVC stereo IR", + "kind": "Video", + "origin": "LocalDevice", + "enabled": true, + "adapter": "ks-camera", + "command": "../native/camera_capture/build/Release/mimir_camera_capture.dll", + "pathNeedle": "vid_f182&pid_0003&mi_00", + "width": 640, + "height": 240, + "pixelFormat": "YUY2", + "minimumFramesPerSecond": 100.0, + "queueDepth": 8 + } + ] +} diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index ff4d759..4102358 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -201,6 +201,13 @@ a named invariant that the native runtime cannot protect yet. Metadata-only cadence frames remain observations with empty payload handles; they do not become fake render requests. The old direct `AquariumGpuSensorFrame` builder has been removed from Mimir's proof path. + The first production-shaped camera driver is `MimirKsVideoCaptureDriver`, + backed by `native/camera_capture/mimir_camera_capture.dll`: it opens a + Kernel Streaming capture pin in process, queues uncompressed UVC frame reads, + returns `MimirVideoFrameDescriptor` samples through `IMimirVideoCaptureDriver`, + and lets `MimirVideoCaptureDriverSource` upload those raw frames into + Fensalir texture leases. MJPG/H264 remain outside this lane; they need a + device/GPU decode producer rather than a CPU convenience detour. 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 new file mode 100644 index 0000000..3e26966 --- /dev/null +++ b/native/camera_capture/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.20) + +project(mimir_camera_capture LANGUAGES CXX) + +add_library(mimir_camera_capture SHARED + mimir_ks_camera_capture.cpp) + +target_compile_features(mimir_camera_capture PRIVATE cxx_std_20) +target_compile_definitions(mimir_camera_capture PRIVATE + WIN32_LEAN_AND_MEAN + NOMINMAX) +target_link_libraries(mimir_camera_capture PRIVATE + setupapi + ksuser) diff --git a/native/camera_capture/mimir_ks_camera_capture.cpp b/native/camera_capture/mimir_ks_camera_capture.cpp new file mode 100644 index 0000000..618f68c --- /dev/null +++ b/native/camera_capture/mimir_ks_camera_capture.cpp @@ -0,0 +1,702 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +struct Handle +{ + HANDLE value = INVALID_HANDLE_VALUE; + + Handle() = default; + explicit Handle(HANDLE handle) : value(handle) {} + Handle(const Handle&) = delete; + Handle& operator=(const Handle&) = delete; + Handle(Handle&& other) noexcept : value(other.value) { other.value = INVALID_HANDLE_VALUE; } + Handle& operator=(Handle&& other) noexcept + { + if (this != &other) + { + close(); + value = other.value; + other.value = INVALID_HANDLE_VALUE; + } + + return *this; + } + + ~Handle() { close(); } + + void close() + { + if (value != INVALID_HANDLE_VALUE && value != nullptr) + { + CloseHandle(value); + value = INVALID_HANDLE_VALUE; + } + } + + explicit operator bool() const { return value != INVALID_HANDLE_VALUE && value != nullptr; } +}; + +struct DeviceInfoSet +{ + HDEVINFO value = INVALID_HANDLE_VALUE; + + explicit DeviceInfoSet(HDEVINFO info) : value(info) {} + DeviceInfoSet(const DeviceInfoSet&) = delete; + DeviceInfoSet& operator=(const DeviceInfoSet&) = delete; + ~DeviceInfoSet() + { + if (value != INVALID_HANDLE_VALUE) + { + SetupDiDestroyDeviceInfoList(value); + } + } +}; + +using NtDeviceIoControlFileFn = NTSTATUS(NTAPI*)( + HANDLE FileHandle, + HANDLE Event, + PIO_APC_ROUTINE ApcRoutine, + PVOID ApcContext, + PIO_STATUS_BLOCK IoStatusBlock, + ULONG IoControlCode, + PVOID InputBuffer, + ULONG InputBufferLength, + PVOID OutputBuffer, + ULONG OutputBufferLength); + +constexpr NTSTATUS StatusPending = static_cast(0x00000103L); + +struct PinCandidate +{ + ULONG pinId = 0; + std::vector format; + LONG width = 0; + LONG height = 0; + LONG imageBytes = 0; + LONGLONG interval100ns = 0; + GUID subtype{}; + std::string fourcc; +}; + +struct MimirKsCameraFrame +{ + std::vector data; + std::int64_t timestampNs = 0; + std::uint64_t sequence = 0; + int byteLength = 0; +}; + +struct MimirKsCameraCapture +{ + Handle filter; + Handle pin; + PinCandidate candidate; + std::thread worker; + std::mutex mutex; + std::condition_variable condition; + std::deque queue; + std::atomic running = false; + int queueDepth = 8; + std::uint64_t sequence = 0; +}; + +long long nowNs() +{ + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +std::string lowercase(std::string value) +{ + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return value; +} + +std::string wideToUtf8(const wchar_t* value) +{ + if (!value) + { + return {}; + } + + const int bytes = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr); + if (bytes <= 1) + { + return {}; + } + + std::string text(static_cast(bytes - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, value, -1, text.data(), bytes, nullptr, nullptr); + return text; +} + +std::string fourccOrGuid(const GUID& guid) +{ + if (guid.Data2 == 0x0000 && + guid.Data3 == 0x0010 && + guid.Data4[0] == 0x80 && + guid.Data4[1] == 0x00 && + guid.Data4[2] == 0x00 && + guid.Data4[3] == 0xaa && + guid.Data4[4] == 0x00 && + guid.Data4[5] == 0x38 && + guid.Data4[6] == 0x9b && + guid.Data4[7] == 0x71) + { + char text[5]{}; + text[0] = static_cast(guid.Data1 & 0xff); + text[1] = static_cast((guid.Data1 >> 8) & 0xff); + text[2] = static_cast((guid.Data1 >> 16) & 0xff); + text[3] = static_cast((guid.Data1 >> 24) & 0xff); + return text; + } + + return {}; +} + +bool ksProperty(HANDLE handle, void* property, DWORD propertyBytes, void* output, DWORD outputBytes, DWORD* returned = nullptr) +{ + DWORD bytes = 0; + const BOOL ok = DeviceIoControl( + handle, + IOCTL_KS_PROPERTY, + property, + propertyBytes, + output, + outputBytes, + &bytes, + nullptr); + if (returned) + { + *returned = bytes; + } + + return ok != FALSE; +} + +template +bool getPinProperty(HANDLE filter, ULONG pinId, ULONG propertyId, T& value) +{ + KSP_PIN property{}; + property.Property.Set = KSPROPSETID_Pin; + property.Property.Id = propertyId; + property.Property.Flags = KSPROPERTY_TYPE_GET; + property.PinId = pinId; + DWORD returned = 0; + return ksProperty(filter, &property, sizeof(property), &value, sizeof(value), &returned); +} + +std::vector enumerateCapturePaths() +{ + std::vector paths; + DeviceInfoSet info(SetupDiGetClassDevsA( + &KSCATEGORY_CAPTURE, + nullptr, + nullptr, + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)); + if (info.value == INVALID_HANDLE_VALUE) + { + return paths; + } + + for (DWORD index = 0;; ++index) + { + SP_DEVICE_INTERFACE_DATA interfaceData{}; + interfaceData.cbSize = sizeof(interfaceData); + if (!SetupDiEnumDeviceInterfaces(info.value, nullptr, &KSCATEGORY_CAPTURE, index, &interfaceData)) + { + break; + } + + DWORD required = 0; + SetupDiGetDeviceInterfaceDetailW(info.value, &interfaceData, nullptr, 0, &required, nullptr); + if (required == 0) + { + continue; + } + + std::vector storage(required); + auto* detail = reinterpret_cast(storage.data()); + detail->cbSize = sizeof(*detail); + if (SetupDiGetDeviceInterfaceDetailW(info.value, &interfaceData, detail, required, nullptr, nullptr)) + { + paths.push_back(wideToUtf8(detail->DevicePath)); + } + } + + return paths; +} + +std::vector inspectPins(HANDLE filter) +{ + ULONG pinCount = 0; + KSPROPERTY countProperty{}; + countProperty.Set = KSPROPSETID_Pin; + countProperty.Id = KSPROPERTY_PIN_CTYPES; + countProperty.Flags = KSPROPERTY_TYPE_GET; + if (!ksProperty(filter, &countProperty, sizeof(countProperty), &pinCount, sizeof(pinCount))) + { + return {}; + } + + std::vector candidates; + for (ULONG pinId = 0; pinId < pinCount; ++pinId) + { + KSPIN_DATAFLOW dataflow{}; + if (!getPinProperty(filter, pinId, KSPROPERTY_PIN_DATAFLOW, dataflow) || + dataflow != KSPIN_DATAFLOW_OUT) + { + continue; + } + + KSP_PIN rangeProperty{}; + rangeProperty.Property.Set = KSPROPSETID_Pin; + rangeProperty.Property.Id = KSPROPERTY_PIN_DATARANGES; + rangeProperty.Property.Flags = KSPROPERTY_TYPE_GET; + rangeProperty.PinId = pinId; + + DWORD rangeBytes = 0; + ksProperty(filter, &rangeProperty, sizeof(rangeProperty), nullptr, 0, &rangeBytes); + if (rangeBytes == 0) + { + continue; + } + + std::vector ranges(rangeBytes); + DWORD returned = 0; + if (!ksProperty(filter, &rangeProperty, sizeof(rangeProperty), ranges.data(), static_cast(ranges.size()), &returned)) + { + continue; + } + + auto* multiple = reinterpret_cast(ranges.data()); + auto* cursor = ranges.data() + sizeof(KSMULTIPLE_ITEM); + for (ULONG i = 0; i < multiple->Count; ++i) + { + auto* dataRange = reinterpret_cast(cursor); + const bool videoInfo = + IsEqualGUID(dataRange->MajorFormat, KSDATAFORMAT_TYPE_VIDEO) && + IsEqualGUID(dataRange->Specifier, KSDATAFORMAT_SPECIFIER_VIDEOINFO) && + dataRange->FormatSize >= sizeof(KS_DATARANGE_VIDEO); + + if (videoInfo) + { + auto* video = reinterpret_cast(cursor); + const auto& bmi = video->VideoInfoHeader.bmiHeader; + PinCandidate candidate{}; + candidate.pinId = pinId; + candidate.width = bmi.biWidth; + candidate.height = bmi.biHeight; + candidate.imageBytes = bmi.biSizeImage > 0 ? bmi.biSizeImage : static_cast(dataRange->SampleSize); + candidate.interval100ns = video->VideoInfoHeader.AvgTimePerFrame; + candidate.subtype = dataRange->SubFormat; + candidate.fourcc = fourccOrGuid(candidate.subtype); + candidate.format.resize(sizeof(KS_DATAFORMAT_VIDEOINFOHEADER)); + auto* format = reinterpret_cast(candidate.format.data()); + format->DataFormat.FormatSize = sizeof(KS_DATAFORMAT_VIDEOINFOHEADER); + format->DataFormat.SampleSize = candidate.imageBytes; + format->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_VIDEO; + format->DataFormat.SubFormat = dataRange->SubFormat; + format->DataFormat.Specifier = KSDATAFORMAT_SPECIFIER_VIDEOINFO; + format->VideoInfoHeader = video->VideoInfoHeader; + format->VideoInfoHeader.bmiHeader.biSizeImage = candidate.imageBytes; + candidates.push_back(std::move(candidate)); + } + + cursor += dataRange->FormatSize; + } + } + + return candidates; +} + +const PinCandidate* findCandidate( + const std::vector& candidates, + int width, + int height, + const char* subtype, + double minFps) +{ + const std::string target = subtype ? subtype : ""; + for (const auto& candidate : candidates) + { + const double fps = candidate.interval100ns > 0 + ? 10000000.0 / static_cast(candidate.interval100ns) + : 0.0; + if (candidate.width == width && + candidate.height == height && + fps >= minFps && + candidate.fourcc == target) + { + return &candidate; + } + } + + return nullptr; +} + +bool setState(HANDLE pin, KSSTATE state) +{ + KSPROPERTY property{}; + property.Set = KSPROPSETID_Connection; + property.Id = KSPROPERTY_CONNECTION_STATE; + property.Flags = KSPROPERTY_TYPE_SET; + DWORD returned = 0; + return DeviceIoControl( + pin, + IOCTL_KS_PROPERTY, + &property, + sizeof(property), + &state, + sizeof(state), + &returned, + nullptr) != FALSE; +} + +int strideBytes(const PinCandidate& candidate) +{ + return candidate.height > 0 && candidate.imageBytes > 0 + ? candidate.imageBytes / candidate.height + : 0; +} + +void pushFrame(MimirKsCameraCapture& capture, const std::uint8_t* data, ULONG byteLength) +{ + MimirKsCameraFrame frame; + frame.byteLength = static_cast(byteLength); + frame.timestampNs = nowNs(); + frame.sequence = capture.sequence++; + frame.data.resize(byteLength); + std::memcpy(frame.data.data(), data, byteLength); + + { + std::lock_guard lock(capture.mutex); + capture.queue.push_back(std::move(frame)); + while (capture.queue.size() > 32) + { + capture.queue.pop_front(); + } + } + capture.condition.notify_one(); +} + +void captureThread(MimirKsCameraCapture* capture) +{ + auto* ntDeviceIoControlFile = reinterpret_cast( + GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtDeviceIoControlFile")); + if (!ntDeviceIoControlFile) + { + capture->running.store(false); + return; + } + + const ULONG connectBytes = sizeof(KSPIN_CONNECT) + static_cast(capture->candidate.format.size()); + std::vector connectStorage(connectBytes); + auto* connect = reinterpret_cast(connectStorage.data()); + connect->Interface.Set = KSINTERFACESETID_Standard; + connect->Interface.Id = KSINTERFACE_STANDARD_STREAMING; + connect->Medium.Set = KSMEDIUMSETID_Standard; + connect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE; + connect->PinId = capture->candidate.pinId; + connect->Priority.PriorityClass = KSPRIORITY_NORMAL; + connect->Priority.PrioritySubClass = 1; + std::memcpy(connectStorage.data() + sizeof(KSPIN_CONNECT), capture->candidate.format.data(), capture->candidate.format.size()); + + HANDLE rawPin = INVALID_HANDLE_VALUE; + const HRESULT hr = KsCreatePin(capture->filter.value, connect, GENERIC_READ, &rawPin); + if (FAILED(hr)) + { + capture->running.store(false); + return; + } + + capture->pin = Handle(rawPin); + if (!setState(capture->pin.value, KSSTATE_ACQUIRE) || + !setState(capture->pin.value, KSSTATE_PAUSE) || + !setState(capture->pin.value, KSSTATE_RUN)) + { + capture->running.store(false); + return; + } + + const DWORD frameBytes = static_cast(capture->candidate.imageBytes); + struct ReadSlot + { + Handle event; + IO_STATUS_BLOCK status{}; + KSSTREAM_HEADER header{}; + std::vector frame; + bool pending = false; + }; + + std::vector slots(static_cast(std::max(1, capture->queueDepth))); + std::vector waitEvents(slots.size()); + for (auto& slot : slots) + { + slot.event = Handle(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + if (!slot.event) + { + capture->running.store(false); + return; + } + + slot.frame.resize(frameBytes); + slot.header.Size = sizeof(KSSTREAM_HEADER); + slot.header.FrameExtent = frameBytes; + slot.header.Data = slot.frame.data(); + slot.header.PresentationTime.Numerator = 1; + slot.header.PresentationTime.Denominator = 1; + waitEvents[&slot - slots.data()] = slot.event.value; + } + + auto submit = [&](ReadSlot& slot) -> bool { + ResetEvent(slot.event.value); + slot.status = {}; + slot.header.DataUsed = 0; + slot.header.OptionsFlags = 0; + const NTSTATUS status = ntDeviceIoControlFile( + capture->pin.value, + slot.event.value, + nullptr, + nullptr, + &slot.status, + IOCTL_KS_READ_STREAM, + &slot.header, + sizeof(slot.header), + &slot.header, + sizeof(slot.header)); + + if (status == StatusPending) + { + slot.pending = true; + return true; + } + + slot.pending = false; + if (status >= 0 && slot.header.DataUsed > 0) + { + pushFrame(*capture, slot.frame.data(), slot.header.DataUsed); + return true; + } + + return false; + }; + + for (auto& slot : slots) + { + if (!submit(slot)) + { + capture->running.store(false); + return; + } + } + + while (capture->running.load()) + { + const DWORD waitResult = WaitForMultipleObjects( + static_cast(waitEvents.size()), + waitEvents.data(), + FALSE, + 100); + if (waitResult == WAIT_TIMEOUT) + { + continue; + } + + if (waitResult < WAIT_OBJECT_0 || waitResult >= WAIT_OBJECT_0 + waitEvents.size()) + { + break; + } + + auto& slot = slots[static_cast(waitResult - WAIT_OBJECT_0)]; + slot.pending = false; + if (slot.status.Status < 0 || slot.header.DataUsed == 0) + { + break; + } + + pushFrame(*capture, slot.frame.data(), slot.header.DataUsed); + if (!submit(slot)) + { + break; + } + } + + setState(capture->pin.value, KSSTATE_STOP); + CancelIoEx(capture->pin.value, nullptr); + for (auto& slot : slots) + { + if (slot.pending) + { + WaitForSingleObject(slot.event.value, 100); + } + } + capture->running.store(false); +} + +} // namespace + +extern "C" +{ +__declspec(dllexport) MimirKsCameraCapture* mimir_ks_create( + const char* pathNeedle, + int width, + int height, + const char* subtype, + double minFps, + int queueDepth) +{ + const std::string needle = lowercase(pathNeedle ? pathNeedle : ""); + for (const auto& path : enumerateCapturePaths()) + { + if (!needle.empty() && lowercase(path).find(needle) == std::string::npos) + { + continue; + } + + Handle filter(CreateFileA( + path.c_str(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + nullptr)); + if (!filter) + { + continue; + } + + auto candidates = inspectPins(filter.value); + const auto* candidate = findCandidate(candidates, width, height, subtype, minFps); + if (!candidate) + { + continue; + } + + auto* capture = new MimirKsCameraCapture(); + capture->filter = std::move(filter); + capture->candidate = *candidate; + capture->queueDepth = std::max(1, std::min(queueDepth, 32)); + return capture; + } + + return nullptr; +} + +__declspec(dllexport) int mimir_ks_start(MimirKsCameraCapture* capture) +{ + if (!capture || capture->running.exchange(true)) + { + return 0; + } + + capture->worker = std::thread(captureThread, capture); + return 1; +} + +__declspec(dllexport) int mimir_ks_read( + MimirKsCameraCapture* capture, + int* width, + int* height, + int* stride, + char* fourcc, + int fourccCapacity, + std::int64_t* timestampNs, + std::uint64_t* sequence, + std::uint8_t* destination, + int destinationBytes) +{ + if (!capture || !destination || destinationBytes <= 0) + { + return 0; + } + + MimirKsCameraFrame frame; + { + std::lock_guard lock(capture->mutex); + if (capture->queue.empty()) + { + return 0; + } + + frame = std::move(capture->queue.front()); + capture->queue.pop_front(); + } + + if (frame.byteLength > destinationBytes) + { + return -frame.byteLength; + } + + std::memcpy(destination, frame.data.data(), static_cast(frame.byteLength)); + if (width) + { + *width = static_cast(capture->candidate.width); + } + if (height) + { + *height = static_cast(capture->candidate.height); + } + if (stride) + { + *stride = strideBytes(capture->candidate); + } + if (fourcc && fourccCapacity > 0) + { + std::snprintf(fourcc, static_cast(fourccCapacity), "%s", capture->candidate.fourcc.c_str()); + } + if (timestampNs) + { + *timestampNs = frame.timestampNs; + } + if (sequence) + { + *sequence = frame.sequence; + } + + return frame.byteLength; +} + +__declspec(dllexport) void mimir_ks_destroy(MimirKsCameraCapture* capture) +{ + if (!capture) + { + return; + } + + capture->running.store(false); + if (capture->pin) + { + CancelIoEx(capture->pin.value, nullptr); + } + if (capture->worker.joinable()) + { + capture->worker.join(); + } + + delete capture; +} +} diff --git a/notes/current-system-map.md b/notes/current-system-map.md index 33418e1..85d54c6 100644 --- a/notes/current-system-map.md +++ b/notes/current-system-map.md @@ -344,6 +344,11 @@ performs the one declared CPU-to-GPU upload into the Fensalir lease, drops the managed payload from the live sample, and increments `UnavoidableCopyCount`. NV12 CPU upload is rejected until Fensalir owns a real planar upload path; device/GPU NV12 producers should write the leased texture directly. +`MimirKsVideoCaptureDriver` plus `native/camera_capture/mimir_camera_capture.dll` +is the first production-shaped KS/UVC driver: it opens a Kernel Streaming pin +in process, queues uncompressed UVC frames, and feeds the same +`IMimirVideoCaptureDriver` source path. MJPG/H264 still need a device/GPU +decode producer; the KS driver rejects compressed capture formats. 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 2ce385c..5595c38 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -55,6 +55,11 @@ Get-Content .\state\evidence.jsonl -Tail 8 which increments `UnavoidableCopyCount` and clears live managed payload bytes after upload. NV12 CPU upload is rejected until Fensalir owns planar copy; device/GPU NV12 producers should write the leased texture directly. + The first direct KS/UVC driver is `MimirKsVideoCaptureDriver` backed by + `native/camera_capture/mimir_camera_capture.dll`; the example config + `config/mimir-runtime.ks-camera.example.json` targets LeapUVC 640x240 YUY2. + Compressed MJPG/H264 still need a device/GPU decode producer, not this raw + upload lane. 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 d123320..efe3e5d 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -113,6 +113,11 @@ if (args.Any(arg => string.Equals(arg, "--fensalir-texture-lease-smoke", StringC return RunFensalirTextureLeaseSmoke(); } +if (args.Any(arg => string.Equals(arg, "--ks-camera-driver-smoke", StringComparison.OrdinalIgnoreCase))) +{ + return RunKsCameraDriverSmoke(args); +} + if (args.Any(arg => string.Equals(arg, "--mimir-spectrum-upload-smoke", StringComparison.OrdinalIgnoreCase))) { return RunMimirSpectrumUploadSmoke(); @@ -792,7 +797,7 @@ static int RunFensalirTextureLeaseSmoke() var expectedResourceKey = MimirFensalirTextureLeaseClient.ResourceKeyForSource("kiyo-pro-rgb"); Console.WriteLine( - $"fensalir-texture-lease-smoke leased={lease.IsValid} committed={broker.CommittedFenceValue > 0} driverClient={receiverDriver.HasClient} uploaded={broker.UploadedResourceKey} copies={receiverSource.LastUploadedCopyCount} resources={frame.Resources.Count} claims={frame.Claims.Count} errors={validation.HasErrors}"); + $"fensalir-texture-lease-smoke leased={lease.IsValid} committed={broker.CommittedFenceValue > 0} driverClient={receiverDriver.HasClient} uploaded={broker.UploadedResourceKey} uploadedBytes={receiverSource.LastUploadedByteLength} copies={receiverSource.LastUploadedCopyCount} resources={frame.Resources.Count} claims={frame.Claims.Count} errors={validation.HasErrors}"); return lease.IsValid && receiverDriver.HasClient && @@ -814,6 +819,63 @@ static int RunFensalirTextureLeaseSmoke() : 1; } +static int RunKsCameraDriverSmoke(string[] args) +{ + var library = ParseStringOption(args, "--native-library", Path.GetFullPath("native/camera_capture/build/Release/mimir_camera_capture.dll")); + var sourceId = ParseStringOption(args, "--source-id", "leap-stereo-ir"); + var pathNeedle = ParseStringOption(args, "--path-needle", "vid_f182&pid_0003&mi_00"); + var width = ParseIntOption(args, "--width", 640); + var height = ParseIntOption(args, "--height", 240); + var fourCc = ParseStringOption(args, "--fourcc", "YUY2"); + var minFps = ParseDoubleOption(args, "--min-fps", 100.0); + var timeoutMs = ParseIntOption(args, "--timeout-ms", 3000); + + var broker = new FakeFieldResourceBroker(); + using var driver = new MimirKsVideoCaptureDriver(new MimirKsVideoCaptureDriverOptions( + library, + sourceId, + pathNeedle, + width, + height, + fourCc, + minFps)); + using var source = new MimirVideoCaptureDriverSource( + new MimirStreamDescriptor(sourceId, MimirStreamKind.Video, MimirStreamOrigin.LocalDevice), + driver, + static () => StopwatchTicksToNs(Stopwatch.GetTimestamp())); + source.AttachTextureLeaseClient(new MimirFensalirTextureLeaseClient(broker)); + + 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; + Console.WriteLine( + $"ks-camera-driver-smoke source={sample.SourceId} {frame?.Width}x{frame?.Height} format={frame?.PixelFormat} liveBytes={sample.ByteLength} uploadedBytes={source.LastUploadedByteLength} uploaded={broker.UploadedResourceKey} copies={source.LastUploadedCopyCount}"); + return frame != null && + frame.Width == width && + frame.Height == height && + source.LastUploadedByteLength > 0 && + source.LastUploadedCopyCount == 1 && + broker.UploadedResourceKey == MimirFensalirTextureLeaseClient.ResourceKeyForSource(sourceId) + ? 0 + : 1; + } + + Console.WriteLine($"ks-camera-driver-smoke timeout source={sourceId} pathNeedle={pathNeedle} {width}x{height} {fourCc}"); + return 1; +} + +static long StopwatchTicksToNs(long ticks) +{ + return checked((long)(ticks * (1_000_000_000.0 / Stopwatch.Frequency))); +} + static int RunMimirSpectrumUploadSmoke() { var previousSyntheticPreview = Environment.GetEnvironmentVariable("MIMIR_SYNTHETIC_SPECTRUM_PREVIEW"); diff --git a/src/Mimir.Runtime/Synchronization/MimirKsVideoCaptureDriver.cs b/src/Mimir.Runtime/Synchronization/MimirKsVideoCaptureDriver.cs new file mode 100644 index 0000000..b00f271 --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirKsVideoCaptureDriver.cs @@ -0,0 +1,232 @@ +using System.Runtime.InteropServices; + +namespace Mimir.Runtime.Synchronization; + +public sealed record MimirKsVideoCaptureDriverOptions( + string NativeLibraryPath, + string SourceId, + string PathNeedle, + int Width, + int Height, + string FourCc, + double MinimumFramesPerSecond, + int QueueDepth = 8); + +public sealed unsafe class MimirKsVideoCaptureDriver : IMimirVideoCaptureDriver, IMimirFensalirTextureLeaseReceiver +{ + private readonly Native native; + private readonly nint capture; + private readonly byte[] scratch; + private readonly string sourceId; + private readonly string fourCc; + private MimirFensalirTextureLeaseClient? textureLeaseClient; + private string resourceKey = ""; + private bool disposed; + + public MimirKsVideoCaptureDriver(MimirKsVideoCaptureDriverOptions options) + { + if (string.IsNullOrWhiteSpace(options.NativeLibraryPath)) + { + throw new ArgumentException("KS camera capture requires a native library path.", nameof(options)); + } + + if (string.IsNullOrWhiteSpace(options.SourceId)) + { + throw new ArgumentException("KS camera capture requires a source id.", nameof(options)); + } + + if (IsCompressed(options.FourCc)) + { + throw new NotSupportedException("KS camera capture driver only accepts uncompressed frame formats. Use a GPU decode producer for MJPG/H264."); + } + + native = Native.Load(options.NativeLibraryPath); + sourceId = options.SourceId; + fourCc = options.FourCc.Trim(); + capture = native.Create( + options.PathNeedle, + options.Width, + options.Height, + fourCc, + options.MinimumFramesPerSecond, + Math.Clamp(options.QueueDepth, 1, 32)); + if (capture == 0) + { + throw new InvalidOperationException($"KS camera capture could not open {options.PathNeedle} {options.Width}x{options.Height} {fourCc}."); + } + + scratch = new byte[checked(options.Width * options.Height * 4)]; + if (!native.Start(capture)) + { + throw new InvalidOperationException("KS camera capture could not start."); + } + } + + public string DriverName => "ks-uvc-direct"; + + public void AttachTextureLeaseClient(MimirFensalirTextureLeaseClient? client) + { + textureLeaseClient = client; + resourceKey = ""; + } + + public bool TryCapture(out MimirVideoFrameDescriptor frame, out ReadOnlyMemory data) + { + fixed (byte* destination = scratch) + { + Span fourCcBytes = stackalloc byte[16]; + var byteLength = native.Read( + capture, + out var width, + out var height, + out var stride, + fourCcBytes, + out var timestampNs, + out var sequence, + destination, + scratch.Length); + if (byteLength <= 0) + { + frame = default!; + data = default; + return false; + } + + var pixelFormat = PixelFormatFromFourCc(FourCcFromBytes(fourCcBytes)); + EnsureLease(width, height, pixelFormat, stride, timestampNs, sequence); + frame = new MimirVideoFrameDescriptor( + width, + height, + pixelFormat, + stride, + timestampNs, + ResourceKey: resourceKey, + ProducerFenceValue: sequence); + data = scratch.AsMemory(0, byteLength).ToArray(); + return true; + } + } + + public void Dispose() + { + if (disposed) + { + return; + } + + disposed = true; + native.Destroy(capture); + native.Dispose(); + } + + private void EnsureLease(int width, int height, MimirVideoPixelFormat pixelFormat, int stride, long timestampNs, ulong version) + { + if (!string.IsNullOrWhiteSpace(resourceKey) || textureLeaseClient == null) + { + return; + } + + if (textureLeaseClient.TryLeaseTexture2D(new MimirFensalirTextureLeaseRequest( + sourceId, + width, + height, + pixelFormat, + stride, + timestampNs, + version), out var lease)) + { + resourceKey = lease.Frame.ResourceKey; + } + } + + private static MimirVideoPixelFormat PixelFormatFromFourCc(string value) + { + return value.Trim().ToUpperInvariant() switch + { + "YUY2" or "YUYV" => MimirVideoPixelFormat.Yuy2, + "GREY" or "Y800" => MimirVideoPixelFormat.Gray8, + "RG8" or "R8G8" => MimirVideoPixelFormat.Rg8, + "BA81" or "BGGR" or "GBRG" or "GRBG" or "RGGB" => MimirVideoPixelFormat.Bayer8, + _ => MimirVideoPixelFormat.Unknown, + }; + } + + private static bool IsCompressed(string value) + { + return value.Trim().ToUpperInvariant() is "MJPG" or "H264"; + } + + 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] start; + 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_ks_create"); + start = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_ks_start"); + read = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_ks_read"); + destroy = (delegate* unmanaged[Stdcall])NativeLibrary.GetExport(library, "mimir_ks_destroy"); + } + + public static Native Load(string path) => new(NativeLibrary.Load(path)); + + public nint Create(string pathNeedle, int width, int height, string subtype, double minFps, int queueDepth) + { + var pathNeedleBytes = System.Text.Encoding.UTF8.GetBytes(pathNeedle + "\0"); + var subtypeBytes = System.Text.Encoding.UTF8.GetBytes(subtype + "\0"); + fixed (byte* pathNeedlePointer = pathNeedleBytes) + fixed (byte* subtypePointer = subtypeBytes) + { + return create(pathNeedlePointer, width, height, subtypePointer, minFps, queueDepth); + } + } + + public bool Start(nint capture) => start(capture) != 0; + + public int Read( + nint capture, + out int width, + out int height, + out int stride, + Span fourCc, + out long timestampNs, + out ulong sequence, + byte* destination, + int destinationBytes) + { + fixed (byte* fourCcPointer = fourCc) + { + return read(capture, out width, out height, out stride, fourCcPointer, fourCc.Length, out timestampNs, out sequence, destination, destinationBytes); + } + } + + 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 34cdf0b..33186bd 100644 --- a/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs +++ b/src/Mimir.Runtime/Synchronization/MimirRuntimeConfiguration.cs @@ -150,6 +150,28 @@ public sealed class MimirRuntimeConfiguration #pragma warning restore CA1416 } + if (string.Equals(stream.Adapter, "ks-camera", StringComparison.OrdinalIgnoreCase) + || string.Equals(stream.Adapter, "uvc-direct", StringComparison.OrdinalIgnoreCase)) + { + if (!OperatingSystem.IsWindows()) + { + throw new PlatformNotSupportedException("The Mimir KS camera source requires Windows."); + } + + return new MimirStreamSourceFactory(descriptor, () => new MimirVideoCaptureDriverSource( + descriptor, + new MimirKsVideoCaptureDriver(new MimirKsVideoCaptureDriverOptions( + ResolveCommand(stream.Command, configDirectory), + stream.SourceId, + stream.PathNeedle, + stream.Width, + stream.Height, + stream.PixelFormat, + stream.MinimumFramesPerSecond, + stream.QueueDepth)), + static () => StopwatchTicksToNs(System.Diagnostics.Stopwatch.GetTimestamp()))); + } + if (string.Equals(stream.Adapter, "frame-events", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Adapter, "json-lines", StringComparison.OrdinalIgnoreCase)) { @@ -198,6 +220,11 @@ public sealed class MimirRuntimeConfiguration return Path.GetFullPath(Path.Combine(configDirectory, command)); } + private static long StopwatchTicksToNs(long ticks) + { + return checked((long)(ticks * (1_000_000_000.0 / System.Diagnostics.Stopwatch.Frequency))); + } + private static MimirStreamKind ParseKind(string value) { return Enum.TryParse(value, ignoreCase: true, out var kind) @@ -271,6 +298,11 @@ public sealed class MimirAudioSyncConfig }; } + private static long StopwatchTicksToNs(long ticks) + { + return checked((long)(ticks * (1_000_000_000.0 / System.Diagnostics.Stopwatch.Frequency))); + } + private static string ResolveConfigPath(string path, string? configDirectory) { var trimmed = path.Trim(); @@ -308,6 +340,18 @@ public sealed class MimirStreamConfig public string DriverClsid { get; set; } = ""; + public string PathNeedle { get; set; } = ""; + + public int Width { get; set; } + + public int Height { get; set; } + + public string PixelFormat { get; set; } = ""; + + public double MinimumFramesPerSecond { get; set; } + + public int QueueDepth { get; set; } = 8; + public string DisplayNameForSource(string sourceId) { if (SourceLabels.TryGetValue(sourceId, out var label) && !string.IsNullOrWhiteSpace(label)) diff --git a/src/Mimir.Runtime/Synchronization/MimirVideoCaptureDriverSource.cs b/src/Mimir.Runtime/Synchronization/MimirVideoCaptureDriverSource.cs index cd70b03..77b3f91 100644 --- a/src/Mimir.Runtime/Synchronization/MimirVideoCaptureDriverSource.cs +++ b/src/Mimir.Runtime/Synchronization/MimirVideoCaptureDriverSource.cs @@ -28,6 +28,8 @@ public sealed class MimirVideoCaptureDriverSource : IMimirStreamSource, IMimirFe public int LastUploadedCopyCount { get; private set; } + public int LastUploadedByteLength { get; private set; } + public void AttachTextureLeaseClient(MimirFensalirTextureLeaseClient? client) { textureLeaseClient = client; @@ -55,6 +57,7 @@ public sealed class MimirVideoCaptureDriverSource : IMimirStreamSource, IMimirFe { frame = frame with { UnavoidableCopyCount = frame.UnavoidableCopyCount + 1 }; LastUploadedCopyCount = frame.UnavoidableCopyCount; + LastUploadedByteLength = data.Length; data = default; } } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index bb80122..81071b9 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -177,3 +177,5 @@ {"ts": "2026-05-27T13:32:24+01:00", "type": "decision", "status": "ok", "note": "Texture lease services now propagate from MimirRuntime into direct video capture sources. MimirVideoCaptureDriverSource forwards a MimirFensalirTextureLeaseClient to drivers that implement IMimirFensalirTextureLeaseReceiver, so a direct camera driver can request its Fensalir-owned destination texture before it emits the frame descriptor and producer fence value."} {"ts": "2026-05-27T13:37:42+01:00", "type": "decision", "status": "ok", "note": "Camera ingest policy is now closest-to-device first. Fensalir-owned Texture2D leases remain the render-input authority, but each native camera backend must choose the most direct device path available and report unavoidable copy count. Managed wrappers, process bridges, and system-memory rings are diagnostics or fallbacks, not production hot-path owners."} {"ts": "2026-05-27T14:07:32+01:00", "type": "decision", "status": "ok", "note": "Raw single-plane CPU-origin camera frames now have an explicit Fensalir texture upload fallback. MimirVideoCaptureDriverSource uploads returned frame bytes into the leased Fensalir Texture2D through the broker, clears the live managed payload after successful upload, and increments MimirVideoFrameDescriptor.UnavoidableCopyCount. CPU NV12 upload is rejected until Fensalir has a real planar copy path; GPU/direct producers should bypass this lane and remain at zero copies."} +{"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."} diff --git a/state/map.yaml b/state/map.yaml index 7591593..47b3439 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -323,6 +323,12 @@ accepted_design: `UnavoidableCopyCount`. NV12 CPU upload is rejected until Fensalir has a real planar upload path; device/GPU NV12 producers should write the leased texture directly. + `MimirKsVideoCaptureDriver` plus + `native/camera_capture/mimir_camera_capture.dll` is the first + production-shaped KS/UVC direct camera path: it opens a Kernel Streaming pin + in process, queues uncompressed UVC frames, and feeds the same driver source + and Fensalir lease upload path. MJPG/H264 remain future device/GPU decode + producer 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