Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Add shared GPU transport for the Windows webcam

AS814864f85c5055ae
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 4952ec1..adf2621 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -1772,14 +1772,12 @@ Item {
readonly property bool isThisPhone: (Webcam.phase === "streaming" || Webcam.phase === "asking")
&& Webcam.activeDevice === home.deviceId
visible: isThisPhone
- onIsThisPhoneChanged: {
- if (isThisPhone)
- Webcam.setPreviewActive(true)
- }
- Component.onCompleted: {
- if (isThisPhone)
- Webcam.setPreviewActive(true)
- }
+ readonly property bool previewWanted: isThisPhone && visible && home.visible
+ && webcamHomeCard.Window.window !== null && webcamHomeCard.Window.window.visible
+ && webcamHomeCard.Window.window.visibility !== Window.Minimized
+ onPreviewWantedChanged: Webcam.setPreviewVisible("home", previewWanted)
+ Component.onCompleted: Webcam.setPreviewVisible("home", previewWanted)
+ Component.onDestruction: Webcam.setPreviewVisible("home", false)
Column {
width: parent.width
spacing: 10
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 4c70a3a..623c47c 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -38,7 +38,9 @@ Item {
}
function syncSectionSideEffects() {
- Webcam.setPreviewActive(page.active && (page.currentSection === "camera_audio" || Webcam.phase === "streaming"))
+ Webcam.setPreviewVisible("settings", page.active && page.currentSection === "camera_audio"
+ && page.Window.window !== null && page.Window.window.visible
+ && page.Window.window.visibility !== Window.Minimized)
if (page.active && (page.currentSection === "storage" || page.currentSection === "appearance"))
AppController.refreshDataRetention()
}
@@ -116,7 +118,12 @@ Item {
if (active)
syncSectionSideEffects()
}
- Component.onDestruction: Webcam.setPreviewActive(false)
+ Component.onDestruction: Webcam.setPreviewVisible("settings", false)
+
+ Connections {
+ target: page.Window.window
+ function onVisibilityChanged() { page.syncSectionSideEffects() }
+ }
Connections {
target: DeviceList
diff --git a/desktop/app/src/bridge/webcam.rs b/desktop/app/src/bridge/webcam.rs
index 49277ef..dd78f43 100644
--- a/desktop/app/src/bridge/webcam.rs
+++ b/desktop/app/src/bridge/webcam.rs
@@ -65,6 +65,9 @@ pub mod qobject {
#[qinvokable]
#[cxx_name = "setPreviewActive"]
fn set_preview_active(self: &Webcam, active: bool);
+ #[qinvokable]
+ #[cxx_name = "setPreviewVisible"]
+ fn set_preview_visible(self: &Webcam, owner: &QString, active: bool);
}
}
@@ -171,4 +174,7 @@ impl qobject::Webcam {
pub fn set_preview_active(&self, active: bool) {
webcam::set_preview_active(active);
}
+ pub fn set_preview_visible(&self, owner: &QString, active: bool) {
+ webcam::set_preview_visible(&String::from(owner), active);
+ }
}
diff --git a/desktop/app/src/webcam.rs b/desktop/app/src/webcam.rs
index 88d0fd6..1a402c3 100644
--- a/desktop/app/src/webcam.rs
+++ b/desktop/app/src/webcam.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Phone as a webcam (`docs/protocol/webcam.md`): decodes a phone's H.264
-//! camera stream on a dedicated thread, publishes BGRX frames into the
-//! shared-memory mapping read by `nectarlink_vcam.dll` (the global one the
+//! camera stream on a dedicated thread, publishes shared GPU NV12 textures or
+//! fallback BGRX frames into the mapping read by `nectarlink_vcam.dll` (the global one the
//! camera creates inside Windows' Frame Server, or this session's while it
//! isn't there), and feeds the live preview `VideoView` (`stream:
//! "webcam"`) in Settings.
@@ -92,6 +92,21 @@ static HEIGHT: AtomicU32 = AtomicU32::new(720);
/// (offered until a phone says it can't).
static UHD: AtomicBool = AtomicBool::new(true);
static PREVIEW_ACTIVE: AtomicBool = AtomicBool::new(false);
+struct PreviewRequests(AtomicU32);
+impl PreviewRequests {
+ fn set(&self, bit: u32, requested: bool) -> bool {
+ let mask = if requested {
+ self.0.fetch_or(bit, Ordering::AcqRel) | bit
+ } else {
+ self.0.fetch_and(!bit, Ordering::AcqRel) & !bit
+ };
+ mask != 0
+ }
+ fn clear(&self) {
+ self.0.store(0, Ordering::Release);
+ }
+}
+static PREVIEW_DEMAND: PreviewRequests = PreviewRequests(AtomicU32::new(0));
fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {
f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
@@ -443,6 +458,22 @@ fn refresh_idle_frame() {
/// Marks whether the Settings webcam preview is on screen so the idle
/// placeholder image is only held while needed.
pub fn set_preview_active(active: bool) {
+ set_preview_demand(1, active);
+}
+
+/// Each view owns its request so hiding one cannot turn off another visible
+/// preview. Window visibility participates in the QML demand expression.
+pub fn set_preview_visible(owner: &str, active: bool) {
+ let bit = match owner {
+ "home" => 2,
+ "settings" => 4,
+ _ => return,
+ };
+ set_preview_demand(bit, active);
+}
+
+fn set_preview_demand(bit: u32, requested: bool) {
+ let active = PREVIEW_DEMAND.set(bit, requested);
let prev = PREVIEW_ACTIVE.swap(active, Ordering::AcqRel);
if active && !prev {
refresh_idle_frame();
@@ -457,6 +488,7 @@ pub fn set_preview_active(active: bool) {
/// Releases the idle preview image and any local-only shared mapping when the
/// main window closes to the tray.
pub fn release_idle_resources() {
+ PREVIEW_DEMAND.clear();
PREVIEW_ACTIVE.store(false, Ordering::Release);
let is_streaming = state(|s| {
let streaming = matches!(s.phase, Phase::Streaming { .. });
@@ -648,12 +680,17 @@ impl WebcamSink for Sink {
fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
let Some(video) = self.video.get() else { return };
+ // Count before publishing: the receiver may consume immediately.
+ video.waiting.fetch_add(1, Ordering::AcqRel);
match video.queue.try_send(Item::Packet { keyframe, time_us, data }) {
- Ok(()) => {
- video.waiting.fetch_add(1, Ordering::AcqRel);
+ Ok(()) => {}
+ Err(TrySendError::Disconnected(_)) => {
+ video.waiting.fetch_sub(1, Ordering::AcqRel);
+ }
+ Err(TrySendError::Full(_)) => {
+ video.waiting.fetch_sub(1, Ordering::AcqRel);
+ self.keyframe_please();
}
- Err(TrySendError::Disconnected(_)) => {}
- Err(TrySendError::Full(_)) => self.keyframe_please(),
}
}
@@ -704,6 +741,10 @@ fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
let mut need_keyframe = true;
let mut local_mapping = mapping();
let mut last_mapping_check = Instant::now();
+ #[cfg(windows)]
+ let mut gpu_publisher = nectarlink_vcam::gpu::GpuPublisher::new();
+ #[cfg(windows)]
+ let mut shared_transport = false;
while let Ok(item) = items.recv() {
match item {
@@ -720,7 +761,11 @@ fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
continue;
}
need_keyframe = false;
- let pictures = match decoder.decode(&data, time_us) {
+ #[cfg(windows)]
+ let decoded = decoder.decode_frames(&data, time_us);
+ #[cfg(not(windows))]
+ let decoded = decoder.decode(&data, time_us);
+ let pictures = match decoded {
Ok(pictures) => pictures,
Err(e) => {
tracing::debug!(error = %e, "webcam packet didn't decode");
@@ -736,8 +781,54 @@ fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
if src_w == 0 || src_h == 0 {
continue;
}
- let mut bgrx = to_bgrx(picture, w, h);
let flip = mirror();
+ let preview = PREVIEW_ACTIVE.load(Ordering::Relaxed);
+ #[cfg(not(windows))]
+ let published = false;
+ #[cfg(windows)]
+ let published = if !flip {
+ match picture.gpu_surface() {
+ Ok(Some((texture, index))) => match gpu_publisher.publish(
+ &texture,
+ index,
+ &picture.sample,
+ (src_w, src_h),
+ picture.colors.bt601,
+ picture.colors.full_range,
+ ) {
+ Ok(published) => published,
+ Err(error) => {
+ tracing::warn!(%error,"GPU webcam sharing unavailable; using CPU frames");
+ gpu_publisher.disable();
+ false
+ }
+ },
+ _ => false,
+ }
+ } else {
+ false
+ };
+ #[cfg(windows)]
+ if shared_transport != published {
+ tracing::info!(shared_textures = published, "webcam transport changed");
+ shared_transport = published;
+ }
+ if published && !preview {
+ continue;
+ }
+ #[cfg(windows)]
+ let cpu_picture = match decoder.read_frame(picture) {
+ Ok(picture) => picture,
+ Err(error) => {
+ tracing::warn!(%error,"webcam frame readback failed");
+ need_keyframe = true;
+ keyframe_please();
+ continue;
+ }
+ };
+ #[cfg(windows)]
+ let picture = &cpu_picture;
+ let mut bgrx = to_bgrx(picture, w, h);
if flip {
mirror_bgrx_in_place(&mut bgrx, src_w, src_h);
}
@@ -745,17 +836,27 @@ fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
local_mapping = mapping();
last_mapping_check = Instant::now();
}
- if let Some(ref map) = local_mapping {
+ if !published && let Some(ref map) = local_mapping {
// Already flipped in place if `flip` is true, so pass `false` here.
map.write_frame(&phone_name, src_w, src_h, time_us, &bgrx, false);
}
- ffi::video_frame(PREVIEW_STREAM, src_w, src_h, &bgrx);
+ // Publish the CPU fallback before deselecting the previous
+ // GPU frame so a transport switch cannot expose an idle gap.
+ #[cfg(windows)]
+ if !published {
+ gpu_publisher.idle();
+ }
+ if preview {
+ ffi::video_frame(PREVIEW_STREAM, src_w, src_h, &bgrx);
+ }
}
}
Item::Ended => break,
}
}
+ #[cfg(windows)]
+ drop(gpu_publisher);
state(|s| {
if matches!(s.phase, Phase::Streaming { device: d, .. } if d == device) {
s.phase = Phase::Idle;
@@ -769,6 +870,18 @@ fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
mod tests {
use super::*;
+ #[test]
+ fn hiding_one_preview_does_not_disable_another_visible_view() {
+ let requests = PreviewRequests(AtomicU32::new(0));
+ assert!(requests.set(2, true));
+ assert!(requests.set(4, true));
+ assert!(requests.set(2, false));
+ assert!(!requests.set(4, false));
+ assert!(requests.set(2, true));
+ requests.clear();
+ assert!(!requests.set(4, false));
+ }
+
#[test]
fn maps_720_1080_and_2160_4k_dimensions() {
assert_eq!(dimensions("720"), (1280, 720));
diff --git a/desktop/app/src/win/h264.rs b/desktop/app/src/win/h264.rs
index ee12daf..6dc92c1 100644
--- a/desktop/app/src/win/h264.rs
+++ b/desktop/app/src/win/h264.rs
@@ -52,6 +52,27 @@ pub struct Picture {
pub colors: Colors,
}
+/// A decoder-owned sample retained until the consumer finishes using its GPU
+/// surface. Materializing CPU pixels is optional and explicit.
+#[derive(Debug)]
+pub struct DecodedFrame {
+ pub sample: IMFSample,
+ pub width: u32,
+ pub height: u32,
+ pub colors: Colors,
+}
+impl DecodedFrame {
+ pub fn gpu_surface(&self) -> windows::core::Result<Option<(ID3D11Texture2D, u32)>> {
+ unsafe {
+ let buffer = self.sample.GetBufferByIndex(0)?;
+ let Ok(dxgi) = buffer.cast::<IMFDXGIBuffer>() else { return Ok(None) };
+ let mut texture: Option<ID3D11Texture2D> = None;
+ dxgi.GetResource(&ID3D11Texture2D::IID, std::ptr::from_mut(&mut texture).cast())?;
+ texture.map(|t| dxgi.GetSubresourceIndex().map(|i| (t, i))).transpose()
+ }
+ }
+}
+
/// The YUV-to-RGB formula a stream uses (its VUI, as the decoder reports
/// it). Phones are asked for BT.709 limited range, but not all comply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -330,6 +351,13 @@ impl Decoder {
/// rest of the stream and returns the error: the caller starts over from
/// the next keyframe, as after any decoding error.
pub fn decode(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<Picture>> {
+ let frames = self.decode_frames(data, time_us)?;
+ frames.iter().map(|frame| self.read_frame(frame)).collect()
+ }
+
+ /// Decode without reading GPU pixels back. Reference frames are still
+ /// decoded even when the caller discards their output to catch up.
+ pub fn decode_frames(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<DecodedFrame>> {
let result = self.decode_on(data, time_us);
if result.is_err()
&& self.gpu.is_some()
@@ -341,7 +369,7 @@ impl Decoder {
result
}
- fn decode_on(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<Picture>> {
+ fn decode_on(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<DecodedFrame>> {
let expects_picture = has_slice(&self.codec, data);
// Windows' HEVC decoder holds a picture until the next access unit
// starts, a frame late; ending each one with an access unit
@@ -370,7 +398,7 @@ impl Decoder {
}
}
- fn drain(&mut self, expects_picture: bool) -> windows::core::Result<Vec<Picture>> {
+ fn drain(&mut self, expects_picture: bool) -> windows::core::Result<Vec<DecodedFrame>> {
let mut pictures = Vec::new();
let mut waits = 0u32;
loop {
@@ -399,7 +427,12 @@ impl Decoder {
match result {
Ok(()) => {
if let Some(sample) = sample {
- pictures.push(self.picture(&sample)?);
+ pictures.push(DecodedFrame {
+ sample,
+ width: self.coded.0,
+ height: self.coded.1,
+ colors: self.colors,
+ });
}
}
Err(e) if e.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => {
@@ -422,19 +455,31 @@ impl Decoder {
}
}
- fn picture(&mut self, sample: &IMFSample) -> windows::core::Result<Picture> {
- let (width, height) = self.coded;
+ pub fn read_frame(&mut self, frame: &DecodedFrame) -> windows::core::Result<Picture> {
+ let result = self.picture(frame);
+ if result.is_err()
+ && self.gpu.is_some()
+ && let Ok(software) = Self::create(&self.codec, false)
+ {
+ tracing::info!("GPU video readback failed; decoding in software");
+ *self = software;
+ }
+ result
+ }
+
+ fn picture(&mut self, frame: &DecodedFrame) -> windows::core::Result<Picture> {
+ let (width, height) = (frame.width, frame.height);
+ let colors = frame.colors;
+ let sample = &frame.sample;
// SAFETY: the buffer is locked while it's read and unlocked after.
unsafe {
let buffer = sample.ConvertToContiguousBuffer()?;
- if self.gpu.is_some()
- && let Ok(dxgi) = buffer.cast::<IMFDXGIBuffer>()
- {
+ if let Ok(dxgi) = buffer.cast::<IMFDXGIBuffer>() {
let mut texture: Option<ID3D11Texture2D> = None;
dxgi.GetResource(&ID3D11Texture2D::IID, std::ptr::from_mut(&mut texture).cast())?;
let texture = texture.ok_or_else(|| windows::core::Error::from(E_FAIL))?;
let index = dxgi.GetSubresourceIndex()?;
- return self.read_texture(&texture, index, width, height);
+ return self.read_texture(&texture, index, width, height, colors);
}
if let Ok(two_d) = buffer.cast::<IMF2DBuffer>() {
let mut scan0 = std::ptr::null_mut();
@@ -445,7 +490,7 @@ impl Decoder {
let len = stride * rows * 3 / 2;
let nv12 = std::slice::from_raw_parts(scan0, len).to_vec();
two_d.Unlock2D()?;
- return Ok(Picture { width, height, stride, plane_rows: rows, nv12, colors: self.colors });
+ return Ok(Picture { width, height, stride, plane_rows: rows, nv12, colors });
}
let mut data = std::ptr::null_mut();
let mut length = 0;
@@ -454,7 +499,7 @@ impl Decoder {
buffer.Unlock()?;
let stride = width as usize;
let plane_rows = (nv12.len() * 2 / 3) / stride.max(1);
- Ok(Picture { width, height, stride, plane_rows, nv12, colors: self.colors })
+ Ok(Picture { width, height, stride, plane_rows, nv12, colors })
}
}
}
@@ -469,6 +514,7 @@ impl Decoder {
index: u32,
width: u32,
height: u32,
+ colors: Colors,
) -> windows::core::Result<Picture> {
// SAFETY: Direct3D calls on the decoder's own device; the staging
// texture is mapped while it's read and unmapped after.
@@ -508,7 +554,7 @@ impl Decoder {
let len = stride * plane_rows * 3 / 2;
let nv12 = std::slice::from_raw_parts(mapped.pData.cast::<u8>(), len).to_vec();
context.Unmap(staging, 0);
- Ok(Picture { width, height, stride, plane_rows, nv12, colors: self.colors })
+ Ok(Picture { width, height, stride, plane_rows, nv12, colors })
}
}
}
@@ -595,6 +641,33 @@ fn clamp(v: i32) -> u8 {
mod tests {
use super::*;
+ #[test]
+ fn gpu_frames_can_be_discarded_without_readback_then_materialized() {
+ let mut decoder = Decoder::new_gpu("h264").unwrap();
+ let mut count = 0;
+ let mut surfaces = 0;
+ for (i, unit) in test_stream("h264").iter().enumerate() {
+ for frame in decoder.decode_frames(unit, i as u64 * 33_333).unwrap() {
+ count += 1;
+ if frame.gpu_surface().unwrap().is_some() {
+ surfaces += 1;
+ }
+ assert!(decoder.staging.is_none(), "decode_frames must not download discarded frames");
+ if count == 10 {
+ let picture = decoder.read_frame(&frame).unwrap();
+ assert_eq!((picture.width, picture.height), (320, 240));
+ assert!(picture.nv12.len() >= 320 * 240 * 3 / 2);
+ assert_eq!(picture.colors, frame.colors);
+ }
+ }
+ }
+ assert_eq!(count, 10);
+ if decoder.on_gpu() {
+ assert_eq!(surfaces, 10);
+ assert!(decoder.staging.is_some());
+ }
+ }
+
#[test]
#[ignore]
fn bench_to_bgrx_4k() {
@@ -616,6 +689,79 @@ mod tests {
eprintln!("BENCH to_bgrx 4K: {:.1} ms/frame", start.elapsed().as_secs_f64() * 1000.0 / n as f64);
}
+ #[test]
+ fn decoder_sample_pool_survives_sustained_gpu_publication() {
+ let (done, finished) = std::sync::mpsc::channel();
+ let worker = std::thread::spawn(move || {
+ use nectarlink_vcam::gpu::{GpuPublisher, GpuReader};
+ use windows::Win32::Media::MediaFoundation::MFCreateDXGISurfaceBuffer;
+ let mut decoder = Decoder::new_gpu("h264").unwrap();
+ if !decoder.on_gpu() {
+ done.send(()).unwrap();
+ return;
+ }
+ let name = format!("Local\\NectarlinkDecoderPoolTest_{}", std::process::id());
+ let mut reader = GpuReader::new_with_mapping(&name).unwrap();
+ let mut publisher = GpuPublisher::new_with_mapping(&name).unwrap();
+ let mut output = None;
+ let mut count = 0;
+ for _ in 0..20 {
+ for unit in test_stream("h264") {
+ for frame in decoder.decode_frames(unit, count * 33_333).unwrap() {
+ let (texture, index) = frame.gpu_surface().unwrap().unwrap();
+ if output.is_none() {
+ unsafe {
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ texture.GetDesc(&mut desc);
+ desc.ArraySize = 1;
+ desc.MipLevels = 1;
+ desc.BindFlags =
+ windows::Win32::Graphics::Direct3D11::D3D11_BIND_RENDER_TARGET.0 as u32;
+ let mut destination = None;
+ texture
+ .GetDevice()
+ .unwrap()
+ .CreateTexture2D(&desc, None, Some(&mut destination))
+ .unwrap();
+ output = Some(
+ MFCreateDXGISurfaceBuffer(
+ &ID3D11Texture2D::IID,
+ &destination.unwrap(),
+ 0,
+ false,
+ )
+ .unwrap(),
+ );
+ }
+ }
+ assert!(
+ publisher
+ .publish(
+ &texture,
+ index,
+ &frame.sample,
+ (frame.width, frame.height),
+ false,
+ false
+ )
+ .unwrap()
+ );
+ assert!(
+ reader.write_nv12(output.as_ref().unwrap(), frame.width, frame.height).unwrap()
+ );
+ count += 1;
+ }
+ }
+ }
+ assert_eq!(count, 200);
+ assert_eq!(publisher.stats(), Some((200, 0)));
+ assert!(decoder.staging.is_none(), "publication must not download the decoded frames");
+ done.send(()).unwrap();
+ });
+ finished.recv_timeout(std::time::Duration::from_secs(30)).expect("decoder sample pool stalled");
+ worker.join().unwrap();
+ }
+
#[test]
#[ignore]
fn bench_decode_4k() {
diff --git a/desktop/vcam/Cargo.toml b/desktop/vcam/Cargo.toml
index 4297d50..0338201 100644
--- a/desktop/vcam/Cargo.toml
+++ b/desktop/vcam/Cargo.toml
@@ -22,6 +22,10 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows = { workspace = true, features = [
"Win32_Foundation",
+ "Win32_Graphics_Direct3D",
+ "Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Dxgi",
+ "Win32_Graphics_Dxgi_Common",
"Win32_Media_KernelStreaming",
"Win32_Media_MediaFoundation",
"Win32_Security",
diff --git a/desktop/vcam/src/gpu.rs b/desktop/vcam/src/gpu.rs
new file mode 100644
index 0000000..b09f319
--- /dev/null
+++ b/desktop/vcam/src/gpu.rs
@@ -0,0 +1,1124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Optional cross-process NV12 transport. Its separate versioned control mapping
+//! leaves the existing RGB transport usable by older app/DLL combinations.
+//! Each reader owns a stable GPU snapshot. Keyed mutexes protect shared slots;
+//! a busy writer never replaces a completed snapshot with an idle placeholder.
+
+use crate::shm::{MAX_HEIGHT, MAX_WIDTH, SharedFrameMapping, fit_bgrx_aspect, fit_nv12_aspect};
+use std::{
+ sync::atomic::{AtomicU64, Ordering},
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
+};
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, E_FAIL, E_INVALIDARG, HANDLE, HLOCAL, LUID, LocalFree, S_OK},
+ Graphics::{
+ Direct3D::D3D_DRIVER_TYPE_UNKNOWN,
+ Direct3D11::*,
+ Dxgi::{Common::*, *},
+ },
+ Media::MediaFoundation::{
+ IMF2DBuffer2, IMFDXGIBuffer, IMFMediaBuffer, IMFSample, MF2DBuffer_LockFlags_Write,
+ },
+ Security::{
+ Authorization::{ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1},
+ PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
+ },
+ },
+ core::{HSTRING, Interface},
+};
+
+const GLOBAL: &str = "Global\\NectarlinkVcamGpu_v1";
+const LOCAL: &str = "Local\\NectarlinkVcamGpu_v1";
+const ACCESS: u32 = DXGI_SHARED_RESOURCE_READ.0 | DXGI_SHARED_RESOURCE_WRITE.0;
+static NEXT_EPOCH: AtomicU64 = AtomicU64::new(0);
+#[path = "gpu_scale.rs"]
+mod video_scale;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct Descriptor {
+ pid: u32,
+ slot: u32,
+ epoch: u64,
+ coded_w: u32,
+ coded_h: u32,
+ width: u32,
+ height: u32,
+ colors: u32,
+ frame: u64,
+ adapter: u64,
+}
+impl Descriptor {
+ fn bytes(self) -> Vec<u8> {
+ let mut b = Vec::with_capacity(56);
+ for n in [self.pid, self.slot] {
+ b.extend(n.to_le_bytes());
+ }
+ b.extend(self.epoch.to_le_bytes());
+ for n in [self.coded_w, self.coded_h, self.width, self.height, self.colors, 0] {
+ b.extend(n.to_le_bytes());
+ }
+ b.extend(self.frame.to_le_bytes());
+ b.extend(self.adapter.to_le_bytes());
+ b
+ }
+ fn parse(b: &[u8]) -> Option<Self> {
+ if b.len() != 56 {
+ return None;
+ }
+ let u32_at = |at| u32::from_le_bytes(b[at..at + 4].try_into().unwrap());
+ let d = Self {
+ pid: u32_at(0),
+ slot: u32_at(4),
+ epoch: u64::from_le_bytes(b[8..16].try_into().unwrap()),
+ coded_w: u32_at(16),
+ coded_h: u32_at(20),
+ width: u32_at(24),
+ height: u32_at(28),
+ colors: u32_at(32),
+ frame: u64::from_le_bytes(b[40..48].try_into().unwrap()),
+ adapter: u64::from_le_bytes(b[48..56].try_into().unwrap()),
+ };
+ (d.pid != 0
+ && d.slot < 3
+ && d.width > 0
+ && d.height > 0
+ && d.width.is_multiple_of(2)
+ && d.height.is_multiple_of(2)
+ && d.width <= d.coded_w
+ && d.height <= d.coded_h
+ && d.coded_w <= MAX_WIDTH
+ && d.coded_h <= MAX_HEIGHT + 32
+ && d.coded_w.is_multiple_of(2)
+ && d.coded_h.is_multiple_of(2)
+ && d.colors <= 3)
+ .then_some(d)
+ }
+ fn name(self) -> HSTRING {
+ HSTRING::from(format!("Global\\NectarlinkVcamGpu_{}_{}_{}", self.pid, self.epoch, self.slot))
+ }
+}
+
+// AcquireSync returns positive WAIT_TIMEOUT/WAIT_ABANDONED codes, which the
+// generated Result wrapper treats as success. Only S_OK grants ownership.
+#[allow(unsafe_code)]
+fn acquire(mutex: &IDXGIKeyedMutex, key: u64) -> windows::core::Result<bool> {
+ let status = unsafe { (mutex.vtable().AcquireSync)(mutex.as_raw(), key, 0) };
+ if status == S_OK {
+ Ok(true)
+ } else if status.0 == 258 {
+ Ok(false)
+ } else if status.is_err() {
+ Err(windows::core::Error::from_hresult(status))
+ } else {
+ Err(E_FAIL.into())
+ }
+}
+
+#[cfg(test)]
+#[allow(unsafe_code)]
+fn device() -> windows::core::Result<ID3D11Device> {
+ use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_HARDWARE;
+ let mut device = None;
+ unsafe {
+ D3D11CreateDevice(
+ None,
+ D3D_DRIVER_TYPE_HARDWARE,
+ Default::default(),
+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ None,
+ )?;
+ }
+ device.ok_or_else(|| E_FAIL.into())
+}
+
+#[allow(unsafe_code)]
+fn adapter_luid(device: &ID3D11Device) -> windows::core::Result<u64> {
+ let luid = unsafe { device.cast::<IDXGIDevice>()?.GetAdapter()?.GetDesc()?.AdapterLuid };
+ Ok(u64::from(luid.LowPart) | ((luid.HighPart as u32 as u64) << 32))
+}
+
+#[allow(unsafe_code)]
+fn device_for_adapter(luid: u64) -> windows::core::Result<ID3D11Device> {
+ unsafe {
+ let factory: IDXGIFactory4 = CreateDXGIFactory1()?;
+ let adapter: IDXGIAdapter =
+ factory.EnumAdapterByLuid(LUID { LowPart: luid as u32, HighPart: (luid >> 32) as i32 })?;
+ let mut device = None;
+ D3D11CreateDevice(
+ &adapter,
+ D3D_DRIVER_TYPE_UNKNOWN,
+ Default::default(),
+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ None,
+ )?;
+ let device = device.ok_or(E_FAIL)?;
+ if let Ok(multithread) = device.cast::<ID3D11Multithread>() {
+ let _ = multithread.SetMultithreadProtected(true);
+ }
+ Ok(device)
+ }
+}
+
+struct SharedSlot {
+ texture: ID3D11Texture2D,
+ mutex: IDXGIKeyedMutex,
+ handle: HANDLE,
+ initialized: bool,
+ source: Option<IMFSample>,
+}
+impl Drop for SharedSlot {
+ #[allow(unsafe_code)]
+ fn drop(&mut self) {
+ unsafe {
+ let _ = CloseHandle(self.handle);
+ }
+ }
+}
+
+/// Publisher belongs exclusively to the webcam decoder thread.
+pub struct GpuPublisher {
+ mapping: Option<SharedFrameMapping>,
+ mapping_global: bool,
+ slots: Vec<SharedSlot>,
+ shape: Option<(u32, u32, usize)>,
+ epoch: u64,
+ frame: u64,
+ next: usize,
+ checked: Option<Instant>,
+ unavailable: bool,
+}
+impl std::fmt::Debug for GpuPublisher {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GpuPublisher").field("shape", &self.shape).field("frame", &self.frame).finish()
+ }
+}
+impl Default for GpuPublisher {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+impl GpuPublisher {
+ pub fn new() -> Self {
+ Self {
+ mapping: None,
+ mapping_global: false,
+ slots: Vec::new(),
+ shape: None,
+ epoch: 0,
+ frame: 0,
+ next: 0,
+ checked: None,
+ unavailable: false,
+ }
+ }
+ pub fn idle(&self) {
+ if let Some(m) = &self.mapping {
+ m.set_idle("");
+ }
+ }
+ /// Join a dedicated control mapping, for isolated transports and tests.
+ pub fn new_with_mapping(name: &str) -> windows::core::Result<Self> {
+ let mut publisher = Self::new();
+ publisher.mapping = Some(SharedFrameMapping::open_existing_control(name)?);
+ publisher.mapping_global = true;
+ Ok(publisher)
+ }
+ pub fn disable(&mut self) {
+ self.unavailable = true;
+ }
+ /// Counts observed by consumers, useful for verifying which allocator path
+ /// Windows selected without logging per-frame data or saving camera images.
+ pub fn stats(&self) -> Option<(u32, u32)> {
+ self.mapping.as_ref().map(|m| m.control_stats())
+ }
+ pub fn failure_code(&self) -> Option<i32> {
+ self.mapping.as_ref().map(|m| m.control_code()).filter(|code| *code != 0)
+ }
+ /// Returns false to request the existing CPU/RGB fallback. No camera client
+ /// (or an old DLL) is a normal case, not a fatal decoder error.
+ #[allow(unsafe_code)]
+ pub fn publish(
+ &mut self,
+ texture: &ID3D11Texture2D,
+ index: u32,
+ sample: &IMFSample,
+ dimensions: (u32, u32),
+ bt601: bool,
+ full_range: bool,
+ ) -> windows::core::Result<bool> {
+ let (width, height) = dimensions;
+ if !self.mapping_global && self.checked.is_none_or(|at| at.elapsed() >= Duration::from_secs(1)) {
+ self.checked = Some(Instant::now());
+ if let Ok(global) = SharedFrameMapping::open_existing_control(GLOBAL) {
+ self.idle();
+ self.mapping = Some(global);
+ self.mapping_global = true;
+ self.unavailable = false;
+ } else if self.mapping.is_none() {
+ self.mapping = SharedFrameMapping::open_existing_control(LOCAL).ok();
+ }
+ }
+ if self.unavailable {
+ return Ok(false);
+ }
+ let Some(mapping) = &self.mapping else { return Ok(false) };
+ if mapping.control_failed() {
+ self.unavailable = true;
+ let code = mapping.control_code();
+ let status = windows::core::HRESULT(code);
+ return Err(windows::core::Error::from_hresult(if status.is_err() { status } else { E_FAIL }));
+ }
+ unsafe {
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ texture.GetDesc(&mut desc);
+ if desc.Format != DXGI_FORMAT_NV12
+ || width == 0
+ || height == 0
+ || !width.is_multiple_of(2)
+ || !height.is_multiple_of(2)
+ || width > desc.Width
+ || height > desc.Height
+ || desc.Width > MAX_WIDTH
+ || desc.Height > MAX_HEIGHT + 32
+ {
+ return Ok(false);
+ }
+ let device = texture.GetDevice()?;
+ let shape = (desc.Width, desc.Height, device.as_raw() as usize);
+ if self.shape != Some(shape) {
+ self.idle();
+ self.slots.clear();
+ self.shape = None;
+ self.epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos()
+ as u64
+ ^ NEXT_EPOCH.fetch_add(1, Ordering::Relaxed);
+ let mut sd = PSECURITY_DESCRIPTOR::default();
+ ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ windows::core::w!("D:P(A;;GA;;;SY)(A;;GA;;;LS)(A;;GA;;;BA)(A;;GRGW;;;IU)"),
+ SDDL_REVISION_1,
+ &mut sd,
+ None,
+ )?;
+ let attrs = SECURITY_ATTRIBUTES {
+ nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
+ lpSecurityDescriptor: sd.0,
+ bInheritHandle: false.into(),
+ };
+ let result = (|| -> windows::core::Result<()> {
+ for slot in 0..3 {
+ let descriptor = Descriptor {
+ pid: std::process::id(),
+ slot,
+ epoch: self.epoch,
+ coded_w: desc.Width,
+ coded_h: desc.Height,
+ width,
+ height,
+ colors: 0,
+ frame: 0,
+ adapter: adapter_luid(&device)?,
+ };
+ let mut shared = None;
+ device.CreateTexture2D(
+ &D3D11_TEXTURE2D_DESC {
+ Width: desc.Width,
+ Height: desc.Height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_NV12,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: 0,
+ CPUAccessFlags: 0,
+ MiscFlags: (D3D11_RESOURCE_MISC_SHARED_NTHANDLE
+ | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX)
+ .0 as u32,
+ },
+ None,
+ Some(&mut shared),
+ )?;
+ let shared = shared.ok_or(E_FAIL)?;
+ let mutex = shared.cast()?;
+ let handle = shared.cast::<IDXGIResource1>()?.CreateSharedHandle(
+ Some(&attrs),
+ ACCESS,
+ &descriptor.name(),
+ )?;
+ self.slots.push(SharedSlot {
+ texture: shared,
+ mutex,
+ handle,
+ initialized: false,
+ source: None,
+ });
+ }
+ Ok(())
+ })();
+ let _ = LocalFree(Some(HLOCAL(sd.0)));
+ result?;
+ self.shape = Some(shape);
+ }
+ for _ in 0..self.slots.len() {
+ let slot = self.next;
+ self.next = (self.next + 1) % self.slots.len();
+ let shared = &mut self.slots[slot];
+ if !acquire(&shared.mutex, if shared.initialized { 1 } else { 0 })? {
+ continue;
+ }
+ // Reacquiring the slot also means its previous GPU work finished.
+ // Retaining the decoder sample prevents its surface being recycled.
+ shared.source = Some(sample.clone());
+ let context = device.GetImmediateContext()?;
+ context.CopySubresourceRegion(&shared.texture, 0, 0, 0, 0, texture, index, None);
+ context.Flush();
+ shared.mutex.ReleaseSync(1)?;
+ shared.initialized = true;
+ self.frame = self.frame.wrapping_add(1);
+ let descriptor = Descriptor {
+ pid: std::process::id(),
+ slot: slot as u32,
+ epoch: self.epoch,
+ coded_w: desc.Width,
+ coded_h: desc.Height,
+ width,
+ height,
+ colors: u32::from(bt601) | (u32::from(full_range) << 1),
+ frame: self.frame,
+ adapter: adapter_luid(&device)?,
+ };
+ self.mapping.as_ref().unwrap().write_control(&descriptor.bytes());
+ return Ok(true);
+ }
+ }
+ // All slots busy: retain the last published frame, never flash idle or
+ // force an expensive CPU readback just because a reader owns a slot.
+ Ok(self.frame != 0)
+ }
+}
+impl Drop for GpuPublisher {
+ fn drop(&mut self) {
+ self.idle();
+ }
+}
+
+/// One reader per media source stream. No source pixels are read while another
+/// process may write them; only the reader-owned GPU snapshot is sampled.
+pub struct GpuReader {
+ mapping: SharedFrameMapping,
+ device: Option<ID3D11Device>,
+ unshareable_device: Option<usize>,
+ descriptor: Option<Descriptor>,
+ snapshot: Option<ID3D11Texture2D>,
+ staging: Option<ID3D11Texture2D>,
+ cpu_frame: Option<u64>,
+ cpu: Vec<u8>,
+ rgb_frame: Option<u64>,
+ rgb: Vec<u8>,
+ scaled_key: Option<(Descriptor, u32, u32)>,
+ scaled: Vec<u8>,
+ scaler: Option<video_scale::GpuScaler>,
+}
+impl std::fmt::Debug for GpuReader {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GpuReader").field("descriptor", &self.descriptor).finish()
+ }
+}
+impl GpuReader {
+ pub fn new() -> windows::core::Result<Self> {
+ let mapping = SharedFrameMapping::open_or_create_control(GLOBAL)
+ .or_else(|_| SharedFrameMapping::open_or_create_control(LOCAL))?;
+ Ok(Self::from_mapping(mapping))
+ }
+ /// Uses an isolated metadata mapping without changing the live camera.
+ pub fn new_with_mapping(name: &str) -> windows::core::Result<Self> {
+ Ok(Self::from_mapping(SharedFrameMapping::open_or_create_control(name)?))
+ }
+ fn from_mapping(mapping: SharedFrameMapping) -> Self {
+ Self {
+ mapping,
+ device: None,
+ unshareable_device: None,
+ descriptor: None,
+ snapshot: None,
+ staging: None,
+ cpu_frame: None,
+ cpu: Vec::new(),
+ rgb_frame: None,
+ rgb: Vec::new(),
+ scaled_key: None,
+ scaled: Vec::new(),
+ scaler: None,
+ }
+ }
+ pub fn disable(&mut self) {
+ self.mapping.fail_control();
+ self.descriptor = None;
+ self.snapshot = None;
+ }
+ pub fn disable_with_error(&mut self, error: &windows::core::Error) {
+ self.mapping.fail_control_code(error.code().0);
+ self.descriptor = None;
+ self.snapshot = None;
+ }
+ pub fn active_device(&mut self) -> windows::core::Result<Option<ID3D11Device>> {
+ if self.refresh(None)? { Ok(self.device.clone()) } else { Ok(None) }
+ }
+ #[allow(unsafe_code)]
+ fn refresh(&mut self, preferred: Option<ID3D11Device>) -> windows::core::Result<bool> {
+ if self.mapping.control_failed() {
+ return Ok(false);
+ }
+ let Some((_, bytes)) = self.mapping.read_control() else { return Ok(self.snapshot.is_some()) };
+ if bytes.is_empty() {
+ self.descriptor = None;
+ self.snapshot = None;
+ self.cpu_frame = None;
+ self.rgb_frame = None;
+ return Ok(false);
+ }
+ let next = Descriptor::parse(&bytes).ok_or(E_INVALIDARG)?;
+ let preferred_id = preferred.as_ref().map(|d| d.as_raw() as usize);
+ if let Some(preferred) = preferred
+ && self.unshareable_device != Some(preferred.as_raw() as usize)
+ && adapter_luid(&preferred)? == next.adapter
+ && self.device.as_ref().is_none_or(|d| d.as_raw() != preferred.as_raw())
+ {
+ self.device = Some(preferred);
+ self.snapshot = None;
+ self.staging = None;
+ self.descriptor = None;
+ }
+ if self.descriptor == Some(next) && self.snapshot.is_some() {
+ return Ok(true);
+ }
+ if self.device.as_ref().is_none_or(|device| adapter_luid(device).ok() != Some(next.adapter)) {
+ self.device = Some(device_for_adapter(next.adapter)?);
+ self.snapshot = None;
+ self.staging = None;
+ self.descriptor = None;
+ }
+ let mut device = self.device.as_ref().unwrap().clone();
+ unsafe {
+ let shared: ID3D11Texture2D =
+ match device.cast::<ID3D11Device1>()?.OpenSharedResourceByName(&next.name(), ACCESS) {
+ Ok(shared) => shared,
+ Err(error) if preferred_id == Some(device.as_raw() as usize) => {
+ self.unshareable_device = preferred_id;
+ device = device_for_adapter(next.adapter)?;
+ self.device = Some(device.clone());
+ self.snapshot = None;
+ self.staging = None;
+ self.descriptor = None;
+ device
+ .cast::<ID3D11Device1>()?
+ .OpenSharedResourceByName(&next.name(), ACCESS)
+ .map_err(|_| error)?
+ }
+ Err(error) => return Err(error),
+ };
+ let mutex: IDXGIKeyedMutex = shared.cast()?;
+ if !acquire(&mutex, 1)? {
+ return Ok(self.snapshot.is_some());
+ }
+ let result = (|| -> windows::core::Result<bool> {
+ // Validate the descriptor again after ownership; the slot may have
+ // been replaced while this reader was opening its handle.
+ if self.mapping.read_control().and_then(|(_, b)| Descriptor::parse(&b)) != Some(next) {
+ return Ok(self.snapshot.is_some());
+ }
+ let mut actual = D3D11_TEXTURE2D_DESC::default();
+ shared.GetDesc(&mut actual);
+ if actual.Format != DXGI_FORMAT_NV12
+ || actual.Width != next.coded_w
+ || actual.Height != next.coded_h
+ || actual.ArraySize != 1
+ {
+ return Err(E_INVALIDARG.into());
+ }
+ let same_shape = self
+ .descriptor
+ .is_some_and(|old| old.coded_w == next.coded_w && old.coded_h == next.coded_h);
+ if self.snapshot.is_none() || !same_shape {
+ let mut snapshot = None;
+ device.CreateTexture2D(
+ &D3D11_TEXTURE2D_DESC {
+ Usage: D3D11_USAGE_DEFAULT,
+ MiscFlags: 0,
+ CPUAccessFlags: 0,
+ ..actual
+ },
+ None,
+ Some(&mut snapshot),
+ )?;
+ self.snapshot = snapshot;
+ self.staging = None;
+ }
+ let context = device.GetImmediateContext()?;
+ context.CopySubresourceRegion(self.snapshot.as_ref().unwrap(), 0, 0, 0, 0, &shared, 0, None);
+ context.Flush();
+ self.descriptor = Some(next);
+ self.cpu_frame = None;
+ self.rgb_frame = None;
+ Ok(true)
+ })();
+ let release = mutex.ReleaseSync(1);
+ release?;
+ result
+ }
+ }
+ #[allow(unsafe_code)]
+ fn download(&mut self) -> windows::core::Result<()> {
+ let d = self.descriptor.ok_or(E_FAIL)?;
+ if self.cpu_frame == Some(d.frame) {
+ return Ok(());
+ }
+ unsafe {
+ let device = self.device.as_ref().ok_or(E_FAIL)?;
+ if self.staging.is_none() {
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ self.snapshot.as_ref().ok_or(E_FAIL)?.GetDesc(&mut desc);
+ let mut staging = None;
+ device.CreateTexture2D(
+ &D3D11_TEXTURE2D_DESC {
+ Usage: D3D11_USAGE_STAGING,
+ BindFlags: 0,
+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
+ ..desc
+ },
+ None,
+ Some(&mut staging),
+ )?;
+ self.staging = staging;
+ }
+ let context = device.GetImmediateContext()?;
+ let staging = self.staging.as_ref().unwrap();
+ context.CopySubresourceRegion(staging, 0, 0, 0, 0, self.snapshot.as_ref().unwrap(), 0, None);
+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
+ context.Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
+ let stride = mapped.RowPitch as usize;
+ let width = d.width as usize;
+ let height = d.height as usize;
+ self.cpu.resize(width * height * 3 / 2, 0);
+ for row in 0..height {
+ std::ptr::copy_nonoverlapping(
+ mapped.pData.cast::<u8>().add(row * stride),
+ self.cpu.as_mut_ptr().add(row * width),
+ width,
+ );
+ }
+ let uv = mapped.pData.cast::<u8>().add(stride * d.coded_h as usize);
+ for row in 0..height / 2 {
+ std::ptr::copy_nonoverlapping(
+ uv.add(row * stride),
+ self.cpu.as_mut_ptr().add(width * height + row * width),
+ width,
+ );
+ }
+ context.Unmap(staging, 0);
+ self.cpu_frame = Some(d.frame);
+ self.mapping.count_download();
+ Ok(())
+ }
+ }
+ /// Native NV12 output, using GPU copies when the allocator provides a DXGI
+ /// surface and one readback otherwise. No RGB round trip for matching modes.
+ #[allow(unsafe_code)]
+ pub fn write_nv12(
+ &mut self,
+ buffer: &IMFMediaBuffer,
+ width: u32,
+ height: u32,
+ ) -> windows::core::Result<bool> {
+ unsafe {
+ let destination = if let Ok(dxgi) = buffer.cast::<IMFDXGIBuffer>() {
+ let mut texture: Option<ID3D11Texture2D> = None;
+ dxgi.GetResource(&ID3D11Texture2D::IID, std::ptr::from_mut(&mut texture).cast())?;
+ texture.map(|t| dxgi.GetSubresourceIndex().map(|i| (t, i))).transpose()?
+ } else {
+ None
+ };
+ let preferred = destination.as_ref().map(|(t, _)| t.GetDevice()).transpose()?;
+ if !self.refresh(preferred)? {
+ return Ok(false);
+ }
+ let d = self.descriptor.ok_or(E_FAIL)?;
+ // Different colorimetry is normalized via the RGB fallback.
+ if d.colors != 0
+ || width == 0
+ || height == 0
+ || !width.is_multiple_of(2)
+ || !height.is_multiple_of(2)
+ {
+ return Ok(false);
+ }
+ if let Some((destination, index)) = destination
+ && self.device.as_ref().is_some_and(|device| {
+ destination.GetDevice().is_ok_and(|d| d.as_raw() == device.as_raw())
+ })
+ {
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ destination.GetDesc(&mut desc);
+ if desc.Format != DXGI_FORMAT_NV12 || desc.Width < width || desc.Height < height {
+ return Ok(false);
+ }
+ if (d.width, d.height) != (width, height) {
+ let device = self.device.as_ref().ok_or(E_FAIL)?;
+ if self
+ .scaler
+ .as_ref()
+ .is_none_or(|s| !s.matches(device, (d.coded_w, d.coded_h), (width, height)))
+ {
+ self.scaler =
+ video_scale::GpuScaler::new(device, (d.coded_w, d.coded_h), (width, height)).ok();
+ }
+ if let Some(scaler) = &self.scaler
+ && scaler
+ .blit(
+ self.snapshot.as_ref().ok_or(E_FAIL)?,
+ &destination,
+ index,
+ (d.width, d.height),
+ )
+ .is_ok()
+ {
+ self.mapping.count_gpu_sample();
+ return Ok(true);
+ }
+ } else {
+ let context = destination.GetDevice()?.GetImmediateContext()?;
+ let region =
+ D3D11_BOX { left: 0, top: 0, front: 0, right: width, bottom: height, back: 1 };
+ context.CopySubresourceRegion(
+ &destination,
+ index,
+ 0,
+ 0,
+ 0,
+ self.snapshot.as_ref().ok_or(E_FAIL)?,
+ 0,
+ Some(&region),
+ );
+ context.Flush();
+ self.mapping.count_gpu_sample();
+ return Ok(true);
+ }
+ }
+ self.download()?;
+ let data = if (d.width, d.height) == (width, height) {
+ &self.cpu
+ } else {
+ if self.scaled_key != Some((d, width, height)) {
+ self.scaled.resize(width as usize * height as usize * 3 / 2, 0);
+ if !fit_nv12_aspect(&self.cpu, d.width, d.height, &mut self.scaled, width, height) {
+ return Err(E_INVALIDARG.into());
+ }
+ self.scaled_key = Some((d, width, height));
+ }
+ &self.scaled
+ };
+ if let Ok(two_d) = buffer.cast::<IMF2DBuffer2>() {
+ let mut ptr = std::ptr::null_mut();
+ let mut pitch = 0i32;
+ let mut start = std::ptr::null_mut();
+ let mut len = 0;
+ two_d.Lock2DSize(MF2DBuffer_LockFlags_Write, &mut ptr, &mut pitch, &mut start, &mut len)?;
+ let stride = pitch.unsigned_abs() as usize;
+ let w = width as usize;
+ let h = height as usize;
+ let end = (ptr as usize)
+ .checked_sub(start as usize)
+ .and_then(|offset| offset.checked_add(stride * h * 3 / 2));
+ let result: windows::core::Result<()> = if pitch <= 0
+ || stride < w
+ || end.is_none_or(|end| end > len as usize)
+ || start.is_null()
+ || ptr.is_null()
+ {
+ Err(E_INVALIDARG.into())
+ } else {
+ for row in 0..h {
+ std::ptr::copy_nonoverlapping(data.as_ptr().add(row * w), ptr.add(row * stride), w);
+ }
+ for row in 0..h / 2 {
+ std::ptr::copy_nonoverlapping(
+ data.as_ptr().add(w * h + row * w),
+ ptr.add(stride * h + row * stride),
+ w,
+ );
+ }
+ Ok(())
+ };
+ let unlock = two_d.Unlock2D();
+ unlock?;
+ result?;
+ } else {
+ if (buffer.GetMaxLength()? as usize) < data.len() {
+ return Err(E_INVALIDARG.into());
+ }
+ let mut ptr = std::ptr::null_mut();
+ buffer.Lock(&mut ptr, None, None)?;
+ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr, data.len());
+ buffer.Unlock()?;
+ buffer.SetCurrentLength(data.len() as u32)?;
+ }
+ Ok(true)
+ }
+ }
+ /// CPU fallback for RGB clients, scaled output, or nonstandard source colors.
+ pub fn read_bgrx(&mut self, width: u32, height: u32, out: &mut [u8]) -> windows::core::Result<bool> {
+ if !self.refresh(None)? {
+ return Ok(false);
+ }
+ self.download()?;
+ let d = self.descriptor.ok_or(E_FAIL)?;
+ if self.rgb_frame != Some(d.frame) {
+ let w = d.width as usize;
+ let h = d.height as usize;
+ self.rgb.resize(w * h * 4, 0);
+ let full = d.colors & 2 != 0;
+ let bt601 = d.colors & 1 != 0;
+ let (vr, ug, vg, ub) = match (bt601, full) {
+ (false, false) => (459, 55, 136, 541),
+ (false, true) => (403, 48, 120, 475),
+ (true, false) => (409, 100, 208, 516),
+ (true, true) => (359, 88, 183, 454),
+ };
+ let cpu = &self.cpu;
+ let convert = |first: usize, output: &mut [u8]| {
+ for (row, line) in output.chunks_exact_mut(w * 4).enumerate() {
+ let y = first + row;
+ for x in 0..w {
+ let l = (i32::from(cpu[y * w + x]) - if full { 0 } else { 16 })
+ * if full { 256 } else { 298 };
+ let uv = w * h + (y / 2) * w + (x & !1);
+ let u = i32::from(cpu[uv]) - 128;
+ let v = i32::from(cpu[uv + 1]) - 128;
+ let at = x * 4;
+ line[at] = ((l + ub * u + 128) >> 8).clamp(0, 255) as u8;
+ line[at + 1] = ((l - ug * u - vg * v + 128) >> 8).clamp(0, 255) as u8;
+ line[at + 2] = ((l + vr * v + 128) >> 8).clamp(0, 255) as u8;
+ line[at + 3] = 255;
+ }
+ }
+ };
+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get()).min(8);
+ if w * h >= 1920 * 1080 && cores > 1 {
+ let band = h.div_ceil(cores).next_multiple_of(2);
+ std::thread::scope(|scope| {
+ for (i, rows) in self.rgb.chunks_mut(band * w * 4).enumerate() {
+ let convert = &convert;
+ scope.spawn(move || convert(i * band, rows));
+ }
+ });
+ } else {
+ convert(0, &mut self.rgb);
+ }
+ self.rgb_frame = Some(d.frame);
+ }
+ let needed = width as usize * height as usize * 4;
+ if out.len() < needed {
+ return Err(E_INVALIDARG.into());
+ }
+ if (width, height) == (d.width, d.height) {
+ out[..needed].copy_from_slice(&self.rgb);
+ } else {
+ fit_bgrx_aspect(&self.rgb, d.width, d.height, &mut out[..needed], width, height);
+ }
+ Ok(true)
+ }
+}
+
+#[cfg(test)]
+#[allow(unsafe_code)]
+mod tests {
+ use super::*;
+ use std::os::windows::process::CommandExt;
+ use windows::Win32::Media::MediaFoundation::{
+ IMF2DBuffer, MF_VERSION, MFCreate2DMediaBuffer, MFCreateDXGISurfaceBuffer, MFCreateSample,
+ MFSTARTUP_NOSOCKET, MFStartup, MFVideoFormat_NV12,
+ };
+ static TEST_ID: AtomicU64 = AtomicU64::new(0);
+
+ fn pair() -> (GpuPublisher, GpuReader) {
+ let name = format!(
+ "Local\\NectarlinkGpuTest_{}_{}",
+ std::process::id(),
+ TEST_ID.fetch_add(1, Ordering::Relaxed)
+ );
+ let mapping = SharedFrameMapping::open_or_create_control(&name).unwrap();
+ let mut publisher = GpuPublisher::new();
+ publisher.mapping = Some(SharedFrameMapping::open_existing_control(&name).unwrap());
+ publisher.mapping_global = true;
+ let reader = GpuReader {
+ mapping,
+ device: None,
+ unshareable_device: None,
+ descriptor: None,
+ snapshot: None,
+ staging: None,
+ cpu_frame: None,
+ cpu: Vec::new(),
+ rgb_frame: None,
+ rgb: Vec::new(),
+ scaled_key: None,
+ scaled: Vec::new(),
+ scaler: None,
+ };
+ unsafe {
+ MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET).unwrap();
+ }
+ (publisher, reader)
+ }
+ fn texture(device: &ID3D11Device, w: u32, h: u32, y: u8) -> (ID3D11Texture2D, IMFSample) {
+ unsafe {
+ let mut data = vec![128u8; (w * h * 3 / 2) as usize];
+ data[..(w * h) as usize].fill(y);
+ let mut texture = None;
+ device
+ .CreateTexture2D(
+ &D3D11_TEXTURE2D_DESC {
+ Width: w,
+ Height: h,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_NV12,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ },
+ Some(&D3D11_SUBRESOURCE_DATA {
+ pSysMem: data.as_ptr().cast(),
+ SysMemPitch: w,
+ SysMemSlicePitch: data.len() as u32,
+ }),
+ Some(&mut texture),
+ )
+ .unwrap();
+ let texture = texture.unwrap();
+ let sample = MFCreateSample().unwrap();
+ sample
+ .AddBuffer(&MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID, &texture, 0, false).unwrap())
+ .unwrap();
+ (texture, sample)
+ }
+ }
+ fn cpu_buffer(w: u32, h: u32) -> IMFMediaBuffer {
+ unsafe { MFCreate2DMediaBuffer(w, h, MFVideoFormat_NV12.data1, false).unwrap() }
+ }
+ fn pixels(buffer: &IMFMediaBuffer) -> Vec<u8> {
+ unsafe {
+ let b: IMF2DBuffer = buffer.cast().unwrap();
+ let mut bytes = vec![0; b.GetContiguousLength().unwrap() as usize];
+ b.ContiguousCopyTo(&mut bytes).unwrap();
+ bytes
+ }
+ }
+
+ #[test]
+ fn shared_gpu_cpu_output_contention_stop_and_padded_height() {
+ let (mut publisher, mut reader) = pair();
+ let device = device().unwrap();
+ let (a, sa) = texture(&device, 160, 128, 80);
+ let out = cpu_buffer(160, 120);
+ assert!(publisher.publish(&a, 0, &sa, (160, 120), false, false).unwrap());
+ assert!(reader.write_nv12(&out, 160, 120).unwrap());
+ let data = pixels(&out);
+ assert!(data[..160 * 120].iter().all(|b| *b == 80));
+ assert!(data[160 * 120..].iter().all(|b| *b == 128));
+ let (b, sb) = texture(&device, 160, 128, 160);
+ assert!(publisher.publish(&b, 0, &sb, (160, 120), false, false).unwrap());
+ let d = Descriptor::parse(&publisher.mapping.as_ref().unwrap().read_control().unwrap().1).unwrap();
+ let mutex = &publisher.slots[d.slot as usize].mutex;
+ assert!(acquire(mutex, 1).unwrap());
+ let peer: ID3D11Texture2D = unsafe {
+ reader
+ .device
+ .as_ref()
+ .unwrap()
+ .cast::<ID3D11Device1>()
+ .unwrap()
+ .OpenSharedResourceByName(&d.name(), ACCESS)
+ .unwrap()
+ };
+ assert!(!acquire(&peer.cast().unwrap(), 1).unwrap());
+ assert!(reader.write_nv12(&out, 160, 120).unwrap());
+ assert!(pixels(&out)[..160 * 120].iter().all(|b| *b == 80));
+ unsafe {
+ mutex.ReleaseSync(1).unwrap();
+ }
+ assert!(reader.write_nv12(&out, 160, 120).unwrap());
+ assert!(pixels(&out)[..160 * 120].iter().all(|b| *b == 160));
+ publisher.idle();
+ assert!(!reader.write_nv12(&out, 160, 120).unwrap());
+ }
+ #[test]
+ fn shared_gpu_to_allocator_gpu_surface_preserves_pixels() {
+ let (mut publisher, mut reader) = pair();
+ let producer = device().unwrap();
+ let consumer = device().unwrap();
+ let (src, sample) = texture(&producer, 160, 128, 90);
+ assert!(publisher.publish(&src, 0, &sample, (160, 120), false, false).unwrap());
+ let (dst, _) = texture(&consumer, 160, 120, 16);
+ let buffer = unsafe { MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID, &dst, 0, false).unwrap() };
+ assert!(reader.write_nv12(&buffer, 160, 120).unwrap());
+ assert!(reader.cpu.is_empty(), "GPU output must not read pixels back to the CPU");
+ let data = pixels(&buffer);
+ assert!(data[..160 * 120].iter().all(|b| *b == 90));
+ assert!(data[160 * 120..].iter().all(|b| *b == 128));
+ }
+ #[test]
+ fn nonstandard_colors_and_scaled_rgb_clients_keep_a_cpu_fallback() {
+ let (mut publisher, mut reader) = pair();
+ let producer = device().unwrap();
+ let (src, sample) = texture(&producer, 160, 120, 16);
+ assert!(publisher.publish(&src, 0, &sample, (160, 120), true, true).unwrap());
+ assert!(!reader.write_nv12(&cpu_buffer(160, 120), 160, 120).unwrap());
+ let mut rgb = vec![0; 160 * 120 * 4];
+ assert!(reader.read_bgrx(160, 120, &mut rgb).unwrap());
+ assert_eq!(&rgb[..4], &[16, 16, 16, 255]);
+ let mut scaled = vec![0; 320 * 240 * 4];
+ assert!(reader.read_bgrx(320, 240, &mut scaled).unwrap());
+ assert_eq!(&scaled[..4], &[16, 16, 16, 255]);
+ reader.disable();
+ assert!(publisher.publish(&src, 0, &sample, (160, 120), false, false).is_err());
+ assert!(!publisher.publish(&src, 0, &sample, (160, 120), false, false).unwrap());
+ }
+
+ #[test]
+ fn gpu_video_scaling_keeps_pixels_on_gpu_and_letterboxes() {
+ let (mut publisher, mut reader) = pair();
+ let producer = device().unwrap();
+ let consumer = device().unwrap();
+ let (src, sample) = texture(&producer, 160, 128, 90);
+ assert!(publisher.publish(&src, 0, &sample, (160, 120), false, false).unwrap());
+ let mut destination = None;
+ unsafe {
+ consumer
+ .CreateTexture2D(
+ &D3D11_TEXTURE2D_DESC {
+ Width: 320,
+ Height: 180,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_NV12,
+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ },
+ None,
+ Some(&mut destination),
+ )
+ .unwrap();
+ }
+ let buffer = unsafe {
+ MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID, &destination.unwrap(), 0, false).unwrap()
+ };
+ assert!(reader.write_nv12(&buffer, 320, 180).unwrap());
+ assert!(reader.cpu.is_empty(), "GPU scaling must avoid CPU readback");
+ let bytes = pixels(&buffer);
+ assert_eq!(bytes[0], 16);
+ assert_eq!(bytes[100], 90);
+ assert!(bytes[320 * 180..].iter().all(|b| *b == 128));
+ }
+ #[test]
+ fn rejects_malformed_or_oversized_descriptors() {
+ assert!(Descriptor::parse(&[]).is_none());
+ let mut d = Descriptor {
+ pid: 1,
+ slot: 0,
+ epoch: 1,
+ coded_w: 160,
+ coded_h: 120,
+ width: 160,
+ height: 120,
+ colors: 0,
+ frame: 1,
+ adapter: 1,
+ };
+ assert_eq!(Descriptor::parse(&d.bytes()), Some(d));
+ d.width = 161;
+ assert!(Descriptor::parse(&d.bytes()).is_none());
+ d.width = 160;
+ d.coded_w = MAX_WIDTH + 2;
+ assert!(Descriptor::parse(&d.bytes()).is_none());
+ }
+
+ #[test]
+ fn cross_process_gpu_producer() {
+ let Ok(name) = std::env::var("NECTARLINK_GPU_TEST_CONTROL") else { return };
+ let mut publisher = GpuPublisher::new();
+ publisher.mapping = Some(SharedFrameMapping::open_existing_control(&name).unwrap());
+ publisher.mapping_global = true;
+ let device = device().unwrap();
+ for frame in 1..=5 {
+ let (source, sample) = texture(&device, 160, 128, frame * 30);
+ assert!(publisher.publish(&source, 0, &sample, (160, 120), false, false).unwrap());
+ let started = Instant::now();
+ while publisher.stats().unwrap().1 < u32::from(frame) {
+ assert!(started.elapsed() < Duration::from_secs(5), "peer never received GPU frame");
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ }
+ }
+
+ #[test]
+ fn separate_process_opens_and_verifies_shared_gpu_frames() {
+ let (publisher, mut reader) = pair();
+ // pair uses a unique local mapping; derive its test name independently
+ // by allocating a fresh control mapping for this cross-process test.
+ drop(publisher);
+ let name = format!("Local\\NectarlinkGpuCrossProcess_{}", std::process::id());
+ reader.mapping = SharedFrameMapping::open_or_create_control(&name).unwrap();
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .creation_flags(0x08000000)
+ .args(["--exact", "gpu::tests::cross_process_gpu_producer", "--nocapture"])
+ .env("NECTARLINK_GPU_TEST_CONTROL", name)
+ .spawn()
+ .unwrap();
+ let out = cpu_buffer(160, 120);
+ let mut last = 0;
+ let started = Instant::now();
+ while last < 150 {
+ if reader.write_nv12(&out, 160, 120).unwrap() {
+ let bytes = pixels(&out);
+ let value = bytes[0];
+ assert!(bytes[..160 * 120].iter().all(|b| *b == value));
+ assert!(bytes[160 * 120..].iter().all(|b| *b == 128));
+ last = value;
+ }
+ assert!(started.elapsed() < Duration::from_secs(10), "cross-process GPU transfer stalled");
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ assert!(child.wait().unwrap().success());
+ }
+
+ #[test]
+ fn native_nv12_scaling_and_letterbox_avoid_rgb_materialization() {
+ let (mut publisher, mut reader) = pair();
+ let producer = device().unwrap();
+ let (src, sample) = texture(&producer, 160, 120, 90);
+ assert!(publisher.publish(&src, 0, &sample, (160, 120), false, false).unwrap());
+ let output = cpu_buffer(320, 180);
+ assert!(reader.write_nv12(&output, 320, 180).unwrap());
+ assert!(reader.rgb.is_empty(), "NV12 scaling must not convert through RGB");
+ let bytes = pixels(&output);
+ assert_eq!(bytes[0], 16);
+ assert_eq!(bytes[40], 90);
+ assert_eq!(bytes[279], 90);
+ assert_eq!(bytes[280], 16);
+ assert!(bytes[320 * 180..].iter().all(|b| *b == 128));
+ }
+}
diff --git a/desktop/vcam/src/gpu_scale.rs b/desktop/vcam/src/gpu_scale.rs
new file mode 100644
index 0000000..bc534ac
--- /dev/null
+++ b/desktop/vcam/src/gpu_scale.rs
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! NV12 scaling on the video processor, with a CPU fallback in the caller.
+
+use windows::{
+ Win32::{
+ Foundation::{E_FAIL, RECT},
+ Graphics::{Direct3D11::*, Dxgi::Common::*},
+ },
+ core::Interface,
+};
+
+pub(super) struct GpuScaler {
+ device: ID3D11Device,
+ input: (u32, u32),
+ output: (u32, u32),
+ enumerator: ID3D11VideoProcessorEnumerator,
+ processor: ID3D11VideoProcessor,
+}
+impl GpuScaler {
+ pub(super) fn matches(&self, device: &ID3D11Device, input: (u32, u32), output: (u32, u32)) -> bool {
+ self.device.as_raw() == device.as_raw() && self.input == input && self.output == output
+ }
+ #[allow(unsafe_code)]
+ pub(super) fn new(
+ device: &ID3D11Device,
+ input: (u32, u32),
+ output: (u32, u32),
+ ) -> windows::core::Result<Self> {
+ unsafe {
+ let video: ID3D11VideoDevice = device.cast()?;
+ let enumerator = video.CreateVideoProcessorEnumerator(&D3D11_VIDEO_PROCESSOR_CONTENT_DESC {
+ InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,
+ InputFrameRate: DXGI_RATIONAL { Numerator: 30, Denominator: 1 },
+ InputWidth: input.0,
+ InputHeight: input.1,
+ OutputFrameRate: DXGI_RATIONAL { Numerator: 30, Denominator: 1 },
+ OutputWidth: output.0,
+ OutputHeight: output.1,
+ Usage: D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,
+ })?;
+ let processor = video.CreateVideoProcessor(&enumerator, 0)?;
+ Ok(Self { device: device.clone(), input, output, enumerator, processor })
+ }
+ }
+ #[allow(unsafe_code)]
+ pub(super) fn blit(
+ &self,
+ source: &ID3D11Texture2D,
+ destination: &ID3D11Texture2D,
+ index: u32,
+ visible: (u32, u32),
+ ) -> windows::core::Result<()> {
+ unsafe {
+ let video: ID3D11VideoDevice = self.device.cast()?;
+ let context: ID3D11VideoContext = self.device.GetImmediateContext()?.cast()?;
+ let mut input = None;
+ video.CreateVideoProcessorInputView(
+ source,
+ &self.enumerator,
+ &D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC {
+ FourCC: 0,
+ ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D,
+ Anonymous: D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 {
+ Texture2D: D3D11_TEX2D_VPIV { MipSlice: 0, ArraySlice: 0 },
+ },
+ },
+ Some(&mut input),
+ )?;
+ let mut desc = D3D11_TEXTURE2D_DESC::default();
+ destination.GetDesc(&mut desc);
+ let output_desc = if desc.ArraySize > 1 {
+ D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {
+ ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2DARRAY,
+ Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {
+ Texture2DArray: D3D11_TEX2D_ARRAY_VPOV {
+ MipSlice: index % desc.MipLevels,
+ FirstArraySlice: index / desc.MipLevels,
+ ArraySize: 1,
+ },
+ },
+ }
+ } else {
+ D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {
+ ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D,
+ Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {
+ Texture2D: D3D11_TEX2D_VPOV { MipSlice: index },
+ },
+ }
+ };
+ let mut output = None;
+ video.CreateVideoProcessorOutputView(
+ destination,
+ &self.enumerator,
+ &output_desc,
+ Some(&mut output),
+ )?;
+ let (sw, sh) = visible;
+ let (width, height) = self.output;
+ let (fw, fh) = if width * sh <= height * sw {
+ (width, ((sh * width / sw) & !1).max(2))
+ } else {
+ (((sw * height / sh) & !1).max(2), height)
+ };
+ let (x, y) = (((width - fw) / 2) & !1, ((height - fh) / 2) & !1);
+ let source_rect = RECT { left: 0, top: 0, right: sw as i32, bottom: sh as i32 };
+ let target =
+ RECT { left: x as i32, top: y as i32, right: (x + fw) as i32, bottom: (y + fh) as i32 };
+ let full = RECT { left: 0, top: 0, right: width as i32, bottom: height as i32 };
+ context.VideoProcessorSetStreamSourceRect(&self.processor, 0, true, Some(&source_rect));
+ context.VideoProcessorSetStreamDestRect(&self.processor, 0, true, Some(&target));
+ context.VideoProcessorSetOutputTargetRect(&self.processor, true, Some(&full));
+ context.VideoProcessorSetStreamAutoProcessingMode(&self.processor, 0, false);
+ context.VideoProcessorSetOutputBackgroundColor(
+ &self.processor,
+ true,
+ &D3D11_VIDEO_COLOR {
+ Anonymous: D3D11_VIDEO_COLOR_0 {
+ YCbCr: D3D11_VIDEO_COLOR_YCbCrA {
+ Y: 16.0 / 255.0,
+ Cb: 128.0 / 255.0,
+ Cr: 128.0 / 255.0,
+ A: 1.,
+ },
+ },
+ },
+ );
+ let colors: ID3D11VideoContext1 = context.cast()?;
+ colors.VideoProcessorSetStreamColorSpace1(
+ &self.processor,
+ 0,
+ DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709,
+ );
+ colors.VideoProcessorSetOutputColorSpace1(
+ &self.processor,
+ DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709,
+ );
+ let mut stream = D3D11_VIDEO_PROCESSOR_STREAM {
+ Enable: true.into(),
+ pInputSurface: std::mem::ManuallyDrop::new(input),
+ ..Default::default()
+ };
+ let result = context.VideoProcessorBlt(
+ &self.processor,
+ output.as_ref().ok_or(E_FAIL)?,
+ 0,
+ std::slice::from_ref(&stream),
+ );
+ drop(std::mem::ManuallyDrop::take(&mut stream.pInputSurface));
+ result?;
+ self.device.GetImmediateContext()?.Flush();
+ Ok(())
+ }
+ }
+}
diff --git a/desktop/vcam/src/lib.rs b/desktop/vcam/src/lib.rs
index 4bddc1e..ed5b5bd 100644
--- a/desktop/vcam/src/lib.rs
+++ b/desktop/vcam/src/lib.rs
@@ -17,6 +17,8 @@ use windows::{
core::{GUID, HRESULT, IUnknown, Interface},
};
+#[cfg(windows)]
+pub mod gpu;
pub mod shm;
#[cfg(windows)]
pub mod source;
@@ -83,18 +85,29 @@ mod tests {
Media::{
KernelStreaming::PINNAME_VIDEO_CAPTURE,
MediaFoundation::{
- IMFMediaBuffer, IMFMediaSource, IMFMediaStream, IMFMediaStream2, IMFSample, MEMediaSample,
- MENewStream, MESourcePaused, MESourceStarted, MESourceStopped, MEStreamPaused,
- MEStreamStarted, MEStreamStopped, MEUpdatedStream,
+ IMF2DBuffer, IMFMediaSource, IMFMediaStream, IMFMediaStream2, IMFSample,
+ IMFSampleAllocatorControl, IMFVideoSampleAllocator, MEMediaSample, MENewStream,
+ MESourceStarted, MESourceStopped, MEStreamStarted, MEStreamStopped, MEUpdatedStream,
MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MF_DEVICESTREAM_FRAMESERVER_SHARED,
- MF_DEVICESTREAM_STREAM_CATEGORY, MF_DEVICESTREAM_STREAM_ID, MF_EVENT_FLAG_NO_WAIT,
- MF_MT_FRAME_SIZE, MF_MT_SUBTYPE, MF_STREAM_STATE_PAUSED, MF_STREAM_STATE_RUNNING,
- MF_STREAM_STATE_STOPPED, MFFrameSourceTypes_Color, MFVideoFormat_NV12, MFVideoFormat_RGB32,
+ MF_DEVICESTREAM_STREAM_CATEGORY, MF_DEVICESTREAM_STREAM_ID, MF_E_INVALID_STATE_TRANSITION,
+ MF_EVENT_FLAG_NO_WAIT, MF_MT_FRAME_SIZE, MF_MT_SUBTYPE, MF_STREAM_STATE_RUNNING,
+ MF_STREAM_STATE_STOPPED, MFCreateVideoSampleAllocatorEx, MFFrameSourceTypes_Color,
+ MFVideoFormat_NV12, MFVideoFormat_RGB32,
},
},
System::Com::StructuredStorage::PROPVARIANT,
};
+ #[cfg(windows)]
+ fn sample_bytes(sample: &IMFSample) -> Vec<u8> {
+ unsafe {
+ let buffer: IMF2DBuffer = sample.GetBufferByIndex(0).unwrap().cast().unwrap();
+ let mut bytes = vec![0; buffer.GetContiguousLength().unwrap() as usize];
+ buffer.ContiguousCopyTo(&mut bytes).unwrap();
+ bytes
+ }
+ }
+
#[cfg(windows)]
#[test]
fn dll_get_class_object_activates_media_source_in_process() {
@@ -104,8 +117,10 @@ mod tests {
assert_eq!(hr, S_OK);
assert!(!raw.is_null());
let factory: IClassFactory = IClassFactory::from_raw(raw);
- let source: windows::Win32::Media::MediaFoundation::IMFMediaSourceEx =
+ let activate: windows::Win32::Media::MediaFoundation::IMFActivate =
factory.CreateInstance(None).unwrap();
+ let source: windows::Win32::Media::MediaFoundation::IMFMediaSourceEx =
+ activate.ActivateObject().unwrap();
let attrs = source.GetSourceAttributes().unwrap();
assert_eq!(
attrs.GetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES).unwrap(),
@@ -149,6 +164,15 @@ mod tests {
let handler = sd.GetMediaTypeHandler().unwrap();
assert_eq!(handler.GetMediaTypeCount().unwrap(), 4);
+ // Frame Server supplies the allocator before starting the source.
+ // Exercise real 2D buffers rather than only flat test buffers.
+ handler.SetCurrentMediaType(&handler.GetMediaTypeByIndex(1).unwrap()).unwrap();
+ let mut raw_allocator = std::ptr::null_mut();
+ MFCreateVideoSampleAllocatorEx(&IMFVideoSampleAllocator::IID, &mut raw_allocator).unwrap();
+ let allocator = IMFVideoSampleAllocator::from_raw(raw_allocator);
+ let allocator_control: IMFSampleAllocatorControl = source.cast().unwrap();
+ allocator_control.SetDefaultAllocator(0, &allocator).unwrap();
+
// Start the media source.
let start_pos = PROPVARIANT::default();
source.Start(&pd, &GUID::zeroed(), &start_pos).unwrap();
@@ -175,17 +199,13 @@ mod tests {
let s0_val = ev_sample0.GetValue().unwrap();
let sample0: IMFSample =
s0_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
- assert_eq!(sample0.GetSampleTime().unwrap(), 0);
+ let sample_time0 = sample0.GetSampleTime().unwrap();
+ assert!(sample_time0 > 0);
assert_eq!(sample0.GetSampleDuration().unwrap(), SAMPLE_DURATION_100NS);
- let buf0: IMFMediaBuffer = sample0.ConvertToContiguousBuffer().unwrap();
- assert_eq!(buf0.GetCurrentLength().unwrap(), 1280 * 720 * 4);
- let mut ptr0 = std::ptr::null_mut();
- let mut cur_len0 = 0;
- buf0.Lock(&mut ptr0, None, Some(&mut cur_len0)).unwrap();
- let bytes0 = std::slice::from_raw_parts(ptr0, cur_len0 as usize);
+ let bytes0 = sample_bytes(&sample0);
+ assert_eq!(bytes0.len(), 1280 * 720 * 4);
// Placeholder contains amber/white text pixels over the dark background.
assert!(bytes0.as_chunks::<4>().0.iter().any(|px| px[2] > 200));
- buf0.Unlock().unwrap();
// 2. Write a live 1280x720 BGRX frame to shared memory and request a sample.
let mut live_frame = vec![0u8; 1280 * 720 * 4];
@@ -203,56 +223,49 @@ mod tests {
let s1_val = ev_sample1.GetValue().unwrap();
let sample1: IMFSample =
s1_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
- assert_eq!(sample1.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS);
- let buf1: IMFMediaBuffer = sample1.ConvertToContiguousBuffer().unwrap();
- assert_eq!(buf1.GetCurrentLength().unwrap(), 1280 * 720 * 4);
- let mut ptr1 = std::ptr::null_mut();
- let mut cur_len1 = 0;
- buf1.Lock(&mut ptr1, None, Some(&mut cur_len1)).unwrap();
- let bytes1 = std::slice::from_raw_parts(ptr1, cur_len1 as usize);
+ let sample_time1 = sample1.GetSampleTime().unwrap();
+ assert!(sample_time1 >= sample_time0 + SAMPLE_DURATION_100NS);
+ let bytes1 = sample_bytes(&sample1);
+ assert_eq!(bytes1.len(), 1280 * 720 * 4);
assert_eq!(&bytes1[..4], &[0x22, 0x88, 0xEE, 0xFF]);
assert_eq!(&bytes1[bytes1.len() - 4..], &[0x22, 0x88, 0xEE, 0xFF]);
- buf1.Unlock().unwrap();
// 3. Switch stream media type to NV12 @ 1280x720 and request a sample.
- let mt_nv12 = handler.GetMediaTypeByIndex(1).unwrap();
+ let mt_nv12 = handler.GetMediaTypeByIndex(0).unwrap();
assert_eq!(mt_nv12.GetGUID(&MF_MT_SUBTYPE).unwrap(), MFVideoFormat_NV12);
handler.SetCurrentMediaType(&mt_nv12).unwrap();
+ allocator.UninitializeSampleAllocator().unwrap();
+ allocator.InitializeSampleAllocator(10, &mt_nv12).unwrap();
stream.RequestSample(None).unwrap();
let ev_sample2 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
let s2_val = ev_sample2.GetValue().unwrap();
let sample2: IMFSample =
s2_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
- assert_eq!(sample2.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS * 2);
- let buf2: IMFMediaBuffer = sample2.ConvertToContiguousBuffer().unwrap();
- assert_eq!(buf2.GetCurrentLength().unwrap(), 1280 * 720 * 3 / 2);
+ let sample_time2 = sample2.GetSampleTime().unwrap();
+ assert!(sample_time2 >= sample_time1 + SAMPLE_DURATION_100NS);
+ assert_eq!(sample_bytes(&sample2).len(), 1280 * 720 * 3 / 2);
// 4. Switch stream media type to RGB32 @ 1920x1080 and request a sample.
- let mt_1080 = handler.GetMediaTypeByIndex(2).unwrap();
+ let mt_1080 = handler.GetMediaTypeByIndex(3).unwrap();
assert_eq!(mt_1080.GetGUID(&MF_MT_SUBTYPE).unwrap(), MFVideoFormat_RGB32);
assert_eq!(mt_1080.GetUINT64(&MF_MT_FRAME_SIZE).unwrap(), (1920u64 << 32) | 1080u64);
handler.SetCurrentMediaType(&mt_1080).unwrap();
+ allocator.UninitializeSampleAllocator().unwrap();
+ allocator.InitializeSampleAllocator(10, &mt_1080).unwrap();
stream.RequestSample(None).unwrap();
let ev_sample3 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
let s3_val = ev_sample3.GetValue().unwrap();
let sample3: IMFSample =
s3_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
- assert_eq!(sample3.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS * 3);
- let buf3: IMFMediaBuffer = sample3.ConvertToContiguousBuffer().unwrap();
- assert_eq!(buf3.GetCurrentLength().unwrap(), 1920 * 1080 * 4);
+ let sample_time3 = sample3.GetSampleTime().unwrap();
+ assert!(sample_time3 >= sample_time2 + SAMPLE_DURATION_100NS);
+ assert_eq!(sample_bytes(&sample3).len(), 1920 * 1080 * 4);
- // Pause, restart (MEUpdatedStream), stop, and shutdown.
- source.Pause().unwrap();
- assert_eq!(stream2.GetStreamState().unwrap(), MF_STREAM_STATE_PAUSED);
- assert_eq!(
- source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
- MESourcePaused.0 as u32
- );
- assert_eq!(
- stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
- MEStreamPaused.0 as u32
- );
+ // A live source rejects pause; restart, stop and shutdown still work.
+ assert_eq!(source.Pause().unwrap_err().code(), MF_E_INVALID_STATE_TRANSITION);
+ assert_eq!(stream2.GetStreamState().unwrap(), MF_STREAM_STATE_RUNNING);
+ allocator.UninitializeSampleAllocator().unwrap();
source.Start(&pd, &GUID::zeroed(), &start_pos).unwrap();
assert_eq!(
source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
diff --git a/desktop/vcam/src/shm.rs b/desktop/vcam/src/shm.rs
index 462da72..4118111 100644
--- a/desktop/vcam/src/shm.rs
+++ b/desktop/vcam/src/shm.rs
@@ -3,7 +3,10 @@
//! `nectarlink_vcam.dll`, plus placeholder frame rendering and RGB32/NV12
//! conversion.
-use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};
+use std::sync::{
+ Mutex,
+ atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering},
+};
use ab_glyph::{Font, FontRef, GlyphId, PxScale, ScaleFont, point};
@@ -67,11 +70,20 @@ pub struct SharedHeader {
pub phone_name: [AtomicU8; 24],
}
+/// Reader-local storage; never part of the shared-memory layout.
+struct CachedLiveFrame {
+ width: u32,
+ height: u32,
+ timestamp_us: u64,
+ bgrx: Vec<u8>,
+}
+
/// Shared-memory mapping handle and view. Safe to share across threads.
#[cfg(windows)]
pub struct SharedFrameMapping {
handle: HANDLE,
view: MEMORY_MAPPED_VIEW_ADDRESS,
+ last_read: Mutex<Option<CachedLiveFrame>>,
}
/// Shared-memory mapping file descriptor and mapped view on Unix (`/dev/shm`).
@@ -79,6 +91,7 @@ pub struct SharedFrameMapping {
pub struct SharedFrameMapping {
fd: std::os::fd::OwnedFd,
view: *mut std::ffi::c_void,
+ last_read: Mutex<Option<CachedLiveFrame>>,
}
#[allow(unsafe_code)]
@@ -131,10 +144,94 @@ fn unix_shm_path(name: &str) -> std::path::PathBuf {
#[cfg(windows)]
impl SharedFrameMapping {
+ #[cfg(windows)]
+ pub(crate) fn control_failed(&self) -> bool {
+ self.header()._pad.load(Ordering::Acquire) != 0
+ }
+
+ #[cfg(windows)]
+ pub(crate) fn fail_control(&self) {
+ self.header()._pad.store(1, Ordering::Release);
+ }
+ #[cfg(windows)]
+ pub(crate) fn fail_control_code(&self, code: i32) {
+ self.header()._pad.store(code as u32, Ordering::Release);
+ }
+
+ #[cfg(windows)]
+ pub(crate) fn control_code(&self) -> i32 {
+ self.header()._pad.load(Ordering::Acquire) as i32
+ }
+
+ #[cfg(windows)]
+ pub(crate) fn control_stats(&self) -> (u32, u32) {
+ (self.header().height.load(Ordering::Relaxed), self.header().stride.load(Ordering::Relaxed))
+ }
+
+ #[cfg(windows)]
+ pub(crate) fn count_gpu_sample(&self) {
+ self.header().height.fetch_add(1, Ordering::Relaxed);
+ }
+
+ #[cfg(windows)]
+ pub(crate) fn count_download(&self) {
+ self.header().stride.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// Binary control messages use their own mapping name, never the RGB mapping.
+ /// A busy writer is distinct from idle so GPU readers can retain a snapshot.
+ #[cfg(windows)]
+ #[allow(unsafe_code)]
+ pub(crate) fn read_control(&self) -> Option<(u64, Vec<u8>)> {
+ let h = self.header();
+ for _ in 0..3 {
+ let seq = h.seq.load(Ordering::Acquire);
+ if seq & 1 != 0 {
+ continue;
+ }
+ if h.active.load(Ordering::Acquire) == 0 {
+ return Some((seq, Vec::new()));
+ }
+ let len = h.width.load(Ordering::Relaxed) as usize;
+ if len > 256 {
+ return Some((seq, Vec::new()));
+ }
+ let bytes = unsafe { std::slice::from_raw_parts(self.payload_ptr(), len) }.to_vec();
+ std::sync::atomic::fence(Ordering::Acquire);
+ if seq == h.seq.load(Ordering::Acquire) {
+ return Some((seq, bytes));
+ }
+ }
+ None
+ }
+
+ #[cfg(windows)]
+ #[allow(unsafe_code)]
+ pub(crate) fn write_control(&self, bytes: &[u8]) {
+ assert!(bytes.len() <= 256);
+ let h = self.header();
+ let seq = h.seq.load(Ordering::Relaxed) | 1;
+ h.seq.store(seq, Ordering::Release);
+ std::sync::atomic::fence(Ordering::AcqRel);
+ unsafe {
+ std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.payload_ptr(), bytes.len());
+ }
+ h.width.store(bytes.len() as u32, Ordering::Relaxed);
+ h.active.store(1, Ordering::Relaxed);
+ h.seq.store(seq.wrapping_add(1), Ordering::Release);
+ }
+
/// Opens or creates the shared-memory frame mapping with `name` (a
/// `Global\` name gets [`GLOBAL_SDDL`]'s permissions).
#[allow(unsafe_code)]
pub fn open_or_create(name: &str) -> windows::core::Result<Self> {
+ Self::create_sized(name, TOTAL_MAPPING_BYTES)
+ }
+ pub(crate) fn open_or_create_control(name: &str) -> windows::core::Result<Self> {
+ Self::create_sized(name, HEADER_BYTES + 256)
+ }
+ #[allow(unsafe_code)]
+ fn create_sized(name: &str, bytes: usize) -> windows::core::Result<Self> {
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
let mut sd = PSECURITY_DESCRIPTOR::default();
if name.starts_with("Global\\") {
@@ -162,7 +259,7 @@ impl SharedFrameMapping {
(!sd.0.is_null()).then_some(&raw const attrs),
PAGE_READWRITE,
0,
- TOTAL_MAPPING_BYTES as u32,
+ bytes as u32,
PCWSTR(wide.as_ptr()),
);
if !sd.0.is_null() {
@@ -170,7 +267,7 @@ impl SharedFrameMapping {
}
handle?
};
- Self::map(handle)
+ Self::map(handle, bytes)
}
/// For the camera's media source: the global mapping, or the caller's
@@ -186,26 +283,33 @@ impl SharedFrameMapping {
/// Opens an existing mapping (the app joining the camera's global one).
#[allow(unsafe_code)]
pub fn open_existing(name: &str) -> windows::core::Result<Self> {
+ Self::open_sized(name, TOTAL_MAPPING_BYTES)
+ }
+ pub(crate) fn open_existing_control(name: &str) -> windows::core::Result<Self> {
+ Self::open_sized(name, HEADER_BYTES + 256)
+ }
+ #[allow(unsafe_code)]
+ fn open_sized(name: &str, bytes: usize) -> windows::core::Result<Self> {
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
// SAFETY: opens a named mapping by a NUL-terminated name.
let handle =
unsafe { OpenFileMappingW((FILE_MAP_READ | FILE_MAP_WRITE).0, false, PCWSTR(wide.as_ptr()))? };
- Self::map(handle)
+ Self::map(handle, bytes)
}
#[allow(unsafe_code)]
- fn map(handle: HANDLE) -> windows::core::Result<Self> {
+ fn map(handle: HANDLE, bytes: usize) -> windows::core::Result<Self> {
// SAFETY: maps the whole section, which is `TOTAL_MAPPING_BYTES` long
// whichever side created it (both use the same size).
unsafe {
// Read and write only: that's all the app is granted on the global one.
- let view = MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, TOTAL_MAPPING_BYTES);
+ let view = MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes);
if view.Value.is_null() {
let err = windows::core::Error::from_thread();
let _ = CloseHandle(handle);
return Err(err);
}
- let mapping = Self { handle, view };
+ let mapping = Self { handle, view, last_read: Mutex::new(None) };
mapping.ensure_initialized();
Ok(mapping)
}
@@ -307,7 +411,7 @@ impl SharedFrameMapping {
if view == libc::MAP_FAILED || view.is_null() {
return Err(std::io::Error::last_os_error());
}
- let mapping = Self { fd, view };
+ let mapping = Self { fd, view, last_read: Mutex::new(None) };
mapping.ensure_initialized();
Ok(mapping)
}
@@ -422,21 +526,28 @@ impl SharedFrameMapping {
/// Reads the latest frame into `out_bgrx` (`out_width * out_height * 4` bytes).
/// Returns `(true, timestamp_us)` when a live frame was read, or
/// `(false, 0)` when idle (in which case `out_bgrx` is filled with the
- /// placeholder frame).
+ /// placeholder frame). While the writer is busy, repeats the last complete
+ /// live frame at the same output dimensions instead of flashing the idle card.
#[allow(unsafe_code)]
pub fn read_bgrx(&self, out_width: u32, out_height: u32, out_bgrx: &mut [u8]) -> (bool, u64) {
let needed = (out_width as usize) * (out_height as usize) * 4;
if out_bgrx.len() < needed || out_width == 0 || out_height == 0 {
return (false, 0);
}
+ let mut last_read = self.last_read.lock().unwrap_or_else(|e| e.into_inner());
let h = self.header();
- if h.magic.load(Ordering::Acquire) == MAGIC && h.active.load(Ordering::Acquire) == 1 {
+ if h.magic.load(Ordering::Acquire) == MAGIC {
+ let mut contended = false;
for _ in 0..3 {
let seq1 = h.seq.load(Ordering::Acquire);
if seq1 == 0 || (seq1 & 1) != 0 {
+ contended = true;
std::hint::spin_loop();
continue;
}
+ if h.active.load(Ordering::Acquire) != 1 {
+ break;
+ }
let src_w = h.width.load(Ordering::Relaxed);
let src_h = h.height.load(Ordering::Relaxed);
let ts = h.timestamp_us.load(Ordering::Relaxed);
@@ -452,11 +563,33 @@ impl SharedFrameMapping {
std::sync::atomic::fence(Ordering::Acquire);
let seq2 = h.seq.load(Ordering::Acquire);
if seq1 == seq2 {
+ let cached = last_read.get_or_insert_with(|| CachedLiveFrame {
+ width: out_width,
+ height: out_height,
+ timestamp_us: ts,
+ bgrx: Vec::new(),
+ });
+ cached.width = out_width;
+ cached.height = out_height;
+ cached.timestamp_us = ts;
+ cached.bgrx.resize(needed, 0);
+ cached.bgrx.copy_from_slice(&out_bgrx[..needed]);
return (true, ts);
}
+ contended = true;
}
}
+ if contended
+ && h.active.load(Ordering::Acquire) == 1
+ && let Some(cached) = last_read.as_ref()
+ && cached.width == out_width
+ && cached.height == out_height
+ {
+ out_bgrx[..needed].copy_from_slice(&cached.bgrx);
+ return (true, cached.timestamp_us);
+ }
}
+ *last_read = None;
let phone = self.load_phone_name();
render_placeholder_bgrx(&mut out_bgrx[..needed], out_width, out_height, &phone);
(false, 0)
@@ -558,6 +691,46 @@ pub fn fit_bgrx_aspect(src: &[u8], src_w: u32, src_h: u32, dst: &mut [u8], dst_w
}
}
+/// Fits packed BT.709 limited-range NV12 without converting through RGB. Chroma
+/// samples move as UV pairs and the fitted rectangle stays aligned to 2x2 pixels.
+pub fn fit_nv12_aspect(src: &[u8], sw: u32, sh: u32, dst: &mut [u8], dw: u32, dh: u32) -> bool {
+ if sw > MAX_WIDTH || dw > MAX_WIDTH || sh > MAX_HEIGHT || dh > MAX_HEIGHT {
+ return false;
+ }
+ if [sw, sh, dw, dh].iter().any(|n| *n == 0 || n % 2 != 0) {
+ return false;
+ }
+ let (sw, sh, dw, dh) = (sw as usize, sh as usize, dw as usize, dh as usize);
+ if src.len() < sw * sh * 3 / 2 || dst.len() < dw * dh * 3 / 2 {
+ return false;
+ }
+ if (sw, sh) == (dw, dh) {
+ dst[..dw * dh * 3 / 2].copy_from_slice(&src[..sw * sh * 3 / 2]);
+ return true;
+ }
+ let (fw, fh) = if dw * sh <= dh * sw {
+ (dw, ((sh * dw / sw) & !1).max(2))
+ } else {
+ (((sw * dh / sh) & !1).max(2), dh)
+ };
+ let (ox, oy) = (((dw - fw) / 2) & !1, ((dh - fh) / 2) & !1);
+ dst[..dw * dh].fill(16);
+ dst[dw * dh..dw * dh * 3 / 2].fill(128);
+ for y in 0..fh {
+ for x in 0..fw {
+ dst[(y + oy) * dw + x + ox] = src[(y * sh / fh) * sw + x * sw / fw];
+ }
+ }
+ for y in 0..fh / 2 {
+ for x in 0..fw / 2 {
+ let s = sw * sh + (y * (sh / 2) / (fh / 2)) * sw + (x * (sw / 2) / (fw / 2)) * 2;
+ let d = dw * dh + (y + oy / 2) * dw + ox + x * 2;
+ dst[d..d + 2].copy_from_slice(&src[s..s + 2]);
+ }
+ }
+ true
+}
+
/// Converts top-down BGRX (`width * height * 4`) to NV12 (`width * height * 3 / 2`,
/// BT.709 limited range).
pub fn bgrx_to_nv12(bgrx: &[u8], width: u32, height: u32, nv12: &mut [u8]) {
@@ -913,15 +1086,75 @@ impl TrueTypeFont {
mod tests {
use super::*;
+ #[test]
+ fn nv12_fit_preserves_uv_pairs_and_neutral_letterbox() {
+ let mut src = vec![90; 160 * 120 * 3 / 2];
+ for pair in src[160 * 120..].as_chunks_mut::<2>().0 {
+ pair.copy_from_slice(&[32, 224]);
+ }
+ let mut dst = vec![0; 320 * 180 * 3 / 2];
+ assert!(fit_nv12_aspect(&src, 160, 120, &mut dst, 320, 180));
+ assert_eq!(dst[0], 16);
+ assert_eq!(dst[40], 90);
+ let uv = 320 * 180;
+ assert_eq!(&dst[uv..uv + 2], &[128, 128]);
+ assert_eq!(&dst[uv + 40..uv + 42], &[32, 224]);
+ assert!(!fit_nv12_aspect(&src, 161, 120, &mut dst, 320, 180));
+ assert!(!fit_nv12_aspect(&src, u32::MAX, u32::MAX, &mut dst, 320, 180));
+ }
+
+ #[test]
+ fn a_busy_writer_keeps_the_last_complete_live_frame() {
+ let name = format!(r"Local\NectarlinkVcamReadCache_{}_busy", std::process::id());
+ let mapping = SharedFrameMapping::open_or_create(&name).unwrap();
+ let first = vec![42u8; 160 * 120 * 4];
+ let second = vec![99u8; 160 * 120 * 4];
+ let mut output = vec![0u8; first.len()];
+ mapping.write_frame("Pixel", 160, 120, 123, &first, false);
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (true, 123));
+ assert_eq!(output, first);
+
+ // Deterministically hold the writer in the middle of its next update.
+ let seq = mapping.header().seq.load(Ordering::Acquire);
+ mapping.header().seq.store(seq + 1, Ordering::Release);
+ output.fill(0);
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (true, 123));
+ assert_eq!(output, first, "writer contention must not flash the idle card");
+
+ mapping.write_frame("Pixel", 160, 120, 456, &second, false);
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (true, 456));
+ assert_eq!(output, second);
+
+ mapping.set_idle("Pixel");
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (false, 0));
+ assert_ne!(output, second, "an explicit stop must still show the idle card");
+
+ mapping.header().active.store(1, Ordering::Release);
+ let seq = mapping.header().seq.load(Ordering::Acquire);
+ mapping.header().seq.store(seq + 1, Ordering::Release);
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (false, 0));
+ assert_ne!(output, second, "an idle transition must clear the cached live frame");
+ }
+
+ #[test]
+ fn busy_reads_do_not_reuse_a_frame_at_different_dimensions() {
+ let name = format!(r"Local\NectarlinkVcamReadCache_{}_resize", std::process::id());
+ let mapping = SharedFrameMapping::open_or_create(&name).unwrap();
+ mapping.write_frame("Pixel", 160, 120, 123, &vec![42u8; 160 * 120 * 4], false);
+ let mut output = vec![0u8; 160 * 120 * 4];
+ assert_eq!(mapping.read_bgrx(160, 120, &mut output), (true, 123));
+ let seq = mapping.header().seq.load(Ordering::Acquire);
+ mapping.header().seq.store(seq + 1, Ordering::Release);
+ assert_eq!(mapping.read_bgrx(120, 160, &mut output), (false, 0));
+ }
+
#[test]
fn the_camera_always_gets_a_mapping_and_the_app_finds_it() {
- // Outside a service the global name usually can't be created; the
- // camera then falls back to this session's mapping.
- let camera = SharedFrameMapping::for_camera(DEFAULT_MAPPING_NAME).unwrap();
+ // Use a private mapping so this test cannot overwrite an active webcam.
+ let name = format!(r"Local\NectarlinkVcamMappingTest_{}", std::process::id());
+ let camera = SharedFrameMapping::for_camera(&name).unwrap();
camera.set_idle("Pixel 9");
- let app = SharedFrameMapping::open_existing(DEFAULT_MAPPING_NAME)
- .or_else(|_| SharedFrameMapping::open_existing(LOCAL_MAPPING_NAME))
- .unwrap();
+ let app = SharedFrameMapping::open_existing(&name).unwrap();
assert_eq!(app.load_phone_name(), "Pixel 9");
}
diff --git a/desktop/vcam/src/source.rs b/desktop/vcam/src/source.rs
index 35674de..6d6e6d5 100644
--- a/desktop/vcam/src/source.rs
+++ b/desktop/vcam/src/source.rs
@@ -12,41 +12,68 @@ use std::sync::{
use windows::{
Win32::{
- Foundation::{E_INVALIDARG, E_POINTER, S_OK},
+ Foundation::{E_INVALIDARG, E_NOTIMPL, E_POINTER, ERROR_SET_NOT_FOUND, S_OK},
Media::{
- KernelStreaming::PINNAME_VIDEO_CAPTURE,
+ KernelStreaming::{
+ IKsControl, IKsControl_Impl, KSCAMERAPROFILE_Legacy, KSIDENTIFIER, PINNAME_VIDEO_CAPTURE,
+ },
MediaFoundation::{
- IMFAttributes, IMFGetService, IMFGetService_Impl, IMFMediaEvent, IMFMediaEventGenerator,
+ IMF2DBuffer2, IMFActivate, IMFActivate_Impl, IMFAttributes, IMFAttributes_Impl,
+ IMFGetService, IMFGetService_Impl, IMFMediaEvent, IMFMediaEventGenerator,
IMFMediaEventGenerator_Impl, IMFMediaEventQueue, IMFMediaSource, IMFMediaSource_Impl,
IMFMediaSourceEx, IMFMediaSourceEx_Impl, IMFMediaStream, IMFMediaStream_Impl,
IMFMediaStream2, IMFMediaStream2_Impl, IMFMediaType, IMFPresentationDescriptor,
- IMFStreamDescriptor, MEDIA_EVENT_GENERATOR_GET_EVENT_FLAGS, MEMediaSample, MENewStream,
- MESourcePaused, MESourceStarted, MESourceStopped, MEStreamPaused, MEStreamStarted,
- MEStreamStopped, MEUpdatedStream, MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES,
- MF_DEVICESTREAM_FRAMESERVER_SHARED, MF_DEVICESTREAM_STREAM_CATEGORY,
- MF_DEVICESTREAM_STREAM_ID, MF_E_NO_MORE_TYPES, MF_E_SHUTDOWN, MF_MT_ALL_SAMPLES_INDEPENDENT,
- MF_MT_AVG_BITRATE, MF_MT_DEFAULT_STRIDE, MF_MT_FIXED_SIZE_SAMPLES, MF_MT_FRAME_RATE,
- MF_MT_FRAME_RATE_RANGE_MAX, MF_MT_FRAME_RATE_RANGE_MIN, MF_MT_FRAME_SIZE,
- MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SAMPLE_SIZE,
- MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MF_STREAM_STATE,
- MF_STREAM_STATE_PAUSED, MF_STREAM_STATE_RUNNING, MF_STREAM_STATE_STOPPED, MFCreateAttributes,
- MFCreateEventQueue, MFCreateMediaType, MFCreateMemoryBuffer, MFCreatePresentationDescriptor,
- MFCreateSample, MFCreateStreamDescriptor, MFFrameSourceTypes_Color, MFMediaType_Video,
- MFNominalRange_0_255, MFNominalRange_16_235, MFSampleExtension_CleanPoint,
- MFSampleExtension_Token, MFVideoFormat_NV12, MFVideoFormat_RGB32,
- MFVideoInterlace_Progressive, MFVideoTransferMatrix_BT709,
+ IMFSampleAllocatorControl, IMFSampleAllocatorControl_Impl, IMFStreamDescriptor,
+ IMFVideoSampleAllocator, MEDIA_EVENT_GENERATOR_GET_EVENT_FLAGS, MEMediaSample, MENewStream,
+ MESourceStarted, MESourceStopped, MEStreamPaused, MEStreamStarted, MEStreamStopped,
+ MEUpdatedStream, MF_DEVICEMFT_SENSORPROFILE_COLLECTION,
+ MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MF_DEVICESTREAM_FRAMESERVER_SHARED,
+ MF_DEVICESTREAM_STREAM_CATEGORY, MF_DEVICESTREAM_STREAM_ID, MF_E_INVALIDSTREAMNUMBER,
+ MF_E_SHUTDOWN, MF_E_UNSUPPORTED_SERVICE, MF_MT_ALL_SAMPLES_INDEPENDENT, MF_MT_AVG_BITRATE,
+ MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE,
+ MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE, MF_STREAM_STATE, MF_STREAM_STATE_PAUSED,
+ MF_STREAM_STATE_RUNNING, MF_STREAM_STATE_STOPPED, MF2DBuffer_LockFlags_Write,
+ MFCreateAttributes, MFCreateEventQueue, MFCreateMediaType, MFCreatePresentationDescriptor,
+ MFCreateSensorProfile, MFCreateSensorProfileCollection, MFCreateStreamDescriptor,
+ MFFrameSourceTypes_Color, MFGetSystemTime, MFMediaType_Video, MFSampleAllocatorUsage,
+ MFSampleExtension_CleanPoint, MFSampleExtension_Token, MFVideoFormat_NV12,
+ MFVideoFormat_RGB32, MFVideoInterlace_Progressive,
},
},
- System::Com::{IClassFactory, IClassFactory_Impl, StructuredStorage::PROPVARIANT},
+ System::Com::{
+ IClassFactory, IClassFactory_Impl,
+ StructuredStorage::{PROPVARIANT, PropVariantClear},
+ },
},
- core::{AsImpl, BOOL, GUID, HRESULT, IUnknown, Interface, Ref, implement},
+ core::{AsImpl, BOOL, GUID, HRESULT, IUnknown, Interface, PCWSTR, PWSTR, Ref, implement},
};
+use crate::gpu::GpuReader;
use crate::shm::{DEFAULT_MAPPING_NAME, SharedFrameMapping, bgrx_to_nv12, render_placeholder_bgrx};
/// Active DLL object/lock counter for `DllCanUnloadNow`.
pub static ACTIVE_OBJECTS: AtomicU32 = AtomicU32::new(0);
+/// Merges attributes from `source` into `destination` without deleting the
+/// destination's existing defaults. `IMFAttributes::CopyAllItems` clears the
+/// destination first, which would erase the media source's own attributes when
+/// the activation store is empty.
+#[allow(unsafe_code)]
+fn merge_attributes(source: &IMFAttributes, destination: &IMFAttributes) -> windows::core::Result<()> {
+ unsafe {
+ for index in 0..source.GetCount()? {
+ let mut key = GUID::zeroed();
+ let mut value = PROPVARIANT::default();
+ source.GetItemByIndex(index, &mut key, Some(&mut value))?;
+ let set_result = destination.SetItem(&key, &value);
+ let clear_result = PropVariantClear(&mut value);
+ set_result?;
+ clear_result?;
+ }
+ }
+ Ok(())
+}
+
/// Sample duration for 30 fps in 100-ns units (`10_000_000 / 30 = 333_333`).
pub const SAMPLE_DURATION_100NS: i64 = 333_333;
@@ -56,7 +83,6 @@ pub const MODES: &[(u32, u32, u32)] = &[(1280, 720, 30), (1920, 1080, 30), (3840
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceState {
Stopped,
- Paused,
Started,
Shutdown,
}
@@ -92,26 +118,26 @@ pub fn create_video_media_type(
mt.SetGUID(&MF_MT_SUBTYPE, subtype)?;
mt.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)?;
mt.SetUINT32(&MF_MT_ALL_SAMPLES_INDEPENDENT, 1)?;
- mt.SetUINT32(&MF_MT_FIXED_SIZE_SAMPLES, 1)?;
let frame_size = (u64::from(width) << 32) | u64::from(height);
mt.SetUINT64(&MF_MT_FRAME_SIZE, frame_size)?;
let frame_rate = (u64::from(fps) << 32) | 1u64;
mt.SetUINT64(&MF_MT_FRAME_RATE, frame_rate)?;
- mt.SetUINT64(&MF_MT_FRAME_RATE_RANGE_MAX, frame_rate)?;
- mt.SetUINT64(&MF_MT_FRAME_RATE_RANGE_MIN, frame_rate)?;
let par = (1u64 << 32) | 1u64;
mt.SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, par)?;
+ // Native GPU NV12 samples use the decoder's BT.709 limited-range fast
+ // path; other source colors are normalized before reaching this type.
+ if *subtype == MFVideoFormat_NV12 {
+ use windows::Win32::Media::MediaFoundation::{
+ MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MFNominalRange_16_235,
+ MFVideoTransferMatrix_BT709,
+ };
+ mt.SetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_16_235.0 as u32)?;
+ mt.SetUINT32(&MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709.0 as u32)?;
+ }
- let (sample_size, stride, nominal_range) = if *subtype == MFVideoFormat_NV12 {
- (width * height * 3 / 2, width, MFNominalRange_16_235.0 as u32)
- } else {
- (width * height * 4, width * 4, MFNominalRange_0_255.0 as u32)
- };
- mt.SetUINT32(&MF_MT_SAMPLE_SIZE, sample_size)?;
- mt.SetUINT32(&MF_MT_DEFAULT_STRIDE, stride)?;
+ let sample_size =
+ if *subtype == MFVideoFormat_NV12 { width * height * 3 / 2 } else { width * height * 4 };
mt.SetUINT32(&MF_MT_AVG_BITRATE, sample_size.saturating_mul(fps).saturating_mul(8))?;
- mt.SetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE, nominal_range)?;
- mt.SetUINT32(&MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709.0 as u32)?;
Ok(mt)
}
}
@@ -125,7 +151,14 @@ struct SourceInner {
stream: Option<IMFMediaStream>,
}
-#[implement(IMFMediaSourceEx, IMFMediaSource, IMFMediaEventGenerator, IMFGetService)]
+#[implement(
+ IMFMediaSourceEx,
+ IMFMediaSource,
+ IMFMediaEventGenerator,
+ IMFGetService,
+ IKsControl,
+ IMFSampleAllocatorControl
+)]
pub struct VcamMediaSource {
_guard: ObjectGuard,
mapping_name: String,
@@ -153,12 +186,20 @@ impl VcamMediaSource {
attrs
.SetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MFFrameSourceTypes_Color.0 as u32)?;
+ // Publish the legacy profile so Frame Server can expose this source
+ // to clients that do not select a camera profile.
+ let profile_collection = MFCreateSensorProfileCollection()?;
+ let legacy_profile = MFCreateSensorProfile(&KSCAMERAPROFILE_Legacy, 0, PCWSTR::null())?;
+ legacy_profile.AddProfileFilter(0, windows::core::w!("((RES==;FRT<=30,1;SUT==))"))?;
+ profile_collection.AddProfile(&legacy_profile)?;
+ attrs.SetUnknown(&MF_DEVICEMFT_SENSORPROFILE_COLLECTION, &profile_collection)?;
+
let modes =
if mapping_name.starts_with("Local\\NectarlinkVcamSrcTest_") { &MODES[..2] } else { MODES };
let mut media_types = Vec::with_capacity(modes.len() * 2);
for &(w, h, fps) in modes {
- media_types.push(Some(create_video_media_type(&MFVideoFormat_RGB32, w, h, fps)?));
media_types.push(Some(create_video_media_type(&MFVideoFormat_NV12, w, h, fps)?));
+ media_types.push(Some(create_video_media_type(&MFVideoFormat_RGB32, w, h, fps)?));
}
let sd = MFCreateStreamDescriptor(0, &media_types)?;
sd.SetGUID(&MF_DEVICESTREAM_STREAM_CATEGORY, &PINNAME_VIDEO_CAPTURE)?;
@@ -324,17 +365,11 @@ impl IMFMediaSource_Impl for VcamMediaSource_Impl {
}
fn Pause(&self) -> windows::core::Result<()> {
- let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if guard.state == SourceState::Shutdown {
return Err(MF_E_SHUTDOWN.into());
}
- guard.state = SourceState::Paused;
- if let Some(stream) = guard.stream.clone() {
- let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
- stream_impl.on_pause()?;
- }
- let empty = PROPVARIANT::default();
- unsafe { guard.events.QueueEventParamVar(MESourcePaused.0 as u32, &GUID::zeroed(), S_OK, &empty) }
+ Err(windows::Win32::Media::MediaFoundation::MF_E_INVALID_STATE_TRANSITION.into())
}
fn Shutdown(&self) -> windows::core::Result<()> {
@@ -375,8 +410,17 @@ impl IMFMediaSourceEx_Impl for VcamMediaSource_Impl {
Ok(stream_impl.attributes())
}
- fn SetD3DManager(&self, _punkmanager: Ref<'_, IUnknown>) -> windows::core::Result<()> {
- // Software camera frames are delivered in system-memory buffers.
+ fn SetD3DManager(&self, manager: Ref<'_, IUnknown>) -> windows::core::Result<()> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ let stream = guard.stream.as_ref().ok_or(MF_E_SHUTDOWN)?;
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ let mut inner = stream_impl.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(allocator) = &inner.sample_allocator {
+ unsafe {
+ allocator.SetDirectXManager(manager.as_ref())?;
+ }
+ }
+ inner.d3d_manager = manager.as_ref().cloned();
Ok(())
}
}
@@ -391,7 +435,141 @@ impl IMFGetService_Impl for VcamMediaSource_Impl {
if !ppvobject.is_null() {
unsafe { *ppvobject = std::ptr::null_mut() };
}
- Err(MF_E_NO_MORE_TYPES.into())
+ Err(MF_E_UNSUPPORTED_SERVICE.into())
+ }
+}
+
+impl IKsControl_Impl for VcamMediaSource_Impl {
+ fn KsProperty(
+ &self,
+ _property: *const KSIDENTIFIER,
+ _propertylength: u32,
+ _propertydata: *mut std::ffi::c_void,
+ _datalength: u32,
+ bytesreturned: *mut u32,
+ ) -> windows::core::Result<()> {
+ if !bytesreturned.is_null() {
+ unsafe { *bytesreturned = 0 };
+ }
+ Err(HRESULT::from_win32(ERROR_SET_NOT_FOUND.0).into())
+ }
+
+ fn KsMethod(
+ &self,
+ _method: *const KSIDENTIFIER,
+ _methodlength: u32,
+ _methoddata: *mut std::ffi::c_void,
+ _datalength: u32,
+ bytesreturned: *mut u32,
+ ) -> windows::core::Result<()> {
+ if !bytesreturned.is_null() {
+ unsafe { *bytesreturned = 0 };
+ }
+ Err(HRESULT::from_win32(ERROR_SET_NOT_FOUND.0).into())
+ }
+
+ fn KsEvent(
+ &self,
+ _event: *const KSIDENTIFIER,
+ _eventlength: u32,
+ _eventdata: *mut std::ffi::c_void,
+ _datalength: u32,
+ bytesreturned: *mut u32,
+ ) -> windows::core::Result<()> {
+ if !bytesreturned.is_null() {
+ unsafe { *bytesreturned = 0 };
+ }
+ Err(HRESULT::from_win32(ERROR_SET_NOT_FOUND.0).into())
+ }
+}
+
+impl IMFSampleAllocatorControl_Impl for VcamMediaSource_Impl {
+ fn SetDefaultAllocator(
+ &self,
+ dwoutputstreamid: u32,
+ pallocator: Ref<'_, IUnknown>,
+ ) -> windows::core::Result<()> {
+ if dwoutputstreamid != 0 {
+ return Err(MF_E_INVALIDSTREAMNUMBER.into());
+ }
+ let pallocator = pallocator.ok()?;
+ let allocator: IMFVideoSampleAllocator = pallocator.cast()?;
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(stream) = guard.stream.as_ref() else {
+ return Err(MF_E_SHUTDOWN.into());
+ };
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ stream_impl.set_sample_allocator(allocator)
+ }
+
+ fn GetAllocatorUsage(
+ &self,
+ dwoutputstreamid: u32,
+ pdwinputstreamid: *mut u32,
+ peusage: *mut MFSampleAllocatorUsage,
+ ) -> windows::core::Result<()> {
+ if dwoutputstreamid != 0 {
+ return Err(MF_E_INVALIDSTREAMNUMBER.into());
+ }
+ if pdwinputstreamid.is_null() || peusage.is_null() {
+ return Err(E_POINTER.into());
+ }
+ unsafe {
+ *pdwinputstreamid = dwoutputstreamid;
+ *peusage = windows::Win32::Media::MediaFoundation::MFSampleAllocatorUsage_UsesCustomAllocator;
+ }
+ Ok(())
+ }
+}
+
+fn owned_allocator(
+ device: Option<&windows::Win32::Graphics::Direct3D11::ID3D11Device>,
+) -> windows::core::Result<(IMFVideoSampleAllocator, Option<IUnknown>)> {
+ use windows::Win32::Media::MediaFoundation::{MFCreateDXGIDeviceManager, MFCreateVideoSampleAllocatorEx};
+ unsafe {
+ let mut raw = std::ptr::null_mut();
+ MFCreateVideoSampleAllocatorEx(&IMFVideoSampleAllocator::IID, &mut raw)?;
+ let allocator = IMFVideoSampleAllocator::from_raw(raw);
+ let manager = if let Some(device) = device {
+ if let Ok(multithread) = device.cast::<windows::Win32::Graphics::Direct3D11::ID3D11Multithread>()
+ {
+ let _ = multithread.SetMultithreadProtected(true);
+ }
+ let mut token = 0;
+ let mut manager = None;
+ MFCreateDXGIDeviceManager(&mut token, &mut manager)?;
+ let manager = manager.ok_or(E_POINTER)?;
+ manager.ResetDevice(device, token)?;
+ allocator.SetDirectXManager(&manager)?;
+ Some(manager.cast()?)
+ } else {
+ None
+ };
+ Ok((allocator, manager))
+ }
+}
+
+fn initialize_allocator(
+ allocator: &IMFVideoSampleAllocator,
+ media_type: &IMFMediaType,
+ gpu: bool,
+) -> windows::core::Result<()> {
+ use windows::Win32::Media::MediaFoundation::{IMFVideoSampleAllocatorEx, MF_SA_D3D11_BINDFLAGS};
+ unsafe {
+ if gpu {
+ let mut attrs = None;
+ MFCreateAttributes(&mut attrs, 1)?;
+ let attrs = attrs.ok_or(E_POINTER)?;
+ attrs.SetUINT32(
+ &MF_SA_D3D11_BINDFLAGS,
+ windows::Win32::Graphics::Direct3D11::D3D11_BIND_RENDER_TARGET.0 as u32,
+ )?;
+ allocator
+ .cast::<IMFVideoSampleAllocatorEx>()?
+ .InitializeSampleAllocatorEx(10, 10, &attrs, media_type)
+ } else {
+ allocator.InitializeSampleAllocator(10, media_type)
+ }
}
}
@@ -403,8 +581,15 @@ struct StreamInner {
sd: IMFStreamDescriptor,
source: IMFMediaSource,
mapping: Option<Arc<SharedFrameMapping>>,
- sample_index: u64,
+ sample_allocator: Option<IMFVideoSampleAllocator>,
+ owns_allocator: bool,
+ gpu_allocator_attempted: bool,
+ retired_allocators: Vec<IMFVideoSampleAllocator>,
+ d3d_manager: Option<IUnknown>,
+ gpu_reader: Option<GpuReader>,
+ last_sample_time: i64,
bgrx_scratch: Vec<u8>,
+ nv12_scratch: Vec<u8>,
}
#[implement(IMFMediaStream2, IMFMediaStream, IMFMediaEventGenerator)]
@@ -437,6 +622,7 @@ impl VcamMediaStream {
attrs
.SetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MFFrameSourceTypes_Color.0 as u32)?;
let mapping = SharedFrameMapping::for_camera(&mapping_name).ok().map(Arc::new);
+ let gpu_reader = if mapping_name == DEFAULT_MAPPING_NAME { GpuReader::new().ok() } else { None };
let stream: IMFMediaStream = Self {
_guard: ObjectGuard::new(),
mapping_name,
@@ -448,8 +634,15 @@ impl VcamMediaStream {
sd: sd.clone(),
source: source.clone(),
mapping,
- sample_index: 0,
+ sample_allocator: None,
+ owns_allocator: false,
+ gpu_allocator_attempted: false,
+ retired_allocators: Vec::new(),
+ d3d_manager: None,
+ gpu_reader,
+ last_sample_time: 0,
bgrx_scratch: Vec::new(),
+ nv12_scratch: Vec::new(),
}),
}
.into();
@@ -470,17 +663,70 @@ impl VcamMediaStream {
if guard.mapping.is_none() {
guard.mapping = SharedFrameMapping::for_camera(&self.mapping_name).ok().map(Arc::new);
}
+ if guard.sample_allocator.is_none() {
+ let device = guard.gpu_reader.as_mut().and_then(|reader| reader.active_device().ok().flatten());
+ let (allocator, manager) = owned_allocator(device.as_ref()).or_else(|_| owned_allocator(None))?;
+ guard.sample_allocator = Some(allocator);
+ guard.d3d_manager = manager;
+ guard.owns_allocator = true;
+ guard.gpu_allocator_attempted = device.is_some();
+ }
+ unsafe {
+ let handler = guard.sd.GetMediaTypeHandler()?;
+ let media_type = handler.GetCurrentMediaType()?;
+ let result = initialize_allocator(
+ guard.sample_allocator.as_ref().ok_or(E_POINTER)?,
+ &media_type,
+ guard.owns_allocator && guard.d3d_manager.is_some(),
+ );
+ if let Err(error) = result {
+ if guard.owns_allocator && guard.d3d_manager.is_some() {
+ let (allocator, _) = owned_allocator(None)?;
+ allocator.InitializeSampleAllocator(10, &media_type)?;
+ guard.sample_allocator = Some(allocator);
+ guard.d3d_manager = None;
+ guard.gpu_allocator_attempted = true;
+ } else {
+ return Err(error);
+ }
+ }
+ }
guard.state = MF_STREAM_STATE_RUNNING;
- guard.sample_index = 0;
+ guard.last_sample_time = 0;
unsafe { guard.events.QueueEventParamVar(MEStreamStarted.0 as u32, &GUID::zeroed(), S_OK, pos) }
}
+ fn set_sample_allocator(&self, allocator: IMFVideoSampleAllocator) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ if guard.state == MF_STREAM_STATE_RUNNING {
+ return Err(E_INVALIDARG.into());
+ }
+ if let Some(manager) = &guard.d3d_manager {
+ unsafe {
+ allocator.SetDirectXManager(manager)?;
+ }
+ }
+ guard.sample_allocator = Some(allocator);
+ guard.owns_allocator = false;
+ Ok(())
+ }
+
fn on_stop(&self) -> windows::core::Result<()> {
let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if guard.shutdown {
return Err(MF_E_SHUTDOWN.into());
}
guard.state = MF_STREAM_STATE_STOPPED;
+ if guard.owns_allocator {
+ guard.sample_allocator = None;
+ guard.d3d_manager = None;
+ guard.retired_allocators.clear();
+ guard.owns_allocator = false;
+ guard.gpu_allocator_attempted = false;
+ }
let empty = PROPVARIANT::default();
unsafe { guard.events.QueueEventParamVar(MEStreamStopped.0 as u32, &GUID::zeroed(), S_OK, &empty) }
}
@@ -594,37 +840,199 @@ impl IMFMediaStream_Impl for VcamMediaStream_Impl {
let height = (frame_size as u32).max(1);
let bgrx_len = (width as usize) * (height as usize) * 4;
- if guard.bgrx_scratch.len() < bgrx_len {
- guard.bgrx_scratch.resize(bgrx_len, 0);
- }
- if let Some(mapping) = guard.mapping.clone() {
- mapping.read_bgrx(width, height, &mut guard.bgrx_scratch[..bgrx_len]);
- } else {
- render_placeholder_bgrx(&mut guard.bgrx_scratch[..bgrx_len], width, height, "");
- }
-
let out_bytes = if subtype == MFVideoFormat_NV12 {
(width as usize) * (height as usize) * 3 / 2
} else {
bgrx_len
};
- let buffer = MFCreateMemoryBuffer(out_bytes as u32)?;
- let mut ptr = std::ptr::null_mut();
- buffer.Lock(&mut ptr, None, None)?;
- let dst = std::slice::from_raw_parts_mut(ptr, out_bytes);
- if subtype == MFVideoFormat_NV12 {
- bgrx_to_nv12(&guard.bgrx_scratch[..bgrx_len], width, height, dst);
+ if guard.owns_allocator && !guard.gpu_allocator_attempted {
+ let device =
+ guard.gpu_reader.as_mut().and_then(|reader| reader.active_device().ok().flatten());
+ if let Some(device) = device {
+ guard.gpu_allocator_attempted = true;
+ if let Ok((allocator, manager)) = owned_allocator(Some(&device))
+ && initialize_allocator(&allocator, &mt, true).is_ok()
+ {
+ if let Some(previous) = guard.sample_allocator.replace(allocator) {
+ guard.retired_allocators.push(previous);
+ }
+ guard.d3d_manager = manager;
+ }
+ }
+ }
+ let allocator = match guard.sample_allocator.as_ref() {
+ Some(allocator) => allocator,
+ None => {
+ return Err(E_POINTER.into());
+ }
+ };
+ let sample = allocator.AllocateSample()?;
+ let buffer = sample.GetBufferByIndex(0)?;
+ // Requests may arrive much faster than the advertised frame rate,
+ // especially with GPU output. Pace repeated frames against QPC;
+ // never stamp a rapidly generated sample far into the future.
+ let now = MFGetSystemTime();
+ let due = guard.last_sample_time.saturating_add(SAMPLE_DURATION_100NS);
+ if now < due {
+ std::thread::sleep(std::time::Duration::from_nanos((due - now) as u64 * 100));
+ }
+ let sample_time = MFGetSystemTime();
+ guard.last_sample_time = sample_time;
+ let gpu_written = if subtype == MFVideoFormat_NV12 {
+ if let Some(reader) = &mut guard.gpu_reader {
+ match reader.write_nv12(&buffer, width, height) {
+ Ok(written) => written,
+ Err(error) => {
+ reader.disable_with_error(&error);
+ false
+ }
+ }
+ } else {
+ false
+ }
} else {
- dst.copy_from_slice(&guard.bgrx_scratch[..bgrx_len]);
+ false
+ };
+ if !gpu_written {
+ if guard.bgrx_scratch.len() < bgrx_len {
+ guard.bgrx_scratch.resize(bgrx_len, 0);
+ }
+ let inner: &mut StreamInner = &mut guard;
+ let gpu_rgb = if let Some(reader) = &mut inner.gpu_reader {
+ match reader.read_bgrx(width, height, &mut inner.bgrx_scratch[..bgrx_len]) {
+ Ok(read) => read,
+ Err(error) => {
+ reader.disable_with_error(&error);
+ false
+ }
+ }
+ } else {
+ false
+ };
+ if !gpu_rgb {
+ if let Some(mapping) = guard.mapping.clone() {
+ mapping.read_bgrx(width, height, &mut guard.bgrx_scratch[..bgrx_len]);
+ } else {
+ render_placeholder_bgrx(&mut guard.bgrx_scratch[..bgrx_len], width, height, "");
+ }
+ }
+ if (buffer.GetMaxLength()? as usize) < out_bytes {
+ return Err(E_INVALIDARG.into());
+ }
+ let buffer2d: windows::core::Result<IMF2DBuffer2> = buffer.cast();
+ match buffer2d {
+ Ok(buffer2d) => {
+ let mut scanline0 = std::ptr::null_mut();
+ let mut pitch = 0i32;
+ let mut buffer_start = std::ptr::null_mut();
+ let mut buffer_length = 0u32;
+ buffer2d.Lock2DSize(
+ MF2DBuffer_LockFlags_Write,
+ &mut scanline0,
+ &mut pitch,
+ &mut buffer_start,
+ &mut buffer_length,
+ )?;
+
+ let write_result = (|| -> windows::core::Result<()> {
+ let stride = pitch.unsigned_abs() as usize;
+ let row_bytes = if subtype == MFVideoFormat_NV12 {
+ width as usize
+ } else {
+ width as usize * 4
+ };
+ let h = height as usize;
+ if scanline0.is_null() || buffer_start.is_null() || stride < row_bytes {
+ return Err(E_INVALIDARG.into());
+ }
+ if subtype == MFVideoFormat_NV12 {
+ if !height.is_multiple_of(2) {
+ return Err(E_INVALIDARG.into());
+ }
+ if guard.nv12_scratch.len() < out_bytes {
+ guard.nv12_scratch.resize(out_bytes, 0);
+ }
+ let inner: &mut StreamInner = &mut guard;
+ bgrx_to_nv12(
+ &inner.bgrx_scratch[..bgrx_len],
+ width,
+ height,
+ &mut inner.nv12_scratch[..out_bytes],
+ );
+ }
+ let plane_bytes = stride
+ .checked_mul(h)
+ .ok_or_else(|| windows::core::Error::from(E_INVALIDARG))?;
+ let required_length = if subtype == MFVideoFormat_NV12 {
+ plane_bytes
+ .checked_add(
+ stride
+ .checked_mul(h / 2)
+ .ok_or_else(|| windows::core::Error::from(E_INVALIDARG))?,
+ )
+ .ok_or_else(|| windows::core::Error::from(E_INVALIDARG))?
+ } else {
+ plane_bytes
+ };
+ if (buffer_length as usize) < required_length {
+ return Err(E_INVALIDARG.into());
+ }
+
+ for row in 0..h {
+ let dst_row = if pitch >= 0 {
+ scanline0.add(row * stride)
+ } else {
+ scanline0.offset((row as isize) * (pitch as isize))
+ };
+ if subtype == MFVideoFormat_NV12 {
+ let src_row = &guard.nv12_scratch
+ [row * width as usize..row * width as usize + row_bytes];
+ std::ptr::copy_nonoverlapping(src_row.as_ptr(), dst_row, row_bytes);
+ } else {
+ let src_row = &guard.bgrx_scratch[row * row_bytes..(row + 1) * row_bytes];
+ std::ptr::copy_nonoverlapping(src_row.as_ptr(), dst_row, row_bytes);
+ }
+ }
+
+ if subtype == MFVideoFormat_NV12 {
+ let uv_plane = if pitch >= 0 {
+ scanline0.add(plane_bytes)
+ } else {
+ buffer_start.add(plane_bytes + stride * (h / 2 - 1))
+ };
+ let source_uv = width as usize * h;
+ for row in 0..(h / 2) {
+ let dst_row = if pitch >= 0 {
+ uv_plane.add(row * stride)
+ } else {
+ uv_plane.sub(row * stride)
+ };
+ let src_row = &guard.nv12_scratch[source_uv + row * width as usize
+ ..source_uv + (row + 1) * width as usize];
+ std::ptr::copy_nonoverlapping(src_row.as_ptr(), dst_row, width as usize);
+ }
+ }
+ Ok(())
+ })();
+ let unlock_result = buffer2d.Unlock2D();
+ write_result?;
+ unlock_result?;
+ }
+ Err(_) => {
+ let mut ptr = std::ptr::null_mut();
+ buffer.Lock(&mut ptr, None, None)?;
+ let dst = std::slice::from_raw_parts_mut(ptr, out_bytes);
+ if subtype == MFVideoFormat_NV12 {
+ bgrx_to_nv12(&guard.bgrx_scratch[..bgrx_len], width, height, dst);
+ } else {
+ dst.copy_from_slice(&guard.bgrx_scratch[..bgrx_len]);
+ }
+ buffer.Unlock()?;
+ buffer.SetCurrentLength(out_bytes as u32)?;
+ }
+ }
}
- buffer.Unlock()?;
- buffer.SetCurrentLength(out_bytes as u32)?;
-
- let sample = MFCreateSample()?;
- sample.AddBuffer(&buffer)?;
- let sample_time = (guard.sample_index as i64).saturating_mul(SAMPLE_DURATION_100NS);
- guard.sample_index = guard.sample_index.wrapping_add(1);
sample.SetSampleTime(sample_time)?;
sample.SetSampleDuration(SAMPLE_DURATION_100NS)?;
sample.SetUINT32(&MFSampleExtension_CleanPoint, 1)?;
@@ -661,7 +1069,238 @@ impl IMFMediaStream2_Impl for VcamMediaStream_Impl {
}
}
-/// COM `IClassFactory` creating [`VcamMediaSource`] instances.
+/// `IMFActivate` implementation returned to Media Foundation for this source.
+/// `MFCreateVirtualCamera` asks the registered class for an activation object;
+/// activation then creates (and caches) the source instance.
+#[implement(IMFActivate)]
+pub struct VcamMediaSourceActivate {
+ attrs: IMFAttributes,
+ source: Mutex<Option<IMFMediaSourceEx>>,
+}
+
+impl std::fmt::Debug for VcamMediaSourceActivate {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VcamMediaSourceActivate").finish()
+ }
+}
+
+impl VcamMediaSourceActivate {
+ fn new() -> windows::core::Result<Self> {
+ let mut attrs = None;
+ unsafe {
+ MFCreateAttributes(&mut attrs, 8)?;
+ }
+ let attrs = attrs.ok_or_else(|| windows::core::Error::from(E_POINTER))?;
+ Ok(Self { attrs, source: Mutex::new(None) })
+ }
+}
+
+impl IMFActivate_Impl for VcamMediaSourceActivate_Impl {
+ fn ActivateObject(
+ &self,
+ riid: *const GUID,
+ ppv: *mut *mut std::ffi::c_void,
+ ) -> windows::core::Result<()> {
+ if ppv.is_null() {
+ return Err(E_POINTER.into());
+ }
+ unsafe {
+ *ppv = std::ptr::null_mut();
+ }
+ if riid.is_null() {
+ return Err(E_INVALIDARG.into());
+ }
+
+ let mut source = self.source.lock().unwrap_or_else(|e| e.into_inner());
+ if source.is_none() {
+ let created = VcamMediaSource::new_with_mapping(DEFAULT_MAPPING_NAME)?;
+ let source_attrs = unsafe { created.GetSourceAttributes() }?;
+ merge_attributes(&self.attrs, &source_attrs)?;
+ source.replace(created);
+ }
+ let source = source.as_ref().expect("source created above");
+ let unknown: IUnknown = source.cast()?;
+ unsafe { unknown.query(riid, ppv).ok() }
+ }
+
+ fn ShutdownObject(&self) -> windows::core::Result<()> {
+ Err(E_NOTIMPL.into())
+ }
+
+ fn DetachObject(&self) -> windows::core::Result<()> {
+ Err(E_NOTIMPL.into())
+ }
+}
+
+impl IMFAttributes_Impl for VcamMediaSourceActivate_Impl {
+ fn GetItem(
+ &self,
+ key: *const GUID,
+ value: *mut windows::Win32::System::Com::StructuredStorage::PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ unsafe { self.attrs.GetItem(key, Some(value)) }
+ }
+ fn GetItemType(
+ &self,
+ key: *const GUID,
+ ) -> windows::core::Result<windows::Win32::Media::MediaFoundation::MF_ATTRIBUTE_TYPE> {
+ unsafe { self.attrs.GetItemType(key) }
+ }
+ fn CompareItem(
+ &self,
+ key: *const GUID,
+ value: *const windows::Win32::System::Com::StructuredStorage::PROPVARIANT,
+ ) -> windows::core::Result<BOOL> {
+ unsafe { self.attrs.CompareItem(key, value) }
+ }
+ fn Compare(
+ &self,
+ theirs: Ref<'_, IMFAttributes>,
+ match_type: windows::Win32::Media::MediaFoundation::MF_ATTRIBUTES_MATCH_TYPE,
+ ) -> windows::core::Result<BOOL> {
+ let theirs = theirs.ok()?;
+ unsafe { self.attrs.Compare(theirs, match_type) }
+ }
+ fn GetUINT32(&self, key: *const GUID) -> windows::core::Result<u32> {
+ unsafe { self.attrs.GetUINT32(key) }
+ }
+ fn GetUINT64(&self, key: *const GUID) -> windows::core::Result<u64> {
+ unsafe { self.attrs.GetUINT64(key) }
+ }
+ fn GetDouble(&self, key: *const GUID) -> windows::core::Result<f64> {
+ unsafe { self.attrs.GetDouble(key) }
+ }
+ fn GetGUID(&self, key: *const GUID) -> windows::core::Result<GUID> {
+ unsafe { self.attrs.GetGUID(key) }
+ }
+ fn GetStringLength(&self, key: *const GUID) -> windows::core::Result<u32> {
+ unsafe { self.attrs.GetStringLength(key) }
+ }
+ fn GetString(
+ &self,
+ key: *const GUID,
+ value: PWSTR,
+ size: u32,
+ length: *mut u32,
+ ) -> windows::core::Result<()> {
+ if value.0.is_null() && size != 0 {
+ return Err(E_POINTER.into());
+ }
+ let buffer = if value.0.is_null() {
+ &mut []
+ } else {
+ unsafe { std::slice::from_raw_parts_mut(value.0, size as usize) }
+ };
+ unsafe { self.attrs.GetString(key, buffer, Some(length)) }
+ }
+ fn GetAllocatedString(
+ &self,
+ key: *const GUID,
+ value: *mut PWSTR,
+ length: *mut u32,
+ ) -> windows::core::Result<()> {
+ unsafe { self.attrs.GetAllocatedString(key, value, length) }
+ }
+ fn GetBlobSize(&self, key: *const GUID) -> windows::core::Result<u32> {
+ unsafe { self.attrs.GetBlobSize(key) }
+ }
+ fn GetBlob(
+ &self,
+ key: *const GUID,
+ value: *mut u8,
+ size: u32,
+ actual: *mut u32,
+ ) -> windows::core::Result<()> {
+ if value.is_null() && size != 0 {
+ return Err(E_POINTER.into());
+ }
+ let buffer = if value.is_null() {
+ &mut []
+ } else {
+ unsafe { std::slice::from_raw_parts_mut(value, size as usize) }
+ };
+ unsafe { self.attrs.GetBlob(key, buffer, Some(actual)) }
+ }
+ fn GetAllocatedBlob(
+ &self,
+ key: *const GUID,
+ value: *mut *mut u8,
+ size: *mut u32,
+ ) -> windows::core::Result<()> {
+ unsafe { self.attrs.GetAllocatedBlob(key, value, size) }
+ }
+ fn GetUnknown(
+ &self,
+ key: *const GUID,
+ riid: *const GUID,
+ value: *mut *mut std::ffi::c_void,
+ ) -> windows::core::Result<()> {
+ let unknown: IUnknown = unsafe { self.attrs.GetUnknown(key) }?;
+ unsafe { unknown.query(riid, value).ok() }
+ }
+ fn SetItem(
+ &self,
+ key: *const GUID,
+ value: *const windows::Win32::System::Com::StructuredStorage::PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetItem(key, value) }
+ }
+ fn DeleteItem(&self, key: *const GUID) -> windows::core::Result<()> {
+ unsafe { self.attrs.DeleteItem(key) }
+ }
+ fn DeleteAllItems(&self) -> windows::core::Result<()> {
+ unsafe { self.attrs.DeleteAllItems() }
+ }
+ fn SetUINT32(&self, key: *const GUID, value: u32) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetUINT32(key, value) }
+ }
+ fn SetUINT64(&self, key: *const GUID, value: u64) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetUINT64(key, value) }
+ }
+ fn SetDouble(&self, key: *const GUID, value: f64) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetDouble(key, value) }
+ }
+ fn SetGUID(&self, key: *const GUID, value: *const GUID) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetGUID(key, value) }
+ }
+ fn SetString(&self, key: *const GUID, value: &PCWSTR) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetString(key, *value) }
+ }
+ fn SetBlob(&self, key: *const GUID, value: *const u8, size: u32) -> windows::core::Result<()> {
+ if value.is_null() && size != 0 {
+ return Err(E_POINTER.into());
+ }
+ let buffer =
+ if value.is_null() { &[] } else { unsafe { std::slice::from_raw_parts(value, size as usize) } };
+ unsafe { self.attrs.SetBlob(key, buffer) }
+ }
+ fn SetUnknown(&self, key: *const GUID, value: Ref<'_, IUnknown>) -> windows::core::Result<()> {
+ unsafe { self.attrs.SetUnknown(key, value.as_ref()) }
+ }
+ fn LockStore(&self) -> windows::core::Result<()> {
+ unsafe { self.attrs.LockStore() }
+ }
+ fn UnlockStore(&self) -> windows::core::Result<()> {
+ unsafe { self.attrs.UnlockStore() }
+ }
+ fn GetCount(&self) -> windows::core::Result<u32> {
+ unsafe { self.attrs.GetCount() }
+ }
+ fn GetItemByIndex(
+ &self,
+ index: u32,
+ key: *mut GUID,
+ value: *mut windows::Win32::System::Com::StructuredStorage::PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ unsafe { self.attrs.GetItemByIndex(index, key, Some(value)) }
+ }
+ fn CopyAllItems(&self, dest: Ref<'_, IMFAttributes>) -> windows::core::Result<()> {
+ let dest = dest.ok()?;
+ unsafe { self.attrs.CopyAllItems(dest) }
+ }
+}
+
+/// COM `IClassFactory` creating IMFActivate objects for [`VcamMediaSource`].
#[implement(IClassFactory)]
pub struct VcamClassFactory {
_guard: ObjectGuard,
@@ -703,8 +1342,9 @@ impl IClassFactory_Impl for VcamClassFactory_Impl {
if riid.is_null() {
return Err(E_INVALIDARG.into());
}
- let source = VcamMediaSource::new_with_mapping(DEFAULT_MAPPING_NAME)?;
- let unk: IUnknown = source.cast()?;
+ let activate = VcamMediaSourceActivate::new()?;
+ let activate: IMFActivate = activate.into();
+ let unk: IUnknown = activate.cast()?;
unsafe { unk.query(riid, ppvobject).ok() }
}