Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
library-ify more windows camera stuff
Brendan Allan8f2ab6b3f582
diff --git a/crates/camera-directshow/Cargo.toml b/crates/camera-directshow/Cargo.tomlindex 6961d8a62..b4aadbd61 100644--- a/crates/camera-directshow/Cargo.toml+++ b/crates/camera-directshow/Cargo.toml@@ -14,6 +14,7 @@ windows = { version = "0.60", features = ["Win32_System_Variant","Win32_Media_KernelStreaming",] }+tracing.workspace = true[lints]workspace = truediff --git a/crates/camera-directshow/examples/cli.rs b/crates/camera-directshow/examples/cli.rsindex e747d4e68..df6cff5fa 100644--- a/crates/camera-directshow/examples/cli.rs+++ b/crates/camera-directshow/examples/cli.rs@@ -1,39 +1,15 @@-use cap_camera_dshow::*;-use std::{- cell::RefCell,- fmt::Display,- mem::ManuallyDrop,- ops::Deref,- ptr::{self, null_mut},- time::Duration,-};-use tracing::{error, info, trace};+use cap_camera_directshow::*;+use std::{fmt::Display, ptr::null_mut, time::Duration};+use tracing::{error, trace};use windows::{Win32::{- Foundation::{E_NOTIMPL, E_OUTOFMEMORY, E_POINTER, S_FALSE, S_OK, SIZE},- Media::{- DirectShow::{- FILTER_STATE, IAMStreamConfig, IAMVideoControl, IBaseFilter, IBaseFilter_Impl,- ICaptureGraphBuilder2, IEnumMediaTypes, IEnumMediaTypes_Impl, IEnumPins,- IEnumPins_Impl, IFilterGraph, IGraphBuilder, IMediaControl, IMediaFilter,- IMediaFilter_Impl, IMemInputPin, IMemInputPin_Impl, IPin, IPin_Impl, PINDIR_INPUT,- PINDIR_OUTPUT, State_Paused, State_Running, State_Stopped, VFW_E_NO_ALLOCATOR,- VFW_E_NOT_CONNECTED,- },- KernelStreaming::{KS_BITMAPINFOHEADER, KS_VIDEOINFOHEADER},- MediaFoundation::{- AM_MEDIA_TYPE, CLSID_CaptureGraphBuilder2, CLSID_FilterGraph, FORMAT_VideoInfo,- MEDIASUBTYPE_YUY2, MEDIATYPE_Video, PIN_CATEGORY_CAPTURE,- },- },- System::Com::{- CLSCTX_INPROC_SERVER, CoCreateInstance, CoInitialize, CoTaskMemAlloc, CoTaskMemFree,- IMoniker, IPersist_Impl, StructuredStorage::IPropertyBag,- },+ Foundation::SIZE,+ Media::{DirectShow::*, MediaFoundation::*},+ System::Com::{StructuredStorage::IPropertyBag, *},},core::Interface,};-use windows_core::{ComObject, ComObjectInner, GUID, implement};+use windows_core::GUID;fn main() {tracing_subscriber::fmt::init();@@ -122,589 +98,6 @@ impl<'a> Display for VideoDeviceSelectOption<'a> {// chromium-#[implement(IPin, IMemInputPin)]-struct SinkInputPin {- current_media_type: RefCell<AMMediaType>,- connected_pin: RefCell<Option<IPin>>,- owner: RefCell<Option<*const IBaseFilter>>,-}--impl SinkInputPin {- unsafe fn get_valid_media_type(&self, index: i32, media_type: &mut AM_MEDIA_TYPE) -> bool {- let video_info_header = &mut *(media_type.pbFormat as *mut KS_VIDEOINFOHEADER);-- video_info_header.bmiHeader.biSize = size_of::<KS_BITMAPINFOHEADER>() as u32;- video_info_header.bmiHeader.biPlanes = 1;- video_info_header.bmiHeader.biClrImportant = 0;- video_info_header.bmiHeader.biClrUsed = 0;-- media_type.majortype = MEDIATYPE_Video;- media_type.formattype = FORMAT_VideoInfo;- media_type.bTemporalCompression = false.into();-- if index == 0 {- video_info_header.bmiHeader.biCompression =- u32::from_ne_bytes(*"yuy2".as_bytes().first_chunk::<4>().unwrap());- video_info_header.bmiHeader.biBitCount = 16;- video_info_header.bmiHeader.biWidth = 640;- video_info_header.bmiHeader.biHeight = 480;- media_type.subtype = MEDIASUBTYPE_YUY2;- true- } else {- false- }- }-}--impl IPin_Impl for SinkInputPin_Impl {- fn Connect(- &self,- preceivepin: windows_core::Ref<'_, IPin>,- pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,- ) -> windows_core::Result<()> {- trace!("Connect entry");- let Some(preceivepin) = preceivepin.as_ref() else {- trace!("Connect exit - E_POINTER");- return E_POINTER.ok();- };-- if pmt.is_null() {- trace!("Connect exit - E_POINTER");- return E_POINTER.ok();- }- let media_type = unsafe { &*pmt };-- dbg!(media_type);- // self.current_media_type.replace(media_type.clone());- self.connected_pin.replace(Some(preceivepin.clone()));- let result = unsafe { preceivepin.ReceiveConnection(&self.cast::<IPin>()?, pmt) };- trace!("Connect exit");- result- }-- fn ReceiveConnection(- &self,- pconnector: windows_core::Ref<'_, IPin>,- pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,- ) -> windows_core::Result<()> {- trace!("ReceiveConnection entry");- self.current_media_type- .replace(AMMediaType::new(unsafe { &*pmt }));- self.connected_pin.replace(pconnector.clone());- trace!("ReceiveConnection exit");- S_OK.ok()- }-- fn Disconnect(&self) -> windows_core::Result<()> {- trace!("Disconnect entry");- let result = match self.connected_pin.borrow_mut().take() {- Some(_) => S_OK.ok(),- None => VFW_E_NOT_CONNECTED.ok(),- };- trace!("Disconnect exit");- result- }-- fn ConnectedTo(&self) -> windows_core::Result<IPin> {- trace!("ConnectedTo entry");- let result = match self.connected_pin.borrow().as_ref() {- Some(connected_pin) => Ok(connected_pin.clone()),- None => Err(VFW_E_NOT_CONNECTED.into()),- };- trace!("ConnectedTo exit");- result- }-- fn ConnectionMediaType(- &self,- pmt: *mut windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,- ) -> windows_core::Result<()> {- trace!("ConnectionMediaType entry");- self.connected_pin- .borrow()- .as_ref()- .ok_or(VFW_E_NOT_CONNECTED)?;-- unsafe { *pmt = self.current_media_type.borrow().clone().into_inner() };-- trace!("ConnectionMediaType exit");- Ok(())- }-- fn QueryPinInfo(- &self,- pinfo: *mut windows::Win32::Media::DirectShow::PIN_INFO,- ) -> windows_core::Result<()> {- trace!("QueryPinInfo before");- unsafe {- (*pinfo).dir = PINDIR_INPUT;- (*pinfo).pFilter =- ManuallyDrop::new(self.owner.borrow().as_ref().map(|v| (&**v).clone()));- (*pinfo).achName[0] = '\0' as u16;- }-- trace!("QueryPinInfo after");- S_OK.ok()- }-- fn QueryDirection(- &self,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::PIN_DIRECTION> {- trace!("QueryDirection entry");- trace!("QueryDirection exit");- Ok(PINDIR_INPUT)- }-- fn QueryId(&self) -> windows_core::Result<windows_core::PWSTR> {- trace!("QueryId entry");- unreachable!()- }-- fn QueryAccept(- &self,- _pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,- ) -> windows_core::HRESULT {- trace!("QueryAccept entry");- trace!("QueryAccept exit");- S_FALSE- }-- fn EnumMediaTypes(- &self,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::IEnumMediaTypes> {- trace!("EnumMediaTypes entry");- Ok(TypeEnumerator {- index: Default::default(),- pin: self,- }- .into())- }-- fn QueryInternalConnections(- &self,- appin: windows_core::OutRef<'_, IPin>,- npin: *mut u32,- ) -> windows_core::Result<()> {- trace!("QueryInternalConnections entry");- Err(E_NOTIMPL.into())- }-- fn EndOfStream(&self) -> windows_core::Result<()> {- trace!("EndOfStream entry");- trace!("EndOfStream exit");- S_OK.ok()- }-- fn BeginFlush(&self) -> windows_core::Result<()> {- trace!("BeginFlush entry");- trace!("BeginFlush exit");- S_OK.ok()- }-- fn EndFlush(&self) -> windows_core::Result<()> {- trace!("EndFlush entry");- trace!("EndFlush exit");- S_OK.ok()- }-- fn NewSegment(&self, _tstart: i64, _tstop: i64, _drate: f64) -> windows_core::Result<()> {- trace!("NewSegment entry");- unreachable!()- }-}--#[implement(IEnumMediaTypes)]-struct TypeEnumerator<'a> {- index: RefCell<i32>,- pin: &'a SinkInputPin,-}--impl<'a> TypeEnumerator<'a> {- unsafe fn free_allocated_media_types(allocated: usize, types: *mut *mut AM_MEDIA_TYPE) {- for i in 0..allocated {- CoTaskMemFree(Some((*(*types.add(i))).pbFormat as *const _));- CoTaskMemFree(Some(*types.add(i) as *const _));- }- }-}--impl<'a> IEnumMediaTypes_Impl for TypeEnumerator_Impl<'a> {- fn Next(- &self,- cmediatypes: u32,- ppmediatypes: *mut *mut AM_MEDIA_TYPE,- pcfetched: *mut u32,- ) -> windows_core::HRESULT {- trace!("TypeEnumerator::Next");- dbg!(cmediatypes);- dbg!(self.index.borrow());-- let mut types_fetched = 0;-- unsafe {- while types_fetched < cmediatypes {- let typ = CoTaskMemAlloc(size_of::<AM_MEDIA_TYPE>()) as *mut AM_MEDIA_TYPE;- if typ.is_null() {- TypeEnumerator::free_allocated_media_types(- types_fetched as usize,- ppmediatypes,- );- return E_OUTOFMEMORY;- }- let typ = &mut *typ;-- *typ = AM_MEDIA_TYPE::default();- typ.cbFormat = size_of::<KS_VIDEOINFOHEADER>() as u32;-- let format =- CoTaskMemAlloc(size_of::<KS_VIDEOINFOHEADER>()) as *mut KS_VIDEOINFOHEADER;- if format.is_null() {- CoTaskMemFree(Some((typ as *const AM_MEDIA_TYPE).cast()));- TypeEnumerator::free_allocated_media_types(- types_fetched as usize,- ppmediatypes,- );- return E_OUTOFMEMORY;- }- typ.pbFormat = format as *mut _;-- if self.pin.get_valid_media_type(*self.index.borrow(), typ) {- self.index.replace_with(|v| *v + 1);-- *ppmediatypes.add(types_fetched as usize) = typ;-- types_fetched += 1;- } else {- CoTaskMemFree(Some(format as *const _));- CoTaskMemFree(Some(typ as *mut _ as *const _));- break;- }- }-- if !pcfetched.is_null() {- *pcfetched = types_fetched;- }- }-- if types_fetched == cmediatypes {- S_OK- } else {- S_FALSE- }- }-- fn Skip(&self, cmediatypes: u32) -> windows_core::Result<()> {- trace!("TypeEnumerator::Skip");- self.index.replace_with(|v| (*v) + cmediatypes as i32);- S_OK.ok()- }-- fn Reset(&self) -> windows_core::Result<()> {- trace!("TypeEnumerator::Reset");- self.index.replace(0);- S_OK.ok()- }-- fn Clone(&self) -> windows_core::Result<IEnumMediaTypes> {- trace!("TypeEnumerator::Clone");- unsafe { self.cast() }- }-}--impl IMemInputPin_Impl for SinkInputPin_Impl {- fn GetAllocator(- &self,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::IMemAllocator> {- trace!("GetAllocator entry");- trace!("GetAllocator exit");- Err(VFW_E_NO_ALLOCATOR.into())- }-- fn NotifyAllocator(- &self,- _pallocator: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IMemAllocator>,- _breadonly: windows_core::BOOL,- ) -> windows_core::Result<()> {- trace!("NotifyAllocator entry");- trace!("NotifyAllocator exit");- S_OK.ok()- }-- fn GetAllocatorRequirements(- &self,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::ALLOCATOR_PROPERTIES> {- trace!("GetAllocatorRequirements entry");- trace!("GetAllocatorRequirements exit");- Err(E_NOTIMPL.into())- }-- fn Receive(- &self,- psample: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IMediaSample>,- ) -> windows_core::Result<()> {- let Some(psample) = psample.as_ref() else {- return Ok(());- };-- let mut ptimestart = 0;- let mut ptimeend = 0;- unsafe {- psample.GetTime(&mut ptimestart, &mut ptimeend).unwrap();- };-- let pts = ptimestart;- let bytes = unsafe { psample.GetActualDataLength() };-- unsafe {- if let Ok(new_media_type) = psample.GetMediaType() {- if !new_media_type.is_null() {- self.current_media_type- .replace(AMMediaType::new(&*new_media_type));- }- }- }-- let media_type = self.current_media_type.borrow();-- let format_str = unsafe { media_type.subtype_str() };-- let video_info =- unsafe { &*(media_type.pbFormat as *const _ as *const KS_VIDEOINFOHEADER) };-- println!(- "New frame: {}x{}, {pts}pts, {bytes} bytes, {}",- video_info.bmiHeader.biWidth,- video_info.bmiHeader.biHeight,- format_str.unwrap_or("unknown format")- );-- Ok(())- }-- fn ReceiveMultiple(- &self,- psamples: *const Option<windows::Win32::Media::DirectShow::IMediaSample>,- mut nsamples: i32,- ) -> windows_core::Result<i32> {- trace!("ReceiveMultiple entry");- let mut processed: i32 = 0;- while nsamples > 0 {- unsafe { self.Receive((&*psamples.offset(processed as isize)).into())? };- nsamples -= 1;- processed += 1;- }-- trace!("ReceiveMultiple exit");- Ok(processed)- }-- fn ReceiveCanBlock(&self) -> windows_core::Result<()> {- trace!("ReceiveCanBlock entry");- trace!("ReceiveCanBlock exit");- S_FALSE.ok()- }-}--#[implement(IBaseFilter, IMediaFilter)]-struct SinkFilter {- state: RefCell<FILTER_STATE>,- owning_graph: RefCell<Option<IFilterGraph>>,- input_pin: ComObject<SinkInputPin>,-}--impl SinkFilter {- fn no_of_pins(&self) -> u32 {- 1- }-- fn get_pin(&self, i: u32) -> Option<IPin> {- if i == 0 {- Some(unsafe { self.input_pin.get().cast() }.unwrap())- } else {- None- }- }-}--// impl Drop for SinkFilter {-// fn drop(&mut self) {-// self.input_pin.owner.borrow_mut().take();-// }-// }--impl AsRef<SinkFilter> for SinkFilter {- fn as_ref(&self) -> &Self {- self- }-}--impl IBaseFilter_Impl for SinkFilter_Impl {- fn EnumPins(&self) -> windows_core::Result<windows::Win32::Media::DirectShow::IEnumPins> {- trace!("FilterBase::EnumPins");- Ok(PinEnumerator {- filter: &self.this,- index: Default::default(),- }- .into())- }-- fn FindPin(- &self,- _id: &windows_core::PCWSTR,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::IPin> {- trace!("FindPin entry");- trace!("FindPin exit");- Err(E_NOTIMPL.into())- }-- fn QueryFilterInfo(- &self,- pinfo: *mut windows::Win32::Media::DirectShow::FILTER_INFO,- ) -> windows_core::Result<()> {- trace!("QueryFilterInfo entry");- unsafe {- (*pinfo).pGraph = ManuallyDrop::new(self.owning_graph.borrow().clone());- (*pinfo).achName[0] = '\0' as u16;- }- trace!("QueryFilterInfo exit");- Ok(())- }-- fn JoinFilterGraph(- &self,- pgraph: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IFilterGraph>,- pname: &windows_core::PCWSTR,- ) -> windows_core::Result<()> {- trace!("JoinFilterGraph");- *self.owning_graph.borrow_mut() = pgraph.clone();-- Ok(())- }-- fn QueryVendorInfo(&self) -> windows_core::Result<windows_core::PWSTR> {- trace!("QueryVendorInfo entry");- trace!("QueryVendorInfo exit");- Ok(windows_core::PWSTR::null())- }-}--impl IMediaFilter_Impl for SinkFilter_Impl {- fn Stop(&self) -> windows_core::Result<()> {- trace!("Stop entry");- self.state.replace(State_Stopped);- trace!("Stop exit");- Ok(())- }-- fn Pause(&self) -> windows_core::Result<()> {- trace!("Pause entry");- self.state.replace(State_Paused);- trace!("Pause exit");- Ok(())- }-- fn Run(&self, _tstart: i64) -> windows_core::Result<()> {- trace!("Run entry");- self.state.replace(State_Running);- trace!("Run exit");- Ok(())- }-- fn GetState(- &self,- _dwmillisecstimeout: u32,- ) -> windows_core::Result<windows::Win32::Media::DirectShow::FILTER_STATE> {- trace!("GetState entry");- trace!("GetState exit");- Ok(*self.state.borrow())- }-- fn SetSyncSource(- &self,- _pclock: windows_core::Ref<'_, windows::Win32::Media::IReferenceClock>,- ) -> windows_core::Result<()> {- trace!("SetSyncSource entry");- trace!("SetSyncSource exit");- S_OK.ok()- }-- fn GetSyncSource(&self) -> windows_core::Result<windows::Win32::Media::IReferenceClock> {- trace!("GetSyncSource entry");- trace!("GetSyncSource exit");- Err(E_NOTIMPL.into())- }-}--impl IPersist_Impl for SinkFilter_Impl {- fn GetClassID(&self) -> windows_core::Result<windows_core::GUID> {- trace!("GetClassID");- unreachable!();- }-}--#[implement(IEnumPins)]-struct PinEnumerator<'a> {- filter: &'a dyn AsRef<SinkFilter>,- index: RefCell<u32>,-}--impl<'a> IEnumPins_Impl for PinEnumerator_Impl<'a> {- fn Next(- &self,- cpins: u32,- pppins: windows_core::OutRef<'_, IPin>,- pcfetched: *mut u32,- ) -> windows_core::HRESULT {- let mut pins_fetched = 0;-- let index = *self.index.borrow();- let filter = self.filter.as_ref();- trace!("IEnumPins Next");- if pins_fetched < cpins && filter.no_of_pins() > index {- let pin = filter.get_pin(index);- self.index.replace_with(|v| *v + 1);- pins_fetched += 1;- pppins.write(pin).unwrap();- }-- if !pcfetched.is_null() {- unsafe {- *pcfetched = pins_fetched;- }- }-- if pins_fetched == cpins { S_OK } else { S_FALSE }- }-- fn Skip(&self, cpins: u32) -> windows_core::Result<()> {- trace!("Skip entry");- let filter = self.filter.as_ref();- if filter.no_of_pins() - *self.index.borrow() > cpins {- self.index.replace_with(|v| *v + 1);- trace!("Skip exit - S_OK");- return S_OK.ok();- }-- self.index.replace(0);- trace!("Skip exit - S_FALSE");- S_FALSE.ok()- }-- fn Reset(&self) -> windows_core::Result<()> {- trace!("Reset entry");- self.index.replace(0);- trace!("Reset exit");- S_OK.ok()- }-- fn Clone(&self) -> windows_core::Result<IEnumPins> {- trace!("Clone entry");- let result = unsafe { self.cast() };- trace!("Clone exit");- result- }-}-unsafe fn chromium_main(capture_filter: IBaseFilter) {let output_capture_pin = capture_filter.get_pin(PINDIR_OUTPUT, PIN_CATEGORY_CAPTURE, GUID::zeroed())@@ -793,18 +186,11 @@ unsafe fn chromium_main(capture_filter: IBaseFilter) {.unwrap();trace!("creating sink filter");- let sink_filter = SinkFilter {- state: RefCell::new(State_Stopped),- owning_graph: RefCell::new(None),- input_pin: SinkInputPin {- current_media_type: RefCell::new(Default::default()),- connected_pin: RefCell::new(None),- owner: RefCell::new(None),- }- .into(),- }- .into_object();- *sink_filter.input_pin.owner.borrow_mut() = Some(&sink_filter.cast::<IBaseFilter>().unwrap());+ let sink_filter = SinkFilter::new(Box::new(|buffer, media_type, time_delta| {+ dbg!(buffer.len());+ dbg!(media_type.subtype_str());+ dbg!(time_delta);+ }));trace!("created sink filter");let input_sink_pin = sink_filter.get_pin(0).unwrap();@@ -855,59 +241,3 @@ unsafe fn chromium_main(capture_filter: IBaseFilter) {std::thread::sleep(Duration::from_secs(10));}--#[derive(Default)]-struct AMMediaType(AM_MEDIA_TYPE);--impl AMMediaType {- pub fn new(typ: &AM_MEDIA_TYPE) -> Self {- Self(unsafe { copy_media_type(typ) })- }-- pub fn into_inner(mut self) -> AM_MEDIA_TYPE {- let inner = std::mem::replace(&mut self.0, unsafe { std::mem::uninitialized() });- std::mem::forget(self);- inner- }-}--impl Deref for AMMediaType {- type Target = AM_MEDIA_TYPE;-- fn deref(&self) -> &Self::Target {- &self.0- }-}--impl Clone for AMMediaType {- fn clone(&self) -> Self {- Self(unsafe { copy_media_type(&self.0) })- }-}--impl Drop for AMMediaType {- fn drop(&mut self) {- unsafe {- if !self.0.pbFormat.is_null() {- CoTaskMemFree(Some(self.0.pbFormat as *mut _));- self.0.pbFormat = null_mut();- }- }- }-}--unsafe fn copy_media_type(src: &AM_MEDIA_TYPE) -> AM_MEDIA_TYPE {- let mut dest = src.clone();-- if src.cbFormat > 0 && !src.pbFormat.is_null() {- let format_size = src.cbFormat as usize;- let new_format = CoTaskMemAlloc(format_size) as *mut u8;-- if !new_format.is_null() {- ptr::copy_nonoverlapping(src.pbFormat, new_format, format_size);- dest.pbFormat = new_format;- }- }-- dest-}diff --git a/crates/camera-directshow/src/lib.rs b/crates/camera-directshow/src/lib.rsindex ff2728f41..e32222ac3 100644--- a/crates/camera-directshow/src/lib.rs+++ b/crates/camera-directshow/src/lib.rs@@ -1,38 +1,31 @@#![cfg(windows)]use std::{+ cell::RefCell,ffi::{OsString, c_void},+ mem::ManuallyDrop,ops::Deref,os::windows::ffi::OsStringExt,- ptr::{null, null_mut},+ ptr::{self, null, null_mut},+ time::Duration,};+use tracing::trace;use windows::{Win32::{- Foundation::{S_OK, SIZE},+ Foundation::*,Media::{- DirectShow::{- AMPROPERTY_PIN_CATEGORY, IAMStreamConfig, IAMVideoControl, IBaseFilter,- ICreateDevEnum, IPin, PIN_DIRECTION, VIDEO_STREAM_CONFIG_CAPS,- },- KernelStreaming::{IKsPropertySet, KS_VIDEOINFOHEADER},- MediaFoundation::{- AM_MEDIA_TYPE, AMPROPSETID_Pin, CLSID_SystemDeviceEnum,- CLSID_VideoInputDeviceCategory, MEDIASUBTYPE_ARGB32, MEDIASUBTYPE_I420,- MEDIASUBTYPE_IYUV, MEDIASUBTYPE_MJPG, MEDIASUBTYPE_NV12, MEDIASUBTYPE_RGB24,- MEDIASUBTYPE_RGB32, MEDIASUBTYPE_UYVY, MEDIASUBTYPE_YUY2,- },+ DirectShow::*,+ KernelStreaming::{IKsPropertySet, KS_BITMAPINFOHEADER, KS_VIDEOINFOHEADER},+ MediaFoundation::*,},System::{- Com::{- CLSCTX_INPROC_SERVER, CoCreateInstance, IEnumMoniker, IErrorLog, IMoniker,- StructuredStorage::IPropertyBag,- },+ Com::{StructuredStorage::IPropertyBag, *},Variant::{VARIANT, VT_BSTR},},},core::Interface,};-use windows_core::{GUID, PWSTR};+use windows_core::{ComObject, ComObjectInner, GUID, PWSTR, implement};pub trait IPinExt {unsafe fn matches_category(&self, category: GUID) -> bool;@@ -115,14 +108,12 @@ impl IBaseFilterExt for IBaseFilter {unsafe fn get_pin_by_name(&self,direction: PIN_DIRECTION,- name: Option<&PWSTR>,+ _name: Option<&PWSTR>,) -> Option<IPin> {let pin_enum = self.EnumPins().unwrap();let _ = pin_enum.Reset();- dbg!(direction);-let mut pin = [None];while pin_enum.Next(&mut pin, None) == S_OK {let Some(pin) = pin[0].take() else {@@ -131,8 +122,6 @@ impl IBaseFilterExt for IBaseFilter {let pin_dir = pin.QueryDirection().unwrap();- dbg!(pin_dir);-if pin_dir == direction {return Some(pin);}@@ -326,3 +315,595 @@ impl VideoInputDeviceEnumerator {monikers}}++#[derive(Default)]+pub struct AMMediaType(AM_MEDIA_TYPE);++impl AMMediaType {+ pub fn new(typ: &AM_MEDIA_TYPE) -> Self {+ Self(unsafe { copy_media_type(typ) })+ }++ pub fn into_inner(mut self) -> AM_MEDIA_TYPE {+ let inner = std::mem::replace(&mut self.0, unsafe { std::mem::uninitialized() });+ std::mem::forget(self);+ inner+ }+}++impl Deref for AMMediaType {+ type Target = AM_MEDIA_TYPE;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++impl Clone for AMMediaType {+ fn clone(&self) -> Self {+ Self(unsafe { copy_media_type(&self.0) })+ }+}++impl Drop for AMMediaType {+ fn drop(&mut self) {+ unsafe {+ if !self.0.pbFormat.is_null() {+ CoTaskMemFree(Some(self.0.pbFormat as *mut _));+ self.0.pbFormat = null_mut();+ }+ }+ }+}++#[implement(IBaseFilter, IMediaFilter)]+pub struct SinkFilter {+ state: RefCell<FILTER_STATE>,+ owning_graph: RefCell<Option<IFilterGraph>>,+ input_pin: ComObject<SinkInputPin>,+}++impl SinkFilter {+ pub fn new(callback: SinkCallback) -> ComObject<Self> {+ let this = SinkFilter {+ state: RefCell::new(State_Stopped),+ owning_graph: RefCell::new(None),+ input_pin: SinkInputPin {+ current_media_type: RefCell::new(Default::default()),+ connected_pin: RefCell::new(None),+ owner: RefCell::new(None),+ callback,+ }+ .into(),+ }+ .into_object();++ *this.input_pin.owner.borrow_mut() = Some(this.cast::<IBaseFilter>().unwrap());++ this+ }++ fn no_of_pins(&self) -> u32 {+ 1+ }++ pub fn get_pin(&self, i: u32) -> Option<IPin> {+ if i == 0 {+ Some(unsafe { self.input_pin.get().cast() }.unwrap())+ } else {+ None+ }+ }+}++impl AsRef<SinkFilter> for SinkFilter {+ fn as_ref(&self) -> &Self {+ self+ }+}++impl IBaseFilter_Impl for SinkFilter_Impl {+ fn EnumPins(&self) -> windows_core::Result<windows::Win32::Media::DirectShow::IEnumPins> {+ Ok(PinEnumerator {+ filter: &self.this,+ index: Default::default(),+ }+ .into())+ }++ fn FindPin(+ &self,+ _id: &windows_core::PCWSTR,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::IPin> {+ Err(E_NOTIMPL.into())+ }++ fn QueryFilterInfo(+ &self,+ pinfo: *mut windows::Win32::Media::DirectShow::FILTER_INFO,+ ) -> windows_core::Result<()> {+ unsafe {+ (*pinfo).pGraph = ManuallyDrop::new(self.owning_graph.borrow().clone());+ (*pinfo).achName[0] = '\0' as u16;+ }+ Ok(())+ }++ fn JoinFilterGraph(+ &self,+ pgraph: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IFilterGraph>,+ _pname: &windows_core::PCWSTR,+ ) -> windows_core::Result<()> {+ *self.owning_graph.borrow_mut() = pgraph.clone();++ Ok(())+ }++ fn QueryVendorInfo(&self) -> windows_core::Result<windows_core::PWSTR> {+ Ok(windows_core::PWSTR::null())+ }+}++impl IMediaFilter_Impl for SinkFilter_Impl {+ fn Stop(&self) -> windows_core::Result<()> {+ self.state.replace(State_Stopped);+ Ok(())+ }++ fn Pause(&self) -> windows_core::Result<()> {+ self.state.replace(State_Paused);+ Ok(())+ }++ fn Run(&self, _tstart: i64) -> windows_core::Result<()> {+ self.state.replace(State_Running);+ Ok(())+ }++ fn GetState(+ &self,+ _dwmillisecstimeout: u32,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::FILTER_STATE> {+ Ok(*self.state.borrow())+ }++ fn SetSyncSource(+ &self,+ _pclock: windows_core::Ref<'_, windows::Win32::Media::IReferenceClock>,+ ) -> windows_core::Result<()> {+ S_OK.ok()+ }++ fn GetSyncSource(&self) -> windows_core::Result<windows::Win32::Media::IReferenceClock> {+ Err(E_NOTIMPL.into())+ }+}++impl IPersist_Impl for SinkFilter_Impl {+ fn GetClassID(&self) -> windows_core::Result<windows_core::GUID> {+ unreachable!();+ }+}++#[implement(IEnumPins)]+struct PinEnumerator<'a> {+ filter: &'a dyn AsRef<SinkFilter>,+ index: RefCell<u32>,+}++impl<'a> IEnumPins_Impl for PinEnumerator_Impl<'a> {+ fn Next(+ &self,+ cpins: u32,+ pppins: windows_core::OutRef<'_, IPin>,+ pcfetched: *mut u32,+ ) -> windows_core::HRESULT {+ let mut pins_fetched = 0;++ let index = *self.index.borrow();+ let filter = self.filter.as_ref();+ if pins_fetched < cpins && filter.no_of_pins() > index {+ let pin = filter.get_pin(index);+ self.index.replace_with(|v| *v + 1);+ pins_fetched += 1;+ pppins.write(pin).unwrap();+ }++ if !pcfetched.is_null() {+ unsafe {+ *pcfetched = pins_fetched;+ }+ }++ if pins_fetched == cpins { S_OK } else { S_FALSE }+ }++ fn Skip(&self, cpins: u32) -> windows_core::Result<()> {+ let filter = self.filter.as_ref();+ if filter.no_of_pins() - *self.index.borrow() > cpins {+ self.index.replace_with(|v| *v + 1);+ return S_OK.ok();+ }++ self.index.replace(0);+ S_FALSE.ok()+ }++ fn Reset(&self) -> windows_core::Result<()> {+ self.index.replace(0);+ S_OK.ok()+ }++ fn Clone(&self) -> windows_core::Result<IEnumPins> {+ let result = unsafe { self.cast() };+ result+ }+}++pub type SinkCallback = Box<dyn Fn(&mut [u8], &AMMediaType, Option<Duration>)>;++#[implement(IPin, IMemInputPin)]+struct SinkInputPin {+ current_media_type: RefCell<AMMediaType>,+ connected_pin: RefCell<Option<IPin>>,+ owner: RefCell<Option<IBaseFilter>>,+ callback: SinkCallback,+}++impl SinkInputPin {+ unsafe fn get_valid_media_type(&self, index: i32, media_type: &mut AM_MEDIA_TYPE) -> bool {+ let video_info_header = &mut *(media_type.pbFormat as *mut KS_VIDEOINFOHEADER);++ video_info_header.bmiHeader.biSize = size_of::<KS_BITMAPINFOHEADER>() as u32;+ video_info_header.bmiHeader.biPlanes = 1;+ video_info_header.bmiHeader.biClrImportant = 0;+ video_info_header.bmiHeader.biClrUsed = 0;++ media_type.majortype = MEDIATYPE_Video;+ media_type.formattype = FORMAT_VideoInfo;+ media_type.bTemporalCompression = false.into();++ if index == 0 {+ video_info_header.bmiHeader.biCompression =+ u32::from_ne_bytes(*"yuy2".as_bytes().first_chunk::<4>().unwrap());+ video_info_header.bmiHeader.biBitCount = 16;+ video_info_header.bmiHeader.biWidth = 640;+ video_info_header.bmiHeader.biHeight = 480;+ media_type.subtype = MEDIASUBTYPE_YUY2;+ true+ } else {+ false+ }+ }+}++impl IPin_Impl for SinkInputPin_Impl {+ fn Connect(+ &self,+ preceivepin: windows_core::Ref<'_, IPin>,+ pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,+ ) -> windows_core::Result<()> {+ let Some(preceivepin) = preceivepin.as_ref() else {+ return E_POINTER.ok();+ };++ if pmt.is_null() {+ return E_POINTER.ok();+ }++ self.connected_pin.replace(Some(preceivepin.clone()));+ unsafe { preceivepin.ReceiveConnection(&self.cast::<IPin>()?, pmt) }+ }++ fn ReceiveConnection(+ &self,+ pconnector: windows_core::Ref<'_, IPin>,+ pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,+ ) -> windows_core::Result<()> {+ self.current_media_type+ .replace(AMMediaType::new(unsafe { &*pmt }));+ self.connected_pin.replace(pconnector.clone());+ S_OK.ok()+ }++ fn Disconnect(&self) -> windows_core::Result<()> {+ let result = match self.connected_pin.borrow_mut().take() {+ Some(_) => S_OK.ok(),+ None => VFW_E_NOT_CONNECTED.ok(),+ };+ result+ }++ fn ConnectedTo(&self) -> windows_core::Result<IPin> {+ let result = match self.connected_pin.borrow().as_ref() {+ Some(connected_pin) => Ok(connected_pin.clone()),+ None => Err(VFW_E_NOT_CONNECTED.into()),+ };+ result+ }++ fn ConnectionMediaType(+ &self,+ pmt: *mut windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,+ ) -> windows_core::Result<()> {+ self.connected_pin+ .borrow()+ .as_ref()+ .ok_or(VFW_E_NOT_CONNECTED)?;++ unsafe { *pmt = self.current_media_type.borrow().clone().into_inner() };++ Ok(())+ }++ fn QueryPinInfo(+ &self,+ pinfo: *mut windows::Win32::Media::DirectShow::PIN_INFO,+ ) -> windows_core::Result<()> {+ unsafe {+ (*pinfo).dir = PINDIR_INPUT;+ (*pinfo).pFilter =+ ManuallyDrop::new(self.owner.borrow().as_ref().map(|v| (&*v).clone()));+ (*pinfo).achName[0] = '\0' as u16;+ }++ S_OK.ok()+ }++ fn QueryDirection(+ &self,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::PIN_DIRECTION> {+ Ok(PINDIR_INPUT)+ }++ fn QueryId(&self) -> windows_core::Result<windows_core::PWSTR> {+ unreachable!()+ }++ fn QueryAccept(+ &self,+ _pmt: *const windows::Win32::Media::MediaFoundation::AM_MEDIA_TYPE,+ ) -> windows_core::HRESULT {+ S_FALSE+ }++ fn EnumMediaTypes(+ &self,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::IEnumMediaTypes> {+ Ok(TypeEnumerator {+ index: Default::default(),+ pin: self,+ }+ .into())+ }++ fn QueryInternalConnections(+ &self,+ _appin: windows_core::OutRef<'_, IPin>,+ _npin: *mut u32,+ ) -> windows_core::Result<()> {+ Err(E_NOTIMPL.into())+ }++ fn EndOfStream(&self) -> windows_core::Result<()> {+ S_OK.ok()+ }++ fn BeginFlush(&self) -> windows_core::Result<()> {+ S_OK.ok()+ }++ fn EndFlush(&self) -> windows_core::Result<()> {+ S_OK.ok()+ }++ fn NewSegment(&self, _tstart: i64, _tstop: i64, _drate: f64) -> windows_core::Result<()> {+ unreachable!()+ }+}++impl IMemInputPin_Impl for SinkInputPin_Impl {+ fn GetAllocator(+ &self,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::IMemAllocator> {+ Err(VFW_E_NO_ALLOCATOR.into())+ }++ fn NotifyAllocator(+ &self,+ _pallocator: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IMemAllocator>,+ _breadonly: windows_core::BOOL,+ ) -> windows_core::Result<()> {+ S_OK.ok()+ }++ fn GetAllocatorRequirements(+ &self,+ ) -> windows_core::Result<windows::Win32::Media::DirectShow::ALLOCATOR_PROPERTIES> {+ Err(E_NOTIMPL.into())+ }++ fn Receive(+ &self,+ psample: windows_core::Ref<'_, windows::Win32::Media::DirectShow::IMediaSample>,+ ) -> windows_core::Result<()> {+ let Some(psample) = psample.as_ref() else {+ return Ok(());+ };++ let mut ptimestart = 0;+ let mut ptimeend = 0;+ unsafe {+ psample.GetTime(&mut ptimestart, &mut ptimeend).unwrap();+ };++ let pts = ptimestart;+ let bytes = unsafe { psample.GetActualDataLength() };++ unsafe {+ if let Ok(new_media_type) = psample.GetMediaType() {+ if !new_media_type.is_null() {+ self.current_media_type+ .replace(AMMediaType::new(&*new_media_type));+ }+ }+ }++ let media_type = self.current_media_type.borrow();++ let format_str = unsafe { media_type.subtype_str() };++ let video_info =+ unsafe { &*(media_type.pbFormat as *const _ as *const KS_VIDEOINFOHEADER) };++ println!(+ "New frame: {}x{}, {pts}pts, {bytes} bytes, {}",+ video_info.bmiHeader.biWidth,+ video_info.bmiHeader.biHeight,+ format_str.unwrap_or("unknown format")+ );++ let length = unsafe { psample.GetActualDataLength() };++ if length <= 0 {+ return S_FALSE.ok();+ }++ let ptr = match unsafe { psample.GetPointer() } {+ Ok(ptr) => ptr,+ Err(_) => return S_FALSE.ok(),+ };++ let buffer = unsafe { std::slice::from_raw_parts_mut(ptr, length as usize) };++ let mut start_time = 0;+ let time_delta = unsafe { psample.GetTime(&mut start_time, &mut 0) }+ .ok()+ .map(|_| Duration::from_micros(start_time as u64 / 10));++ (self.callback)(buffer, &*media_type, time_delta);++ Ok(())+ }++ fn ReceiveMultiple(+ &self,+ psamples: *const Option<windows::Win32::Media::DirectShow::IMediaSample>,+ mut nsamples: i32,+ ) -> windows_core::Result<i32> {+ let mut processed: i32 = 0;+ while nsamples > 0 {+ unsafe { self.Receive((&*psamples.offset(processed as isize)).into())? };+ nsamples -= 1;+ processed += 1;+ }++ Ok(processed)+ }++ fn ReceiveCanBlock(&self) -> windows_core::Result<()> {+ S_FALSE.ok()+ }+}++#[implement(IEnumMediaTypes)]+struct TypeEnumerator<'a> {+ index: RefCell<i32>,+ pin: &'a SinkInputPin,+}++impl<'a> TypeEnumerator<'a> {+ unsafe fn free_allocated_media_types(allocated: usize, types: *mut *mut AM_MEDIA_TYPE) {+ for i in 0..allocated {+ CoTaskMemFree(Some((*(*types.add(i))).pbFormat as *const _));+ CoTaskMemFree(Some(*types.add(i) as *const _));+ }+ }+}++impl<'a> IEnumMediaTypes_Impl for TypeEnumerator_Impl<'a> {+ fn Next(+ &self,+ cmediatypes: u32,+ _ppmediatypes: *mut *mut AM_MEDIA_TYPE,+ pcfetched: *mut u32,+ ) -> windows_core::HRESULT {+ let mut types_fetched = 0;++ println!("next");++ while types_fetched < cmediatypes {+ unsafe {+ println!("loop");+ let typ = CoTaskMemAlloc(size_of::<AM_MEDIA_TYPE>()).cast::<AM_MEDIA_TYPE>();+ (*typ).cbFormat = size_of::<KS_VIDEOINFOHEADER>() as u32;+ if typ.is_null() {+ return E_OUTOFMEMORY;+ }++ let format =+ CoTaskMemAlloc(size_of::<KS_VIDEOINFOHEADER>()).cast::<KS_VIDEOINFOHEADER>();+ if format.is_null() {+ CoTaskMemFree(Some(typ.cast_const().cast()));+ return E_OUTOFMEMORY;+ }+ (*typ).pbFormat = format.cast::<u8>();++ if self+ .pin+ .get_valid_media_type(*self.index.borrow(), &mut *typ)+ {+ *_ppmediatypes.add(types_fetched as usize) = typ;+ self.index.replace_with(|v| (*v) + 1);+ types_fetched += 1;+ } else {+ CoTaskMemFree(Some(format.cast_const().cast()));+ CoTaskMemFree(Some(typ.cast_const().cast()));+ break;+ }+ }+ }++ if !pcfetched.is_null() {+ unsafe {+ *pcfetched = types_fetched;+ }+ }++ if types_fetched == cmediatypes {+ S_OK+ } else {+ S_FALSE+ }+ }++ fn Reset(&self) -> windows_core::Result<()> {+ self.index.replace(0);+ S_OK.ok()+ }++ fn Clone(&self) -> windows_core::Result<IEnumMediaTypes> {+ unsafe { self.cast() }+ }++ fn Skip(&self, _cmediatypes: u32) -> windows_core::Result<()> {+ self.index.replace_with(|v| (*v) + 1);+ S_OK.ok()+ }+}++unsafe fn copy_media_type(src: &AM_MEDIA_TYPE) -> AM_MEDIA_TYPE {+ let mut dest = src.clone();++ if src.cbFormat > 0 && !src.pbFormat.is_null() {+ let format_size = src.cbFormat as usize;+ let new_format = CoTaskMemAlloc(format_size) as *mut u8;++ if !new_format.is_null() {+ ptr::copy_nonoverlapping(src.pbFormat, new_format, format_size);+ dest.pbFormat = new_format;+ }+ }++ dest+}diff --git a/crates/camera-mediafoundation/examples/cli.rs b/crates/camera-mediafoundation/examples/cli.rsindex 597cc02d3..b9f9413ee 100644--- a/crates/camera-mediafoundation/examples/cli.rs+++ b/crates/camera-mediafoundation/examples/cli.rs@@ -1,85 +1,22 @@-use std::{- borrow::Cow,- ffi::{OsStr, OsString},- fmt::Display,- mem::MaybeUninit,- ops::{Deref, DerefMut},- os::windows::ffi::{OsStrExt, OsStringExt},- slice::{self, from_raw_parts},- time::Duration,-};+use std::{fmt::Display, time::Duration};+use camera_mediafoundation::DeviceSourcesIterator;use tracing::warn;use windows::Win32::{Media::MediaFoundation::*, System::Com::CoInitialize};-use windows_core::{GUID, Interface};-use windows_core::{PCWSTR, PWSTR};+use windows_core::GUID;pub fn main() {std::thread::spawn(|| unsafe {CoInitialize(None).unwrap();- let mut attributes = None;- MFCreateAttributes(&mut attributes, 1).unwrap();- let attributes = attributes.unwrap();+ let device_sources = DeviceSourcesIterator::new().unwrap();- attributes- .SetGUID(- &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,- &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID,- )- .unwrap();-- let mut count = 0;- let mut devices: MaybeUninit<*mut Option<IMFActivate>> = MaybeUninit::uninit();-- MFEnumDeviceSources(&attributes, devices.as_mut_ptr(), &mut count).unwrap();-- if count == 0 {+ if device_sources.len() == 0 {warn!("No devices found");return;}- let devices = devices.assume_init();-- let mut device_list = vec![];-- for i in 0..count {- let Some(device) = &mut *devices.add(i as usize) else {- continue;- };-- let mut name_raw = PWSTR(&mut 0);- let mut name_length = 0;- device- .GetAllocatedString(- &MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,- &mut name_raw,- &mut name_length,- )- .unwrap();- let name = OsString::from_wide(from_raw_parts(name_raw.0, name_length as usize));-- let mut id_raw = PWSTR(&mut 0);- let mut id_length = 0;- device- .GetAllocatedString(- &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,- &mut id_raw,- &mut id_length,- )- .unwrap();- let id = OsString::from_wide(from_raw_parts(id_raw.0, id_length as usize));-- let device = device.ActivateObject::<IMFMediaSource>().unwrap();-- device_list.push(Device {- device,- id_raw,- name_raw,- id,- name,- })- }+ let mut device_list = device_sources.collect::<Vec<_>>();let selected = if device_list.len() > 1 {inquire::Select::new("Select a device", device_list)@@ -89,19 +26,17 @@ pub fn main() {device_list.remove(0)};- let reader = MFCreateSourceReaderFromMediaSource(&selected.device, None).unwrap();- let mut stream_index = 0;-- let mut formats = vec![];+ let Ok(reader) = selected.create_source_reader() else {+ return;+ };- while let Ok(typ) =- reader.GetNativeMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32, stream_index)- {- let format = Format::new(typ).unwrap();- formats.push(format);+ let stream_index = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32;- stream_index += 1;- }+ let mut formats = reader+ .native_media_types(stream_index)+ .into_iter()+ .filter_map(|v| VideoFormat::new(v).ok())+ .collect::<Vec<_>>();let mut selected_format = if formats.len() > 1 {inquire::Select::new("Select a format", formats)@@ -112,18 +47,14 @@ pub fn main() {};reader- .SetCurrentMediaType(+ .set_current_media_type(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32,- None,&selected_format.inner,).unwrap();- reader- .SetStreamSelection(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32, true)- .unwrap();+ reader.SetStreamSelection(stream_index, true).unwrap();- let stream_index = MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32;loop {let mut imf_sample = None;let mut stream_flags = 0;@@ -150,7 +81,7 @@ pub fn main() {== MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0{selected_format =- Format::new(reader.GetCurrentMediaType(stream_index).unwrap()).unwrap();+ VideoFormat::new(reader.GetCurrentMediaType(stream_index).unwrap()).unwrap();}println!(@@ -165,49 +96,7 @@ pub fn main() {std::thread::sleep(Duration::from_secs(10));}-struct Device {- device: IMFMediaSource,- id_raw: PWSTR,- name_raw: PWSTR,- id: OsString,- name: OsString,-}--impl Device {- fn device_id(&self) -> String {- self.id.to_string_lossy().to_string()- }-- fn display_name(&self) -> String {- self.name.to_string_lossy().to_string()- }-- fn model_id(&self) -> String {- get_device_model_id(&self.device_id())- }-}--impl Deref for Device {- type Target = IMFMediaSource;-- fn deref(&self) -> &Self::Target {- &self.device- }-}--impl DerefMut for Device {- fn deref_mut(&mut self) -> &mut Self::Target {- &mut self.device- }-}--impl Display for Device {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "{}", self.display_name())- }-}--struct Format {+struct VideoFormat {inner: IMFMediaType,width: u32,height: u32,@@ -216,7 +105,7 @@ struct Format {subtype: GUID,}-impl Format {+impl VideoFormat {fn new(inner: IMFMediaType) -> windows_core::Result<Self> {let size = unsafe { inner.GetUINT64(&MF_MT_FRAME_SIZE)? };let width = (size >> 32) as u32;@@ -243,7 +132,7 @@ impl Format {}}-impl Display for Format {+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)?;if self.frame_rate_ratio.1 != 1 {diff --git a/crates/camera-mediafoundation/src/lib.rs b/crates/camera-mediafoundation/src/lib.rsindex 9ec07beae..9513273c4 100644--- a/crates/camera-mediafoundation/src/lib.rs+++ b/crates/camera-mediafoundation/src/lib.rs@@ -1 +1,191 @@#![cfg(windows)]++use std::{+ ffi::OsString,+ fmt::Display,+ mem::MaybeUninit,+ ops::{Deref, DerefMut},+ os::windows::ffi::OsStringExt,+ slice::from_raw_parts,+};++use windows::Win32::Media::MediaFoundation::*;+use windows_core::PWSTR;++pub struct DeviceSourcesIterator {+ _attributes: IMFAttributes,+ count: u32,+ devices: *mut Option<IMFActivate>,+ index: u32,+}++impl DeviceSourcesIterator {+ pub fn new() -> Result<Self, windows_core::Error> {+ let mut attributes = None;+ unsafe { MFCreateAttributes(&mut attributes, 1)? };+ let attributes = attributes.unwrap();++ unsafe {+ attributes.SetGUID(+ &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,+ &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID,+ )?;+ }++ let mut count = 0;+ let mut devices = MaybeUninit::uninit();++ unsafe {+ MFEnumDeviceSources(&attributes, devices.as_mut_ptr(), &mut count)?;+ }++ Ok(DeviceSourcesIterator {+ _attributes: attributes,+ devices: unsafe { devices.assume_init() },+ count,+ index: 0,+ })+ }++ pub fn len(&self) -> u32 {+ self.count+ }+}++impl Iterator for DeviceSourcesIterator {+ type Item = Device;++ fn next(&mut self) -> Option<Self::Item> {+ if self.count == 0 {+ return None;+ }++ loop {+ let index = self.index;+ if index >= self.count {+ return None;+ }++ self.index += 1;++ let Some(device) = (unsafe { &(*self.devices.add(index as usize)) }) else {+ continue;+ };++ return Some(Device {+ media_source: unsafe { device.ActivateObject::<IMFMediaSource>() }+ .expect("media source doesn't have IMFMediaSource"),+ activate: device.clone(),+ });+ }+ }+}++pub struct Device {+ activate: IMFActivate,+ media_source: IMFMediaSource,+}++impl Device {+ pub fn name(&self) -> Option<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> {+ let mut raw = PWSTR(&mut 0);+ let mut length = 0;+ unsafe {+ self.activate+ .GetAllocatedString(+ &MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,+ &mut raw,+ &mut length,+ )+ .map(|_| OsString::from_wide(from_raw_parts(raw.0, length as usize)))+ .ok()+ }+ }++ pub fn create_source_reader(&self) -> windows_core::Result<SourceReader> {+ unsafe {+ MFCreateSourceReaderFromMediaSource(&self.media_source, None)+ .map(|inner| SourceReader { inner })+ }+ }+}++impl Deref for Device {+ type Target = IMFMediaSource;++ fn deref(&self) -> &Self::Target {+ &self.media_source+ }+}++impl DerefMut for Device {+ fn deref_mut(&mut self) -> &mut Self::Target {+ &mut self.media_source+ }+}++impl Display for Device {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{}",+ self.name()+ .map(|v| v.to_string_lossy().to_string())+ .unwrap_or_else(|| format!("Unknown device name"))+ )+ }+}++pub struct SourceReader {+ inner: IMFSourceReader,+}++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 set_current_media_type(+ &self,+ stream_index: u32,+ media_type: &IMFMediaType,+ ) -> windows_core::Result<()> {+ unsafe {+ self.inner+ .SetCurrentMediaType(stream_index, None, media_type)+ }+ }+}++impl Deref for SourceReader {+ type Target = IMFSourceReader;++ fn deref(&self) -> &Self::Target {+ &self.inner+ }+}++impl DerefMut for SourceReader {+ fn deref_mut(&mut self) -> &mut Self::Target {+ &mut self.inner+ }+}