diff --git a/tracker-native/src/win_camera.cpp b/tracker-native/src/win_camera.cpp index ccea01a..0005112 100644 --- a/tracker-native/src/win_camera.cpp +++ b/tracker-native/src/win_camera.cpp @@ -119,6 +119,9 @@ bool Camera::open(const std::wstring& symbolic_link, int width, int height) { IMFAttributes* ra = nullptr; MFCreateAttributes(&ra, 1); ra->SetUINT32(MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, TRUE); + // Cut the source reader's internal frame buffering so ReadSample returns the + // freshest frame instead of a queued (stale) one - critical for low latency. + ra->SetUINT32(MF_LOW_LATENCY, TRUE); IMFSourceReader* reader = nullptr; HRESULT hr = MFCreateSourceReaderFromMediaSource(src, ra, &reader); SafeRelease(&ra); diff --git a/tracker-native/src/win_main.cpp b/tracker-native/src/win_main.cpp index 2ea42d8..cd7bb6b 100644 --- a/tracker-native/src/win_main.cpp +++ b/tracker-native/src/win_main.cpp @@ -241,14 +241,55 @@ void WorkerLoop(bool image_mode, std::wstring symlink, int req_w, int req_h) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); + // Capture thread: continuously pull frames and keep only the LATEST one, so + // the inference loop never processes a stale queued frame. This bounds + // end-to-end latency to a single inference instead of a growing FIFO backlog + // (the source reader queues frames when inference is slower than the camera). + std::mutex cap_mutex; + std::vector cap_bgra; + int cap_w = 0, cap_h = 0; + std::atomic cap_seq{0}; + std::atomic cap_running{true}; + std::thread cap_thread; + if (!image_mode) { + cap_thread = std::thread([&] { + CoInitializeEx(nullptr, COINIT_MULTITHREADED); + std::vector tmp; + int tw = 0, th = 0; + while (cap_running.load() && g_app.running) { + if (camera.read_frame(tmp, tw, th)) { + std::lock_guard lk(cap_mutex); + cap_bgra.swap(tmp); + cap_w = tw; + cap_h = th; + cap_seq.fetch_add(1, std::memory_order_release); + } + } + CoUninitialize(); + }); + } + uint64_t last_seq = 0; + while (g_app.running) { if (image_mode) { bgra = source_bgra; w = src_w; h = src_h; Sleep(33); - } else if (!camera.read_frame(bgra, w, h)) { - continue; + } else { + // Grab the freshest captured frame; skip if none newer has arrived. + const uint64_t s = cap_seq.load(std::memory_order_acquire); + if (s == last_seq) { + Sleep(1); + continue; + } + { + std::lock_guard lk(cap_mutex); + bgra = cap_bgra; + w = cap_w; + h = cap_h; + } + last_seq = s; } // Mirror horizontally at the source so the preview and the published // depth/color/skeleton all read like a mirror (the mapper's own mirror is @@ -295,7 +336,11 @@ void WorkerLoop(bool image_mode, std::wstring symlink, int req_w, int req_h) { g_app.status_text = tracked ? "Tracking (player detected)" : "No player detected"; } } - if (!image_mode) camera.close(); + if (!image_mode) { + cap_running = false; + if (cap_thread.joinable()) cap_thread.join(); + camera.close(); + } CoUninitialize(); }