diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3988456..5a62177 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,15 @@ on: pull_request: jobs: + preview: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - run: node --test crates/secbird-tray/src/*.test.cjs + check: runs-on: windows-latest steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f37615..7938682 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -131,6 +131,15 @@ - Tartarus V2: colour and brightness changes did nothing. It uses the newer lighting commands, not the older ones the device list had (#46, thanks fen0z). +## Unreleased +## Unreleased + +### Added +- Experimental Windows support for the Razer Kiyo Pro (RZ19-0364): HDR, HDR mode, field of view, + autofocus strategy, and driver-reported standard image/camera controls. Profiles retain explicit + settings; unsupported controls are disabled. Physical control effects are not verified yet. +- Optional browser-based, video-only preview in the tray editor to inspect camera changes. It asks + for camera access only when started and can contend with other camera applications. ## [0.4.9] - 2026-10-21 ### Added diff --git a/Cargo.lock b/Cargo.lock index e194de6..503bd9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -172,6 +172,7 @@ dependencies = [ "hidapi", "serde", "serde_json", + "windows", "windows-sys 0.59.0", ] @@ -219,7 +220,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.7", ] [[package]] @@ -250,6 +251,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.7" @@ -328,12 +340,81 @@ dependencies = [ "libc", ] +[[package]] +name = "windows" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1" +dependencies = [ + "windows-core", + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-core" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-strings", + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-implement" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83577b051e2f49a058c308f17f273b570a6a758386fc291b5f6a934dd84e48c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -358,7 +439,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -385,13 +466,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -404,6 +502,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -416,6 +520,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -428,12 +538,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -446,6 +568,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -458,6 +586,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -470,6 +604,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -482,6 +622,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" diff --git a/NOTICE b/NOTICE index 585a95d..d7b3637 100644 --- a/NOTICE +++ b/NOTICE @@ -6,5 +6,10 @@ documented by the OpenRazer project (https://github.com/openrazer/openrazer, GPL-2.0), checkout 477f4d6 from 2026-10-05. The facts were extracted with tools/restate_openrazer.py; no OpenRazer code is included or executed. +The Kiyo Pro USB identity, extension-unit GUID and control payload facts are +restated from https://github.com/soyersoyer/kiyoproctrls (MIT). Its Python source +is not included or executed; the Rust implementation independently encodes the +documented device protocol. + Razer, Synapse, Chroma and product names are trademarks of Razer Inc. Secretarybird is an independent project and is not affiliated with or endorsed by Razer. diff --git a/README.md b/README.md index 6bf9f25..99c6b20 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,47 @@ one at a time. Bug reports from Linux are very welcome, with `secbird report` ou back when you leave it, button remaps included. Windows tells the tray when the window in front changes, so nothing polls. +## Kiyo Pro webcam (experimental, Windows) + +Kiyo Pro RZ1900364 (`1532:0E05`) support is implemented but **not yet verified on +physical hardware**. The Camera section provides HDR, HDR mode, field of view, +and responsive/passive autofocus strategy. Settings are saved in profiles; +vendor-extension values are saved requests, not live hardware readbacks. Standard +Windows controls display values read from the camera. + +The **Image** and **Camera** sections also expose driver-supported Windows +controls: brightness, contrast, saturation, sharpness, gain, white balance, +backlight compensation, anti-flicker, zoom, pan/tilt, focus, exposure, and +low-light compensation. Hue, gamma, color enable, aperture and roll are displayed +but disabled when the driver doesn't support them. Auto/manual modes and numeric +ranges come from the driver; **Reset to driver default** is available where a +default is known. These controls save to the active profile, and successful +writes are read back. Standard autofocus Auto is separate from the vendor's +responsive/passive autofocus strategy. Low-light compensation can lower FPS in +dim light; anti-flicker 50/60 Hz is the lighting frequency, not video FPS. + +Optional live preview lets you inspect the image while changing controls. Enable +preview, allow browser camera access, and explicitly select the matching camera +source. Preview resolution/FPS choices apply only to this session, not OBS, +Teams, or other apps. Untested combinations are labeled as candidates; the actual +negotiated format is shown. Stop preview to release camera access for other apps. +No microphone, photo recording, video recording, or webcam firmware updates are +included. Camera control is Windows-only; the existing Linux CLI is unchanged. + +```text +secbird list +secbird -d 0E05 camera fov wide +secbird -d 0E05 camera hdr on +secbird -d 0E05 camera af-mode passive +secbird -d 0E05 camera controls +secbird -d 0E05 camera white-balance auto +secbird -d 0E05 camera exposure -6 +``` + +With multiple Kiyo Pros, use the full camera identity from `list`, quoted in your +shell. Identities are tied to the Windows device path and can change when USB +ports change. See [setup and hardware verification](docs/kiyo-pro-verification.md). + ## Moving from Synapse 1. Close Synapse (tray icon → Exit). If both run, Synapse overwrites your settings, and diff --git a/crates/secbird-core/Cargo.toml b/crates/secbird-core/Cargo.toml index 20f519e..f90b3d8 100644 --- a/crates/secbird-core/Cargo.toml +++ b/crates/secbird-core/Cargo.toml @@ -11,6 +11,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" [target.'cfg(windows)'.dependencies] +windows = { version = "0.59", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Ole", "Win32_System_Variant", "Win32_Media_DirectShow", "Win32_Media_KernelStreaming"] } hidapi = { version = "2.6", default-features = false, features = ["windows-native"] } windows-sys = { version = "0.59", features = [ "Win32_Devices_HumanInterfaceDevice", diff --git a/crates/secbird-core/devices.json b/crates/secbird-core/devices.json index fbedc02..bbcbdf0 100644 --- a/crates/secbird-core/devices.json +++ b/crates/secbird-core/devices.json @@ -1,4 +1,5 @@ [ +{"pid":"0E05","name":"Razer Kiyo Pro","kind":"webcam","source":"kiyoproctrls-protocol-facts"}, {"pid":"0013","name":"Orochi 2011","kind":"mouse","txid":"FF","dpi":{"min":100,"max":4000,"step":50},"polling":"standard","source":"openrazer"}, {"pid":"0015","name":"Naga","kind":"mouse","txid":"FF","dpi":{"min":100,"max":5600,"step":50},"polling":"standard","lighting":"standard","source":"openrazer"}, {"pid":"0016","name":"DeathAdder 3.5G","kind":"mouse","dpi":{"min":100,"max":3500,"step":50},"polling":"standard","source":"openrazer"}, diff --git a/crates/secbird-core/src/camera/actions.rs b/crates/secbird-core/src/camera/actions.rs new file mode 100644 index 0000000..68ce0f5 --- /dev/null +++ b/crates/secbird-core/src/camera/actions.rs @@ -0,0 +1,88 @@ +//! Apply explicit controls and persist only successfully sent settings. +use super::controls::{Control, ControlState, ControlValue}; +use super::{CameraBackend, CameraSettings, Setting}; +use crate::{profile::Applied, Error, Profile, Result, Store}; + +pub fn set_control( + backend: &dyn CameraBackend, + id: &str, + store: &mut Store, + profile: &str, + control: Control, + value: ControlValue, +) -> Result { + if !store.for_camera(id).profiles.contains_key(profile) { + return Err(Error::NotFound(format!("profile '{profile}'"))); + } + let state = backend.set_control(id, control, value)?; + store + .for_camera(id) + .profiles + .get_mut(profile) + .expect("checked profile") + .camera + .get_or_insert_with(CameraSettings::default) + .controls + .insert(control, state.saved()); + store.save().map_err(|error| { + Error::System(format!( + "camera changed but profile could not be saved: {error}" + )) + })?; + Ok(state) +} + +pub fn set( + backend: &dyn CameraBackend, + id: &str, + store: &mut Store, + profile: &str, + setting: Setting, +) -> Result<()> { + if !store.for_camera(id).profiles.contains_key(profile) { + return Err(Error::NotFound(format!("profile '{profile}'"))); + } + backend.set(id, setting)?; + let settings = store + .for_camera(id) + .profiles + .get_mut(profile) + .expect("profile checked above") + .camera + .get_or_insert_with(CameraSettings::default); + match setting { + Setting::Hdr(value) => settings.hdr = Some(value), + Setting::HdrMode(value) => settings.hdr_mode = Some(value), + Setting::FieldOfView(value) => settings.fov = Some(value), + Setting::AutofocusMode(value) => settings.af_mode = Some(value), + } + store.save().map_err(|error| { + Error::System(format!( + "camera changed but profile could not be saved: {error}" + )) + }) +} + +pub fn apply(backend: &dyn CameraBackend, id: &str, profile: &Profile) -> Vec { + let Some(settings) = &profile.camera else { + return Vec::new(); + }; + let mut applied: Vec<_> = [ + settings.hdr_mode.map(Setting::HdrMode), + settings.hdr.map(Setting::Hdr), + settings.fov.map(Setting::FieldOfView), + settings.af_mode.map(Setting::AutofocusMode), + ] + .into_iter() + .flatten() + .map(|setting| Applied { + setting: format!("camera {setting:?}"), + result: backend.set(id, setting), + }) + .collect(); + applied.extend(settings.controls.iter().map(|(&control, &value)| Applied { + setting: format!("camera {}", control.name()), + result: backend.set_control(id, control, value).map(|_| ()), + })); + applied +} diff --git a/crates/secbird-core/src/camera/controls.rs b/crates/secbird-core/src/camera/controls.rs new file mode 100644 index 0000000..b645d9d --- /dev/null +++ b/crates/secbird-core/src/camera/controls.rs @@ -0,0 +1,363 @@ +use crate::{Error, Result}; +use serde::{Deserialize, Serialize}; +use std::str::FromStr; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Control { + Brightness, + Contrast, + Hue, + Saturation, + Sharpness, + Gamma, + WhiteBalance, + BacklightCompensation, + Gain, + ColorEnable, + #[serde(rename = "anti-flicker")] + PowerlineFrequency, + Zoom, + Pan, + Tilt, + Focus, + Exposure, + #[serde(rename = "aperture")] + Iris, + Roll, + LowLightCompensation, +} +impl Control { + pub const ALL: [Self; 19] = [ + Self::Brightness, + Self::Contrast, + Self::Hue, + Self::Saturation, + Self::Sharpness, + Self::Gamma, + Self::WhiteBalance, + Self::BacklightCompensation, + Self::Gain, + Self::ColorEnable, + Self::PowerlineFrequency, + Self::Zoom, + Self::Pan, + Self::Tilt, + Self::Focus, + Self::Exposure, + Self::Iris, + Self::Roll, + Self::LowLightCompensation, + ]; + pub fn name(self) -> &'static str { + match self { + Self::Brightness => "brightness", + Self::Contrast => "contrast", + Self::Hue => "hue", + Self::Saturation => "saturation", + Self::Sharpness => "sharpness", + Self::Gamma => "gamma", + Self::WhiteBalance => "white-balance", + Self::BacklightCompensation => "backlight-compensation", + Self::Gain => "gain", + Self::ColorEnable => "color-enable", + Self::PowerlineFrequency => "anti-flicker", + Self::Zoom => "zoom", + Self::Pan => "pan", + Self::Tilt => "tilt", + Self::Focus => "focus", + Self::Exposure => "exposure", + Self::Iris => "aperture", + Self::Roll => "roll", + Self::LowLightCompensation => "low-light-compensation", + } + } + pub fn group(self) -> &'static str { + if Self::ALL[..11].contains(&self) { + "image" + } else { + "camera" + } + } + pub fn kind(self) -> &'static str { + match self { + Self::PowerlineFrequency => "frequency", + Self::ColorEnable | Self::LowLightCompensation => "toggle", + _ => "range", + } + } +} +impl FromStr for Control { + type Err = Error; + fn from_str(name: &str) -> Result { + Self::ALL + .into_iter() + .find(|control| control.name() == name) + .ok_or_else(|| Error::InvalidArg(format!("unknown camera control '{name}'"))) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "mode", content = "value", rename_all = "lowercase")] +pub enum ControlValue { + Manual(i32), + Auto, + Default, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct ControlState { + pub value: i32, + pub automatic: bool, +} +impl ControlState { + pub fn saved(self) -> ControlValue { + if self.automatic { + ControlValue::Auto + } else { + ControlValue::Manual(self.value) + } + } +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ControlRange { + pub min: i32, + pub max: i32, + pub step: i32, + pub default: Option, + pub automatic: bool, + pub manual: bool, + pub choices: Vec, +} +impl ControlRange { + pub fn accepts(&self, value: i32) -> bool { + self.step > 0 + && value >= self.min + && value <= self.max + && (i64::from(value) - i64::from(self.min)) % i64::from(self.step) == 0 + && (self.choices.is_empty() || self.choices.contains(&value)) + } + pub fn validate(&self) -> Result<()> { + if self.min > self.max + || self.step <= 0 + || (!self.automatic && !self.manual) + || self.default.is_some_and(|value| !self.accepts(value)) + || self.choices.iter().any(|value| !self.accepts(*value)) + { + Err(Error::Unsupported( + "driver returned an invalid control range".into(), + )) + } else { + Ok(()) + } + } + pub fn resolve( + &self, + requested: ControlValue, + current: Option, + ) -> Result { + self.validate()?; + match requested { + ControlValue::Auto if self.automatic => Ok(ControlState { + value: current + .map(|s| s.value) + .filter(|v| self.accepts(*v)) + .or(self.default) + .unwrap_or(self.min), + automatic: true, + }), + ControlValue::Manual(value) if self.manual && self.accepts(value) => Ok(ControlState { + value, + automatic: false, + }), + ControlValue::Default => self + .default + .map(|value| ControlState { + value, + automatic: !self.manual, + }) + .ok_or_else(|| { + Error::Unsupported("driver did not report a default for this control".into()) + }), + _ => Err(Error::InvalidArg(format!( + "unsupported control mode/value; range {}..{} step {}", + self.min, self.max, self.step + ))), + } + } +} +#[derive(Debug, Clone, Serialize)] +pub struct ControlInfo { + pub control: Control, + pub group: &'static str, + pub kind: &'static str, + pub range: Option, + pub current: Option, + pub error: Option, +} + +pub fn validate_prerequisite( + control: Control, + requested: ControlState, + related: Option, +) -> Result<()> { + if control == Control::LowLightCompensation + && requested.value != 0 + && !related.is_some_and(|flags| flags & 1 != 0) + { + return Err(Error::InvalidArg( + "low-light compensation needs automatic exposure; enable Exposure Auto first".into(), + )); + } + if control == Control::Exposure && !requested.automatic && related == Some(1) { + return Err(Error::InvalidArg( + "turn off low-light compensation before switching Exposure to Manual".into(), + )); + } + Ok(()) +} +impl ControlInfo { + pub fn new( + control: Control, + range: Option, + current: Option, + error: Option, + ) -> Self { + Self { + control, + group: control.group(), + kind: control.kind(), + range, + current, + error, + } + } +} +pub fn parse_control(name: &str, text: &str) -> Result<(Control, ControlValue)> { + let control: Control = name.parse()?; + let value = match (control, text) { + (_, "default") => ControlValue::Default, + (Control::PowerlineFrequency, "off") => ControlValue::Manual(0), + (Control::PowerlineFrequency, "50hz") => ControlValue::Manual(1), + (Control::PowerlineFrequency, "60hz") => ControlValue::Manual(2), + (Control::PowerlineFrequency, "auto") => ControlValue::Manual(3), + (Control::ColorEnable | Control::LowLightCompensation, "off") => ControlValue::Manual(0), + (Control::ColorEnable | Control::LowLightCompensation, "on") => ControlValue::Manual(1), + (_, "auto") => ControlValue::Auto, + _ => ControlValue::Manual( + text.parse() + .map_err(|_| Error::InvalidArg(format!("invalid {name} value")))?, + ), + }; + Ok((control, value)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn validation_and_modes() { + let range = ControlRange { + min: -12, + max: -2, + step: 2, + default: Some(-6), + automatic: true, + manual: true, + choices: vec![], + }; + assert_eq!( + range.resolve(ControlValue::Auto, None).unwrap().saved(), + ControlValue::Auto + ); + assert_eq!( + range.resolve(ControlValue::Manual(-6), None).unwrap().value, + -6 + ); + assert!(range.resolve(ControlValue::Manual(-5), None).is_err()); + assert_eq!( + range.resolve(ControlValue::Default, None).unwrap().value, + -6 + ); + assert!(ControlRange { + default: None, + ..range.clone() + } + .resolve(ControlValue::Default, None) + .is_err()); + assert!(ControlRange { + step: 0, + ..range.clone() + } + .validate() + .is_err()); + } + #[test] + fn parse_and_persist_auto_separately_from_strategy() { + assert_eq!( + parse_control("focus", "auto").unwrap(), + (Control::Focus, ControlValue::Auto) + ); + assert_eq!( + parse_control("anti-flicker", "60hz").unwrap(), + (Control::PowerlineFrequency, ControlValue::Manual(2)) + ); + assert_eq!( + parse_control("exposure", "-6").unwrap(), + (Control::Exposure, ControlValue::Manual(-6)) + ); + assert!(parse_control("fps", "60").is_err()); + assert_eq!( + serde_json::to_string(&ControlValue::Auto).unwrap(), + r#"{"mode":"auto"}"# + ); + } + + #[test] + fn exposure_manual_requires_low_light_compensation_off() { + assert!(validate_prerequisite( + Control::Exposure, + ControlState { + value: -6, + automatic: false + }, + Some(1) + ) + .is_err()); + assert!(validate_prerequisite( + Control::Exposure, + ControlState { + value: -6, + automatic: false + }, + Some(0) + ) + .is_ok()); + assert!(validate_prerequisite( + Control::Exposure, + ControlState { + value: -6, + automatic: true + }, + Some(1) + ) + .is_ok()); + assert!(validate_prerequisite( + Control::LowLightCompensation, + ControlState { + value: 1, + automatic: false + }, + Some(0) + ) + .is_err()); + assert!(validate_prerequisite( + Control::LowLightCompensation, + ControlState { + value: 1, + automatic: false + }, + Some(1) + ) + .is_ok()); + } +} diff --git a/crates/secbird-core/src/camera/mod.rs b/crates/secbird-core/src/camera/mod.rs new file mode 100644 index 0000000..985be8f --- /dev/null +++ b/crates/secbird-core/src/camera/mod.rs @@ -0,0 +1,145 @@ +//! Kiyo Pro controls, separate from the HID peripheral protocol. + +use crate::{Error, Result}; +use serde::{Deserialize, Serialize}; + +pub mod actions; +pub mod controls; + +#[cfg(any(windows, test))] +mod protocol; +#[cfg(windows)] +mod windows; +#[cfg(windows)] +mod windows_controls; +#[cfg(any(windows, test))] +mod worker; + +pub const KIYO_PRO_PID: u16 = 0x0E05; + +#[derive(Debug, Clone, Serialize)] +pub struct CameraInfo { + pub id: String, + pub pid: u16, + pub name: String, + pub control_error: Option, +} + +pub trait CameraBackend: Send { + fn discover(&self) -> Result>; + fn set(&self, id: &str, setting: Setting) -> Result<()>; + fn controls(&self, _id: &str) -> Result> { + Err(Error::Unsupported( + "standard controls require Windows".into(), + )) + } + fn set_control( + &self, + _id: &str, + _control: controls::Control, + _value: controls::ControlValue, + ) -> Result { + Err(Error::Unsupported( + "standard controls require Windows".into(), + )) + } +} + +pub fn backend() -> Result> { + #[cfg(windows)] + { + windows::start() + } + #[cfg(not(windows))] + { + Ok(Box::new(Unsupported)) + } +} + +#[cfg(not(windows))] +struct Unsupported; +#[cfg(not(windows))] +impl CameraBackend for Unsupported { + fn discover(&self) -> Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, _: Setting) -> Result<()> { + Err(Error::Unsupported( + "camera controls require Windows 10/11".into(), + )) + } +} + +#[cfg(any(windows, test))] +fn camera_id(path: &str) -> String { + format!("camera:{}", path.to_ascii_lowercase()) +} + +#[cfg(any(windows, test))] +fn is_kiyo_pro_path(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + let parts: Vec<_> = lower.split(['#', '&', '\\', '?']).collect(); + parts.contains(&"vid_1532") && parts.contains(&"pid_0e05") +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum HdrMode { + Dark, + Bright, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FieldOfView { + Wide, + Medium, + Narrow, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AutofocusMode { + Responsive, + Passive, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Setting { + Hdr(bool), + HdrMode(HdrMode), + FieldOfView(FieldOfView), + AutofocusMode(AutofocusMode), +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct CameraSettings { + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub controls: std::collections::BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hdr: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hdr_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fov: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub af_mode: Option, +} + +pub fn parse_setting(control: &str, value: &str) -> Result { + match (control, value) { + ("hdr", "on") => Ok(Setting::Hdr(true)), + ("hdr", "off") => Ok(Setting::Hdr(false)), + ("hdr-mode", "dark") => Ok(Setting::HdrMode(HdrMode::Dark)), + ("hdr-mode", "bright") => Ok(Setting::HdrMode(HdrMode::Bright)), + ("fov", "wide") => Ok(Setting::FieldOfView(FieldOfView::Wide)), + ("fov", "medium") => Ok(Setting::FieldOfView(FieldOfView::Medium)), + ("fov", "narrow") => Ok(Setting::FieldOfView(FieldOfView::Narrow)), + ("af-mode", "responsive") => Ok(Setting::AutofocusMode(AutofocusMode::Responsive)), + ("af-mode", "passive") => Ok(Setting::AutofocusMode(AutofocusMode::Passive)), + _ => Err(Error::InvalidArg(format!("camera {control} {value}: expected hdr on|off, hdr-mode dark|bright, fov wide|medium|narrow, or af-mode responsive|passive"))), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/secbird-core/src/camera/protocol.rs b/crates/secbird-core/src/camera/protocol.rs new file mode 100644 index 0000000..4a71464 --- /dev/null +++ b/crates/secbird-core/src/camera/protocol.rs @@ -0,0 +1,90 @@ +//! Independently encoded protocol facts from the public Kiyo Pro controls reference. + +use super::{AutofocusMode, FieldOfView, HdrMode, Setting}; +use crate::Result; + +fn commands(setting: Setting) -> Vec<[u8; 8]> { + let (register, value) = match setting { + Setting::Hdr(on) => (2, u8::from(on)), + Setting::HdrMode(mode) => (7, u8::from(mode == HdrMode::Bright)), + Setting::AutofocusMode(mode) => (6, u8::from(mode == AutofocusMode::Passive)), + Setting::FieldOfView(fov) => { + let index = match fov { + FieldOfView::Wide => 0, + FieldOfView::Medium => 1, + FieldOfView::Narrow => 2, + }; + let mut out = vec![[0xff, 1, 0, 3, index, 0, 0, 0]]; + if index != 0 { + out.push([0xff, 1, 1, 3, index, 0, 0, 0]); + } + return out; + } + }; + vec![[0xff, register, value, 0, 0, 0, 0, 0]] +} + +pub(super) fn send_setting( + setting: Setting, + mut send: impl FnMut(&[u8; 8]) -> Result<()>, +) -> Result<()> { + for command in commands(setting) { + send(&command)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::camera::{AutofocusMode as Af, FieldOfView as Fov, HdrMode, Setting}; + + #[test] + fn camera_payloads_match_documented_registers() { + for (setting, expected) in [ + (Setting::Hdr(false), vec![[0xff, 2, 0, 0, 0, 0, 0, 0]]), + (Setting::Hdr(true), vec![[0xff, 2, 1, 0, 0, 0, 0, 0]]), + ( + Setting::HdrMode(HdrMode::Dark), + vec![[0xff, 7, 0, 0, 0, 0, 0, 0]], + ), + ( + Setting::HdrMode(HdrMode::Bright), + vec![[0xff, 7, 1, 0, 0, 0, 0, 0]], + ), + ( + Setting::AutofocusMode(Af::Responsive), + vec![[0xff, 6, 0, 0, 0, 0, 0, 0]], + ), + ( + Setting::AutofocusMode(Af::Passive), + vec![[0xff, 6, 1, 0, 0, 0, 0, 0]], + ), + ( + Setting::FieldOfView(Fov::Wide), + vec![[0xff, 1, 0, 3, 0, 0, 0, 0]], + ), + ( + Setting::FieldOfView(Fov::Medium), + vec![[0xff, 1, 0, 3, 1, 0, 0, 0], [0xff, 1, 1, 3, 1, 0, 0, 0]], + ), + ( + Setting::FieldOfView(Fov::Narrow), + vec![[0xff, 1, 0, 3, 2, 0, 0, 0], [0xff, 1, 1, 3, 2, 0, 0, 0]], + ), + ] { + assert_eq!(commands(setting), expected); + } + } + + #[test] + fn camera_sequence_aborts_on_first_failed_write() { + let mut writes = Vec::new(); + let result = send_setting(Setting::FieldOfView(Fov::Narrow), |command| { + writes.push(*command); + Err(crate::Error::System("disconnected".into())) + }); + assert!(result.is_err()); + assert_eq!(writes, vec![[0xff, 1, 0, 3, 2, 0, 0, 0]]); + } +} diff --git a/crates/secbird-core/src/camera/tests.rs b/crates/secbird-core/src/camera/tests.rs new file mode 100644 index 0000000..32c4fa8 --- /dev/null +++ b/crates/secbird-core/src/camera/tests.rs @@ -0,0 +1,383 @@ +use super::*; +use std::sync::Mutex; + +#[test] +fn standard_camera_controls_save_requested_mode_and_replay_only_recorded_settings() { + use super::controls::{Control, ControlState, ControlValue}; + struct Fake(Mutex>); + impl CameraBackend for Fake { + fn discover(&self) -> crate::Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, _: Setting) -> crate::Result<()> { + panic!("no vendor control in this profile") + } + fn set_control( + &self, + _: &str, + control: Control, + value: ControlValue, + ) -> crate::Result { + self.0.lock().unwrap().push((control, value)); + Ok(match value { + ControlValue::Auto => ControlState { + value: 5000, + automatic: true, + }, + ControlValue::Manual(value) => ControlState { + value, + automatic: false, + }, + ControlValue::Default => ControlState { + value: 128, + automatic: false, + }, + }) + } + } + let fake = Fake(Mutex::new(Vec::new())); + let mut old: crate::Profile = serde_json::from_str(r#"{"camera":{"hdr":null}}"#).unwrap(); + assert!(old.camera.as_ref().unwrap().controls.is_empty()); + assert!(actions::apply(&fake, "camera:test", &old).is_empty()); + old.camera + .as_mut() + .unwrap() + .controls + .insert(Control::WhiteBalance, ControlValue::Auto); + assert_eq!(actions::apply(&fake, "camera:test", &old).len(), 1); + assert_eq!( + fake.0.lock().unwrap().as_slice(), + &[(Control::WhiteBalance, ControlValue::Auto)] + ); + assert_eq!( + serde_json::from_str::(&serde_json::to_string(&old).unwrap()).unwrap(), + old + ); +} + +#[test] +fn standard_controls_save_auto_without_freezing_readback_and_replay_only_explicit_fields() { + use super::controls::{Control, ControlState, ControlValue}; + struct FakeStandard(Mutex>); + impl CameraBackend for FakeStandard { + fn discover(&self) -> crate::Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, _: Setting) -> crate::Result<()> { + panic!("no vendor control requested") + } + fn set_control( + &self, + _: &str, + control: Control, + value: ControlValue, + ) -> crate::Result { + self.0.lock().unwrap().push((control, value)); + Ok(match value { + ControlValue::Auto => ControlState { + value: 5000, + automatic: true, + }, + ControlValue::Manual(value) => ControlState { + value, + automatic: false, + }, + ControlValue::Default => ControlState { + value: 128, + automatic: false, + }, + }) + } + } + let backend = FakeStandard(Mutex::new(Vec::new())); + let mut old: crate::Profile = serde_json::from_str(r#"{"camera":{"hdr":null}}"#).unwrap(); + assert!(old.camera.as_ref().unwrap().controls.is_empty()); + assert!(actions::apply(&backend, "camera:test", &old).is_empty()); + old.camera + .as_mut() + .unwrap() + .controls + .insert(Control::WhiteBalance, ControlValue::Auto); + assert_eq!(actions::apply(&backend, "camera:test", &old).len(), 1); + assert_eq!( + backend.0.lock().unwrap().as_slice(), + &[(Control::WhiteBalance, ControlValue::Auto)] + ); + assert_eq!( + serde_json::from_str::(&serde_json::to_string(&old).unwrap()).unwrap(), + old + ); +} + +#[test] +fn camera_second_fov_write_failure_is_not_saved() { + struct SecondWriteFailure(Mutex); + impl CameraBackend for SecondWriteFailure { + fn discover(&self) -> crate::Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, setting: Setting) -> crate::Result<()> { + super::protocol::send_setting(setting, |_| { + let mut writes = self.0.lock().unwrap(); + *writes += 1; + if *writes == 2 { + Err(crate::Error::System("second FOV write failed".into())) + } else { + Ok(()) + } + }) + } + } + let backend = SecondWriteFailure(Mutex::new(0)); + let mut store = crate::Store::default(); + let error = actions::set( + &backend, + "camera:test", + &mut store, + "Default", + Setting::FieldOfView(FieldOfView::Narrow), + ) + .unwrap_err(); + assert!(error.to_string().contains("second FOV write failed")); + assert_eq!(*backend.0.lock().unwrap(), 2); + assert!(store.for_camera("camera:test").active().camera.is_none()); +} + +#[test] +fn camera_and_hid_apply_only_their_own_fields_in_imported_profile() { + let profile: crate::Profile = + serde_json::from_str(r#"{"dpi":[1600,1600],"camera":{"hdr":true}}"#).unwrap(); + let sim = crate::sim::Sim::mouse(); + let device = sim + .open( + crate::sim::MOUSE_PID, + crate::sim::Sim::spec_for(crate::sim::MOUSE_PID), + ) + .unwrap(); + let applied = profile.apply(&device); + assert_eq!(applied.len(), 1); + assert!(applied[0].result.is_ok()); + assert_eq!(device.dpi().unwrap(), (1600, 1600)); + let camera = Fake::default(); + let applied = actions::apply(&camera, "camera:test", &profile); + assert_eq!(applied.len(), 1); + assert_eq!(*camera.writes.lock().unwrap(), vec![Setting::Hdr(true)]); +} + +#[derive(Default)] +struct Fake { + writes: Mutex>, + fail: bool, +} +impl CameraBackend for Fake { + fn discover(&self) -> crate::Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, setting: Setting) -> crate::Result<()> { + self.writes.lock().unwrap().push(setting); + if self.fail { + Err(crate::Error::System("disconnected".into())) + } else { + Ok(()) + } + } +} + +#[test] +fn camera_successful_write_is_saved_and_save_failure_is_reported() { + let directory = std::env::temp_dir().join(format!( + "secbird-camera-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let path = directory.join("profiles.json"); + let fake = Fake::default(); + let mut store = crate::Store::load(&path).unwrap(); + actions::set( + &fake, + "camera:test", + &mut store, + "Default", + Setting::Hdr(true), + ) + .unwrap(); + let mut loaded = crate::Store::load(&path).unwrap(); + assert_eq!( + loaded + .for_camera("camera:test") + .active() + .camera + .as_ref() + .unwrap() + .hdr, + Some(true) + ); + let mut invalid_store = crate::Store::default(); + let error = actions::set( + &fake, + "camera:test", + &mut invalid_store, + "Default", + Setting::Hdr(false), + ) + .unwrap_err(); + assert!(error + .to_string() + .contains("camera changed but profile could not be saved")); + std::fs::remove_file(path).unwrap(); + std::fs::remove_dir(directory).unwrap(); +} + +#[test] +fn camera_profiles_only_apply_explicit_camera_settings_and_continue_after_failure() { + let fake = Fake { + fail: true, + ..Fake::default() + }; + let mut profile: crate::Profile = serde_json::from_str(r#"{"dpi":[1600,1600]}"#).unwrap(); + assert!(profile.camera.is_none()); + assert!(actions::apply(&fake, "camera:test", &profile).is_empty()); + profile.camera = Some(CameraSettings { + hdr: Some(true), + fov: Some(FieldOfView::Narrow), + ..Default::default() + }); + let results = actions::apply(&fake, "camera:test", &profile); + assert_eq!(results.len(), 2); + assert!(results.iter().all(|r| r.result.is_err())); + assert_eq!( + *fake.writes.lock().unwrap(), + vec![ + Setting::Hdr(true), + Setting::FieldOfView(FieldOfView::Narrow) + ] + ); +} + +#[test] +fn camera_failed_write_and_missing_profile_never_change_saved_values() { + let fake = Fake { + fail: true, + ..Fake::default() + }; + let mut store = crate::Store::default(); + store.for_camera("camera:test").active_mut().camera = Some(CameraSettings { + hdr: Some(false), + ..Default::default() + }); + assert!(actions::set( + &fake, + "camera:test", + &mut store, + "Default", + Setting::Hdr(true) + ) + .is_err()); + assert_eq!( + store + .for_camera("camera:test") + .active() + .camera + .as_ref() + .unwrap() + .hdr, + Some(false) + ); + assert!(actions::set( + &fake, + "camera:test", + &mut store, + "missing", + Setting::Hdr(true) + ) + .is_err()); + assert_eq!(fake.writes.lock().unwrap().len(), 1); +} + +#[test] +fn camera_profile_clone_import_and_identity_are_preserved() { + let mut store = crate::Store::default(); + store.device(0x0e05).active_mut().dpi = Some((100, 100)); + let profiles = store.for_camera("camera:one"); + profiles.active_mut().camera = Some(CameraSettings { + hdr: Some(true), + ..Default::default() + }); + profiles.active_mut().apps = vec!["obs.exe".into()]; + profiles.create("copy").unwrap(); + assert!(profiles.profiles["copy"].apps.is_empty()); + assert_eq!( + profiles.profiles["copy"].camera.as_ref().unwrap().hdr, + Some(true) + ); + assert!(store.for_camera("camera:two").active().camera.is_none()); + assert!(store.devices.contains_key("0E05")); + let json = serde_json::to_string(&store).unwrap(); + let mut imported = crate::Store::default(); + imported.import(serde_json::from_str(&json).unwrap()); + assert_eq!( + imported + .for_camera("camera:one") + .active() + .camera + .as_ref() + .unwrap() + .hdr, + Some(true) + ); +} + +#[test] +fn camera_usb_matching_is_exact_and_identity_keeps_units_apart() { + let path = r"\\?\usb#vid_1532&pid_0e05&mi_00#one"; + assert!(is_kiyo_pro_path(path)); + assert!(is_kiyo_pro_path(&path.to_uppercase())); + for path in [ + "", + "Razer Kiyo Pro", + "vid_1532&pid_0e050", + "vid_15320&pid_0e05", + "vid_9999&pid_0e05", + ] { + assert!(!is_kiyo_pro_path(path), "{path}"); + } + assert_eq!(camera_id(path), camera_id(&path.to_uppercase())); + assert_ne!(camera_id(path), camera_id(&path.replace("one", "two"))); +} + +#[cfg(not(windows))] +#[test] +fn camera_fallback_is_explicitly_windows_only() { + let backend = backend().unwrap(); + assert!(backend.discover().unwrap().is_empty()); + assert!(matches!( + backend.set("camera:test", Setting::Hdr(true)), + Err(crate::Error::Unsupported(_)) + )); +} + +#[test] +fn camera_settings_default_does_not_invent_values() { + let settings = CameraSettings::default(); + assert_eq!(serde_json::to_string(&settings).unwrap(), "{}"); + for (control, value) in [ + ("hdr", "yes"), + ("fov", "90"), + ("af-mode", "auto"), + ("other", "on"), + ] { + assert!(parse_setting(control, value).is_err()); + } + assert_eq!(parse_setting("hdr", "off").unwrap(), Setting::Hdr(false)); +} + +#[test] +fn camera_database_has_no_peripheral_capabilities() { + let db = crate::Db::builtin().unwrap(); + let spec = db.get(0x0e05).expect("Kiyo Pro entry"); + assert_eq!(spec.kind, crate::Kind::Webcam); + assert!(spec.leds.is_empty() && spec.dpi.is_none() && spec.polling.is_none()); +} diff --git a/crates/secbird-core/src/camera/windows.rs b/crates/secbird-core/src/camera/windows.rs new file mode 100644 index 0000000..1d85f82 --- /dev/null +++ b/crates/secbird-core/src/camera/windows.rs @@ -0,0 +1,383 @@ +//! Windows UVC controls through the inbox driver, owned by a single COM thread. +use super::{ + camera_id, + controls::{Control, ControlInfo, ControlState, ControlValue}, + is_kiyo_pro_path, protocol, worker, CameraBackend, CameraInfo, Setting, KIYO_PRO_PID, +}; +use crate::{Error, Result}; +use std::{ + collections::BTreeMap, + mem::size_of, + sync::mpsc::{self, Sender, SyncSender}, + thread, +}; +use windows::{ + core::{w, Interface, BSTR, GUID, PCWSTR}, + Win32::{ + Media::{ + DirectShow::{IBaseFilter, ICreateDevEnum}, + KernelStreaming::*, + }, + System::{ + Com::{StructuredStorage::IPropertyBag, *}, + Variant::VARIANT, + }, + }, +}; + +const DEVICE_ENUM: GUID = GUID::from_u128(0x62be5d10_60eb_11d0_bd3b_00a0c911ce86); +const VIDEO_CATEGORY: GUID = GUID::from_u128(0x860bb310_5d01_11d0_bd3b_00a0c911ce86); +const EXTENSION: GUID = GUID::from_u128(0x23e49ed0_1178_4f31_ae52_d2fb8a8d3b48); + +enum Request { + Discover(Sender>>), + Set(String, Setting, Sender>), + Controls(String, Sender>>), + SetControl(String, Control, ControlValue, Sender>), +} +struct Worker { + sender: Option>, + thread: Option>, +} + +impl CameraBackend for Worker { + fn discover(&self) -> Result> { + worker::call( + self.sender.as_ref().expect("live worker"), + Request::Discover, + ) + } + fn set(&self, id: &str, setting: Setting) -> Result<()> { + worker::call(self.sender.as_ref().expect("live worker"), |reply| { + Request::Set(id.into(), setting, reply) + }) + } + fn controls(&self, id: &str) -> Result> { + worker::call(self.sender.as_ref().expect("live worker"), |reply| { + Request::Controls(id.into(), reply) + }) + } + fn set_control(&self, id: &str, control: Control, value: ControlValue) -> Result { + worker::call(self.sender.as_ref().expect("live worker"), |reply| { + Request::SetControl(id.into(), control, value, reply) + }) + } +} +impl Drop for Worker { + fn drop(&mut self) { + self.sender.take(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +pub(super) fn system(context: &str, error: windows::core::Error) -> Error { + Error::System(format!("camera {context}: {error} (HRESULT {:08X}); check camera access or close other camera apps", error.code().0 as u32)) +} + +pub(super) fn start() -> Result> { + let (sender, receiver) = mpsc::sync_channel(16); + let (ready, initialized) = mpsc::channel(); + let thread = thread::Builder::new() + .name("secbird-camera".into()) + .spawn(move || { + // SAFETY: this new thread owns all COM initialization and objects below. + let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }; + if let Err(error) = initialized { + let _ = ready.send(Err(system("initialize COM", error))); + return; + } + let _ = ready.send(Ok(())); + { + let mut cameras = BTreeMap::::new(); + for request in receiver { + match request { + Request::Discover(reply) => { + cameras.clear(); + let result = enumerate(&mut cameras); + let _ = reply.send(result); + } + Request::Set(id, setting, reply) => { + let result = cameras + .get(&id) + .ok_or_else(|| { + Error::NotFound("camera disconnected; rescan devices".into()) + }) + .and_then(|camera| { + let vendor = camera + .vendor + .as_ref() + .map_err(|error| Error::Unsupported(error.clone()))?; + protocol::send_setting(setting, |payload| vendor.write(payload)) + }); + if let Err(error) = &result { + if let Some(camera) = cameras.get_mut(&id) { + camera.vendor = Err(error.to_string()); + } + } + let _ = reply.send(result); + } + Request::Controls(id, reply) => { + let result = cameras + .get(&id) + .map(|camera| super::windows_controls::list(&camera.filter)) + .ok_or_else(|| { + Error::NotFound("camera disconnected; rescan devices".into()) + }); + let _ = reply.send(result); + } + Request::SetControl(id, control, value, reply) => { + let result = cameras + .get(&id) + .ok_or_else(|| { + Error::NotFound("camera disconnected; rescan devices".into()) + }) + .and_then(|camera| { + super::windows_controls::set(&camera.filter, control, value) + }); + let _ = reply.send(result); + } + } + } + } // Release filters and node interfaces before CoUninitialize. + unsafe { + CoUninitialize(); + } + }) + .map_err(|e| Error::System(format!("start camera worker: {e}")))?; + match initialized.recv() { + Ok(Ok(())) => Ok(Box::new(Worker { + sender: Some(sender), + thread: Some(thread), + })), + other => { + drop(sender); + let _ = thread.join(); + Err(match other { + Ok(Err(error)) => error, + _ => Error::System("camera initialization worker stopped".into()), + }) + } + } +} + +fn property(bag: &IPropertyBag, key: PCWSTR) -> windows::core::Result { + let mut value = VARIANT::default(); + unsafe { + bag.Read(key, &mut value, None)?; + } + Ok(BSTR::try_from(&value)?.to_string()) +} + +fn enumerate(cameras: &mut BTreeMap) -> Result> { + // SAFETY: called only on the initialized worker; all returned objects remain there. + unsafe { + let enumerator: ICreateDevEnum = CoCreateInstance(&DEVICE_ENUM, None, CLSCTX_INPROC_SERVER) + .map_err(|e| system("enumerate video devices", e))?; + let mut monikers = None; + enumerator + .CreateClassEnumerator(&VIDEO_CATEGORY, &mut monikers, 0) + .map_err(|e| system("enumerate video inputs", e))?; + let Some(monikers) = monikers else { + return Ok(Vec::new()); + }; + let mut found = BTreeMap::new(); + loop { + let mut next = [None]; + let status = monikers.Next(&mut next, None); + if status.is_err() { + return Err(system( + "read video input", + windows::core::Error::from_hresult(status), + )); + } + let Some(moniker) = next[0].take() else { + break; + }; + let Ok(bag) = moniker.BindToStorage::<_, _, IPropertyBag>(None, None) else { + continue; + }; + let Ok(path) = property(&bag, w!("DevicePath")) else { + continue; + }; + if !is_kiyo_pro_path(&path) { + continue; + } + let id = camera_id(&path); + if found.contains_key(&id) { + continue; + } + let native = moniker + .BindToObject::<_, _, IBaseFilter>(None, None) + .map_err(|e| system("open Kiyo Pro", e)); + let control_error = match native { + Ok(filter) => { + let vendor = + VendorControl::open(filter.clone()).map_err(|error| error.to_string()); + let error = vendor.as_ref().err().cloned(); + cameras.insert(id.clone(), NativeCamera { filter, vendor }); + error + } + Err(e) => Some(e.to_string()), + }; + found.insert( + id.clone(), + CameraInfo { + id, + pid: KIYO_PRO_PID, + name: "Razer Kiyo Pro".into(), + control_error, + }, + ); + } + Ok(found.into_values().collect()) + } +} + +struct NativeCamera { + filter: IBaseFilter, + vendor: std::result::Result, +} + +struct VendorControl { + control: IKsControl, + node: u32, +} + +fn header(node: u32, flags: u32) -> KSP_NODE { + KSP_NODE { + Property: KSIDENTIFIER { + Anonymous: KSIDENTIFIER_0 { + Anonymous: KSIDENTIFIER_0_0 { + Set: EXTENSION, + Id: 1, + Flags: flags | KSPROPERTY_TYPE_TOPOLOGY, + }, + }, + }, + NodeId: node, + Reserved: 0, + } +} + +fn validate_metadata(access: u32, returned: u32, length: u32) -> Result<()> { + if returned != 4 || access & KSPROPERTY_TYPE_SET == 0 || length != 8 { + return Err(Error::Unsupported("Kiyo Pro extension selector 1 is missing, read-only, or has an unexpected payload size".into())); + } + Ok(()) +} + +impl VendorControl { + fn open(filter: IBaseFilter) -> Result { + unsafe { + let topology: IKsTopologyInfo = filter + .cast() + .map_err(|e| system("query camera topology", e))?; + let count = topology + .NumNodes() + .map_err(|e| system("count camera nodes", e))?; + if count > 256 { + return Err(Error::Unsupported( + "camera returned too many topology nodes".into(), + )); + } + for node in 0..count { + if topology + .get_NodeType(node) + .map_err(|e| system("read node type", e))? + != KSNODETYPE_DEV_SPECIFIC + { + continue; + } + let mut raw = std::ptr::null_mut(); + if topology + .CreateNodeInstance(node, &IKsControl::IID, &mut raw) + .is_err() + || raw.is_null() + { + continue; + } + let control = IKsControl::from_raw(raw); + let camera = Self { control, node }; + if camera.validate().is_ok() { + return Ok(camera); + } + } + } + Err(Error::Unsupported( + "Kiyo Pro UVC extension controls unavailable; check camera permissions, then rescan" + .into(), + )) + } + + fn validate(&self) -> Result<()> { + let mut access = 0u32; + let mut returned = 0; + self.query( + KSPROPERTY_TYPE_BASICSUPPORT, + (&mut access as *mut u32).cast(), + 4, + &mut returned, + ) + .map_err(|e| system("query extension support", e))?; + let mut length = 0; + // A zero-length GET queries required size, following Microsoft's UVC sample. + let size = self.query(KSPROPERTY_TYPE_GET, std::ptr::null_mut(), 0, &mut length); + match size { + Ok(()) => {} + Err(error) if error.code().0 as u32 == 0x800700ea => {} // ERROR_MORE_DATA + Err(error) => return Err(system("query extension length", error)), + } + validate_metadata(access, returned, length) + } + + fn query( + &self, + flags: u32, + data: *mut std::ffi::c_void, + size: u32, + returned: &mut u32, + ) -> windows::core::Result<()> { + let property = header(self.node, flags); + // SAFETY: property and data live through this synchronous call. Caller supplies + // a buffer of size bytes (or null for the documented size query). + unsafe { + self.control.KsProperty( + &property.Property, + size_of::() as u32, + data, + size, + returned, + ) + } + } + + fn write(&self, payload: &[u8; 8]) -> Result<()> { + let mut data = *payload; + let mut returned = 0; + self.query( + KSPROPERTY_TYPE_SET, + data.as_mut_ptr().cast(), + 8, + &mut returned, + ) + .map_err(|e| system("write extension control", e)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn camera_rejects_malformed_or_readonly_metadata() { + assert!(validate_metadata(KSPROPERTY_TYPE_SET, 4, 8).is_ok()); + for (access, bytes, size) in [ + (0, 4, 8), + (KSPROPERTY_TYPE_SET, 0, 8), + (KSPROPERTY_TYPE_SET, 4, 9), + ] { + assert!(validate_metadata(access, bytes, size).is_err()); + } + } +} diff --git a/crates/secbird-core/src/camera/windows_controls.rs b/crates/secbird-core/src/camera/windows_controls.rs new file mode 100644 index 0000000..58c79bb --- /dev/null +++ b/crates/secbird-core/src/camera/windows_controls.rs @@ -0,0 +1,321 @@ +//! Standard controls through the inbox DirectShow camera interfaces. Power-line +//! frequency and low-light exposure priority use their KS properties instead. +use super::{ + controls::{ + validate_prerequisite, Control, ControlInfo, ControlRange, ControlState, ControlValue, + }, + windows::system, +}; +use crate::{Error, Result}; +use std::mem::{offset_of, size_of}; +use windows::{ + core::Interface, + Win32::Media::{ + DirectShow::{IAMCameraControl, IAMVideoProcAmp, IBaseFilter}, + KernelStreaming::*, + }, +}; + +fn location(control: Control) -> (bool, i32) { + match control { + Control::Brightness => (false, 0), + Control::Contrast => (false, 1), + Control::Hue => (false, 2), + Control::Saturation => (false, 3), + Control::Sharpness => (false, 4), + Control::Gamma => (false, 5), + Control::ColorEnable => (false, 6), + Control::WhiteBalance => (false, 7), + Control::BacklightCompensation => (false, 8), + Control::Gain => (false, 9), + Control::PowerlineFrequency => (false, 13), + Control::Pan => (true, 0), + Control::Tilt => (true, 1), + Control::Roll => (true, 2), + Control::Zoom => (true, 3), + Control::Exposure => (true, 4), + Control::Iris => (true, 5), + Control::Focus => (true, 6), + Control::LowLightCompensation => (true, 19), + } +} +fn ks_only(control: Control) -> bool { + matches!( + control, + Control::PowerlineFrequency | Control::LowLightCompensation + ) +} + +fn ks_property(control: Control, flags: u32) -> KSIDENTIFIER { + let (camera, id) = location(control); + KSIDENTIFIER { + Anonymous: KSIDENTIFIER_0 { + Anonymous: KSIDENTIFIER_0_0 { + Set: if camera { + PROPSETID_VIDCAP_CAMERACONTROL + } else { + PROPSETID_VIDCAP_VIDEOPROCAMP + }, + Id: id as u32, + Flags: flags, + }, + }, + } +} +fn support(filter: &IBaseFilter, control: Control) -> Result { + let ks: IKsControl = filter + .cast() + .map_err(|error| system("query camera KS interface", error))?; + let property = ks_property(control, KSPROPERTY_TYPE_BASICSUPPORT); + let mut flags = 0u32; + let mut returned = 0u32; + // SAFETY: initialized property and output buffers remain live for the COM call. + unsafe { + ks.KsProperty( + &property, + size_of::() as u32, + (&mut flags as *mut u32).cast(), + 4, + &mut returned, + ) + } + .map_err(|error| system(&format!("query {} support", control.name()), error))?; + if returned < 4 { + return Err(Error::Unsupported(format!( + "{} support reply is truncated", + control.name() + ))); + } + Ok(flags & KSPROPERTY_TYPE_SET != 0 && flags & KSPROPERTY_TYPE_GET != 0) +} + +fn ks_state( + filter: &IBaseFilter, + control: Control, + requested: Option, +) -> Result { + let ks: IKsControl = filter + .cast() + .map_err(|error| system("query camera KS interface", error))?; + let mut property = KSPROPERTY_CAMERACONTROL_S { + Property: ks_property( + control, + if requested.is_some() { + KSPROPERTY_TYPE_SET + } else { + KSPROPERTY_TYPE_GET + }, + ), + Value: requested.map_or(0, |state| state.value), + Flags: 0, + Capabilities: 0, + }; + let mut result = property; + let mut returned = 0; + // SAFETY: synchronous property call with valid initialized buffers; these enum + // controls encode Auto as a numeric value (frequency=3), not an Auto flag. + unsafe { + ks.KsProperty( + (&mut property as *mut KSPROPERTY_CAMERACONTROL_S).cast(), + size_of::() as u32, + (&mut result as *mut KSPROPERTY_CAMERACONTROL_S).cast(), + size_of::() as u32, + &mut returned, + ) + } + .map_err(|error| { + system( + &format!( + "{} {}", + if requested.is_some() { "write" } else { "read" }, + control.name() + ), + error, + ) + })?; + if requested.is_none() + && returned < (offset_of!(KSPROPERTY_CAMERACONTROL_S, Value) + size_of::()) as u32 + { + return Err(Error::Unsupported( + "camera KS value reply is truncated".into(), + )); + } + Ok(requested.unwrap_or(ControlState { + value: result.Value, + automatic: false, + })) +} + +fn range(filter: &IBaseFilter, control: Control) -> Result { + if ks_only(control) { + if !support(filter, control)? { + return Err(Error::Unsupported(format!( + "{} is not readable/writable", + control.name() + ))); + } + let current = ks_state(filter, control, None)?.value; + // These two controls have fixed values in the Windows UVC specification; + // don't assume optional frequency Auto(3) unless the driver reports it. + let choices = if control == Control::LowLightCompensation { + vec![0, 1] + } else if current == 3 { + vec![0, 1, 2, 3] + } else { + vec![0, 1, 2] + }; + let max = *choices.last().expect("fixed control choices"); + let range = ControlRange { + min: 0, + max, + step: 1, + default: (control == Control::LowLightCompensation).then_some(0), + automatic: false, + manual: true, + choices, + }; + range.validate()?; + return Ok(range); + } + let (camera, id) = location(control); + let (mut min, mut max, mut step, mut default, mut flags) = (0, 0, 0, 0, 0); + // SAFETY: native interfaces and output scalars stay on the initialized worker. + unsafe { + if camera { + filter.cast::().and_then(|api| { + api.GetRange(id, &mut min, &mut max, &mut step, &mut default, &mut flags) + }) + } else { + filter.cast::().and_then(|api| { + api.GetRange(id, &mut min, &mut max, &mut step, &mut default, &mut flags) + }) + } + } + .map_err(|error| system(&format!("query {} range", control.name()), error))?; + let range = ControlRange { + min, + max, + step, + default: Some(default), + automatic: flags & 1 != 0, + manual: flags & 2 != 0, + choices: Vec::new(), + }; + range.validate()?; + Ok(range) +} + +fn read(filter: &IBaseFilter, control: Control) -> Result { + if ks_only(control) { + return ks_state(filter, control, None); + } + let (camera, id) = location(control); + let (mut value, mut flags) = (0, 0); + unsafe { + if camera { + filter + .cast::() + .and_then(|api| api.Get(id, &mut value, &mut flags)) + } else { + filter + .cast::() + .and_then(|api| api.Get(id, &mut value, &mut flags)) + } + } + .map_err(|error| system(&format!("read {}", control.name()), error))?; + if flags & 3 != 1 && flags & 3 != 2 { + return Err(Error::Unsupported( + "camera reported an unknown Auto/manual state".into(), + )); + } + Ok(ControlState { + value, + automatic: flags & 1 != 0, + }) +} + +pub(super) fn list(filter: &IBaseFilter) -> Vec { + Control::ALL + .into_iter() + .map(|control| match range(filter, control) { + Err(error) => ControlInfo::new(control, None, None, Some(error.to_string())), + Ok(range) => match read(filter, control) { + Ok(value) => ControlInfo::new(control, Some(range), Some(value), None), + Err(error) => ControlInfo::new(control, Some(range), None, Some(error.to_string())), + }, + }) + .collect() +} +pub(super) fn set( + filter: &IBaseFilter, + control: Control, + value: ControlValue, +) -> Result { + let range = range(filter, control)?; + let current = read(filter, control).ok(); + let requested = range.resolve(value, current)?; + if current == Some(requested) { + return Ok(requested); + } + let related = match control { + Control::LowLightCompensation => read(filter, Control::Exposure) + .ok() + .map(|state| i32::from(state.automatic)), + Control::Exposure => read(filter, Control::LowLightCompensation) + .ok() + .map(|state| state.value), + _ => None, + }; + validate_prerequisite(control, requested, related)?; + if ks_only(control) { + ks_state(filter, control, Some(requested))?; + } else { + let (camera, id) = location(control); + let flags = if requested.automatic { 1 } else { 2 }; + unsafe { + if camera { + filter + .cast::() + .and_then(|api| api.Set(id, requested.value, flags)) + } else { + filter + .cast::() + .and_then(|api| api.Set(id, requested.value, flags)) + } + } + .map_err(|error| system(&format!("write {}", control.name()), error))?; + } + let state = read(filter, control).map_err(|error| { + Error::System(format!( + "{} may have changed but readback failed: {error}", + control.name() + )) + })?; + if state.automatic != requested.automatic + || (!state.automatic && state.value != requested.value) + { + return Err(Error::System(format!( + "{} may have changed but readback differs", + control.name() + ))); + } + Ok(state) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn native_standard_camera_ids_match_windows_sdk() { + assert_eq!(location(Control::Focus), (true, 6)); + assert_eq!( + location(Control::PowerlineFrequency), + (false, KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY.0) + ); + assert_eq!( + location(Control::LowLightCompensation), + (true, KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY.0) + ); + assert_eq!(size_of::(), 36); + } +} diff --git a/crates/secbird-core/src/camera/worker.rs b/crates/secbird-core/src/camera/worker.rs new file mode 100644 index 0000000..3dfd977 --- /dev/null +++ b/crates/secbird-core/src/camera/worker.rs @@ -0,0 +1,46 @@ +//! Plain-value request boundary; no COM objects cross threads. +use crate::{Error, Result}; +use std::sync::mpsc::{self, Sender, SyncSender, TrySendError}; + +pub(super) fn call( + sender: &SyncSender, + make: impl FnOnce(Sender>) -> R, +) -> Result { + let (reply, receive) = mpsc::channel(); + sender.try_send(make(reply)).map_err(|error| match error { + TrySendError::Full(_) => Error::System("camera worker busy; try again".into()), + TrySendError::Disconnected(_) => Error::System("camera worker disconnected".into()), + })?; + receive + .recv() + .map_err(|_| Error::System("camera worker stopped before replying".into()))? +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn camera_worker_handles_closed_full_and_lost_reply() { + let (tx, rx) = mpsc::sync_channel::>>(1); + tx.send(mpsc::channel().0).unwrap(); + assert!(call(&tx, |reply| reply) + .unwrap_err() + .to_string() + .contains("busy")); + drop(rx); + assert!(call(&tx, |reply| reply) + .unwrap_err() + .to_string() + .contains("disconnected")); + let (tx, rx) = mpsc::sync_channel::>>(1); + let thread = std::thread::spawn(move || { + drop(rx.recv().unwrap()); + }); + assert!(call(&tx, |reply| reply) + .unwrap_err() + .to_string() + .contains("replying")); + thread.join().unwrap(); + } +} diff --git a/crates/secbird-core/src/db.rs b/crates/secbird-core/src/db.rs index afd0af7..12a93d0 100644 --- a/crates/secbird-core/src/db.rs +++ b/crates/secbird-core/src/db.rs @@ -22,6 +22,7 @@ pub enum Kind { Keypad, Laptop, Accessory, + Webcam, } /// Which lighting command set a device speaks. diff --git a/crates/secbird-core/src/device.rs b/crates/secbird-core/src/device.rs index 1058113..1e19fd1 100644 --- a/crates/secbird-core/src/device.rs +++ b/crates/secbird-core/src/device.rs @@ -266,6 +266,7 @@ fn discover_hid(api: &HidApi, db: &Db) -> Vec { pids.dedup(); pids.into_iter() + .filter(|pid| !db.get(*pid).is_some_and(|spec| spec.kind == Kind::Webcam)) .filter_map(|pid| -> Option> { let spec = db.spec(pid); let mut ifaces: Vec<&Candidate> = all.iter().filter(|c| c.pid == pid).collect(); diff --git a/crates/secbird-core/src/lib.rs b/crates/secbird-core/src/lib.rs index de0b79b..059620f 100644 --- a/crates/secbird-core/src/lib.rs +++ b/crates/secbird-core/src/lib.rs @@ -11,6 +11,7 @@ pub mod actions; pub mod buttons; +pub mod camera; pub mod commands; #[cfg(windows)] pub mod debloat; diff --git a/crates/secbird-core/src/profile.rs b/crates/secbird-core/src/profile.rs index cdb0e2c..d7cc9f2 100644 --- a/crates/secbird-core/src/profile.rs +++ b/crates/secbird-core/src/profile.rs @@ -27,6 +27,9 @@ pub struct Zone { #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct Profile { + /// UVC controls; absent fields leave the camera unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub camera: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub dpi: Option<(u16, u16)>, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -372,6 +375,10 @@ impl Store { self.profiles_for(&dev.key(), dev.pid) } + pub fn for_camera(&mut self, id: &str) -> &mut DeviceProfiles { + self.devices.entry(id.to_owned()).or_default() + } + pub fn device(&mut self, pid: u16) -> &mut DeviceProfiles { self.devices.entry(format!("{pid:04X}")).or_default() } diff --git a/crates/secbird-core/src/report.rs b/crates/secbird-core/src/report.rs index 49d9837..9358a2f 100644 --- a/crates/secbird-core/src/report.rs +++ b/crates/secbird-core/src/report.rs @@ -65,6 +65,15 @@ pub struct Report { pub os: String, pub interfaces: Vec, pub devices: Vec, + pub cameras: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct CameraReport { + pub id: String, + pub name: String, + pub pid: String, + pub error: Option, } /// Read-only GETs: (name, command, size, args). @@ -157,6 +166,7 @@ pub fn build(api: &HidApi, db: &Db) -> Report { for info in infos { let pid = info.product_id(); + if db.get(pid).is_some_and(|spec| spec.kind == crate::Kind::Webcam) { continue; } let features = crate::transport::feature_reports(api, info.path()); let dev = crate::device::open_interface(api, info.path(), pid, info.interface_number(), &TXID_CANDIDATES, db.spec(pid)); interfaces.push(Interface { @@ -182,6 +192,13 @@ pub fn build(api: &HidApi, db: &Db) -> Report { os: format!("{} {}", std::env::consts::OS, std::env::consts::ARCH), interfaces, devices, + cameras: match crate::camera::backend().and_then(|backend| backend.discover()) { + Ok(cameras) => cameras.into_iter().enumerate().map(|(index, camera)| CameraReport { + id: format!("camera-{}", index + 1), name: camera.name, + pid: format!("{:04X}", camera.pid), error: camera.control_error, + }).collect(), + Err(error) => vec![CameraReport { id: "camera-backend".into(), name: "Camera discovery".into(), pid: String::new(), error: Some(error.to_string()) }], + }, } } @@ -312,6 +329,10 @@ impl std::fmt::Display for Report { if self.devices.is_empty() { writeln!(f, "\nNo interface answered Protocol 2.5.")?; } + for camera in &self.cameras { + writeln!(f, "\nCamera {} {} ({})", camera.pid, camera.name, camera.id)?; + writeln!(f, " {}", camera.error.as_deref().unwrap_or("UVC controls available; current settings not read back"))?; + } Ok(()) } } diff --git a/crates/secbird-tray/src/camera-controls.js b/crates/secbird-tray/src/camera-controls.js new file mode 100644 index 0000000..1683f20 --- /dev/null +++ b/crates/secbird-tray/src/camera-controls.js @@ -0,0 +1,25 @@ +(function(root){ + 'use strict'; + function accepts(range,value){return !!range&&Number.isInteger(value)&&range.step>0&&value>=range.min&&value<=range.max + &&(value-range.min)%range.step===0&&(!range.choices?.length||range.choices.includes(value));} + function model(info,all){ + let disabled=!info?.range?info?.error||'Not supported by this driver':null; + const lowLight=all.find(item=>item.control==='low-light-compensation')?.current?.value===1; + return {disabled,manualDisabled:!!disabled||!info?.range?.manual||info?.current?.automatic===true + || (info?.control==='exposure'&&lowLight), + autoDisabled:!!disabled||!info?.range?.automatic,defaultDisabled:!!disabled||info?.range?.default==null, + prerequisite:info?.control==='exposure'&&lowLight?'Turn off low-light compensation before switching Exposure to Manual.':null}; + } + function manualValue(info,text){ + if(typeof text!=='string'||!text.trim()||!accepts(info.range,Number(text)))throw new Error('Value must match the driver range and step.'); + return String(Number(text)); + } + function options(info,all=[]){ + const choices=info.kind==='frequency'?[[0,'Off'],[1,'50 Hz'],[2,'60 Hz'],[3,'Auto']]:[[0,'Off'],[1,'On']]; + return choices.filter(([value])=>accepts(info.range,value) + && !(value===1&&info.control==='low-light-compensation'&&!all.find(item=>item.control==='exposure')?.current?.automatic)) + .map(([value,label])=>({value,label})); + } + const api={model,manualValue,options}; + if(typeof module!=='undefined'&&module.exports)module.exports=api;else root.SecbirdControls=api; +})(globalThis); diff --git a/crates/secbird-tray/src/camera-controls.test.cjs b/crates/secbird-tray/src/camera-controls.test.cjs new file mode 100644 index 0000000..04fa6a7 --- /dev/null +++ b/crates/secbird-tray/src/camera-controls.test.cjs @@ -0,0 +1,34 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const {model,manualValue,options} = require('./camera-controls.js'); +const info = () => ({control:'exposure',kind:'range',range:{min:-12,max:-2,step:2,default:-6,automatic:true,manual:true,choices:[]},current:{value:-6,automatic:true}}); +test('auto prevents manual entry but can be switched off',()=>{ + assert.equal(model(info(),[info()]).manualDisabled,true); + assert.equal(model({...info(),current:{value:-6,automatic:false}},[info()]).manualDisabled,false); +}); +test('manual input respects signed range and step',()=>{ + assert.equal(manualValue(info(),'-6'),'-6'); + for(const input of ['',' ','-5','-13','NaN'])assert.throws(()=>manualValue(info(),input)); +}); +test('unsupported and low-light controls require support and Auto exposure',()=>{ + assert.match(model({...info(),range:null,error:'unsupported'},[]).disabled,/unsupported/); + const item={...info(),control:'low-light-compensation',kind:'toggle',range:{min:0,max:1,step:1,choices:[],manual:true}}; + assert.deepEqual(options(item,[{...info(),current:{value:-6,automatic:false}}]).map(choice=>choice.value),[0]); +}); +test('anti-flicker choices do not invent Auto support',()=>{ + const f={...info(),kind:'frequency',range:{min:0,max:2,step:1,manual:true,choices:[]}}; + assert.deepEqual(options(f).map(choice=>choice.value),[0,1,2]); +}); +test('low-light can always be turned off even if exposure is manual',()=>{ + const item={...info(),control:'low-light-compensation',kind:'toggle',range:{min:0,max:1,step:1,default:0,manual:true,choices:[]},current:{value:1,automatic:false}}; + const exposure={...info(),current:{value:-6,automatic:false}}; + assert.equal(model(item,[exposure]).manualDisabled,false); + assert.deepEqual(options(item, [exposure]).map(choice=>choice.value),[0]); +}); +test('manual exposure stays disabled until active low-light compensation is off',()=>{ + const exp=info(), low={...info(),control:'low-light-compensation',kind:'toggle',current:{value:1,automatic:false},range:{min:0,max:1,step:1,manual:true,choices:[]}}; + assert.equal(model(exp,[exp,low]).manualDisabled,true); + assert.match(model(exp,[exp,low]).prerequisite,/Turn off low-light/); + assert.equal(model({...exp,current:{value:-6,automatic:true}},[exp,low]).autoDisabled,false); + assert.equal(model({...exp,current:{value:-6,automatic:false}},[exp,{...low,current:{value:0,automatic:false}}]).manualDisabled,false); +}); diff --git a/crates/secbird-tray/src/camera-preview.js b/crates/secbird-tray/src/camera-preview.js new file mode 100644 index 0000000..3dafae0 --- /dev/null +++ b/crates/secbird-tray/src/camera-preview.js @@ -0,0 +1,126 @@ +// Browser-owned capture: no frame copies, recording, microphone, or server stream. +(function (root) { + 'use strict'; + const presets = [[1920, 1080, 60], [1920, 1080, 30], [1280, 720, 60], [1280, 720, 30], [640, 480, 30], [640, 480, 15]]; + function exactConstraints(deviceId, format) { + if (typeof deviceId !== 'string' || !deviceId) throw new Error('Select a preview camera first.'); + const video = {deviceId: {exact: deviceId}}; + if (format) { + if (!Number.isInteger(format.width) || format.width <= 0 || !Number.isInteger(format.height) || format.height <= 0 || !Number.isFinite(format.frameRate) || format.frameRate <= 0) { + throw new Error('Preview requires positive whole-pixel dimensions and a finite positive FPS.'); + } + for (const key of ['width', 'height', 'frameRate']) video[key] = {exact: format[key]}; + } + return {audio: false, video}; + } + function candidateFormats(capabilities = {}) { + return presets.map(([width, height, frameRate]) => ({width, height, frameRate})).filter(format => + Object.entries(format).every(([key, value]) => { + const range = capabilities[key]; + return !range || (value >= range.min && value <= range.max); + })); + } + const release = stream => stream?.getTracks().forEach(track => track.stop()); + const actualOf = track => { + const {width, height, frameRate} = track.getSettings(); + return {width, height, frameRate}; + }; + const matches = (wanted, actual) => !wanted || (wanted.width === actual.width && wanted.height === actual.height && Math.abs(wanted.frameRate - actual.frameRate) < 0.1); + const explain = error => ({ + NotAllowedError: 'Camera permission denied. Allow camera access in your browser and Windows privacy settings.', + NotReadableError: 'Camera is busy or inaccessible. Stop preview in OBS, Teams, or other camera apps and try again.', + NotFoundError: 'Selected camera is unavailable. Refresh sources and select it again.', + }[error.name] || error.message || 'Camera preview failed.'); + + function createPreview({mediaDevices, video, onState = () => {}}) { + let generation = 0, stream = null, state = 'stopped', actual = null, error = null, sourceId = null, formatBusy = false; + const snapshot = () => ({state, actual: actual && {...actual}, error}); + const publish = () => onState(snapshot()); + const requireMedia = () => { + if (!mediaDevices?.getUserMedia || !mediaDevices?.enumerateDevices) throw new Error('This browser does not provide camera access. Open the local editor in a current browser.'); + }; + function stop() { + generation++; + const previous = stream; + stream = null; sourceId = null; actual = null; state = 'stopped'; error = null; formatBusy = false; + video.srcObject = null; + release(previous); + publish(); + } + function failed(cause) { + stop(); state = 'error'; error = explain(cause); publish(); + } + async function sources(requestPermission = false) { + requireMedia(); + if (requestPermission) { + const temporary = await mediaDevices.getUserMedia({audio: false, video: true}); + release(temporary); + } + return (await mediaDevices.enumerateDevices()).filter(device => device.kind === 'videoinput') + .map(({deviceId, label}) => ({deviceId, label})); + } + async function start(deviceId, format = null) { + stop(); + const epoch = generation; + let acquired = null; + try { + requireMedia(); + const constraints = exactConstraints(deviceId, format); + state = 'starting'; publish(); + acquired = await mediaDevices.getUserMedia(constraints); + if (epoch !== generation) { release(acquired); return; } + const track = acquired.getVideoTracks()[0]; + if (!track || acquired.getAudioTracks().length || track.getSettings().deviceId !== deviceId) throw new Error('The browser returned a different preview source. Select the intended camera explicitly.'); + const negotiated = actualOf(track); + if (!matches(format, negotiated)) throw new Error('The requested preview format was not negotiated. Try a different combination.'); + stream = acquired; sourceId = deviceId; actual = negotiated; + track.addEventListener('ended', () => { + if (stream === acquired) failed(new Error('Camera preview ended or disconnected. Restart it explicitly when ready.')); + }); + video.srcObject = stream; + await video.play(); + if (epoch !== generation) { release(acquired); return; } + state = 'playing'; publish(); + } catch (cause) { + release(acquired); + if (epoch !== generation) return; + failed(cause); throw cause; + } + } + async function setFormat(format) { + if (!stream || state !== 'playing') throw new Error('Start preview before changing its format.'); + if (formatBusy) throw new Error('A preview format change is already in progress.'); + const wanted = exactConstraints(sourceId, format).video; + const epoch = generation, track = stream.getVideoTracks()[0], previous = actualOf(track); + const restore = exactConstraints(sourceId, previous).video; + formatBusy = true; + try { + await track.applyConstraints(wanted); + if (epoch !== generation) return; + const negotiated = actualOf(track); + if (!matches(format, negotiated)) throw new Error('Requested preview format was not negotiated.'); + actual = negotiated; error = null; publish(); + } catch (cause) { + if (epoch !== generation) return; + try { + await track.applyConstraints(restore); + if (epoch !== generation) return; + if (!matches(previous, actualOf(track))) throw new Error('Previous preview format could not be restored.'); + actual = actualOf(track); error = explain(cause); publish(); + } catch (restoreError) { + if (epoch === generation) failed(restoreError); + } + throw cause; + } finally { if (epoch === generation) formatBusy = false; } + } + function refresh() { + if (!stream) return; + actual = actualOf(stream.getVideoTracks()[0]); publish(); + } + const formats = () => candidateFormats(stream?.getVideoTracks()[0]?.getCapabilities?.() || {}); + return {sources, start, setFormat, stop, snapshot, refresh, formats}; + } + const api = {createPreview, exactConstraints, candidateFormats}; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + else root.SecbirdPreview = api; +})(globalThis); diff --git a/crates/secbird-tray/src/camera-preview.test.cjs b/crates/secbird-tray/src/camera-preview.test.cjs new file mode 100644 index 0000000..fc9caf5 --- /dev/null +++ b/crates/secbird-tray/src/camera-preview.test.cjs @@ -0,0 +1,146 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const {createPreview, exactConstraints, candidateFormats} = require('./camera-preview.js'); + +function stream(id = 'camera-a') { + let settings = {deviceId: id, width: 1920, height: 1080, frameRate: 30}; + const listeners = {}; + const track = { + stopped: false, reject: false, + stop() { this.stopped = true; }, + getSettings() { return {...settings}; }, + getConstraints() { return {deviceId: {exact: id}}; }, + getCapabilities() { return {width: {min: 640, max: 1920}, height: {min: 480, max: 1080}, frameRate: {min: 15, max: 60}}; }, + addEventListener(name, callback) { listeners[name] = callback; }, + end() { listeners.ended?.(); }, + async applyConstraints(constraints) { + if (this.reject && constraints.frameRate?.exact === 60) throw Object.assign(new Error('Unsupported combination'), {name: 'OverconstrainedError'}); + for (const key of ['width', 'height', 'frameRate']) if (constraints[key]?.exact) settings[key] = constraints[key].exact; + }, + }; + return {track, getTracks: () => [track], getVideoTracks: () => [track], getAudioTracks: () => []}; +} +function fixture(getUserMedia = async () => stream()) { + const calls = []; + const video = {srcObject: null, play: async () => {}}; + const mediaDevices = { + getUserMedia: constraints => { calls.push(constraints); return getUserMedia(constraints); }, + enumerateDevices: async () => [{kind: 'videoinput', deviceId: 'camera-a', label: 'Kiyo Pro'}, {kind: 'audioinput', deviceId: 'mic', label: 'Microphone'}], + }; + const preview = createPreview({mediaDevices, video, onState() {}}); + return {preview, calls, video}; +} +const deferred = () => { let resolve; const promise = new Promise(r => resolve = r); return {promise, resolve}; }; + +test('constructing or listing sources never starts capture', async () => { + const {preview, calls} = fixture(); + assert.equal(preview.snapshot().state, 'stopped'); + assert.deepEqual(await preview.sources(), [{deviceId: 'camera-a', label: 'Kiyo Pro'}]); + assert.equal(calls.length, 0); +}); +test('exact video-only constraints reject invalid inputs', () => { + assert.deepEqual(exactConstraints('camera-a', {width: 1920, height: 1080, frameRate: 30}), { + audio: false, video: {deviceId: {exact: 'camera-a'}, width: {exact: 1920}, height: {exact: 1080}, frameRate: {exact: 30}}, + }); + for (const format of [{width: 0, height: 1080, frameRate: 30}, {width: 640.5, height: 480, frameRate: 30}, {width: 640, height: 480, frameRate: Infinity}]) { + assert.throws(() => exactConstraints('camera-a', format)); + } + assert.throws(() => exactConstraints('', null)); +}); +test('stop during pending permission stops late-arriving tracks', async () => { + const pending = deferred(), source = stream(); + const {preview, video} = fixture(() => pending.promise); + const start = preview.start('camera-a', null); + preview.stop(); + pending.resolve(source); + await start; + assert.equal(source.track.stopped, true); + assert.equal(video.srcObject, null); + assert.equal(preview.snapshot().state, 'stopped'); +}); +test('newer start wins and superseded source is released', async () => { + const first = deferred(), old = stream('camera-a'), current = stream('camera-b'); + const {preview, video} = fixture(c => c.video.deviceId.exact === 'camera-a' ? first.promise : Promise.resolve(current)); + const start = preview.start('camera-a', null); + await preview.start('camera-b', null); + first.resolve(old); + await start; + assert.equal(old.track.stopped, true); + assert.equal(video.srcObject, current); +}); +test('wrong returned source is rejected and released', async () => { + const source = stream('other'); + const {preview, video} = fixture(async () => source); + await assert.rejects(preview.start('camera-a', null)); + assert.equal(source.track.stopped, true); + assert.equal(video.srcObject, null); +}); +test('permission failures and missing API are visible', async () => { + const {preview} = fixture(async () => { throw Object.assign(new Error('Denied'), {name: 'NotAllowedError'}); }); + await assert.rejects(preview.start('camera-a', null)); + assert.equal(preview.snapshot().state, 'error'); + const missing = createPreview({video: {srcObject: null}, onState() {}}); + await assert.rejects(missing.start('camera-a', null)); +}); +test('ended track releases capture without restarting', async () => { + const source = stream(), {preview, calls, video} = fixture(async () => source); + await preview.start('camera-a', null); + source.track.end(); + assert.equal(source.track.stopped, true); + assert.equal(video.srcObject, null); + assert.equal(calls.length, 1); + assert.equal(preview.snapshot().state, 'error'); +}); +test('actual format comes from negotiated track settings', async () => { + const {preview} = fixture(); + await preview.start('camera-a', null); + assert.deepEqual(preview.snapshot().actual, {width: 1920, height: 1080, frameRate: 30}); + await preview.setFormat({width: 1280, height: 720, frameRate: 60}); + assert.deepEqual(preview.snapshot().actual, {width: 1280, height: 720, frameRate: 60}); +}); +test('unsupported combination restores previous format without claiming success', async () => { + const source = stream(), {preview} = fixture(async () => source); + source.track.reject = true; + await preview.start('camera-a', null); + await assert.rejects(preview.setFormat({width: 1920, height: 1080, frameRate: 60})); + assert.equal(preview.snapshot().state, 'playing'); + assert.equal(preview.snapshot().actual.frameRate, 30); + assert.match(preview.snapshot().error, /Unsupported/); +}); +test('capability ranges filter candidate tuples, not manufacture supported combinations', () => { + const formats = candidateFormats({width: {min: 640, max: 1280}, height: {min: 480, max: 720}, frameRate: {min: 15, max: 30}}); + assert.ok(formats.length > 0); + assert.ok(formats.every(f => f.width <= 1280 && f.height <= 720 && f.frameRate <= 30)); +}); +test('permission source discovery releases temporary capture', async () => { + const source = stream(), {preview, video, calls} = fixture(async () => source); + await preview.sources(true); + assert.equal(source.track.stopped, true); + assert.equal(video.srcObject, null); + assert.equal(calls[0].audio, false); +}); +test('failed restoration releases capture and requires explicit restart', async () => { + const source = stream(), {preview, video, calls} = fixture(async () => source); + await preview.start('camera-a', null); + source.track.applyConstraints = async () => { throw new Error('Driver lost capture'); }; + await assert.rejects(preview.setFormat({width: 1280, height: 720, frameRate: 60})); + assert.equal(source.track.stopped, true); + assert.equal(video.srcObject, null); + assert.equal(preview.snapshot().state, 'error'); + assert.equal(calls.length, 1); +}); +test('a track that silently negotiates another format is not labeled successful', async () => { + const source = stream(), {preview} = fixture(async () => source); + await preview.start('camera-a', null); + source.track.applyConstraints = async () => {}; + await assert.rejects(preview.setFormat({width: 1280, height: 720, frameRate: 60})); + assert.equal(preview.snapshot().actual.frameRate, 30); + assert.match(preview.snapshot().error, /not negotiated/); +}); +test('unexpected microphone tracks are rejected and stopped', async () => { + const source = stream(); + source.getAudioTracks = () => [source.track]; + const {preview} = fixture(async () => source); + await assert.rejects(preview.start('camera-a', null)); + assert.equal(source.track.stopped, true); +}); diff --git a/crates/secbird-tray/src/camera.rs b/crates/secbird-tray/src/camera.rs new file mode 100644 index 0000000..ab192b4 --- /dev/null +++ b/crates/secbird-tray/src/camera.rs @@ -0,0 +1,368 @@ +//! Camera editor schema and dispatch; standard controls have native readbacks. +use secbird_core::{ + camera::{ + actions, + controls::{parse_control, Control as StandardControl}, + parse_setting, CameraBackend, CameraInfo, + }, + Error, Result, Store, +}; +use serde::Deserialize; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Control { + id: String, + control: String, + value: String, + #[serde(default)] + profile: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ReadControls { + id: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ProfileRequest { + id: String, + action: String, + name: String, + #[serde(default)] + apps: Vec, +} + +pub(crate) fn device_json( + camera: &CameraInfo, + store: &mut Store, + foreground: Option<&str>, +) -> Value { + let profiles = store.for_camera(&camera.id); + let active = profiles.effective(foreground); + json!({ + "id": camera.id, "pid": format!("{:04X}", camera.pid), "name": camera.name, + "kind": "webcam", "known": true, "leds": [], "macros": false, "lighting_control": false, + "profiles": profiles.profiles.keys().collect::>(), "active": active, + "manual_active": profiles.active, "profile": profiles.profiles.get(active), + "profilesData": profiles.profiles, "camera": { "state": "saved", "error": camera.control_error }, + }) +} + +pub(crate) fn label(camera: &CameraInfo, cameras: &[CameraInfo]) -> String { + if cameras + .iter() + .filter(|other| other.pid == camera.pid) + .count() + > 1 + { + let index = cameras + .iter() + .position(|other| other.id == camera.id) + .unwrap_or(0) + + 1; + format!("{} ({index})", camera.name) + } else { + camera.name.clone() + } +} + +fn labeled_device_json( + camera: &CameraInfo, + cameras: &[CameraInfo], + store: &mut Store, + foreground: Option<&str>, +) -> Value { + let mut value = device_json(camera, store, foreground); + value["label"] = label(camera, cameras).into(); + value +} + +pub(crate) fn device_list_json( + cameras: &[CameraInfo], + store: &mut Store, + foreground: Option<&str>, +) -> Vec { + cameras + .iter() + .map(|camera| labeled_device_json(camera, cameras, store, foreground)) + .collect() +} + +fn dispatch( + backend: &dyn CameraBackend, + cameras: &[CameraInfo], + foreground: Option<&str>, + path: &str, + body: &[u8], + store: &mut Store, +) -> Result { + let invalid = |error: serde_json::Error| Error::InvalidArg(error.to_string()); + let find = |id: &str| { + cameras + .iter() + .find(|camera| camera.id == id) + .ok_or_else(|| Error::NotFound("camera identity not found; rescan devices".into())) + }; + match path { + "/api/camera-controls" => { + let request: ReadControls = serde_json::from_slice(body).map_err(invalid)?; + let camera = find(&request.id)?; + Ok(json!({"controls":backend.controls(&camera.id)?})) + } + "/api/camera" => { + let request: Control = serde_json::from_slice(body).map_err(invalid)?; + let camera = find(&request.id)?; + let name = store + .for_camera(&camera.id) + .effective(foreground) + .to_owned(); + if request + .profile + .as_ref() + .is_some_and(|expected| *expected != name) + { + return Err(Error::InvalidArg( + "effective camera profile changed; refresh before editing".into(), + )); + } + if request.control.parse::().is_ok() { + let (control, value) = parse_control(&request.control, &request.value)?; + let state = + actions::set_control(backend, &camera.id, store, &name, control, value)?; + let controls = backend.controls(&camera.id).ok(); + return Ok( + json!({"device":labeled_device_json(camera,cameras,store,foreground),"written_state":state, + "controls":controls,"failures":[]}), + ); + } + let setting = parse_setting(&request.control, &request.value)?; + actions::set(backend, &camera.id, store, &name, setting)?; + Ok( + json!({ "device": labeled_device_json(camera, cameras, store, foreground), "failures": [] }), + ) + } + "/api/camera-profile" => { + let request: ProfileRequest = serde_json::from_slice(body).map_err(invalid)?; + let camera = find(&request.id)?; + let profiles = store.for_camera(&camera.id); + match request.action.as_str() { + "new" => profiles.create(request.name.trim())?, + "delete" => profiles.delete(&request.name)?, + "use" => profiles.switch(&request.name)?, + "apps" => profiles.set_apps(&request.name, &request.apps)?, + _ => return Err(Error::InvalidArg("unknown camera profile action".into())), + } + let effective = profiles.effective(foreground).to_owned(); + let profile = profiles.profiles[&effective].clone(); + store.save()?; + let failures = if matches!(request.action.as_str(), "use" | "apps" | "delete") { + actions::apply(backend, &camera.id, &profile) + .into_iter() + .filter_map(|item| item.result.err().map(|e| format!("{}: {e}", item.setting))) + .collect::>() + } else { + Vec::new() + }; + Ok( + json!({ "device": labeled_device_json(camera, cameras, store, foreground), "failures": failures }), + ) + } + _ => Err(Error::NotFound(path.into())), + } +} + +#[cfg(windows)] +pub(crate) fn post( + engine: &mut crate::engine::Engine, + path: &str, + body: &[u8], +) -> Option> { + if !matches!( + path, + "/api/camera" | "/api/camera-profile" | "/api/camera-controls" + ) { + return None; + } + Some((|| { + let mut store = Store::load(&secbird_core::config_dir().join("profiles.json"))?; + dispatch( + engine.camera_backend(), + engine.cameras(), + engine.foreground(), + path, + body, + &mut store, + ) + })()) +} + +#[cfg(test)] +mod tests { + use super::*; + use secbird_core::camera::{CameraBackend, CameraInfo, Setting}; + use std::sync::Mutex; + + #[test] + fn standard_camera_api_does_not_write_for_wrong_target_or_stale_profile() { + use secbird_core::camera::controls::{Control, ControlInfo, ControlState, ControlValue}; + struct Fake(Mutex); + impl CameraBackend for Fake { + fn discover(&self) -> Result> { + Ok(vec![]) + } + fn set(&self, _: &str, _: Setting) -> Result<()> { + panic!("unexpected vendor write") + } + fn controls(&self, _: &str) -> Result> { + Ok(vec![ControlInfo::new( + Control::Exposure, + None, + None, + Some("unavailable".into()), + )]) + } + fn set_control(&self, _: &str, _: Control, _: ControlValue) -> Result { + *self.0.lock().unwrap() += 1; + Err(Error::System("driver rejected".into())) + } + } + let backend = Fake(Mutex::new(0)); + let mut store = Store::default(); + let cameras = [camera()]; + assert_eq!( + dispatch( + &backend, + &cameras, + None, + "/api/camera-controls", + br#"{"id":"camera:test"}"#, + &mut store + ) + .unwrap()["controls"][0]["control"], + "exposure" + ); + for json in [ + br#"{"id":"0099","control":"exposure","value":"-6"}"#.as_slice(), + br#"{"id":"camera:test","control":"exposure","value":"-6","profile":"stale"}"#, + br#"{"id":"camera:test","control":"exposure","value":"nope"}"#, + ] { + assert!(dispatch(&backend, &cameras, None, "/api/camera", json, &mut store).is_err()); + } + assert_eq!(*backend.0.lock().unwrap(), 0); + assert!(store.for_camera("camera:test").active().camera.is_none()); + } + + #[derive(Default)] + struct Fake(Mutex>); + impl CameraBackend for Fake { + fn discover(&self) -> secbird_core::Result> { + Ok(Vec::new()) + } + fn set(&self, _: &str, value: Setting) -> secbird_core::Result<()> { + self.0.lock().unwrap().push(value); + Ok(()) + } + } + fn camera() -> CameraInfo { + CameraInfo { + id: "camera:test".into(), + pid: 0x0e05, + name: "Razer Kiyo Pro".into(), + control_error: None, + } + } + + #[test] + fn camera_api_rejects_invalid_requests_without_writes() { + let fake = Fake::default(); + let mut store = secbird_core::Store::default(); + for body in [ + r#"{"id":"","control":"hdr","value":"on"}"#, + r#"{"id":"camera:test","control":"hdr","value":"yes"}"#, + r#"{"id":"camera:test","control":"hdr","value":"on","extra":1}"#, + r#"{"id":"0099","control":"hdr","value":"on"}"#, + ] { + assert!(dispatch( + &fake, + &[camera()], + None, + "/api/camera", + body.as_bytes(), + &mut store + ) + .is_err()); + } + assert!(fake.0.lock().unwrap().is_empty()); + } + + #[test] + fn camera_json_uses_effective_profile_without_peripheral_probes() { + let mut store = secbird_core::Store::default(); + let profiles = store.for_camera("camera:test"); + profiles.create("Streaming").unwrap(); + profiles.set_apps("Streaming", &["obs.exe".into()]).unwrap(); + let value = device_json(&camera(), &mut store, Some("obs.exe")); + assert_eq!(value["active"], "Streaming"); + assert_eq!(value["manual_active"], "Default"); + assert_eq!(value["kind"], "webcam"); + assert_eq!(value["leds"], serde_json::json!([])); + assert!(value["firmware"].is_null()); + assert_eq!(value["camera"]["state"], "saved"); + } + + #[test] + fn camera_twins_have_distinct_labels_and_inspectable_local_identity() { + let first = camera(); + let mut second = camera(); + second.id = "camera:second".into(); + let values = device_list_json(&[first, second], &mut Store::default(), None); + assert_eq!(values[0]["label"], "Razer Kiyo Pro (1)"); + assert_eq!(values[1]["label"], "Razer Kiyo Pro (2)"); + assert_eq!(values[0]["id"], "camera:test"); + assert_eq!(values[1]["id"], "camera:second"); + } + + #[test] + fn camera_api_writes_effective_profile_and_rejects_stale_profile() { + let path = std::env::temp_dir().join(format!( + "secbird-api-{}-{}.json", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut store = Store::load(&path).unwrap(); + let fake = Fake::default(); + let profiles = store.for_camera("camera:test"); + profiles.create("Streaming").unwrap(); + profiles.set_apps("Streaming", &["obs.exe".into()]).unwrap(); + let cameras = [camera()]; + let result = dispatch( + &fake, + &cameras, + Some("obs.exe"), + "/api/camera", + br#"{"id":"camera:test","control":"fov","value":"wide","profile":"Streaming"}"#, + &mut store, + ) + .unwrap(); + assert_eq!(result["device"]["profile"]["camera"]["fov"], "wide"); + assert!(store.for_camera("camera:test").active().camera.is_none()); + assert!(dispatch( + &fake, + &cameras, + Some("obs.exe"), + "/api/camera", + br#"{"id":"camera:test","control":"hdr","value":"on","profile":"Default"}"#, + &mut store + ) + .is_err()); + assert_eq!(fake.0.lock().unwrap().len(), 1); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/secbird-tray/src/editor-profiles.js b/crates/secbird-tray/src/editor-profiles.js new file mode 100644 index 0000000..65b69c3 --- /dev/null +++ b/crates/secbird-tray/src/editor-profiles.js @@ -0,0 +1,55 @@ +// Capture target IDs before awaits. Responses must not mutate a different device +// merely because it happens to be selected when a response arrives. +(function (root) { + 'use strict'; + function deviceLabel(device, devices) { + if (device.label) return device.label; + return devices.filter(other => other.pid === device.pid).length > 1 && device.serial + ? device.name + ' (' + device.serial.slice(-4) + ')' : device.name; + } + function createProfileActions({api, update}) { + const generations = new Map(); + function begin(target) { + const id = target.id, generation = (generations.get(id) || 0) + 1; + generations.set(id, generation); + const current = () => generations.get(id) === generation; + return { + async send(action, name, extra = {}) { + const response = await api('/api/profile', {id, action, name, ...extra}); + if (!current()) return null; + if (response.device?.id !== id) throw new Error('Profile response did not match the requested device. Refresh the editor.'); + return response; + }, + commit(response) { + if (!current() || !response) return null; + update(id, response.device); + return response; + }, + }; + } + async function activate(target, name) { + const operation = begin(target); + return operation.commit(await operation.send('use', name)); + } + async function create(target, name) { + const operation = begin(target); + const created = await operation.send('new', name); + if (!created) return null; + return operation.commit(await operation.send('use', name)); + } + async function remove(target, name) { + const other = name === target.active ? target.profiles.find(profile => profile !== name) : null; + const operation = begin(target); + if (other && !await operation.send('use', other)) return null; + return operation.commit(await operation.send('delete', name)); + } + async function setApps(target, name, apps) { + const operation = begin(target); + return operation.commit(await operation.send('apps', name, {apps})); + } + return {activate, create, remove, setApps}; + } + const api = {createProfileActions, deviceLabel}; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + else root.SecbirdProfiles = api; +})(globalThis); diff --git a/crates/secbird-tray/src/editor-profiles.test.cjs b/crates/secbird-tray/src/editor-profiles.test.cjs new file mode 100644 index 0000000..0d08bca --- /dev/null +++ b/crates/secbird-tray/src/editor-profiles.test.cjs @@ -0,0 +1,53 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const {createProfileActions, deviceLabel} = require('./editor-profiles.js'); +const deferred = () => { let resolve; const promise = new Promise(r => resolve = r); return {promise, resolve}; }; +const camera = () => ({id:'camera:one', kind:'webcam', active:'Default', profiles:['Default','Streaming'], profile:{}}); + +test('rendered camera labels preserve backend disambiguation', () => { + const devices = [ {...camera(), pid:'0E05', name:'Kiyo Pro', label:'Kiyo Pro (1)'}, {...camera(), id:'camera:two', pid:'0E05', name:'Kiyo Pro', label:'Kiyo Pro (2)'} ]; + assert.equal(deviceLabel(devices[0], devices), 'Kiyo Pro (1)'); + assert.equal(deviceLabel(devices[1], devices), 'Kiyo Pro (2)'); +}); +test('late camera response updates its captured device, never newly selected mouse', async () => { + const pending = deferred(), target = camera(), mouse = {id:'0099:mouse',kind:'mouse',active:'Default'}; + const devices = [target, mouse]; let selected = target; + const actions = createProfileActions({api:async () => pending.promise, update(id, device) {Object.assign(devices.find(d => d.id === id), device);}}); + const operation = actions.activate(target,'Streaming'); + selected = mouse; + pending.resolve({device:{...camera(),active:'Streaming'},failures:[]}); + await operation; + assert.equal(selected,mouse); + assert.equal(mouse.id,'0099:mouse'); + assert.equal(mouse.kind,'mouse'); + assert.equal(target.active,'Streaming'); +}); +test('multi-step create keeps camera identity after selection changes', async () => { + const pending = deferred(), target = camera(), requests=[]; + const actions = createProfileActions({api:async(path,body)=>{requests.push(body);return requests.length===1 ? pending.promise : {device:{...camera(),active:'New'},failures:[]};},update(){}}); + const operation = actions.create(target,'New'); + pending.resolve({device:camera(),failures:[]}); + await operation; + assert.deepEqual(requests.map(r=>[r.id,r.action]), [['camera:one','new'],['camera:one','use']]); +}); +test('multi-step deletion keeps captured camera identity', async () => { + const target = {...camera(),active:'Streaming'}, requests=[]; + const actions = createProfileActions({api:async(path,body)=>{requests.push(body);return {device:camera(),failures:[]};},update(){}}); + await actions.remove(target,'Streaming'); + assert.deepEqual(requests.map(r=>[r.id,r.action,r.name]), [['camera:one','use','Default'],['camera:one','delete','Streaming']]); +}); +test('superseded responses cannot restore older profile data', async () => { + const old = deferred(), target=camera(), updates=[];let calls=0; + const actions=createProfileActions({api:async()=>++calls===1?old.promise:{device:{...camera(),active:'Latest'},failures:[]},update:(id,d)=>updates.push(d.active)}); + const first=actions.activate(target,'Streaming'); + await actions.activate(target,'Latest'); + old.resolve({device:{...camera(),active:'Streaming'},failures:[]}); + assert.equal(await first,null); + assert.deepEqual(updates,['Latest']); +}); +test('wrong-device response is rejected without changing state', async () => { + const updates=[]; + const actions=createProfileActions({api:async()=>({device:{id:'camera:other'},failures:[]}),update:(id,d)=>updates.push(d)}); + await assert.rejects(actions.activate(camera(),'Streaming')); + assert.deepEqual(updates,[]); +}); diff --git a/crates/secbird-tray/src/editor.html b/crates/secbird-tray/src/editor.html index b5a7e40..8a21605 100644 --- a/crates/secbird-tray/src/editor.html +++ b/crates/secbird-tray/src/editor.html @@ -123,6 +123,10 @@ .dot.off { background: none; border: 1.5px dashed var(--line-strong); } .tiles { overflow-y: auto; padding: 16px 20px 20px; min-width: 0; } + .camera-preview { margin-top: 16px; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } + .camera-preview video { width: 100%; max-height: 38vh; aspect-ratio: 16 / 9; object-fit: contain; background: #111; display: block; margin: 10px 0; } + .camera-preview .row { flex-wrap: wrap; } + .camera-preview select { max-width: 100%; min-height: 36px; } .sechead { display: flex; align-items: center; gap: 14px; margin: 0 0 12px; min-height: 30px; flex-wrap: wrap; } .sechead h2 { margin: 0; font-size: 17px; font-weight: 650; } .sechead .tools { display: flex; align-items: center; gap: 12px; margin-left: auto; } @@ -489,6 +493,9 @@

+ + +