Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

introduce camera-windows

Brendan Allan881b694e7ae5
diff --git a/Cargo.lock b/Cargo.lock
index 106a7f9d3..9454e3b30 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -895,16 +895,6 @@ dependencies = [
"system-deps",
]
-[[package]]
-name = "camera-mediafoundation"
-version = "0.1.0"
-dependencies = [
- "inquire",
- "tracing",
- "windows 0.60.0",
- "windows-core 0.60.1",
-]
-
[[package]]
name = "camino"
version = "1.1.9"
@@ -971,6 +961,29 @@ dependencies = [
"windows-core 0.60.1",
]
+[[package]]
+name = "cap-camera-mediafoundation"
+version = "0.1.0"
+dependencies = [
+ "inquire",
+ "tracing",
+ "windows 0.60.0",
+ "windows-core 0.60.1",
+]
+
+[[package]]
+name = "cap-camera-windows"
+version = "0.1.0"
+dependencies = [
+ "cap-camera-directshow",
+ "cap-camera-mediafoundation",
+ "ffmpeg-next",
+ "inquire",
+ "thiserror 1.0.69",
+ "windows 0.60.0",
+ "windows-core 0.60.1",
+]
+
[[package]]
name = "cap-cursor-capture"
version = "0.1.0"
diff --git a/crates/camera-directshow/examples/cli.rs b/crates/camera-directshow/examples/cli.rs
index df6cff5fa..accc82541 100644
--- a/crates/camera-directshow/examples/cli.rs
+++ b/crates/camera-directshow/examples/cli.rs
@@ -17,7 +17,7 @@ fn main() {
unsafe {
CoInitialize(None).unwrap();
- let devices = VideoInputDeviceEnumerator::new().unwrap().to_vec();
+ let devices = VideoInputDeviceIterator::new().unwrap().collect::<Vec<_>>();
let mut devices = devices
.iter()
@@ -36,11 +36,11 @@ fn main() {
let property_data: IPropertyBag = moniker.BindToStorage(None, None).unwrap();
let device_name = property_data
- .read(windows_core::w!("FriendlyName"), None)
+ .read(windows_core::w!("FriendlyName"))
.unwrap();
let device_path = property_data
- .read(windows_core::w!("DevicePath"), None)
+ .read(windows_core::w!("DevicePath"))
.unwrap_or_default();
let device_name = device_name.to_os_string().unwrap();
@@ -78,21 +78,11 @@ impl Display for Format {
}
}
-struct VideoDeviceSelectOption<'a>(&'a IMoniker);
+struct VideoDeviceSelectOption<'a>(&'a VideoInputDevice);
impl<'a> Display for VideoDeviceSelectOption<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let device_name = unsafe {
- let property_data: IPropertyBag = self.0.BindToStorage(None, None).unwrap();
-
- let device_name = property_data
- .read(windows_core::w!("FriendlyName"), None)
- .unwrap();
-
- device_name.to_os_string().unwrap()
- };
-
- write!(f, "{:?}", device_name)
+ write!(f, "{:?}", self.0.name().unwrap())
}
}
@@ -106,7 +96,7 @@ unsafe fn chromium_main(capture_filter: IBaseFilter) {
let stream_config = output_capture_pin.cast::<IAMStreamConfig>().unwrap();
let video_control = output_capture_pin.cast::<IAMVideoControl>().ok();
- let mut media_types_iter = stream_config.media_types();
+ let mut media_types_iter = stream_config.media_types().unwrap();
// println!("Formats: {}", media_types_iter.count());
diff --git a/crates/camera-directshow/src/lib.rs b/crates/camera-directshow/src/lib.rs
index e32222ac3..3fdb620c3 100644
--- a/crates/camera-directshow/src/lib.rs
+++ b/crates/camera-directshow/src/lib.rs
@@ -15,7 +15,9 @@ use windows::{
Foundation::*,
Media::{
DirectShow::*,
- KernelStreaming::{IKsPropertySet, KS_BITMAPINFOHEADER, KS_VIDEOINFOHEADER},
+ KernelStreaming::{
+ IKsPropertySet, KS_BITMAPINFOHEADER, KS_VIDEOINFO, KS_VIDEOINFOHEADER,
+ },
MediaFoundation::*,
},
System::{
@@ -27,6 +29,10 @@ use windows::{
};
use windows_core::{ComObject, ComObjectInner, GUID, PWSTR, implement};
+pub fn initialize_directshow() -> windows_core::Result<()> {
+ unsafe { CoInitialize(None) }.ok()
+}
+
pub trait IPinExt {
unsafe fn matches_category(&self, category: GUID) -> bool;
unsafe fn matches_major_type(&self, major_type: GUID) -> bool;
@@ -60,44 +66,38 @@ impl IPinExt for IPin {
}
pub trait IBaseFilterExt {
- unsafe fn get_pin(
- &self,
- direction: PIN_DIRECTION,
- category: GUID,
- major_type: GUID,
- ) -> Option<IPin>;
+ fn get_pin(&self, direction: PIN_DIRECTION, category: GUID, major_type: GUID) -> Option<IPin>;
unsafe fn get_pin_by_name(
&self,
direction: PIN_DIRECTION,
name: Option<&PWSTR>,
- ) -> Option<IPin>;
+ ) -> windows_core::Result<Option<IPin>>;
}
impl IBaseFilterExt for IBaseFilter {
- unsafe fn get_pin(
- &self,
- direction: PIN_DIRECTION,
- category: GUID,
- major_type: GUID,
- ) -> Option<IPin> {
- let pin_enum = self.EnumPins().unwrap();
-
- let _ = pin_enum.Reset();
-
- let mut pin = [None];
- while pin_enum.Next(&mut pin, None) == S_OK {
- let Some(pin) = pin[0].take() else {
- break;
- };
+ fn get_pin(&self, direction: PIN_DIRECTION, category: GUID, major_type: GUID) -> Option<IPin> {
+ unsafe {
+ let pin_enum = self.EnumPins().ok()?;
- let pin_dir = pin.QueryDirection().unwrap();
+ let _ = pin_enum.Reset();
- if pin_dir == direction {
- if (category == GUID::zeroed() || pin.matches_category(category))
- && (major_type == GUID::zeroed() || pin.matches_major_type(major_type))
- {
- return Some(pin);
+ let mut pin = [None];
+ while pin_enum.Next(&mut pin, None) == S_OK {
+ let Some(pin) = pin[0].take() else {
+ break;
+ };
+
+ let Ok(pin_dir) = pin.QueryDirection() else {
+ continue;
+ };
+
+ if pin_dir == direction {
+ if (category == GUID::zeroed() || pin.matches_category(category))
+ && (major_type == GUID::zeroed() || pin.matches_major_type(major_type))
+ {
+ return Some(pin);
+ }
}
}
}
@@ -109,8 +109,8 @@ impl IBaseFilterExt for IBaseFilter {
&self,
direction: PIN_DIRECTION,
_name: Option<&PWSTR>,
- ) -> Option<IPin> {
- let pin_enum = self.EnumPins().unwrap();
+ ) -> windows_core::Result<Option<IPin>> {
+ let pin_enum = self.EnumPins()?;
let _ = pin_enum.Reset();
@@ -123,22 +123,24 @@ impl IBaseFilterExt for IBaseFilter {
let pin_dir = pin.QueryDirection().unwrap();
if pin_dir == direction {
- return Some(pin);
+ return Ok(Some(pin));
}
}
- None
+ Ok(None)
}
}
pub trait VARIANTExt {
- unsafe fn to_os_string(&self) -> Option<OsString>;
+ fn to_os_string(&self) -> Option<OsString>;
}
impl VARIANTExt for VARIANT {
- unsafe fn to_os_string(&self) -> Option<OsString> {
- (self.Anonymous.Anonymous.vt == VT_BSTR)
- .then(|| OsString::from_wide(self.Anonymous.Anonymous.Anonymous.bstrVal.deref()))
+ fn to_os_string(&self) -> Option<OsString> {
+ unsafe {
+ (self.Anonymous.Anonymous.vt == VT_BSTR)
+ .then(|| OsString::from_wide(self.Anonymous.Anonymous.Anonymous.bstrVal.deref()))
+ }
}
}
@@ -150,7 +152,7 @@ pub struct IAMStreamConfigMediaTypes<'a> {
}
impl<'a> IAMStreamConfigMediaTypes<'a> {
- pub unsafe fn next(&mut self) -> Option<(&'a AM_MEDIA_TYPEVideo, i32)> {
+ pub fn next(&mut self) -> Option<(&'a AM_MEDIA_TYPEVideo, i32)> {
let i = self.i;
if i >= self.count as i32 {
@@ -161,15 +163,17 @@ impl<'a> IAMStreamConfigMediaTypes<'a> {
let mut media_type = null_mut();
- self.stream_config
- .GetStreamCaps(i, &mut media_type, (&raw mut self.caps).cast::<u8>())
- .unwrap();
+ unsafe {
+ self.stream_config
+ .GetStreamCaps(i, &mut media_type, (&raw mut self.caps).cast::<u8>())
+ .unwrap();
- if media_type.is_null() {
- return None;
- }
+ if media_type.is_null() {
+ return None;
+ }
- Some((&*media_type, i))
+ Some((&*media_type, i))
+ }
}
pub fn count(&self) -> u32 {
@@ -178,20 +182,20 @@ impl<'a> IAMStreamConfigMediaTypes<'a> {
}
pub trait IAMStreamConfigExt {
- unsafe fn media_types(&self) -> IAMStreamConfigMediaTypes;
+ fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes>;
}
impl IAMStreamConfigExt for IAMStreamConfig {
- unsafe fn media_types(&self) -> IAMStreamConfigMediaTypes {
+ fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes> {
let mut count = 0;
- self.GetNumberOfCapabilities(&mut count, &mut 0).unwrap();
+ unsafe { self.GetNumberOfCapabilities(&mut count, &mut 0) }?;
- IAMStreamConfigMediaTypes {
+ Ok(IAMStreamConfigMediaTypes {
stream_config: &self,
count: count as u32,
caps: VIDEO_STREAM_CONFIG_CAPS::default(),
i: 0,
- }
+ })
}
}
@@ -252,67 +256,147 @@ impl IAMVideoControlExt for IAMVideoControl {
}
pub trait IPropertyBagExt {
- unsafe fn read<P0, P2>(&self, pszpropname: P0, perrorlog: P2) -> windows_core::Result<VARIANT>
+ unsafe fn read<P0>(&self, pszpropname: P0) -> windows_core::Result<VARIANT>
where
- P0: windows_core::Param<windows_core::PCWSTR>,
- P2: windows_core::Param<IErrorLog>;
+ P0: windows_core::Param<windows_core::PCWSTR>;
}
impl IPropertyBagExt for IPropertyBag {
- unsafe fn read<P0, P2>(&self, pszpropname: P0, perrorlog: P2) -> windows_core::Result<VARIANT>
+ unsafe fn read<P0>(&self, pszpropname: P0) -> windows_core::Result<VARIANT>
where
P0: windows_core::Param<windows_core::PCWSTR>,
- P2: windows_core::Param<IErrorLog>,
{
let mut ret = VARIANT::default();
- self.Read(pszpropname, &mut ret, perrorlog)?;
+ self.Read(pszpropname, &mut ret, None)?;
Ok(ret)
}
}
-type VideoInputDeviceIMoniker = IMoniker;
-
-pub struct VideoInputDeviceEnumerator {
+pub struct VideoInputDeviceIterator {
enum_moniker: IEnumMoniker,
- moniker: [Option<VideoInputDeviceIMoniker>; 1],
+ moniker: [Option<IMoniker>; 1],
}
-impl VideoInputDeviceEnumerator {
- pub unsafe fn new() -> windows_core::Result<Self> {
- let create_device_enum: ICreateDevEnum = CoCreateInstance(
- &CLSID_SystemDeviceEnum,
- None::<&windows_core::IUnknown>,
- CLSCTX_INPROC_SERVER,
- )?;
+impl VideoInputDeviceIterator {
+ pub fn new() -> windows_core::Result<Self> {
+ let enum_moniker = unsafe {
+ let create_device_enum: ICreateDevEnum = CoCreateInstance(
+ &CLSID_SystemDeviceEnum,
+ None::<&windows_core::IUnknown>,
+ CLSCTX_INPROC_SERVER,
+ )?;
- let mut enum_moniker = None;
+ let mut enum_moniker = None;
- create_device_enum.CreateClassEnumerator(
- &CLSID_VideoInputDeviceCategory,
- &mut enum_moniker,
- 0,
- )?;
+ create_device_enum.CreateClassEnumerator(
+ &CLSID_VideoInputDeviceCategory,
+ &mut enum_moniker,
+ 0,
+ )?;
+
+ enum_moniker.expect("enum_moniker is None after create succeeded!")
+ };
Ok(Self {
- enum_moniker: enum_moniker.unwrap(),
+ enum_moniker,
moniker: [None],
})
}
+}
- pub unsafe fn next(&mut self) -> Option<VideoInputDeviceIMoniker> {
- if self.enum_moniker.Next(&mut self.moniker, None) == S_OK {
- return self.moniker[0].take();
+impl Iterator for VideoInputDeviceIterator {
+ type Item = VideoInputDevice;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ while unsafe { self.enum_moniker.Next(&mut self.moniker, None) } == S_OK {
+ if let Some(device) = self.moniker[0]
+ .take()
+ .and_then(|moniker| VideoInputDevice::new(moniker).ok())
+ {
+ return Some(device);
+ }
}
None
}
+}
+
+#[derive(Clone)]
+pub struct VideoInputDevice {
+ moniker: IMoniker,
+ prop_bag: IPropertyBag,
+ filter: IBaseFilter,
+ stream_config: Option<IAMStreamConfig>,
+}
+
+impl VideoInputDevice {
+ fn new(moniker: IMoniker) -> windows_core::Result<Self> {
+ let prop_bag: IPropertyBag = unsafe { moniker.BindToStorage(None, None) }?;
+ let filter: IBaseFilter = unsafe { moniker.BindToObject(None, None) }?;
+
+ let stream_config = filter
+ .get_pin(PINDIR_OUTPUT, PIN_CATEGORY_CAPTURE, GUID::zeroed())
+ .and_then(|f| f.cast::<IAMStreamConfig>().ok());
- pub unsafe fn to_vec(mut self) -> Vec<VideoInputDeviceIMoniker> {
- let mut monikers = Vec::new();
- while let Some(moniker) = self.next() {
- monikers.push(moniker);
+ Ok(Self {
+ moniker,
+ prop_bag,
+ filter,
+ stream_config,
+ })
+ }
+
+ pub fn name(&self) -> Option<OsString> {
+ unsafe {
+ self.prop_bag
+ .read(windows_core::w!("Description"))
+ .or_else(|_| self.prop_bag.read(windows_core::w!("FriendlyName")))
}
- monikers
+ .ok()?
+ .to_os_string()
+ }
+
+ pub fn id(&self) -> Option<OsString> {
+ unsafe { self.prop_bag.read(windows_core::w!("DevicePath")) }
+ .ok()
+ .and_then(|v| v.to_os_string())
+ .or_else(|| self.name())
+ }
+
+ pub fn model_id(&self) -> Option<String> {
+ self.id()
+ .and_then(|v| get_device_model_id(&v.to_string_lossy()))
+ }
+
+ pub fn media_types(&self) -> Option<VideoMediaTypesIterator> {
+ self.stream_config.as_ref().and_then(|stream_config| {
+ stream_config
+ .media_types()
+ .map(|inner| VideoMediaTypesIterator { inner })
+ .ok()
+ })
+ }
+}
+
+impl Deref for VideoInputDevice {
+ type Target = IMoniker;
+
+ fn deref(&self) -> &Self::Target {
+ &self.moniker
+ }
+}
+
+pub struct VideoMediaTypesIterator<'a> {
+ inner: IAMStreamConfigMediaTypes<'a>,
+}
+
+impl Iterator for VideoMediaTypesIterator<'_> {
+ type Item = AMMediaType;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.inner
+ .next()
+ .map(|media_type| AMMediaType::new(media_type.0))
}
}
@@ -907,3 +991,21 @@ unsafe fn copy_media_type(src: &AM_MEDIA_TYPE) -> AM_MEDIA_TYPE {
dest
}
+
+fn get_device_model_id(device_id: &str) -> Option<String> {
+ const VID_PID_SIZE: usize = 4;
+
+ let vid_location = device_id.find("vid_")?;
+ let pid_location = device_id.find("pid_")?;
+
+ if vid_location + "vid_".len() + 4 > device_id.len()
+ || pid_location + "pid_".len() + 4 > device_id.len()
+ {
+ return None;
+ }
+
+ let id_vendor = &device_id[vid_location + 4..vid_location + 8];
+ let id_product = &device_id[pid_location + 4..pid_location + 8];
+
+ Some(format!("{id_vendor}:{id_product}"))
+}
diff --git a/crates/camera-mediafoundation/Cargo.toml b/crates/camera-mediafoundation/Cargo.toml
index 7e3755981..f514b427f 100644
--- a/crates/camera-mediafoundation/Cargo.toml
+++ b/crates/camera-mediafoundation/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "camera-mediafoundation"
+name = "cap-camera-mediafoundation"
version = "0.1.0"
edition = "2024"
diff --git a/crates/camera-mediafoundation/examples/cli.rs b/crates/camera-mediafoundation/examples/cli.rs
index b9f9413ee..301839b25 100644
--- a/crates/camera-mediafoundation/examples/cli.rs
+++ b/crates/camera-mediafoundation/examples/cli.rs
@@ -1,6 +1,6 @@
use std::{fmt::Display, time::Duration};
-use camera_mediafoundation::DeviceSourcesIterator;
+use cap_camera_mediafoundation::DeviceSourcesIterator;
use tracing::warn;
use windows::Win32::{Media::MediaFoundation::*, System::Com::CoInitialize};
use windows_core::GUID;
@@ -34,7 +34,7 @@ pub fn main() {
let mut formats = reader
.native_media_types(stream_index)
- .into_iter()
+ .unwrap()
.filter_map(|v| VideoFormat::new(v).ok())
.collect::<Vec<_>>();
@@ -150,31 +150,6 @@ impl Display for VideoFormat {
}
}
-fn get_device_model_id(device_id: &str) -> String {
- const VID_PID_SIZE: usize = 4;
-
- let vid_location = device_id.find("vid_");
- let pid_location = device_id.find("pid_");
-
- let Some(vid_location) = vid_location else {
- return String::new();
- };
- let Some(pid_location) = pid_location else {
- return String::new();
- };
-
- if vid_location + "vid_".len() + 4 > device_id.len()
- || pid_location + "pid_".len() + 4 > device_id.len()
- {
- return String::new();
- }
-
- let id_vendor = &device_id[vid_location + 4..vid_location + 8];
- let id_product = &device_id[pid_location + 4..pid_location + 8];
-
- format!("{id_vendor}:{id_product}")
-}
-
fn media_subtype_str(subtype: &GUID) -> Option<&'static str> {
Some(match *subtype {
t if t == MFVideoFormat_I420 => "i420",
diff --git a/crates/camera-mediafoundation/src/lib.rs b/crates/camera-mediafoundation/src/lib.rs
index 9513273c4..d8f2eed83 100644
--- a/crates/camera-mediafoundation/src/lib.rs
+++ b/crates/camera-mediafoundation/src/lib.rs
@@ -9,9 +9,13 @@ use std::{
slice::from_raw_parts,
};
-use windows::Win32::Media::MediaFoundation::*;
+use windows::Win32::{Media::MediaFoundation::*, System::Com::CoInitialize};
use windows_core::PWSTR;
+pub fn initialize_mediafoundation() -> windows_core::Result<()> {
+ unsafe { CoInitialize(None) }.ok()
+}
+
pub struct DeviceSourcesIterator {
_attributes: IMFAttributes,
count: u32,
@@ -81,24 +85,24 @@ impl Iterator for DeviceSourcesIterator {
}
}
+#[derive(Clone)]
pub struct Device {
activate: IMFActivate,
media_source: IMFMediaSource,
}
impl Device {
- pub fn name(&self) -> Option<OsString> {
+ pub fn name(&self) -> windows_core::Result<OsString> {
let mut raw = PWSTR(&mut 0);
let mut length = 0;
unsafe {
self.activate
.GetAllocatedString(&MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &mut raw, &mut length)
.map(|_| OsString::from_wide(from_raw_parts(raw.0, length as usize)))
- .ok()
}
}
- pub fn id(&self) -> Option<OsString> {
+ pub fn id(&self) -> windows_core::Result<OsString> {
let mut raw = PWSTR(&mut 0);
let mut length = 0;
unsafe {
@@ -109,10 +113,15 @@ impl Device {
&mut length,
)
.map(|_| OsString::from_wide(from_raw_parts(raw.0, length as usize)))
- .ok()
}
}
+ pub fn model_id(&self) -> Option<String> {
+ self.id()
+ .ok()
+ .and_then(|v| get_device_model_id(&*v.to_string_lossy()))
+ }
+
pub fn create_source_reader(&self) -> windows_core::Result<SourceReader> {
unsafe {
MFCreateSourceReaderFromMediaSource(&self.media_source, None)
@@ -142,7 +151,7 @@ impl Display for Device {
"{}",
self.name()
.map(|v| v.to_string_lossy().to_string())
- .unwrap_or_else(|| format!("Unknown device name"))
+ .unwrap_or_else(|_| format!("Unknown device name"))
)
}
}
@@ -152,16 +161,11 @@ pub struct SourceReader {
}
impl SourceReader {
- pub fn native_media_types(&self, stream_index: u32) -> Vec<IMFMediaType> {
- let mut i = 0;
- let mut ret = vec![];
-
- while let Ok(typ) = unsafe { self.inner.GetNativeMediaType(stream_index, i) } {
- i += 1;
- ret.push(typ);
- }
-
- ret
+ pub fn native_media_types(
+ &self,
+ stream_index: u32,
+ ) -> windows_core::Result<NativeMediaTypesIterator> {
+ NativeMediaTypesIterator::new(&self.inner, stream_index)
}
pub fn set_current_media_type(
@@ -176,6 +180,36 @@ impl SourceReader {
}
}
+pub struct NativeMediaTypesIterator<'a> {
+ reader: &'a IMFSourceReader,
+ i: u32,
+ stream_index: u32,
+}
+
+impl<'a> NativeMediaTypesIterator<'a> {
+ fn new(reader: &'a IMFSourceReader, stream_index: u32) -> windows_core::Result<Self> {
+ unsafe { reader.GetNativeMediaType(stream_index, 0) }?;
+
+ Ok(Self {
+ reader,
+ i: 0,
+ stream_index,
+ })
+ }
+}
+
+impl Iterator for NativeMediaTypesIterator<'_> {
+ type Item = IMFMediaType;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let ret = unsafe { self.reader.GetNativeMediaType(self.stream_index, self.i) }.ok()?;
+
+ self.i += 1;
+
+ Some(ret)
+ }
+}
+
impl Deref for SourceReader {
type Target = IMFSourceReader;
@@ -189,3 +223,21 @@ impl DerefMut for SourceReader {
&mut self.inner
}
}
+
+fn get_device_model_id(device_id: &str) -> Option<String> {
+ const VID_PID_SIZE: usize = 4;
+
+ let vid_location = device_id.find("vid_")?;
+ let pid_location = device_id.find("pid_")?;
+
+ if vid_location + "vid_".len() + 4 > device_id.len()
+ || pid_location + "pid_".len() + 4 > device_id.len()
+ {
+ return None;
+ }
+
+ let id_vendor = &device_id[vid_location + 4..vid_location + 8];
+ let id_product = &device_id[pid_location + 4..pid_location + 8];
+
+ Some(format!("{id_vendor}:{id_product}"))
+}
diff --git a/crates/camera-windows/Cargo.toml b/crates/camera-windows/Cargo.toml
new file mode 100644
index 000000000..3130a63ee
--- /dev/null
+++ b/crates/camera-windows/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "cap-camera-windows"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+ffmpeg = { workspace = true }
+cap-camera-mediafoundation = { path = "../camera-mediafoundation" }
+cap-camera-directshow = { path = "../camera-directshow" }
+
+windows = { version = "0.60", features = ["Win32_Media_MediaFoundation"] }
+windows-core = { version = "0.60" }
+thiserror.workspace = true
+
+[lints]
+workspace = true
+
+[dev-dependencies]
+inquire = "0.7.5"
diff --git a/crates/camera-windows/examples/cli.rs b/crates/camera-windows/examples/cli.rs
new file mode 100644
index 000000000..8d011f1e0
--- /dev/null
+++ b/crates/camera-windows/examples/cli.rs
@@ -0,0 +1,3 @@
+fn main() {
+ dbg!(cap_camera_windows::get_devices().unwrap());
+}
diff --git a/crates/camera-windows/src/lib.rs b/crates/camera-windows/src/lib.rs
new file mode 100644
index 000000000..9ac605b64
--- /dev/null
+++ b/crates/camera-windows/src/lib.rs
@@ -0,0 +1,297 @@
+#![cfg(windows)]
+
+use cap_camera_directshow::{AM_MEDIA_TYPEVideoExt, AMMediaType};
+use std::{
+ ffi::OsString,
+ fmt::{Debug, Display},
+};
+use windows::Win32::Media::MediaFoundation::*;
+use windows_core::GUID;
+
+#[derive(Clone)]
+pub struct DeviceInfo {
+ id: OsString,
+ name: OsString,
+ model_id: Option<String>,
+ formats: Vec<VideoFormat>,
+ inner: DeviceInfoInner,
+}
+
+impl Debug for DeviceInfo {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("DeviceInfo")
+ .field("id", &self.id)
+ .field("name", &self.name)
+ .field("format_count", &self.formats.len())
+ .field("inner", &self.inner)
+ .finish()
+ }
+}
+
+impl DeviceInfo {
+ fn is_mf(&self) -> bool {
+ matches!(self.inner, DeviceInfoInner::MediaFoundation(_))
+ }
+
+ fn name_and_model(&self) -> String {
+ if let Some(model_id) = &self.model_id {
+ format!("{} ({model_id})", self.name.to_string_lossy())
+ } else {
+ self.name.to_string_lossy().to_string()
+ }
+ }
+}
+
+#[derive(Clone)]
+enum DeviceInfoInner {
+ MediaFoundation(cap_camera_mediafoundation::Device),
+ DirectShow(cap_camera_directshow::VideoInputDevice),
+}
+
+impl Debug for DeviceInfoInner {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::DirectShow(_) => write!(f, "DirectShow"),
+ Self::MediaFoundation(_) => write!(f, "MediaFoundation"),
+ }
+ }
+}
+
+#[derive(Debug)]
+pub enum GetDevicesError {
+ MFDeviceEnumerationFailed(windows_core::Error),
+ DSDeviceEnumerationFailed(windows_core::Error),
+}
+
+pub fn get_devices() -> Result<Vec<DeviceInfo>, GetDevicesError> {
+ let _ = cap_camera_directshow::initialize_directshow();
+ let _ = cap_camera_mediafoundation::initialize_mediafoundation();
+
+ let mf_devices = cap_camera_mediafoundation::DeviceSourcesIterator::new()
+ .map_err(GetDevicesError::MFDeviceEnumerationFailed)?
+ .map(|device| {
+ let name = device.name()?;
+ let id = device.id()?;
+ let model_id = device.model_id();
+
+ let reader = device.create_source_reader()?;
+ let stream_index = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32;
+
+ let formats = reader
+ .native_media_types(stream_index)?
+ .filter_map(|t| VideoFormat::new_mf(&t).ok())
+ .collect::<Vec<_>>();
+
+ Ok::<_, windows_core::Error>(DeviceInfo {
+ name,
+ id,
+ model_id,
+ formats,
+ inner: DeviceInfoInner::MediaFoundation(device),
+ })
+ })
+ .filter_map(|result| match result {
+ Ok(r) => Some(r),
+ Err(e) => {
+ println!("Failed to load MF device info: {e}");
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+
+ let dshow_devices = cap_camera_directshow::VideoInputDeviceIterator::new()
+ .map_err(GetDevicesError::DSDeviceEnumerationFailed)?
+ .map(|device| {
+ let id = device.id()?;
+ let name = device.name()?;
+ let model_id = device.model_id();
+
+ let formats = device
+ .media_types()
+ .into_iter()
+ .flatten()
+ .filter_map(|media_type| VideoFormat::new_ds(&media_type).ok())
+ .collect::<Vec<_>>();
+
+ Some(DeviceInfo {
+ name,
+ id,
+ model_id,
+ formats,
+ inner: DeviceInfoInner::DirectShow(device),
+ })
+ })
+ .filter_map(|result| {
+ if result.is_none() {
+ println!("Failed to load DS device info");
+ }
+ result
+ })
+ .collect::<Vec<_>>();
+
+ let mut devices = mf_devices;
+
+ for dshow_device in dshow_devices {
+ let name_and_model = dshow_device.name_and_model();
+ // dbg!(&name_and_model);
+
+ let mf_device = devices
+ .iter()
+ .enumerate()
+ .find(|(_, device)| device.is_mf() && device.name_and_model() == name_and_model);
+
+ match mf_device {
+ Some((i, mf_device)) => {
+ if mf_device.formats.len() == 0 {
+ devices.push(mf_device.clone());
+ devices.swap_remove(i);
+ }
+ }
+ None => devices.push(dshow_device),
+ }
+ }
+
+ Ok(devices)
+}
+
+#[derive(Debug, Clone)]
+struct VideoFormat {
+ width: u32,
+ height: u32,
+ frame_rate: f32,
+ pixel_format: ffmpeg::format::Pixel,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum VideoFormatError {
+ #[error("Provided format is not video")]
+ NotVideo,
+ #[error("Invalid pixel format '{0:?}'")]
+ InvalidPixelFormat(GUID),
+ #[error("{0}")]
+ Other(#[from] windows_core::Error),
+}
+
+impl VideoFormat {
+ fn new_mf(inner: &IMFMediaType) -> Result<Self, VideoFormatError> {
+ if unsafe { inner.GetMajorType()? } != MFMediaType_Video {
+ return Err(VideoFormatError::NotVideo);
+ }
+
+ let size = unsafe { inner.GetUINT64(&MF_MT_FRAME_SIZE)? };
+ let width = (size >> 32) as u32;
+ let height = (size & 0xFFFFFFFF) as u32;
+
+ let frame_rate_ratio = {
+ let frame_rate = unsafe { inner.GetUINT64(&MF_MT_FRAME_RATE)? };
+ let numerator = (frame_rate >> 32) as u32;
+ let denominator = frame_rate as u32;
+ (numerator, denominator)
+ };
+ let frame_rate = frame_rate_ratio.0 as f32 / frame_rate_ratio.1 as f32;
+
+ let subtype = unsafe { inner.GetGUID(&MF_MT_SUBTYPE)? };
+
+ Ok(Self {
+ width,
+ height,
+ frame_rate,
+ pixel_format: MFPixelFormat::new(subtype)
+ .ok_or(VideoFormatError::InvalidPixelFormat(subtype))?
+ .as_ffmpeg(),
+ })
+ }
+
+ fn new_ds(inner: &AMMediaType) -> Result<Self, VideoFormatError> {
+ if inner.majortype != MFMediaType_Video {
+ return Err(VideoFormatError::NotVideo);
+ }
+
+ let video_info = unsafe { inner.video_info() };
+
+ Ok(VideoFormat {
+ width: video_info.bmiHeader.biWidth as u32,
+ height: video_info.bmiHeader.biHeight as u32,
+ frame_rate: ((10_000_000.0 / video_info.AvgTimePerFrame as f32) * 100.0).round()
+ / 100.0,
+ pixel_format: DSPixelFormat::new(inner)
+ .ok_or(VideoFormatError::InvalidPixelFormat(inner.subtype))?
+ .as_ffmpeg(),
+ })
+ }
+}
+
+impl Display for VideoFormat {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}x{} {}fps", self.width, self.height, self.frame_rate)?;
+ write!(f, " {:?}", self.pixel_format)
+ }
+}
+
+struct MFPixelFormat {
+ ffmpeg: ffmpeg::format::Pixel,
+ mf: GUID,
+}
+
+impl MFPixelFormat {
+ fn new(subtype: GUID) -> Option<Self> {
+ use ffmpeg::format::Pixel;
+
+ let get_ffmpeg = || {
+ Some(match subtype {
+ t if t == MFVideoFormat_I420 || t == MFVideoFormat_IYUV => Pixel::YUV420P,
+ t if t == MFVideoFormat_RGB24 => Pixel::RGB24,
+ t if t == MFVideoFormat_RGB32 => Pixel::RGB32,
+ t if t == MFVideoFormat_YUY2 => Pixel::YUYV422,
+ t if t == MFVideoFormat_UYVY => Pixel::UYVY422,
+ t if t == MFVideoFormat_ARGB32 => Pixel::ARGB,
+ t if t == MFVideoFormat_NV12 => Pixel::NV12,
+ _ => return None,
+ })
+ };
+
+ Some(Self {
+ ffmpeg: get_ffmpeg()?,
+ mf: subtype,
+ })
+ }
+
+ pub fn as_ffmpeg(&self) -> ffmpeg::format::Pixel {
+ self.ffmpeg
+ }
+}
+
+struct DSPixelFormat {
+ ffmpeg: ffmpeg::format::Pixel,
+ ds: GUID,
+}
+
+impl DSPixelFormat {
+ fn new(major_type: &AM_MEDIA_TYPE) -> Option<Self> {
+ use ffmpeg::format::Pixel;
+
+ let subtype = major_type.subtype;
+
+ let get_ffmpeg = || {
+ Some(match subtype {
+ t if t == MEDIASUBTYPE_I420 || t == MEDIASUBTYPE_IYUV => Pixel::YUV420P,
+ t if t == MEDIASUBTYPE_RGB24 => Pixel::RGB24,
+ t if t == MEDIASUBTYPE_RGB32 => Pixel::RGB32,
+ t if t == MEDIASUBTYPE_YUY2 => Pixel::YUYV422,
+ t if t == MEDIASUBTYPE_UYVY => Pixel::UYVY422,
+ t if t == MEDIASUBTYPE_ARGB32 => Pixel::ARGB,
+ t if t == MEDIASUBTYPE_NV12 => Pixel::NV12,
+ _ => return None,
+ })
+ };
+
+ Some(Self {
+ ffmpeg: get_ffmpeg()?,
+ ds: subtype,
+ })
+ }
+
+ pub fn as_ffmpeg(&self) -> ffmpeg::format::Pixel {
+ self.ffmpeg
+ }
+}