From 9fcb89e3e31caeb67e766ad9d13defa2bfc07ad4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 21 May 2026 19:22:46 +0100 Subject: [PATCH] Queue LeapUVC KS reads --- docs/native-capture-cadence.md | 20 +- .../leap_ks_cadence/leap_ks_cadence.cpp | 250 +++++++++++++----- state/evidence.jsonl | 1 + state/map.yaml | 10 +- 4 files changed, 204 insertions(+), 77 deletions(-) diff --git a/docs/native-capture-cadence.md b/docs/native-capture-cadence.md index d0989ae..e4b8da4 100644 --- a/docs/native-capture-cadence.md +++ b/docs/native-capture-cadence.md @@ -69,20 +69,20 @@ Probe source: - `native/probes/leap_ks_cadence` -Advertised modes and measured single-buffer pull rates: +Advertised modes and measured queued KS pull rates: | Mode | Advertised FPS | Frames | Elapsed | Delivered FPS | Bytes / Frame | | --- | ---: | ---: | ---: | ---: | ---: | -| 752x480 YUY2 | 50.00 | 173 | 5.002s | 34.58 | 721,920 | -| 640x480 YUY2 | 57.50 | 203 | 5.019s | 40.45 | 614,400 | -| 640x240 YUY2 | 115.00 | 415 | 5.003s | 82.95 | 307,200 | -| 640x120 YUY2 | 214.00 | 778 | 5.006s | 155.40 | 153,600 | -| 752x240 YUY2 | 100.00 | 293 | 5.004s | 58.55 | 360,960 | -| 752x120 YUY2 | 190.00 | 592 | 5.006s | 118.27 | 180,480 | +| 752x480 YUY2 | 50.00 | 173 | 5.008s | 34.55 | 721,920 | +| 640x480 YUY2 | 57.50 | 204 | 5.017s | 40.66 | 614,400 | +| 640x240 YUY2 | 115.00 | 415 | 5.004s | 82.93 | 307,200 | +| 640x120 YUY2 | 214.00 | 777 | 5.000s | 155.39 | 153,600 | +| 752x240 YUY2 | 100.00 | 308 | 5.013s | 61.44 | 360,960 | +| 752x120 YUY2 | 190.00 | 589 | 5.008s | 117.62 | 180,480 | Conclusion: the current direct KS probe can pull real frames from LeapUVC, but -the simple one-buffer blocking read loop does not reach the device's advertised +even eight queued asynchronous reads do not reach the device's advertised cadence. The useful stereo IR mode is `640x240 YUY2`, advertised at 115 fps and -currently measured at about 83 fps with this minimal read loop. The next cut -should implement a proper queued KS/AVStream worker, or deliberately rebind to a +currently measured at about 83 fps. The next cut should either tune LeapUVC +controls that affect exposure/frame interval or deliberately rebind to a WinUSB/libusb UVC path if we decide the Windows UVC stack is the bottleneck. diff --git a/native/probes/leap_ks_cadence/leap_ks_cadence.cpp b/native/probes/leap_ks_cadence/leap_ks_cadence.cpp index 903084f..b8a4738 100644 --- a/native/probes/leap_ks_cadence/leap_ks_cadence.cpp +++ b/native/probes/leap_ks_cadence/leap_ks_cadence.cpp @@ -3,13 +3,12 @@ #include #include #include +#include #include -#include #include #include #include -#include #include #include @@ -39,16 +38,30 @@ struct Handle void close() { - if (value != INVALID_HANDLE_VALUE) + if (value != INVALID_HANDLE_VALUE && value != nullptr) { CloseHandle(value); value = INVALID_HANDLE_VALUE; } } - explicit operator bool() const { return value != INVALID_HANDLE_VALUE; } + explicit operator bool() const { return value != INVALID_HANDLE_VALUE && value != nullptr; } }; +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 DeviceInfoSet { HDEVINFO value = INVALID_HANDLE_VALUE; @@ -382,7 +395,7 @@ std::vector inspectPins(HANDLE filter) return candidates; } -bool measureCandidate(HANDLE filter, const PinCandidate& candidate, int readerCount) +bool measureCandidate(HANDLE filter, const PinCandidate& candidate, int queueDepth) { const ULONG connectBytes = sizeof(KSPIN_CONNECT) + static_cast(candidate.format.size()); std::vector connectStorage(connectBytes); @@ -424,75 +437,188 @@ bool measureCandidate(HANDLE filter, const PinCandidate& candidate, int readerCo return false; } - const DWORD frameBytes = static_cast(candidate.imageBytes > 0 ? candidate.imageBytes : candidate.width * candidate.height * 2); - const auto start = std::chrono::steady_clock::now(); - const auto deadline = start + std::chrono::seconds(5); - std::atomic frames = 0; - std::atomic failed = false; - std::vector readers; - - for (int reader = 0; reader < readerCount; ++reader) + auto* ntDeviceIoControlFile = reinterpret_cast( + GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtDeviceIoControlFile")); + if (!ntDeviceIoControlFile) { - readers.emplace_back([&, reader]() - { - std::vector frame(frameBytes); - KSSTREAM_HEADER header{}; - header.Size = sizeof(header); - header.FrameExtent = frameBytes; - header.Data = frame.data(); - header.PresentationTime.Numerator = 1; - header.PresentationTime.Denominator = 1; - - while (!failed.load(std::memory_order_relaxed) && std::chrono::steady_clock::now() < deadline) - { - header.DataUsed = 0; - header.OptionsFlags = 0; - DWORD returned = 0; - const BOOL ok = DeviceIoControl( - pin.value, - IOCTL_KS_READ_STREAM, - &header, - sizeof(header), - &header, - sizeof(header), - &returned, - nullptr); - if (!ok || header.DataUsed == 0) - { - failed.store(true, std::memory_order_relaxed); - std::printf( - "reader %d failed after %llu frames: ok=%d dataUsed=%lu bytesReturned=%lu error=%s\n", - reader, - static_cast(frames.load()), - ok != FALSE, - static_cast(header.DataUsed), - static_cast(returned), - lastErrorText().c_str()); - break; - } - - frames.fetch_add(1, std::memory_order_relaxed); - } - }); + std::printf("NtDeviceIoControlFile lookup failed.\n"); + return false; } - for (auto& reader : readers) + const DWORD frameBytes = static_cast(candidate.imageBytes > 0 ? candidate.imageBytes : candidate.width * candidate.height * 2); + + struct ReadSlot { - reader.join(); + Handle event; + IO_STATUS_BLOCK status{}; + KSSTREAM_HEADER header{}; + std::vector frame; + bool pending = false; + }; + + std::vector slots(static_cast(queueDepth)); + std::vector waitEvents(static_cast(queueDepth)); + for (int index = 0; index < queueDepth; ++index) + { + auto& slot = slots[static_cast(index)]; + slot.event = Handle(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + if (!slot.event) + { + std::printf("CreateEvent failed: %s\n", lastErrorText().c_str()); + return false; + } + + 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[static_cast(index)] = slot.event.value; + } + + auto submit = [&](ReadSlot& slot, std::uint64_t frameCount) -> bool + { + ResetEvent(slot.event.value); + slot.status = {}; + slot.header.DataUsed = 0; + slot.header.OptionsFlags = 0; + const NTSTATUS status = ntDeviceIoControlFile( + 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; + } + + if (status >= 0) + { + slot.pending = false; + if (slot.header.DataUsed == 0) + { + std::printf( + "NtDeviceIoControlFile returned no payload after %llu frames; status=0x%08lx information=%llu\n", + static_cast(frameCount), + static_cast(status), + static_cast(slot.status.Information)); + return false; + } + return true; + } + + slot.pending = false; + std::printf( + "NtDeviceIoControlFile failed after %llu frames: status=0x%08lx\n", + static_cast(frameCount), + static_cast(status)); + return false; + }; + + const auto start = std::chrono::steady_clock::now(); + const auto deadline = start + std::chrono::seconds(5); + std::uint64_t frames = 0; + bool usingPendingReads = false; + + for (auto& slot : slots) + { + if (!submit(slot, frames)) + { + setState(pin.value, KSSTATE_STOP); + return frames > 0; + } + if (slot.pending) + { + usingPendingReads = true; + } + else + { + ++frames; + } + } + + if (!usingPendingReads) + { + while (std::chrono::steady_clock::now() < deadline) + { + if (!submit(slots.front(), frames)) + { + break; + } + if (slots.front().pending) + { + usingPendingReads = true; + break; + } + ++frames; + } + } + + while (usingPendingReads && std::chrono::steady_clock::now() < deadline) + { + const DWORD waitResult = WaitForMultipleObjects( + static_cast(waitEvents.size()), + waitEvents.data(), + FALSE, + 1000); + if (waitResult < WAIT_OBJECT_0 || waitResult >= WAIT_OBJECT_0 + waitEvents.size()) + { + std::printf("WaitForMultipleObjects failed or timed out after %llu frames: result=0x%08lx error=%s\n", static_cast(frames), static_cast(waitResult), lastErrorText().c_str()); + break; + } + + auto& slot = slots[static_cast(waitResult - WAIT_OBJECT_0)]; + slot.pending = false; + if (slot.status.Status < 0 || slot.header.DataUsed == 0) + { + std::printf( + "queued read failed after %llu frames: status=0x%08lx dataUsed=%lu information=%llu\n", + static_cast(frames), + static_cast(slot.status.Status), + static_cast(slot.header.DataUsed), + static_cast(slot.status.Information)); + break; + } + + ++frames; + if (std::chrono::steady_clock::now() < deadline) + { + if (!submit(slot, frames)) + { + break; + } + } } const auto end = std::chrono::steady_clock::now(); setState(pin.value, KSSTATE_STOP); + for (auto& slot : slots) + { + if (slot.pending) + { + WaitForSingleObject(slot.event.value, 100); + slot.pending = false; + } + } const double elapsed = std::chrono::duration(end - start).count(); - const auto frameCount = frames.load(std::memory_order_relaxed); - const double fps = static_cast(frameCount) / elapsed; + const double fps = static_cast(frames) / elapsed; std::printf( - "measured: %llu frames in %.3fs = %.2f fps, readers=%d, bytes/frame=%lu\n", - static_cast(frameCount), + "measured: %llu frames in %.3fs = %.2f fps, queueDepth=%d, async=%s, bytes/frame=%lu\n", + static_cast(frames), elapsed, fps, - readerCount, + queueDepth, + usingPendingReads ? "yes" : "no", static_cast(frameBytes)); return true; } @@ -543,7 +669,7 @@ int main() candidate.bitCount, fourccOrGuid(candidate.subtype).c_str(), candidate.interval100ns > 0 ? 10000000.0 / static_cast(candidate.interval100ns) : 0.0); - measuredAny = measureCandidate(filter.value, candidate, 1) || measuredAny; + measuredAny = measureCandidate(filter.value, candidate, 8) || measuredAny; } return measuredAny ? 0 : 4; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 53674c2..33bae20 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -4,3 +4,4 @@ {"ts":"2026-05-21T19:05:00+00:00","type":"correction","status":"ok","note":"Restored the research archive as reference-only memory. Research may preserve external examples and failed-path lessons, but live implementation must be rebuilt through direct drivers, native buffers, Aquarium GPU compute, and Faust/native DSP."} {"ts":"2026-05-21T19:30:00+00:00","type":"verification","status":"ok","note":"Raw PS3 Eye libusb/WinUSB cadence probe measured both cameras simultaneously at 320x240 requested 187 Hz: camera 0 delivered 915 frames in 5.005s (182.81 fps), camera 1 delivered 916 frames in 5.005s (183.01 fps). At 640x480 requested 60 Hz they delivered 58.69 fps and 57.09 fps. Leap remains unmeasured in raw UVC/KS mode."} {"ts":"2026-05-21T20:05:00+00:00","type":"verification","status":"ok","note":"Native LeapUVC Kernel Streaming probe measured VID_F182 through usbvideo.sys without Media Foundation, DirectShow, OpenCV, or frame processing. Advertised 640x240 YUY2 stereo IR mode is 115 fps; the minimal one-buffer blocking KS read loop delivered 415 frames in 5.003s (82.95 fps). 640x120 delivered 155.40 fps against a 214 fps advertised mode. Next driver cut needs queued KS/AVStream streaming, or an explicit WinUSB/libusb UVC driver rebind decision if usbvideo.sys remains the bottleneck."} +{"ts":"2026-05-21T20:25:00+00:00","type":"verification","status":"ok","note":"LeapUVC KS probe now keeps eight asynchronous NtDeviceIoControlFile reads queued. The path reports async=yes but cadence stays effectively unchanged: 640x240 YUY2 delivered 415 frames in 5.004s (82.93 fps), and 640x120 delivered 777 frames in 5.000s (155.39 fps). The limiting factor is not simply an empty user-mode read queue."} diff --git a/state/map.yaml b/state/map.yaml index 4828f69..704a5ba 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -83,9 +83,9 @@ current_status: 57-59 fps each at 640x480. A native Kernel Streaming LeapUVC probe can pull frames through usbvideo.sys without Media Foundation, DirectShow, OpenCV, or frame processing; the useful 640x240 stereo IR mode advertises 115 fps and - currently measures about 83 fps with a minimal one-buffer blocking read. + currently measures about 83 fps even with eight queued asynchronous KS reads. next_action: > - Replace the minimal Leap KS read loop with a proper queued streaming worker, - then turn the proven Leap and PS3 Eye capture shapes into - `IMimirVideoCaptureDriver` implementations that feed measured frames into - `MimirSynchronizationHub`. + Test LeapUVC control tuning for exposure/frame interval, then either turn + the queued KS path into an `IMimirVideoCaptureDriver` or make an explicit + WinUSB/libusb UVC driver-rebind decision if usbvideo.sys remains the + bottleneck.