Skip to content

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

feat(linux): audio, MPRIS, vcam, vmic, H.264/MP4, mirroring, and recordings (Part 4)

Jochen Kirstätter355c08b1311a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e772e15..262c25a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -168,7 +168,8 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
- libgl1-mesa-dev libxkbcommon-dev libvulkan-dev libx11-dev
+ libgl1-mesa-dev libxkbcommon-dev libvulkan-dev libx11-dev \
+ ffmpeg
- name: Install Qt
uses: jurplel/install-qt-action@v4
with:
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index deb88c7..808c753 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -115,16 +115,10 @@ pub fn compute_capabilities(
#[cfg(any(windows, target_os = "linux"))]
{
caps.push(nectarlink_core::PC_WAKE.into());
- caps.push(nectarlink_core::DECK_ACTIONS.into());
- }
- #[cfg(windows)]
- {
caps.push("media.control".into());
- caps.push(nectarlink_core::STORAGE_MOUNT.into());
- caps.push(nectarlink_core::STORAGE_READ.into());
- caps.push(nectarlink_core::STORAGE_WRITE.into());
caps.push(nectarlink_core::MIRROR_VIEW.into());
caps.push(nectarlink_core::MIRROR_LISTEN.into());
+ caps.push(nectarlink_core::DECK_ACTIONS.into());
caps.push(nectarlink_core::PC_AUDIO.into());
caps.push(nectarlink_core::RECORDER.into());
caps.push(nectarlink_core::WEBCAM_VIRTUAL.into());
@@ -132,6 +126,12 @@ pub fn compute_capabilities(
caps.push(nectarlink_core::MIC_LISTEN.into());
}
#[cfg(windows)]
+ {
+ caps.push(nectarlink_core::STORAGE_MOUNT.into());
+ caps.push(nectarlink_core::STORAGE_READ.into());
+ caps.push(nectarlink_core::STORAGE_WRITE.into());
+ }
+ #[cfg(any(windows, target_os = "linux"))]
let mut pc_mirror_enabled = crate::pc_mirror::is_active();
#[cfg(any(windows, target_os = "linux"))]
let mut remote_input_enabled = false;
@@ -142,7 +142,6 @@ pub fn compute_capabilities(
for d in devices {
if let Ok(toggles) = node.device_toggles(d.id) {
for (name, on) in toggles {
- #[cfg(windows)]
if on && name == nectarlink_core::PC_MIRROR_TOGGLE {
pc_mirror_enabled = true;
}
@@ -153,8 +152,8 @@ pub fn compute_capabilities(
}
}
}
- #[cfg(windows)]
- if pc_mirror_enabled {
+ #[cfg(any(windows, target_os = "linux"))]
+ if pc_mirror_enabled && crate::pc_mirror::is_capture_available() {
caps.push(nectarlink_core::MIRROR_CAPTURE.into());
}
#[cfg(windows)]
diff --git a/desktop/app/src/linux/audio.rs b/desktop/app/src/linux/audio.rs
index 7f4ee91..61a30fe 100644
--- a/desktop/app/src/linux/audio.rs
+++ b/desktop/app/src/linux/audio.rs
@@ -1,36 +1,393 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Linux speaker volume, mute, output device enumeration, microphone mute
+//! state, and event-driven change notifications via PipeWire (`wpctl`) and
+//! PulseAudio (`pactl`).
+
+use std::io::{BufRead, BufReader};
+use std::process::{Command, Stdio};
+use std::sync::{Mutex, OnceLock, mpsc};
+use std::time::Duration;
use nectarlink_core::AudioOutputDevice;
+static FALLBACK_SPEAKER: Mutex<(u8, bool)> = Mutex::new((50, false));
+static FALLBACK_MIC_MUTED: Mutex<bool> = Mutex::new(false);
+static WATCH_STARTED: OnceLock<()> = OnceLock::new();
+
+/// Parses `wpctl get-volume` output such as `"Volume: 0.45"` or
+/// `"Volume: 0.45 [MUTED]"` into `(volume_percent, muted)`.
+pub(crate) fn parse_wpctl_volume(output: &str) -> Option<(u8, bool)> {
+ let muted = output.contains("[MUTED]");
+ let after_colon = output.split_once("Volume:")?.1;
+ let vol_token = after_colon.split_whitespace().next()?;
+ let val = vol_token.parse::<f32>().ok()?;
+ if !val.is_finite() {
+ return None;
+ }
+ let pct = (val * 100.0).round().clamp(0.0, 100.0) as u8;
+ Some((pct, muted))
+}
+
+/// Parses `pactl get-sink-mute` / `pactl get-source-mute` output such as
+/// `"Mute: yes"` or `"Mute: no"`.
+pub(crate) fn parse_pactl_mute(mute_out: &str) -> Option<bool> {
+ let rhs = mute_out.split_once(':').map(|(_, r)| r).unwrap_or(mute_out).trim();
+ if rhs.eq_ignore_ascii_case("yes") || rhs.eq_ignore_ascii_case("true") || rhs == "1" {
+ Some(true)
+ } else if rhs.eq_ignore_ascii_case("no") || rhs.eq_ignore_ascii_case("false") || rhs == "0" {
+ Some(false)
+ } else {
+ None
+ }
+}
+
+/// Parses `pactl get-sink-volume` and optional `pactl get-sink-mute` output
+/// into `(volume_percent, muted)`.
+pub(crate) fn parse_pactl_volume_and_mute(vol_out: &str, mute_out: Option<&str>) -> Option<(u8, bool)> {
+ let pct_token = vol_out.split_whitespace().find_map(|tok| tok.strip_suffix('%'))?;
+ let pct_val = pct_token.trim().parse::<f32>().ok()?;
+ if !pct_val.is_finite() {
+ return None;
+ }
+ let pct = pct_val.round().clamp(0.0, 100.0) as u8;
+ let muted = mute_out.and_then(parse_pactl_mute).unwrap_or(false);
+ Some((pct, muted))
+}
+
+/// Parses `pactl list sinks` output along with `pactl get-default-sink` into
+/// sorted `AudioOutputDevice` entries (default first, then alphabetical by name).
+pub(crate) fn parse_pactl_sinks(list_out: &str, default_sink: Option<&str>) -> Vec<AudioOutputDevice> {
+ let default_trimmed = default_sink.map(str::trim).filter(|s| !s.is_empty());
+ let mut out = Vec::new();
+ let mut current_id: Option<String> = None;
+ let mut current_desc: Option<String> = None;
+
+ let flush = |id: &mut Option<String>, desc: &mut Option<String>, out: &mut Vec<AudioOutputDevice>| {
+ if let Some(sink_id) = id.take() {
+ let name = desc.take().filter(|d| !d.is_empty()).unwrap_or_else(|| sink_id.clone());
+ let is_default = default_trimmed == Some(sink_id.as_str());
+ out.push(AudioOutputDevice { id: sink_id, name, is_default });
+ } else {
+ *desc = None;
+ }
+ };
+
+ for raw_line in list_out.lines() {
+ let line = raw_line.trim();
+ if line.starts_with("Sink #") {
+ flush(&mut current_id, &mut current_desc, &mut out);
+ } else if let Some(rest) = line.strip_prefix("Name:") {
+ let id = rest.trim();
+ if !id.is_empty() && current_id.is_none() {
+ current_id = Some(id.to_owned());
+ }
+ } else if let Some(rest) = line.strip_prefix("Description:") {
+ let desc = rest.trim();
+ if !desc.is_empty() && current_desc.is_none() {
+ current_desc = Some(desc.to_owned());
+ }
+ }
+ }
+ flush(&mut current_id, &mut current_desc, &mut out);
+
+ out.sort_by(|a, b| b.is_default.cmp(&a.is_default).then_with(|| a.name.cmp(&b.name)));
+ out
+}
+
+/// Returns `true` when a `pactl subscribe` event line indicates a sink, source,
+/// or server state/device change (ignoring per-stream `sink-input` / `source-output` noise).
+pub(crate) fn parse_pactl_subscribe_line(line: &str) -> bool {
+ let trimmed = line.trim();
+ if !trimmed.starts_with("Event '") {
+ return false;
+ }
+ (trimmed.contains(" on sink #")
+ || trimmed.ends_with(" on sink")
+ || trimmed.contains(" on source #")
+ || trimmed.ends_with(" on source")
+ || trimmed.contains(" on server #")
+ || trimmed.ends_with(" on server"))
+ && !trimmed.contains("sink-input")
+ && !trimmed.contains("source-output")
+}
+
+/// Reads the default speaker endpoint's `(volume_percent, muted)`.
pub fn speaker_state() -> Option<(u8, bool)> {
- None
+ if let Ok(out) = Command::new("wpctl").args(["get-volume", "@DEFAULT_AUDIO_SINK@"]).output()
+ && out.status.success()
+ && let Some(state) = parse_wpctl_volume(&String::from_utf8_lossy(&out.stdout))
+ {
+ if let Ok(mut guard) = FALLBACK_SPEAKER.lock() {
+ *guard = state;
+ }
+ return Some(state);
+ }
+
+ if let Ok(vol_out) = Command::new("pactl").args(["get-sink-volume", "@DEFAULT_SINK@"]).output()
+ && vol_out.status.success()
+ {
+ let mute_out = Command::new("pactl")
+ .args(["get-sink-mute", "@DEFAULT_SINK@"])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|o| String::from_utf8_lossy(&o.stdout).into_owned());
+ if let Some(state) =
+ parse_pactl_volume_and_mute(&String::from_utf8_lossy(&vol_out.stdout), mute_out.as_deref())
+ {
+ if let Ok(mut guard) = FALLBACK_SPEAKER.lock() {
+ *guard = state;
+ }
+ return Some(state);
+ }
+ }
+
+ Some(*FALLBACK_SPEAKER.lock().ok()?)
}
-pub fn set_speaker_volume(_level: u8) -> Result<(), String> {
+
+/// Sets the default speaker endpoint's master volume (`0..=100`).
+pub fn set_speaker_volume(level: u8) -> Result<(), String> {
+ let clamped = level.min(100);
+ if let Ok(mut guard) = FALLBACK_SPEAKER.lock() {
+ guard.0 = clamped;
+ }
+ let arg = format!("{clamped}%");
+ let _ = Command::new("wpctl")
+ .args(["set-volume", "@DEFAULT_AUDIO_SINK@", &arg])
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { Err(std::io::Error::other("wpctl failed")) })
+ .or_else(|_| Command::new("pactl").args(["set-sink-volume", "@DEFAULT_SINK@", &arg]).status());
Ok(())
}
-pub fn set_speaker_mute(_muted: bool) -> Result<(), String> {
+
+/// Sets the default speaker endpoint's mute state.
+pub fn set_speaker_mute(muted: bool) -> Result<(), String> {
+ if let Ok(mut guard) = FALLBACK_SPEAKER.lock() {
+ guard.1 = muted;
+ }
+ let flag = if muted { "1" } else { "0" };
+ let _ = Command::new("wpctl")
+ .args(["set-mute", "@DEFAULT_AUDIO_SINK@", flag])
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { Err(std::io::Error::other("wpctl failed")) })
+ .or_else(|_| Command::new("pactl").args(["set-sink-mute", "@DEFAULT_SINK@", flag]).status());
Ok(())
}
+
+/// Steps the default speaker volume up by one increment (2%) and unmutes if muted.
pub fn speaker_volume_up() -> Result<(u8, bool), String> {
- Ok((50, false))
+ let (current, muted) = speaker_state().unwrap_or((50, false));
+ let next = current.saturating_add(2).min(100);
+ set_speaker_volume(next)?;
+ if muted {
+ set_speaker_mute(false)?;
+ }
+ Ok((next, false))
}
+
+/// Steps the default speaker volume down by one increment (2%).
pub fn speaker_volume_down() -> Result<(u8, bool), String> {
- Ok((50, false))
+ let (current, muted) = speaker_state().unwrap_or((50, false));
+ let next = current.saturating_sub(2);
+ set_speaker_volume(next)?;
+ Ok((next, muted))
}
+
+/// Toggles mute on the default speaker endpoint and returns the new muted state.
pub fn toggle_speaker_mute() -> Result<bool, String> {
- Ok(false)
+ let (_, muted) = speaker_state().unwrap_or((50, false));
+ let next = !muted;
+ set_speaker_mute(next)?;
+ Ok(next)
}
+
+/// Reads whether the default capture (microphone) endpoint is muted.
pub fn mic_muted() -> Option<bool> {
- None
+ if let Ok(out) = Command::new("wpctl").args(["get-volume", "@DEFAULT_AUDIO_SOURCE@"]).output()
+ && out.status.success()
+ && let Some((_, muted)) = parse_wpctl_volume(&String::from_utf8_lossy(&out.stdout))
+ {
+ if let Ok(mut guard) = FALLBACK_MIC_MUTED.lock() {
+ *guard = muted;
+ }
+ return Some(muted);
+ }
+
+ if let Ok(out) = Command::new("pactl").args(["get-source-mute", "@DEFAULT_SOURCE@"]).output()
+ && out.status.success()
+ && let Some(muted) = parse_pactl_mute(&String::from_utf8_lossy(&out.stdout))
+ {
+ if let Ok(mut guard) = FALLBACK_MIC_MUTED.lock() {
+ *guard = muted;
+ }
+ return Some(muted);
+ }
+
+ Some(*FALLBACK_MIC_MUTED.lock().ok()?)
}
+
+/// Toggles mute on the default capture (microphone) endpoint and returns the new muted state.
pub fn toggle_mic_mute() -> Result<bool, String> {
- Ok(false)
+ let current = mic_muted().unwrap_or(false);
+ let next = !current;
+ if let Ok(mut guard) = FALLBACK_MIC_MUTED.lock() {
+ *guard = next;
+ }
+ let flag = if next { "1" } else { "0" };
+ let _ = Command::new("wpctl")
+ .args(["set-mute", "@DEFAULT_AUDIO_SOURCE@", flag])
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { Err(std::io::Error::other("wpctl failed")) })
+ .or_else(|_| Command::new("pactl").args(["set-source-mute", "@DEFAULT_SOURCE@", flag]).status());
+ Ok(next)
}
+
+/// Lists active audio output sinks on this PC, marking the current default
+/// output (`is_default: true`) and sorting the default first.
pub fn output_devices() -> Vec<AudioOutputDevice> {
- Vec::new()
+ let default_sink = Command::new("pactl")
+ .arg("get-default-sink")
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
+ .filter(|s| !s.is_empty());
+
+ if let Ok(list_out) = Command::new("pactl").args(["list", "sinks"]).output()
+ && list_out.status.success()
+ {
+ let parsed = parse_pactl_sinks(&String::from_utf8_lossy(&list_out.stdout), default_sink.as_deref());
+ if !parsed.is_empty() {
+ return parsed;
+ }
+ }
+
+ vec![AudioOutputDevice {
+ id: "default".to_string(),
+ name: "Default Output".to_string(),
+ is_default: true,
+ }]
}
-pub fn set_default_output_device(_id: &str) -> Result<(), String> {
- Ok(())
+
+/// Switches the system default output sink to `id`.
+pub fn set_default_output_device(id: &str) -> Result<(), String> {
+ let trimmed = id.trim();
+ if trimmed.is_empty() || trimmed.starts_with('-') || trimmed.chars().any(char::is_control) {
+ return Err("output device id is invalid".to_string());
+ }
+ let status = Command::new("pactl")
+ .args(["set-default-sink", trimmed])
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { Err(std::io::Error::other("pactl failed")) })
+ .or_else(|_| Command::new("wpctl").args(["set-default", trimmed]).status())
+ .map_err(|e| format!("failed to set default output device: {e}"))?;
+
+ if status.success() { Ok(()) } else { Err(format!("audio backend rejected default sink '{trimmed}'")) }
+}
+
+/// Subscribes to PipeWire/PulseAudio sink/source/server events and invokes
+/// `changed` after coalescing rapid event bursts over 80 ms.
+pub fn watch(changed: fn()) {
+ if WATCH_STARTED.set(()).is_err() {
+ return;
+ }
+ let _ = std::thread::Builder::new().name("audio-watch".into()).spawn(move || watch_thread(changed));
+}
+
+fn watch_thread(changed: fn()) {
+ let Ok(mut child) =
+ Command::new("pactl").arg("subscribe").stdout(Stdio::piped()).stderr(Stdio::null()).spawn()
+ else {
+ return;
+ };
+ let Some(stdout) = child.stdout.take() else {
+ let _ = child.kill();
+ let _ = child.wait();
+ return;
+ };
+
+ let (tx, rx) = mpsc::channel::<()>();
+ let _ = std::thread::Builder::new().name("audio-watch-reader".into()).spawn(move || {
+ let reader = BufReader::new(stdout);
+ for line in reader.lines().map_while(Result::ok) {
+ if parse_pactl_subscribe_line(&line) && tx.send(()).is_err() {
+ break;
+ }
+ }
+ });
+
+ while rx.recv().is_ok() {
+ while rx.recv_timeout(Duration::from_millis(80)).is_ok() {}
+ changed();
+ }
+
+ let _ = child.kill();
+ let _ = child.wait();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_wpctl_volume_handles_normal_and_muted_lines() {
+ assert_eq!(parse_wpctl_volume("Volume: 0.45\n"), Some((45, false)));
+ assert_eq!(parse_wpctl_volume("Volume: 0.72 [MUTED]\n"), Some((72, true)));
+ assert_eq!(parse_wpctl_volume("Volume: 1.35"), Some((100, false)));
+ assert_eq!(parse_wpctl_volume("garbage"), None);
+ }
+
+ #[test]
+ fn parse_pactl_volume_and_mute_extracts_percentage_and_mute() {
+ let vol = "Volume: front-left: 32768 / 50% / -18.06 dB, front-right: 32768 / 50% / -18.06 dB\n";
+ assert_eq!(parse_pactl_volume_and_mute(vol, Some("Mute: no\n")), Some((50, false)));
+ assert_eq!(parse_pactl_volume_and_mute(vol, Some("Mute: yes\n")), Some((50, true)));
+ assert_eq!(parse_pactl_volume_and_mute("invalid output", None), None);
+ }
+
+ #[test]
+ fn parse_pactl_sinks_parses_and_sorts_default_first() {
+ let sample = "\
+Sink #41
+\tState: RUNNING
+\tName: alsa_output.pci-0000_00_1f.3.analog-stereo
+\tDescription: Built-in Audio Analog Stereo
+\tVolume: front-left: 40000 / 61%
+
+Sink #52
+\tState: IDLE
+\tName: bluez_output.AA_BB_CC_DD_EE_FF.1
+\tDescription: Pixel Buds Pro
+";
+ let devices = parse_pactl_sinks(sample, Some("bluez_output.AA_BB_CC_DD_EE_FF.1"));
+ assert_eq!(devices.len(), 2);
+ assert_eq!(devices[0].id, "bluez_output.AA_BB_CC_DD_EE_FF.1");
+ assert_eq!(devices[0].name, "Pixel Buds Pro");
+ assert!(devices[0].is_default);
+ assert_eq!(devices[1].id, "alsa_output.pci-0000_00_1f.3.analog-stereo");
+ assert_eq!(devices[1].name, "Built-in Audio Analog Stereo");
+ assert!(!devices[1].is_default);
+ }
+
+ #[test]
+ fn parse_pactl_subscribe_line_filters_relevant_events() {
+ assert!(parse_pactl_subscribe_line("Event 'change' on sink #0"));
+ assert!(parse_pactl_subscribe_line("Event 'change' on source #2"));
+ assert!(parse_pactl_subscribe_line("Event 'change' on server #0"));
+ assert!(!parse_pactl_subscribe_line("Event 'change' on sink-input #44"));
+ assert!(!parse_pactl_subscribe_line("Event 'change' on source-output #12"));
+ assert!(!parse_pactl_subscribe_line("Event 'new' on client #99"));
+ }
+
+ #[test]
+ fn volume_stepping_increments_by_two_percent_and_unmutes_on_up() {
+ let _ = set_speaker_volume(40);
+ let _ = set_speaker_mute(true);
+ let (vol_up, muted_after_up) = speaker_volume_up().unwrap();
+ assert!(!muted_after_up);
+ assert!(vol_up <= 100);
+
+ let (vol_down, _) = speaker_volume_down().unwrap();
+ assert!(vol_down <= 100);
+ }
}
-pub fn watch(_changed: fn()) {}
diff --git a/desktop/app/src/linux/audio_out.rs b/desktop/app/src/linux/audio_out.rs
index 21aee30..bc2a602 100644
--- a/desktop/app/src/linux/audio_out.rs
+++ b/desktop/app/src/linux/audio_out.rs
@@ -1,19 +1,313 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Low-latency 16-bit signed little-endian PCM playback on Linux via
+//! PulseAudio (`pacat`), PipeWire (`pw-play`), or ALSA (`aplay`), backed by an
+//! adaptive jitter buffer with smooth sample interpolation.
-use std::io;
+use std::collections::VecDeque;
+use std::io::{Result, Write};
+use std::process::{Child, Command, Stdio};
+use std::sync::mpsc::{self, SyncSender, TrySendError};
+use std::sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+};
+use std::thread::{self, JoinHandle};
+use std::time::Duration;
-pub struct Player;
+const BYTES_PER_SAMPLE: usize = 2;
+const JITTER_START_MS: usize = 40;
+const JITTER_LOW_MS: usize = 20;
+const JITTER_TARGET_MS: usize = 80;
+const JITTER_HIGH_MS: usize = 160;
+const JITTER_MAX_MS: usize = 220;
+
+/// Linearly interpolates two interleaved `s16le` frames (`a` and `b`) into `out`.
+pub(crate) fn interpolate_frame_s16le(a: &[u8], b: &[u8], out: &mut [u8]) {
+ let len = a.len().min(b.len()).min(out.len()) & !1;
+ for i in (0..len).step_by(2) {
+ let sa = i16::from_le_bytes([a[i], a[i + 1]]);
+ let sb = i16::from_le_bytes([b[i], b[i + 1]]);
+ let mid = ((i32::from(sa) + i32::from(sb)) / 2) as i16;
+ let bytes = mid.to_le_bytes();
+ out[i] = bytes[0];
+ out[i + 1] = bytes[1];
+ }
+}
+
+#[derive(Debug)]
+struct Jitter {
+ pcm: VecDeque<u8>,
+ frame_bytes: usize,
+ start_bytes: usize,
+ low_bytes: usize,
+ target_bytes: usize,
+ high_bytes: usize,
+ max_bytes: usize,
+ primed: bool,
+ last_frame: Vec<u8>,
+}
+
+impl Jitter {
+ fn new(rate: u32, channels: u16) -> Self {
+ let frame_bytes = (channels as usize).max(1) * BYTES_PER_SAMPLE;
+ let bytes_per_ms = ((rate as usize) * frame_bytes / 1000).max(frame_bytes);
+ let align = |ms: usize| {
+ let raw = (ms * bytes_per_ms).max(frame_bytes);
+ (raw / frame_bytes) * frame_bytes
+ };
+ Self {
+ pcm: VecDeque::with_capacity(align(JITTER_MAX_MS)),
+ frame_bytes,
+ start_bytes: align(JITTER_START_MS),
+ low_bytes: align(JITTER_LOW_MS),
+ target_bytes: align(JITTER_TARGET_MS),
+ high_bytes: align(JITTER_HIGH_MS),
+ max_bytes: align(JITTER_MAX_MS),
+ primed: false,
+ last_frame: vec![0u8; frame_bytes],
+ }
+ }
+
+ fn push(&mut self, data: &[u8]) {
+ let usable = (data.len() / self.frame_bytes) * self.frame_bytes;
+ if usable == 0 {
+ return;
+ }
+ self.pcm.extend(&data[..usable]);
+ if self.pcm.len() > self.max_bytes {
+ let drop = ((self.pcm.len() - self.target_bytes) / self.frame_bytes) * self.frame_bytes;
+ self.pcm.drain(..drop.min(self.pcm.len()));
+ }
+ if self.pcm.len() >= self.start_bytes {
+ self.primed = true;
+ }
+ }
+
+ fn pull(&mut self, dst: &mut [u8], frames: usize) -> bool {
+ let total_bytes = (frames * self.frame_bytes).min(dst.len());
+ if !self.primed {
+ dst[..total_bytes].fill(0);
+ return false;
+ }
+
+ if self.pcm.len() > self.high_bytes && frames >= 8 {
+ for _ in 0..self.frame_bytes {
+ let _ = self.pcm.pop_front();
+ }
+ }
+
+ let available_frames = self.pcm.len() / self.frame_bytes;
+ if available_frames == 0 {
+ self.primed = false;
+ self.last_frame.fill(0);
+ dst[..total_bytes].fill(0);
+ return false;
+ }
+
+ let stretch = self.pcm.len() < self.low_bytes && frames >= 16;
+ let mut written = 0usize;
+ let mut produced_frames = 0usize;
+ let mut next_peek = vec![0u8; self.frame_bytes];
+
+ while produced_frames < frames && written + self.frame_bytes <= total_bytes {
+ if self.pcm.len() >= self.frame_bytes {
+ for b in &mut self.last_frame {
+ *b = self.pcm.pop_front().unwrap_or(0);
+ }
+ dst[written..written + self.frame_bytes].copy_from_slice(&self.last_frame);
+ written += self.frame_bytes;
+ produced_frames += 1;
+
+ if stretch && produced_frames == frames / 2 && written + self.frame_bytes <= total_bytes {
+ if self.pcm.len() >= self.frame_bytes {
+ for (i, b) in next_peek.iter_mut().enumerate() {
+ *b = self.pcm.get(i).copied().unwrap_or(0);
+ }
+ interpolate_frame_s16le(
+ &self.last_frame,
+ &next_peek,
+ &mut dst[written..written + self.frame_bytes],
+ );
+ } else {
+ dst[written..written + self.frame_bytes].copy_from_slice(&self.last_frame);
+ }
+ written += self.frame_bytes;
+ produced_frames += 1;
+ }
+ } else {
+ self.primed = false;
+ dst[written..total_bytes].fill(0);
+ break;
+ }
+ }
+ true
+ }
+}
+
+fn spawn_pcm_sink(rate: u32, channels: u16, device_id: Option<&str>) -> Option<Child> {
+ let rate_s = rate.to_string();
+ let ch_s = channels.to_string();
+ let dev = device_id.map(str::trim).filter(|s| {
+ !s.is_empty() && *s != "default" && !s.starts_with('-') && !s.chars().any(char::is_control)
+ });
+
+ let mut pacat = Command::new("pacat");
+ pacat.args([
+ "--playback",
+ "--raw",
+ "--format=s16le",
+ &format!("--rate={rate_s}"),
+ &format!("--channels={ch_s}"),
+ "--latency-msec=20",
+ ]);
+ if let Some(d) = dev {
+ pacat.arg(format!("--device={d}"));
+ }
+ if let Ok(child) = pacat.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
+ return Some(child);
+ }
+
+ let mut pw = Command::new("pw-play");
+ pw.args(["--raw", "--format=s16", &format!("--rate={rate_s}"), &format!("--channels={ch_s}")]);
+ if let Some(d) = dev {
+ pw.arg(format!("--target={d}"));
+ }
+ pw.arg("-");
+ if let Ok(child) = pw.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
+ return Some(child);
+ }
+
+ Command::new("aplay")
+ .args(["-q", "-t", "raw", "-f", "S16_LE", "-r", &rate_s, "-c", &ch_s, "--buffer-size=1920", "-"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()
+}
+
+#[derive(Debug)]
+pub struct Player {
+ tx: SyncSender<Vec<u8>>,
+ stop: Arc<AtomicBool>,
+ handle: Option<JoinHandle<()>>,
+}
impl Player {
- pub fn start(_rate: u32, _channels: u16) -> io::Result<Player> {
- Ok(Player)
+ pub fn start(rate: u32, channels: u16) -> Result<Player> {
+ Self::start_for_device(rate, channels, None)
+ }
+
+ pub fn start_on(device: Option<String>, rate: u32, channels: u16) -> Result<Player> {
+ Self::start_for_device(rate, channels, device.as_deref())
+ }
+
+ pub fn start_for_device(rate: u32, channels: u16, device_id: Option<&str>) -> Result<Player> {
+ let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(64);
+ let stop = Arc::new(AtomicBool::new(false));
+ let thread_stop = Arc::clone(&stop);
+ let clean_rate = rate.max(8_000);
+ let clean_channels = channels.max(1);
+ let dev_owned = device_id.map(str::to_owned);
+
+ let handle = thread::Builder::new().name("nectarlink-audio-out".into()).spawn(move || {
+ let mut jitter = Jitter::new(clean_rate, clean_channels);
+ let frame_bytes = jitter.frame_bytes;
+ let frames_per_tick = ((clean_rate as usize) / 100).max(1);
+ let mut scratch = vec![0u8; frames_per_tick * frame_bytes];
+ let mut child = spawn_pcm_sink(clean_rate, clean_channels, dev_owned.as_deref());
+
+ while !thread_stop.load(Ordering::Acquire) {
+ while let Ok(chunk) = rx.try_recv() {
+ jitter.push(&chunk);
+ }
+ let has_audio = jitter.pull(&mut scratch, frames_per_tick);
+ if has_audio
+ && let Some(proc) = child.as_mut()
+ && let Some(stdin) = proc.stdin.as_mut()
+ && stdin.write_all(&scratch).is_err()
+ {
+ let _ = proc.kill();
+ let _ = proc.wait();
+ child = spawn_pcm_sink(clean_rate, clean_channels, dev_owned.as_deref());
+ }
+ thread::sleep(Duration::from_millis(10));
+ }
+
+ if let Some(mut proc) = child {
+ drop(proc.stdin.take());
+ let _ = proc.kill();
+ let _ = proc.wait();
+ }
+ })?;
+
+ Ok(Player { tx, stop, handle: Some(handle) })
+ }
+
+ pub fn push(&self, data: Vec<u8>) {
+ if data.is_empty() {
+ return;
+ }
+ match self.tx.try_send(data) {
+ Ok(()) | Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => {}
+ }
+ }
+}
+
+impl Drop for Player {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(handle) = self.handle.take() {
+ let _ = handle.join();
+ }
}
- pub fn start_on(_device: Option<String>, _rate: u32, _channels: u16) -> io::Result<Player> {
- Ok(Player)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn jitter_waits_for_prime_threshold_before_emitting_audio() {
+ let mut jitter = Jitter::new(48_000, 2);
+ let mut out = vec![0xFFu8; 480 * 4];
+ jitter.push(&vec![0x11u8; 480 * 4]);
+ assert!(!jitter.pull(&mut out, 480));
+ assert!(out.iter().all(|&b| b == 0));
+
+ jitter.push(&vec![0x22u8; 480 * 4 * 4]);
+ assert!(jitter.pull(&mut out, 480));
+ assert!(out.iter().any(|&b| b != 0));
}
- pub fn start_for_device(_rate: u32, _channels: u16, _device_id: Option<&str>) -> io::Result<Player> {
- Ok(Player)
+
+ #[test]
+ fn jitter_caps_overflow_to_target_depth() {
+ let mut jitter = Jitter::new(48_000, 2);
+ jitter.push(&vec![0x33u8; jitter.max_bytes + 4096]);
+ assert!(jitter.pcm.len() <= jitter.max_bytes);
+ assert!(jitter.pcm.len() >= jitter.target_bytes);
+ }
+
+ #[test]
+ fn interpolate_frame_s16le_averages_per_channel_samples() {
+ let mut a = Vec::new();
+ a.extend_from_slice(&1000i16.to_le_bytes());
+ a.extend_from_slice(&(-2000i16).to_le_bytes());
+
+ let mut b = Vec::new();
+ b.extend_from_slice(&3000i16.to_le_bytes());
+ b.extend_from_slice(&(-1000i16).to_le_bytes());
+
+ let mut out = [0u8; 4];
+ interpolate_frame_s16le(&a, &b, &mut out);
+ assert_eq!(i16::from_le_bytes([out[0], out[1]]), 2000);
+ assert_eq!(i16::from_le_bytes([out[2], out[3]]), -1500);
+ }
+
+ #[test]
+ fn player_starts_accepts_pushes_and_drops_cleanly() {
+ let player = Player::start(48_000, 2).expect("player should start");
+ player.push(vec![0u8; 1920]);
+ drop(player);
}
- pub fn push(&self, _data: Vec<u8>) {}
}
diff --git a/desktop/app/src/linux/browser.rs b/desktop/app/src/linux/browser.rs
index c859dd8..a39c48b 100644
--- a/desktop/app/src/linux/browser.rs
+++ b/desktop/app/src/linux/browser.rs
@@ -1,11 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables, non_camel_case_types, clippy::upper_case_acronyms)]
+//! Find the window that owns a media session on Linux, and read the page
+//! address and the `<video>` rectangle out of a browser when available.
+//!
+//! Matches the public API of `desktop/app/src/win/browser.rs`.
+use std::process::Command;
+
+/// Cross-platform window handle representation matching `windows::Win32::Foundation::HWND`.
+#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct HWND(pub *mut core::ffi::c_void);
+
+// SAFETY: Window handles (X11 XIDs cast to pointer size) are plain integer IDs.
unsafe impl Send for HWND {}
unsafe impl Sync for HWND {}
+/// Cross-platform rectangle matching `windows::Win32::Foundation::RECT`.
+#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RECT {
pub left: i32,
@@ -14,48 +25,381 @@ pub struct RECT {
pub bottom: i32,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub struct Window {
pub hwnd: HWND,
pub program: String,
pub title: String,
}
-pub fn programs_for(_player: &str) -> Vec<String> {
- Vec::new()
+/// Possible process executable names for a MPRIS / SMTC `source_app_user_model_id`.
+///
+/// Supports both Windows `.exe` names (for cross-platform unit tests) and Linux
+/// binary names (`chrome`, `chromium`, `firefox`, `vlc`, `mpv`, etc.).
+pub fn programs_for(player: &str) -> Vec<String> {
+ let trimmed = player.trim();
+ if trimmed.is_empty() {
+ return Vec::new();
+ }
+ let lower = trimmed.to_ascii_lowercase();
+ let mut out = Vec::new();
+ let mut push = |s: &str| {
+ if !s.is_empty() && !out.iter().any(|x: &String| x.eq_ignore_ascii_case(s)) {
+ out.push(s.to_ascii_lowercase());
+ }
+ };
+ if lower.ends_with(".exe") {
+ push(&lower);
+ push(lower.trim_end_matches(".exe"));
+ }
+ for (needle, exe, linux_bins) in [
+ ("chrome", "chrome.exe", &["chrome", "google-chrome", "google-chrome-stable"][..]),
+ ("chromium", "chromium.exe", &["chromium", "chromium-browser"][..]),
+ ("msedge", "msedge.exe", &["msedge", "microsoft-edge", "microsoft-edge-stable"][..]),
+ ("microsoft.microsoftedge", "msedge.exe", &["msedge", "microsoft-edge"][..]),
+ ("brave", "brave.exe", &["brave", "brave-browser"][..]),
+ ("vivaldi", "vivaldi.exe", &["vivaldi", "vivaldi-stable"][..]),
+ ("opera", "opera.exe", &["opera"][..]),
+ ("firefox", "firefox.exe", &["firefox", "firefox-esr", " firefox-bin"][..]),
+ ("308046b0af4a39cb", "firefox.exe", &["firefox", "firefox-esr"][..]),
+ ("mozilla", "firefox.exe", &["firefox", "firefox-esr"][..]),
+ ("zen", "zen.exe", &["zen", "zen-bin"][..]),
+ ("floorp", "floorp.exe", &["floorp"][..]),
+ ("waterfox", "waterfox.exe", &["waterfox"][..]),
+ ("librewolf", "librewolf.exe", &["librewolf"][..]),
+ ("vlc", "vlc.exe", &["vlc"][..]),
+ ("mpv", "mpv.exe", &["mpv"][..]),
+ ("potplayer", "potplayermini64.exe", &["potplayer"][..]),
+ ("mpc-hc", "mpc-hc64.exe", &["mpc-hc"][..]),
+ ("kmplayer", "kmplayer.exe", &["kmplayer"][..]),
+ ("microsoft.zunemusic", "microsoft.media.player.exe", &["rhythmbox", "elisa"][..]),
+ ("microsoft.zunevideo", "video.ui.exe", &["totem", "celluloid", "haruna", "dragon"][..]),
+ ] {
+ if lower.contains(needle) {
+ push(exe);
+ for bin in linux_bins {
+ push(bin.trim());
+ }
+ }
+ }
+ if let Some(head) = lower.split(['!', '_', ' ']).next()
+ && head.len() >= 3
+ {
+ push(&format!("{head}.exe"));
+ push(head);
+ }
+ out
}
-pub fn is_browser(_program: &str) -> bool {
- false
+
+pub fn is_browser(program: &str) -> bool {
+ let base = program.trim().to_ascii_lowercase();
+ let stem = base.trim_end_matches(".exe");
+ matches!(
+ stem,
+ "chrome"
+ | "google-chrome"
+ | "google-chrome-stable"
+ | "chromium"
+ | "chromium-browser"
+ | "msedge"
+ | "microsoft-edge"
+ | "microsoft-edge-stable"
+ | "brave"
+ | "brave-browser"
+ | "vivaldi"
+ | "vivaldi-stable"
+ | "opera"
+ | "firefox"
+ | "firefox-esr"
+ | "firefox-bin"
+ | "zen"
+ | "zen-bin"
+ | "floorp"
+ | "waterfox"
+ | "librewolf"
+ | "arc"
+ )
}
+
+/// Enumerate visible top-level windows via `wmctrl -lp` or `xdotool`.
pub fn windows() -> Vec<Window> {
+ if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() {
+ return Vec::new();
+ }
+
+ // Try `wmctrl -lp` first: `<wid_hex> <desktop> <pid> <host> <title...>`
+ if let Ok(out) = Command::new("wmctrl").arg("-lp").output()
+ && out.status.success()
+ {
+ let text = String::from_utf8_lossy(&out.stdout);
+ let parsed = parse_wmctrl_lp(&text);
+ if !parsed.is_empty() {
+ return parsed;
+ }
+ }
+
+ // Fallback to `xdotool search --onlyvisible --name .+`
+ if let Ok(out) = Command::new("xdotool").args(["search", "--onlyvisible", "--name", ".+"]).output()
+ && out.status.success()
+ {
+ let mut list = Vec::new();
+ for line in String::from_utf8_lossy(&out.stdout).lines() {
+ let Ok(xid) = line.trim().parse::<usize>() else {
+ continue;
+ };
+ if xid == 0 {
+ continue;
+ }
+ let title = Command::new("xdotool")
+ .args(["getwindowname", &xid.to_string()])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
+ .unwrap_or_default();
+ if title.is_empty() {
+ continue;
+ }
+ let pid = Command::new("xdotool")
+ .args(["getwindowpid", &xid.to_string()])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse::<u32>().ok())
+ .unwrap_or(0);
+ let program = program_for_pid(pid).unwrap_or_default();
+ list.push(Window { hwnd: HWND(xid as *mut core::ffi::c_void), program, title });
+ }
+ return list;
+ }
+
Vec::new()
}
-pub fn window_for(_player: &str, _title: &str) -> Option<Window> {
+
+fn parse_wmctrl_lp(text: &str) -> Vec<Window> {
+ let mut out = Vec::new();
+ for line in text.lines() {
+ let mut parts = line.split_whitespace();
+ let Some(wid_str) = parts.next() else { continue };
+ let Some(_desktop) = parts.next() else { continue };
+ let Some(pid_str) = parts.next() else { continue };
+ let Some(host) = parts.next() else { continue };
+ let wid_trimmed = wid_str.trim_start_matches("0x").trim_start_matches("0X");
+ let Ok(xid) = usize::from_str_radix(wid_trimmed, 16) else { continue };
+ if xid == 0 {
+ continue;
+ }
+ let pid = pid_str.parse::<u32>().unwrap_or(0);
+ // Find where `host` ends in `line` to extract the rest as window title
+ let title = if let Some(idx) = line.find(host) {
+ line[idx + host.len()..].trim().to_owned()
+ } else {
+ String::new()
+ };
+ if title.is_empty() {
+ continue;
+ }
+ let program = program_for_pid(pid).unwrap_or_default();
+ out.push(Window { hwnd: HWND(xid as *mut core::ffi::c_void), program, title });
+ }
+ out
+}
+
+fn program_for_pid(pid: u32) -> Option<String> {
+ if pid == 0 {
+ return None;
+ }
+ if let Ok(exe) = std::fs::read_link(format!("/proc/{pid}/exe"))
+ && let Some(name) = exe.file_name().and_then(|n| n.to_str())
+ {
+ return Some(name.to_ascii_lowercase());
+ }
+ if let Ok(comm) = std::fs::read_to_string(format!("/proc/{pid}/comm")) {
+ let trimmed = comm.trim();
+ if !trimmed.is_empty() {
+ return Some(trimmed.to_ascii_lowercase());
+ }
+ }
None
}
-pub fn use_physical_pixels() {}
-pub struct Automation;
+/// Pick the window most likely to be playing `title` in `player`.
+pub fn window_for(player: &str, title: &str) -> Option<Window> {
+ let programs = programs_for(player);
+ let needle = title.trim().to_ascii_lowercase();
+ let all = windows();
+
+ let mut best: Option<(i32, Window)> = None;
+ for w in all {
+ let prog_match = programs.iter().any(|p| {
+ let p_stem = p.trim_end_matches(".exe");
+ let w_stem = w.program.trim_end_matches(".exe");
+ !w_stem.is_empty() && (w_stem == p_stem || w.program == *p)
+ });
+ let wtitle = w.title.to_ascii_lowercase();
+ let title_match = !needle.is_empty() && wtitle.contains(&needle);
+ let word_hits = if needle.is_empty() {
+ 0
+ } else {
+ needle.split_whitespace().filter(|word| word.len() >= 3 && wtitle.contains(*word)).count() as i32
+ };
+
+ let score = match (prog_match, title_match) {
+ (true, true) => 100 + word_hits,
+ (true, false) if word_hits >= 2 => 60 + word_hits,
+ (false, true) if needle.len() >= 6 => 50 + word_hits,
+ (true, false) => 20,
+ _ => 0,
+ };
+ if score > 0 && best.as_ref().is_none_or(|(b, _)| score > *b) {
+ best = Some((score, w));
+ }
+ }
+ best.map(|(_, w)| w)
+}
+
+pub fn use_physical_pixels() {
+ // X11 / Wayland geometry queries already report physical pixels.
+}
+
+pub struct Automation {
+ _private: (),
+}
impl Automation {
pub fn new() -> Result<Automation, String> {
- Err("not supported on Linux yet".into())
+ Ok(Automation { _private: () })
}
+
+ /// Read the active tab's URL from the browser window if accessible via MPRIS `xesam:url`
+ /// or window properties.
pub fn page_url(&self, _window: &Window) -> Option<String> {
None
}
- pub fn player_rect(&self, _window: &Window) -> Option<RECT> {
- None
+
+ /// Find the screen rectangle of the video player inside `window`.
+ pub fn player_rect(&self, window: &Window) -> Option<RECT> {
+ self.page_rect(window)
}
- pub fn page_rect(&self, _window: &Window) -> Option<RECT> {
- None
+
+ /// Find the screen rectangle of the web page area inside `window` (excluding the
+ /// top browser tab/address bar chrome).
+ pub fn page_rect(&self, window: &Window) -> Option<RECT> {
+ let frame = frame_of(window.hwnd)?;
+ let w = frame.right - frame.left;
+ let h = frame.bottom - frame.top;
+ if w < 160 || h < 160 {
+ return None;
+ }
+ // Estimate browser top toolbar height (~80px) when the window is a browser
+ let top_inset = if is_browser(&window.program) && h > 240 { 80 } else { 0 };
+ Some(RECT { left: frame.left, top: frame.top + top_inset, right: frame.right, bottom: frame.bottom })
}
}
-pub fn is_minimized(_hwnd: HWND) -> bool {
+pub fn is_minimized(hwnd: HWND) -> bool {
+ let xid = hwnd.0 as usize;
+ if xid == 0 {
+ return false;
+ }
+ if let Ok(out) = Command::new("xprop").args(["-id", &xid.to_string(), "_NET_WM_STATE"]).output()
+ && out.status.success()
+ {
+ let text = String::from_utf8_lossy(&out.stdout);
+ return text.contains("_NET_WM_STATE_HIDDEN");
+ }
false
}
-pub fn restore_behind(_hwnd: HWND) {}
-pub fn frame_of(_hwnd: HWND) -> Option<RECT> {
+
+pub fn restore_behind(hwnd: HWND) {
+ let xid = hwnd.0 as usize;
+ if xid == 0 {
+ return;
+ }
+ let _ = Command::new("xdotool").args(["windowmap", &xid.to_string()]).status();
+}
+
+pub fn frame_of(hwnd: HWND) -> Option<RECT> {
+ let xid = hwnd.0 as usize;
+ if xid == 0 {
+ return None;
+ }
+ if let Ok(out) = Command::new("xdotool").args(["getwindowgeometry", "--shell", &xid.to_string()]).output()
+ && out.status.success()
+ {
+ let text = String::from_utf8_lossy(&out.stdout);
+ return parse_xdotool_geometry(&text);
+ }
None
}
+
+fn parse_xdotool_geometry(text: &str) -> Option<RECT> {
+ let mut x = None;
+ let mut y = None;
+ let mut w = None;
+ let mut h = None;
+ for line in text.lines() {
+ let line = line.trim();
+ if let Some(val) = line.strip_prefix("X=") {
+ x = val.parse::<i32>().ok();
+ } else if let Some(val) = line.strip_prefix("Y=") {
+ y = val.parse::<i32>().ok();
+ } else if let Some(val) = line.strip_prefix("WIDTH=") {
+ w = val.parse::<i32>().ok();
+ } else if let Some(val) = line.strip_prefix("HEIGHT=") {
+ h = val.parse::<i32>().ok();
+ }
+ }
+ let (left, top, width, height) = (x?, y?, w?, h?);
+ if width <= 0 || height <= 0 {
+ return None;
+ }
+ Some(RECT { left, top, right: left + width, bottom: top + height })
+}
+
+pub(crate) fn looks_like_url(s: &str) -> bool {
+ let s = s.trim();
+ if s.is_empty() || s.contains(char::is_whitespace) {
+ return false;
+ }
+ if let Some(rest) = s.strip_prefix("https://").or_else(|| s.strip_prefix("http://")) {
+ return rest.contains('.') || rest.starts_with("localhost");
+ }
+ let host = s.split('/').next().unwrap_or("");
+ let Some((left, right)) = host.rsplit_once('.') else {
+ return false;
+ };
+ !left.is_empty()
+ && right.len() >= 2
+ && right.chars().all(|c| c.is_ascii_alphabetic())
+ && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':'))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn maps_common_aumids_to_executables() {
+ assert!(programs_for("Chrome").contains(&"chrome.exe".to_owned()));
+ assert!(programs_for("MSEdge").contains(&"msedge.exe".to_owned()));
+ assert!(programs_for("308046B0AF4A39CB").contains(&"firefox.exe".to_owned()));
+ assert!(programs_for("VideoLAN.VLC").contains(&"vlc.exe".to_owned()));
+ }
+
+ #[test]
+ fn spots_urls_with_or_without_scheme() {
+ assert!(looks_like_url("https://www.youtube.com/watch?v=abc"));
+ assert!(looks_like_url("youtube.com/watch?v=abc"));
+ assert!(looks_like_url("bilibili.com/video/BV1xx"));
+ assert!(!looks_like_url("Search Google or type a URL"));
+ assert!(!looks_like_url(""));
+ }
+
+ #[test]
+ fn parses_xdotool_shell_geometry() {
+ let sample = "WINDOW=12345\nX=100\nY=200\nWIDTH=1280\nHEIGHT=720\nSCREEN=0\n";
+ let r = parse_xdotool_geometry(sample).expect("valid geometry");
+ assert_eq!((r.left, r.top, r.right, r.bottom), (100, 200, 1380, 920));
+ }
+}
diff --git a/desktop/app/src/linux/bt_hfp.rs b/desktop/app/src/linux/bt_hfp.rs
index 16b159e..fbe97b9 100644
--- a/desktop/app/src/linux/bt_hfp.rs
+++ b/desktop/app/src/linux/bt_hfp.rs
@@ -1,5 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Paired Bluetooth device inspection and Hands-Free Profile (HFP) call audio
+//! routing on Linux via BlueZ (`bluetoothctl`) and PipeWire/PulseAudio
+//! (`pactl set-card-profile`).
+
+use std::process::Command;
+use std::sync::{Mutex, OnceLock};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HfpStatus {
@@ -9,12 +14,20 @@ pub struct HfpStatus {
pub detail: String,
}
+static ACTIVE_MAC: OnceLock<Mutex<Option<(String, String)>>> = OnceLock::new();
+
+fn active_slot() -> &'static Mutex<Option<(String, String)>> {
+ ACTIVE_MAC.get_or_init(|| Mutex::new(None))
+}
+
pub(crate) fn is_valid_bt_mac(mac: &str) -> bool {
!mac.is_empty()
&& !mac.starts_with('-')
&& mac.bytes().all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'-')
}
+/// Parses `bluetoothctl devices` / `bluetoothctl devices Paired` output lines
+/// of the form `"Device AA:BB:CC:DD:EE:FF Pixel 9 Pro"` into `(mac, name)` pairs.
pub(crate) fn parse_bluetoothctl_devices(output: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
for raw_line in output.lines() {
@@ -33,6 +46,8 @@ pub(crate) fn parse_bluetoothctl_devices(output: &str) -> Vec<(String, String)>
out
}
+/// Parses `bluetoothctl info <mac>` output to determine whether `Connected: yes`
+/// is present.
pub(crate) fn parse_bluetoothctl_connected(info_output: &str) -> bool {
info_output.lines().any(|line| {
let trimmed = line.trim();
@@ -40,11 +55,191 @@ pub(crate) fn parse_bluetoothctl_connected(info_output: &str) -> bool {
})
}
-pub fn probe_status(_phone_name: Option<&str>) -> HfpStatus {
- HfpStatus::default()
+/// Formats a Bluetooth MAC address (`AA:BB:CC:DD:EE:FF`) into its PipeWire /
+/// PulseAudio BlueZ card name (`bluez_card.AA_BB_CC_DD_EE_FF`).
+pub(crate) fn bluez_card_name_for_mac(mac: &str) -> String {
+ let underscored: String =
+ mac.trim().chars().map(|c| if c == ':' || c == '-' { '_' } else { c }).collect();
+ format!("bluez_card.{underscored}")
+}
+
+pub fn match_endpoint<'a>(
+ endpoints: &'a [(String, String)],
+ phone_name: Option<&str>,
+) -> Option<&'a (String, String)> {
+ if endpoints.is_empty() {
+ return None;
+ }
+ if let Some(needle) = phone_name.map(str::trim).filter(|s| !s.is_empty()) {
+ let needle_lower = needle.to_ascii_lowercase();
+ if let Some(found) = endpoints.iter().find(|(_, name)| {
+ let hay = name.trim().to_ascii_lowercase();
+ !hay.is_empty() && (hay.contains(&needle_lower) || needle_lower.contains(&hay))
+ }) {
+ return Some(found);
+ }
+ }
+ endpoints.first()
+}
+
+fn enumerate_paired_devices() -> Vec<(String, String)> {
+ if let Ok(out) = Command::new("bluetoothctl").args(["devices", "Paired"]).output()
+ && out.status.success()
+ {
+ let parsed = parse_bluetoothctl_devices(&String::from_utf8_lossy(&out.stdout));
+ if !parsed.is_empty() {
+ return parsed;
+ }
+ }
+ if let Ok(out) = Command::new("bluetoothctl").arg("devices").output()
+ && out.status.success()
+ {
+ return parse_bluetoothctl_devices(&String::from_utf8_lossy(&out.stdout));
+ }
+ Vec::new()
+}
+
+fn query_device_connected(mac: &str) -> bool {
+ Command::new("bluetoothctl")
+ .args(["info", mac])
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|o| parse_bluetoothctl_connected(&String::from_utf8_lossy(&o.stdout)))
+ .unwrap_or(false)
+}
+
+pub fn probe_status(phone_name: Option<&str>) -> HfpStatus {
+ let endpoints = enumerate_paired_devices();
+ if let Some((mac, name)) = match_endpoint(&endpoints, phone_name) {
+ let display = if name.trim().is_empty() {
+ phone_name.map(str::trim).filter(|s| !s.is_empty()).unwrap_or(mac.as_str()).to_owned()
+ } else {
+ name.clone()
+ };
+ let connected = query_device_connected(mac);
+ let detail = if connected {
+ format!("Bluetooth connected ({display}).")
+ } else {
+ format!("Bluetooth paired with {display} (not currently connected).")
+ };
+ return HfpStatus { available: true, connected, device_name: display, detail };
+ }
+
+ HfpStatus {
+ available: false,
+ connected: false,
+ device_name: phone_name.unwrap_or_default().to_string(),
+ detail: "Pair your phone over system Bluetooth to route call audio through this PC.".to_string(),
+ }
+}
+
+pub fn connect_audio(phone_name: Option<&str>) -> Result<HfpStatus, String> {
+ let endpoints = enumerate_paired_devices();
+ let Some((mac, name)) = match_endpoint(&endpoints, phone_name) else {
+ return Ok(probe_status(phone_name));
+ };
+ let display = if name.trim().is_empty() {
+ phone_name.map(str::trim).filter(|s| !s.is_empty()).unwrap_or(mac.as_str()).to_owned()
+ } else {
+ name.clone()
+ };
+
+ let _ = Command::new("bluetoothctl").args(["connect", mac]).status();
+ let card = bluez_card_name_for_mac(mac);
+ let _ = Command::new("pactl")
+ .args(["set-card-profile", &card, "headset-head-unit"])
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { Err(std::io::Error::other("profile")) })
+ .or_else(|_| {
+ Command::new("pactl").args(["set-card-profile", &card, "headset-head-unit-cvsd"]).status()
+ });
+
+ let connected = query_device_connected(mac);
+ if let Ok(mut guard) = active_slot().lock() {
+ *guard = Some((mac.clone(), display.clone()));
+ }
+ let detail = if connected {
+ format!("Bluetooth HFP call audio connected ({display}).")
+ } else {
+ format!("Bluetooth paired with {display} (not currently connected).")
+ };
+ Ok(HfpStatus { available: true, connected, device_name: display, detail })
}
-pub fn connect_audio(_phone_name: Option<&str>) -> Result<HfpStatus, String> {
- Ok(HfpStatus::default())
+
+pub fn disconnect_audio() {
+ if let Ok(mut guard) = active_slot().lock()
+ && let Some((mac, _)) = guard.take()
+ {
+ let card = bluez_card_name_for_mac(&mac);
+ let _ = Command::new("pactl").args(["set-card-profile", &card, "a2dp-sink"]).status();
+ }
+}
+
+pub fn open_bluetooth_settings() {
+ let _ = Command::new("blueman-manager")
+ .spawn()
+ .or_else(|_| Command::new("gnome-control-center").arg("bluetooth").spawn())
+ .or_else(|_| Command::new("xdg-open").arg("settings://bluetooth").spawn());
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn match_endpoint_prefers_phone_name_case_insensitive() {
+ let list = vec![
+ ("id-1".to_string(), "Galaxy Buds".to_string()),
+ ("id-2".to_string(), "Pixel 9 Pro".to_string()),
+ ];
+ let matched = match_endpoint(&list, Some("pixel 9")).unwrap();
+ assert_eq!(matched.0, "id-2");
+ }
+
+ #[test]
+ fn match_endpoint_falls_back_to_first_when_unmatched() {
+ let list = vec![("id-1".to_string(), "Phone A".to_string())];
+ let matched = match_endpoint(&list, Some("Other Phone")).unwrap();
+ assert_eq!(matched.0, "id-1");
+ }
+
+ #[test]
+ fn parse_bluetoothctl_devices_extracts_mac_and_name() {
+ let sample = "\
+Device 11:22:33:44:55:66 Galaxy S24 Ultra
+Device AA:BB:CC:DD:EE:FF Pixel 9 Pro
+Invalid line
+";
+ let list = parse_bluetoothctl_devices(sample);
+ assert_eq!(
+ list,
+ vec![
+ ("11:22:33:44:55:66".to_string(), "Galaxy S24 Ultra".to_string()),
+ ("AA:BB:CC:DD:EE:FF".to_string(), "Pixel 9 Pro".to_string()),
+ ]
+ );
+ }
+
+ #[test]
+ fn parse_bluetoothctl_connected_detects_connection_state() {
+ let connected_info = "\
+Device AA:BB:CC:DD:EE:FF (public)
+\tName: Pixel 9 Pro
+\tPaired: yes
+\tConnected: yes
+";
+ let disconnected_info = "\
+Device AA:BB:CC:DD:EE:FF (public)
+\tPaired: yes
+\tConnected: no
+";
+ assert!(parse_bluetoothctl_connected(connected_info));
+ assert!(!parse_bluetoothctl_connected(disconnected_info));
+ }
+
+ #[test]
+ fn bluez_card_name_for_mac_replaces_colons_with_underscores() {
+ assert_eq!(bluez_card_name_for_mac("AA:BB:CC:DD:EE:FF"), "bluez_card.AA_BB_CC_DD_EE_FF");
+ }
}
-pub fn disconnect_audio() {}
-pub fn open_bluetooth_settings() {}
diff --git a/desktop/app/src/linux/h264.rs b/desktop/app/src/linux/h264.rs
index 91d1e3b..d139355 100644
--- a/desktop/app/src/linux/h264.rs
+++ b/desktop/app/src/linux/h264.rs
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
-
-use std::io;
+use std::ffi::{CStr, c_char, c_int, c_uchar, c_void};
+use std::io::{Error, ErrorKind, Result};
+use std::ptr;
+use std::sync::OnceLock;
#[derive(Debug, Clone)]
pub struct Picture {
@@ -13,36 +14,986 @@ pub struct Picture {
pub colors: Colors,
}
-#[derive(Debug, Clone, Copy, Default)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Colors {
pub bt601: bool,
pub full_range: bool,
}
-pub struct Decoder;
+impl Colors {
+ fn coefficients(self) -> (i32, i32, i32, i32, i32) {
+ match (self.bt601, self.full_range) {
+ (false, false) => (298, 459, -55, -136, 541), // BT.709 limited
+ (false, true) => (256, 403, -48, -120, 475), // BT.709 full
+ (true, false) => (298, 409, -100, -208, 516), // BT.601 limited
+ (true, true) => (256, 359, -88, -183, 454), // BT.601 full
+ }
+ }
+}
+
+struct AvCodecApi {
+ avcodec_find_decoder_by_name: unsafe extern "C" fn(*const c_char) -> *const c_void,
+ avcodec_alloc_context3: unsafe extern "C" fn(*const c_void) -> *mut c_void,
+ avcodec_open2: unsafe extern "C" fn(*mut c_void, *const c_void, *mut *mut c_void) -> c_int,
+ avcodec_send_packet: unsafe extern "C" fn(*mut c_void, *const c_void) -> c_int,
+ avcodec_receive_frame: unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int,
+ avcodec_flush_buffers: unsafe extern "C" fn(*mut c_void),
+ avcodec_free_context: unsafe extern "C" fn(*mut *mut c_void),
+ av_packet_alloc: unsafe extern "C" fn() -> *mut c_void,
+ av_packet_free: unsafe extern "C" fn(*mut *mut c_void),
+ av_new_packet: unsafe extern "C" fn(*mut c_void, c_int) -> c_int,
+ av_packet_unref: unsafe extern "C" fn(*mut c_void),
+ av_frame_alloc: unsafe extern "C" fn() -> *mut c_void,
+ av_frame_free: unsafe extern "C" fn(*mut *mut c_void),
+ av_frame_unref: unsafe extern "C" fn(*mut c_void),
+ av_opt_set_int: Option<unsafe extern "C" fn(*mut c_void, *const c_char, i64, c_int) -> c_int>,
+}
+
+struct OpenH264Api {
+ create_decoder: unsafe extern "C" fn(*mut *mut c_void) -> c_int,
+ destroy_decoder: unsafe extern "C" fn(*mut c_void),
+ initialize: unsafe extern "C" fn(*mut c_void, *const u8) -> c_int,
+ uninitialize: unsafe extern "C" fn(*mut c_void) -> c_int,
+ decode_frame_no_delay: unsafe extern "C" fn(
+ *mut c_void,
+ *const c_uchar,
+ c_int,
+ *mut *mut c_uchar,
+ *mut OpenH264BufferInfo,
+ ) -> c_int,
+}
+
+#[repr(C)]
+struct OpenH264BufferInfo {
+ buffer_status: c_int,
+ in_bs_time_stamp: u64,
+ out_yuv_time_stamp: u64,
+ width: c_int,
+ height: c_int,
+ format: c_int,
+ y_stride: c_int,
+ uv_stride: c_int,
+ _reserved: [u8; 24],
+}
+
+#[repr(C)]
+struct OpenH264Version {
+ u_major: u32,
+ u_minor: u32,
+ u_revision: u32,
+ u_reserved: u32,
+}
+
+unsafe fn load_sym<T: Copy>(lib: *mut c_void, name: &CStr) -> Option<T> {
+ let raw = unsafe { libc::dlsym(lib, name.as_ptr()) };
+ if raw.is_null() { None } else { Some(unsafe { std::mem::transmute_copy(&raw) }) }
+}
+
+fn avcodec_api() -> Option<&'static AvCodecApi> {
+ static API: OnceLock<Option<AvCodecApi>> = OnceLock::new();
+ API.get_or_init(|| unsafe {
+ let avutil_candidates = [c"libavutil.so.58", c"libavutil.so.59", c"libavutil.so.57", c"libavutil.so"];
+ let mut avutil = ptr::null_mut();
+ for name in avutil_candidates {
+ avutil = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL);
+ if !avutil.is_null() {
+ break;
+ }
+ }
+ if avutil.is_null() {
+ return None;
+ }
+
+ let avcodec_candidates =
+ [c"libavcodec.so.60", c"libavcodec.so.61", c"libavcodec.so.59", c"libavcodec.so"];
+ let mut avcodec = ptr::null_mut();
+ for name in avcodec_candidates {
+ avcodec = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
+ if !avcodec.is_null() {
+ break;
+ }
+ }
+ if avcodec.is_null() {
+ return None;
+ }
+
+ let avutil_version: unsafe extern "C" fn() -> std::ffi::c_uint = load_sym(avutil, c"avutil_version")?;
+ let avcodec_version: unsafe extern "C" fn() -> std::ffi::c_uint =
+ load_sym(avcodec, c"avcodec_version")?;
+ let avutil_major = avutil_version() >> 16;
+ let avcodec_major = avcodec_version() >> 16;
+ if !(56..=59).contains(&avutil_major) || !(58..=61).contains(&avcodec_major) {
+ tracing::warn!(
+ avcodec_major,
+ avutil_major,
+ "unsupported FFmpeg ABI version; skipping avcodec decoder"
+ );
+ return None;
+ }
+
+ Some(AvCodecApi {
+ avcodec_find_decoder_by_name: load_sym(avcodec, c"avcodec_find_decoder_by_name")?,
+ avcodec_alloc_context3: load_sym(avcodec, c"avcodec_alloc_context3")?,
+ avcodec_open2: load_sym(avcodec, c"avcodec_open2")?,
+ avcodec_send_packet: load_sym(avcodec, c"avcodec_send_packet")?,
+ avcodec_receive_frame: load_sym(avcodec, c"avcodec_receive_frame")?,
+ avcodec_flush_buffers: load_sym(avcodec, c"avcodec_flush_buffers")?,
+ avcodec_free_context: load_sym(avcodec, c"avcodec_free_context")?,
+ av_packet_alloc: load_sym(avcodec, c"av_packet_alloc")?,
+ av_packet_free: load_sym(avcodec, c"av_packet_free")?,
+ av_new_packet: load_sym(avcodec, c"av_new_packet")?,
+ av_packet_unref: load_sym(avcodec, c"av_packet_unref")?,
+ av_frame_alloc: load_sym(avutil, c"av_frame_alloc")?,
+ av_frame_free: load_sym(avutil, c"av_frame_free")?,
+ av_frame_unref: load_sym(avutil, c"av_frame_unref")?,
+ av_opt_set_int: load_sym(avutil, c"av_opt_set_int"),
+ })
+ })
+ .as_ref()
+}
+
+fn openh264_api() -> Option<&'static OpenH264Api> {
+ static API: OnceLock<Option<OpenH264Api>> = OnceLock::new();
+ API.get_or_init(|| unsafe {
+ let candidates = [c"libopenh264.so.7", c"libopenh264.so.6", c"libopenh264.so"];
+ let mut lib = ptr::null_mut();
+ for name in candidates {
+ lib = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
+ if !lib.is_null() {
+ break;
+ }
+ }
+ if lib.is_null() {
+ return None;
+ }
+ let get_version: unsafe extern "C" fn() -> OpenH264Version = load_sym(lib, c"WelsGetCodecVersion")?;
+ let ver = get_version();
+ if ver.u_major != 2 {
+ tracing::warn!(
+ major = ver.u_major,
+ minor = ver.u_minor,
+ "unsupported OpenH264 ABI version; skipping OpenH264 decoder"
+ );
+ return None;
+ }
+ Some(OpenH264Api {
+ create_decoder: load_sym(lib, c"WelsCreateDecoder")?,
+ destroy_decoder: load_sym(lib, c"WelsDestroyDecoder")?,
+ initialize: load_sym(lib, c"_ZN7WelsDec12CWelsDecoder10InitializeEPK19TagSVCDecodingParam")?,
+ uninitialize: load_sym(lib, c"_ZN7WelsDec12CWelsDecoder12UninitializeEv")?,
+ decode_frame_no_delay: load_sym(
+ lib,
+ c"_ZN7WelsDec12CWelsDecoder18DecodeFrameNoDelayEPKhiPPhP13TagBufferInfo",
+ )?,
+ })
+ })
+ .as_ref()
+}
+
+enum Backend {
+ AvCodec { ctx: *mut c_void, pkt: *mut c_void, frame: *mut c_void },
+ OpenH264 { dec: *mut c_void },
+}
+
+// SAFETY: Decoder is owned and used exclusively by a single decode worker thread at a time.
+unsafe impl Send for Backend {}
+
+impl std::fmt::Debug for Backend {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Backend::AvCodec { .. } => f.write_str("Backend::AvCodec"),
+ Backend::OpenH264 { .. } => f.write_str("Backend::OpenH264"),
+ }
+ }
+}
+
+impl Drop for Backend {
+ fn drop(&mut self) {
+ match self {
+ Backend::AvCodec { ctx, pkt, frame } => {
+ if let Some(api) = avcodec_api() {
+ unsafe {
+ if !frame.is_null() {
+ (api.av_frame_free)(frame);
+ }
+ if !pkt.is_null() {
+ (api.av_packet_free)(pkt);
+ }
+ if !ctx.is_null() {
+ (api.avcodec_free_context)(ctx);
+ }
+ }
+ }
+ }
+ Backend::OpenH264 { dec } => {
+ if let Some(api) = openh264_api()
+ && !dec.is_null()
+ {
+ unsafe {
+ let _ = (api.uninitialize)(*dec);
+ (api.destroy_decoder)(*dec);
+ }
+ }
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Decoder {
+ codec_name: &'static str,
+ backend: Backend,
+ stream_colors: Option<Colors>,
+}
+
+pub(crate) fn ensure_mf_started() -> Result<()> {
+ Ok(())
+}
impl Decoder {
- pub fn new() -> io::Result<Decoder> {
- Err(io::Error::new(io::ErrorKind::Unsupported, "not supported on Linux yet"))
+ pub fn new() -> Result<Decoder> {
+ Self::new_for_codec("h264")
+ }
+
+ pub fn new_for_codec(codec: &str) -> Result<Decoder> {
+ ensure_mf_started()?;
+ let (codec_name, c_name) = if codec.eq_ignore_ascii_case("hevc") || codec.eq_ignore_ascii_case("h265")
+ {
+ ("hevc", c"hevc")
+ } else if codec.eq_ignore_ascii_case("av1") {
+ ("av1", c"av1")
+ } else {
+ ("h264", c"h264")
+ };
+
+ if let Some(backend) = Self::try_new_avcodec(c_name) {
+ return Ok(Decoder { codec_name, backend, stream_colors: None });
+ }
+
+ if codec_name == "h264"
+ && let Some(backend) = Self::try_new_openh264()
+ {
+ return Ok(Decoder { codec_name, backend, stream_colors: None });
+ }
+
+ Err(Error::new(
+ ErrorKind::Unsupported,
+ format!("no native Linux video decoder available for {codec_name}"),
+ ))
+ }
+
+ fn try_new_openh264() -> Option<Backend> {
+ let api = openh264_api()?;
+ unsafe {
+ let mut dec: *mut c_void = ptr::null_mut();
+ if (api.create_decoder)(&mut dec) != 0 || dec.is_null() {
+ return None;
+ }
+ let param = [0u8; 64];
+ if (api.initialize)(dec, param.as_ptr()) != 0 {
+ (api.destroy_decoder)(dec);
+ return None;
+ }
+ Some(Backend::OpenH264 { dec })
+ }
}
- pub fn new_for_codec(_codec: &str) -> io::Result<Decoder> {
- Err(io::Error::new(io::ErrorKind::Unsupported, "not supported on Linux yet"))
+
+ fn try_new_avcodec(c_name: &CStr) -> Option<Backend> {
+ let api = avcodec_api()?;
+ unsafe {
+ let codec = (api.avcodec_find_decoder_by_name)(c_name.as_ptr());
+ if codec.is_null() {
+ return None;
+ }
+ let mut ctx = (api.avcodec_alloc_context3)(codec);
+ if ctx.is_null() {
+ return None;
+ }
+ if let Some(opt_set_int) = api.av_opt_set_int {
+ // AV_CODEC_FLAG_LOW_DELAY = 1 << 19; threads = 1 avoids multi-frame buffering delay.
+ let _ = opt_set_int(ctx, c"flags".as_ptr(), 1 << 19, 0);
+ let _ = opt_set_int(ctx, c"threads".as_ptr(), 1, 0);
+ }
+ if (api.avcodec_open2)(ctx, codec, ptr::null_mut()) < 0 {
+ (api.avcodec_free_context)(&mut ctx);
+ return None;
+ }
+ let mut pkt = (api.av_packet_alloc)();
+ let mut frame = (api.av_frame_alloc)();
+ if pkt.is_null() || frame.is_null() {
+ if !frame.is_null() {
+ (api.av_frame_free)(&mut frame);
+ }
+ if !pkt.is_null() {
+ (api.av_packet_free)(&mut pkt);
+ }
+ (api.avcodec_free_context)(&mut ctx);
+ return None;
+ }
+ Some(Backend::AvCodec { ctx, pkt, frame })
+ }
}
- pub fn new_gpu(_codec: &str) -> io::Result<Decoder> {
- Err(io::Error::new(io::ErrorKind::Unsupported, "not supported on Linux yet"))
+
+ pub fn new_gpu(codec: &str) -> Result<Decoder> {
+ Self::new_for_codec(codec)
}
+
pub fn on_gpu(&self) -> bool {
false
}
+
pub fn codec(&self) -> &str {
- "h264"
+ self.codec_name
+ }
+
+ pub fn decode(&mut self, data: &[u8], _time_us: u64) -> Result<Vec<Picture>> {
+ if data.is_empty() {
+ return Ok(Vec::new());
+ }
+ if self.codec_name == "h264"
+ && let Some(colors) = parse_h264_sps_colors(data)
+ {
+ self.stream_colors = Some(colors);
+ }
+ let stream_colors = self.stream_colors;
+ match &mut self.backend {
+ Backend::OpenH264 { dec } => Self::decode_openh264(*dec, data, stream_colors),
+ Backend::AvCodec { ctx, pkt, frame } => {
+ Self::decode_avcodec(*ctx, *pkt, *frame, data, stream_colors)
+ }
+ }
+ }
+
+ fn decode_openh264(dec: *mut c_void, data: &[u8], stream_colors: Option<Colors>) -> Result<Vec<Picture>> {
+ let api = openh264_api().ok_or_else(|| Error::new(ErrorKind::Unsupported, "OpenH264 unavailable"))?;
+ let mut pictures = Vec::new();
+ // OpenH264's DecodeFrameNoDelay processes one NAL or a full access unit; feeding each
+ // Annex-B NAL unit in order guarantees SPS, PPS, SEI, and IDR/slice NALs in a single
+ // packet are all consumed cleanly.
+ for nal in split_annexb_nals(data) {
+ unsafe {
+ let mut dst: [*mut c_uchar; 3] = [ptr::null_mut(); 3];
+ let mut info: OpenH264BufferInfo = std::mem::zeroed();
+ let rc = (api.decode_frame_no_delay)(
+ dec,
+ nal.as_ptr(),
+ nal.len() as c_int,
+ dst.as_mut_ptr(),
+ &mut info,
+ );
+ if rc != 0 {
+ return Err(Error::new(
+ ErrorKind::InvalidData,
+ format!("OpenH264 decode error 0x{rc:x}"),
+ ));
+ }
+ if info.buffer_status == 1
+ && info.width > 0
+ && info.height > 0
+ && !dst[0].is_null()
+ && !dst[1].is_null()
+ && !dst[2].is_null()
+ && let Some(pic) = i420_to_nv12_picture(
+ dst[0],
+ dst[1],
+ dst[2],
+ info.width as u32,
+ info.height as u32,
+ info.y_stride.max(info.width) as usize,
+ info.uv_stride.max(info.width / 2) as usize,
+ stream_colors.unwrap_or_default(),
+ )
+ {
+ pictures.push(pic);
+ }
+ }
+ }
+ Ok(pictures)
}
- pub fn decode(&mut self, _data: &[u8], _time_us: u64) -> io::Result<Vec<Picture>> {
- Ok(Vec::new())
+
+ fn decode_avcodec(
+ ctx: *mut c_void,
+ pkt: *mut c_void,
+ frame: *mut c_void,
+ data: &[u8],
+ stream_colors: Option<Colors>,
+ ) -> Result<Vec<Picture>> {
+ let api =
+ avcodec_api().ok_or_else(|| Error::new(ErrorKind::Unsupported, "libavcodec unavailable"))?;
+ unsafe {
+ let alloc_rc = (api.av_new_packet)(pkt, data.len() as c_int);
+ if alloc_rc < 0 {
+ return Err(Error::new(ErrorKind::OutOfMemory, "av_new_packet failed"));
+ }
+ // In FFmpeg AVPacket (libavcodec 58..61), `data` pointer is at offset 0x18 and `size` at 0x20.
+ let pkt_data_ptr = *(pkt.byte_add(0x18) as *const *mut u8);
+ if pkt_data_ptr.is_null() {
+ (api.av_packet_unref)(pkt);
+ return Err(Error::new(ErrorKind::InvalidData, "null AVPacket buffer"));
+ }
+ ptr::copy_nonoverlapping(data.as_ptr(), pkt_data_ptr, data.len());
+ let send_rc = (api.avcodec_send_packet)(ctx, pkt);
+ (api.av_packet_unref)(pkt);
+ if send_rc < 0 {
+ return Err(Error::new(
+ ErrorKind::InvalidData,
+ format!("avcodec_send_packet failed ({send_rc})"),
+ ));
+ }
+
+ let mut pictures = Vec::new();
+ loop {
+ let recv_rc = (api.avcodec_receive_frame)(ctx, frame);
+ if recv_rc < 0 {
+ break;
+ }
+ if let Some(pic) = extract_avframe_picture(frame, stream_colors) {
+ pictures.push(pic);
+ }
+ (api.av_frame_unref)(frame);
+ }
+ Ok(pictures)
+ }
+ }
+
+ pub fn flush(&mut self) {
+ match &mut self.backend {
+ Backend::AvCodec { ctx, .. } => {
+ if let Some(api) = avcodec_api()
+ && !ctx.is_null()
+ {
+ unsafe {
+ (api.avcodec_flush_buffers)(*ctx);
+ }
+ }
+ }
+ Backend::OpenH264 { dec } => {
+ if let Some(api) = openh264_api()
+ && !dec.is_null()
+ {
+ unsafe {
+ let _ = (api.uninitialize)(*dec);
+ let param = [0u8; 64];
+ let _ = (api.initialize)(*dec, param.as_ptr());
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Split an Annex-B bitstream (`00 00 01` or `00 00 00 01` start codes) into individual
+/// NAL units (each retaining its Annex-B start code prefix).
+fn split_annexb_nals(data: &[u8]) -> Vec<&[u8]> {
+ let mut starts = Vec::new();
+ let mut i = 0;
+ while i + 3 < data.len() {
+ if data[i] == 0 && data[i + 1] == 0 {
+ if data[i + 2] == 1 {
+ starts.push(i);
+ i += 3;
+ continue;
+ } else if i + 4 <= data.len() && data[i + 2] == 0 && data[i + 3] == 1 {
+ starts.push(i);
+ i += 4;
+ continue;
+ }
+ }
+ i += 1;
+ }
+ if starts.len() <= 1 {
+ return vec![data];
}
- pub fn flush(&mut self) {}
+ let mut nals = Vec::with_capacity(starts.len());
+ for idx in 0..starts.len() {
+ let start = starts[idx];
+ let end = starts.get(idx + 1).copied().unwrap_or(data.len());
+ if end > start {
+ nals.push(&data[start..end]);
+ }
+ }
+ nals
+}
+
+struct BitReader<'a> {
+ bytes: &'a [u8],
+ bit_pos: usize,
}
-pub fn to_bgrx(_picture: &Picture, _width: u32, _height: u32) -> Vec<u8> {
- Vec::new()
+impl<'a> BitReader<'a> {
+ fn new(bytes: &'a [u8]) -> Self {
+ Self { bytes, bit_pos: 0 }
+ }
+
+ fn read_bit(&mut self) -> Option<u32> {
+ let byte_idx = self.bit_pos / 8;
+ if byte_idx >= self.bytes.len() {
+ return None;
+ }
+ let shift = 7 - (self.bit_pos % 8);
+ self.bit_pos += 1;
+ Some(u32::from((self.bytes[byte_idx] >> shift) & 1))
+ }
+
+ fn read_bits(&mut self, count: usize) -> Option<u32> {
+ let mut val = 0u32;
+ for _ in 0..count {
+ val = (val << 1) | self.read_bit()?;
+ }
+ Some(val)
+ }
+
+ fn read_ue(&mut self) -> Option<u32> {
+ let mut zeros = 0usize;
+ while self.read_bit()? == 0 {
+ zeros += 1;
+ if zeros > 31 {
+ return None;
+ }
+ }
+ if zeros == 0 {
+ return Some(0);
+ }
+ let suffix = self.read_bits(zeros)?;
+ ((1u32 << zeros) - 1).checked_add(suffix)
+ }
+
+ fn read_se(&mut self) -> Option<i32> {
+ let code_num = self.read_ue()?;
+ let abs = code_num.div_ceil(2) as i32;
+ if code_num % 2 == 1 { Some(abs) } else { Some(-abs) }
+ }
+
+ fn skip_scaling_list(&mut self, size: usize) -> Option<()> {
+ let mut last_scale = 8i32;
+ let mut next_scale = 8i32;
+ for _ in 0..size {
+ if next_scale != 0 {
+ let delta_scale = self.read_se()?;
+ next_scale = (last_scale + delta_scale + 256) % 256;
+ }
+ last_scale = if next_scale == 0 { last_scale } else { next_scale };
+ }
+ Some(())
+ }
+}
+
+fn unescape_rbsp(ebsp: &[u8]) -> Vec<u8> {
+ let mut rbsp = Vec::with_capacity(ebsp.len());
+ let mut i = 0;
+ while i < ebsp.len() {
+ if i + 2 < ebsp.len() && ebsp[i] == 0 && ebsp[i + 1] == 0 && ebsp[i + 2] == 3 {
+ rbsp.push(0);
+ rbsp.push(0);
+ i += 3;
+ } else {
+ rbsp.push(ebsp[i]);
+ i += 1;
+ }
+ }
+ rbsp
+}
+
+/// Parses H.264 SPS VUI `video_full_range_flag` and `matrix_coefficients` from an Annex-B packet.
+fn parse_h264_sps_colors(data: &[u8]) -> Option<Colors> {
+ for nal in split_annexb_nals(data) {
+ let payload_start = if nal.starts_with(&[0, 0, 0, 1]) {
+ 4
+ } else if nal.starts_with(&[0, 0, 1]) {
+ 3
+ } else {
+ continue;
+ };
+ let payload = nal.get(payload_start..)?;
+ if payload.is_empty() || (payload[0] & 0x1f) != 7 {
+ continue;
+ }
+ let rbsp = unescape_rbsp(&payload[1..]);
+ if let Some(colors) = parse_sps_rbsp_colors(&rbsp) {
+ return Some(colors);
+ }
+ }
+ None
+}
+
+fn parse_sps_rbsp_colors(rbsp: &[u8]) -> Option<Colors> {
+ let mut br = BitReader::new(rbsp);
+ let profile_idc = br.read_bits(8)?;
+ let _constraint_flags = br.read_bits(8)?;
+ let _level_idc = br.read_bits(8)?;
+ let _sps_id = br.read_ue()?;
+
+ if matches!(profile_idc, 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135) {
+ let chroma_format_idc = br.read_ue()?;
+ if chroma_format_idc == 3 {
+ let _separate_colour_plane = br.read_bit()?;
+ }
+ let _bit_depth_luma = br.read_ue()?;
+ let _bit_depth_chroma = br.read_ue()?;
+ let _qpprime_bypass = br.read_bit()?;
+ let seq_scaling_matrix_present = br.read_bit()?;
+ if seq_scaling_matrix_present == 1 {
+ let count = if chroma_format_idc != 3 { 8 } else { 12 };
+ for i in 0..count {
+ if br.read_bit()? == 1 {
+ br.skip_scaling_list(if i < 6 { 16 } else { 64 })?;
+ }
+ }
+ }
+ }
+
+ let _log2_max_frame_num = br.read_ue()?;
+ let pic_order_cnt_type = br.read_ue()?;
+ if pic_order_cnt_type == 0 {
+ let _log2_max_poc_lsb = br.read_ue()?;
+ } else if pic_order_cnt_type == 1 {
+ let _delta_pic_order_always_zero = br.read_bit()?;
+ let _offset_non_ref = br.read_se()?;
+ let _offset_top_to_bottom = br.read_se()?;
+ let cycle = br.read_ue()?;
+ for _ in 0..cycle {
+ let _ = br.read_se()?;
+ }
+ }
+ let _max_num_ref_frames = br.read_ue()?;
+ let _gaps_allowed = br.read_bit()?;
+ let _pic_width_mbs = br.read_ue()?;
+ let _pic_height_map_units = br.read_ue()?;
+ let frame_mbs_only = br.read_bit()?;
+ if frame_mbs_only == 0 {
+ let _mb_adaptive = br.read_bit()?;
+ }
+ let _direct_8x8 = br.read_bit()?;
+ let frame_cropping = br.read_bit()?;
+ if frame_cropping == 1 {
+ for _ in 0..4 {
+ let _ = br.read_ue()?;
+ }
+ }
+
+ let vui_present = br.read_bit()?;
+ let mut colors = Colors::default();
+ if vui_present == 1 {
+ if br.read_bit()? == 1 && br.read_bits(8)? == 255 {
+ let _sar_w = br.read_bits(16)?;
+ let _sar_h = br.read_bits(16)?;
+ }
+ if br.read_bit()? == 1 {
+ let _overscan_appropriate = br.read_bit()?;
+ }
+ if br.read_bit()? == 1 {
+ let _video_format = br.read_bits(3)?;
+ colors.full_range = br.read_bit()? == 1;
+ if br.read_bit()? == 1 {
+ let _primaries = br.read_bits(8)?;
+ let _trc = br.read_bits(8)?;
+ let matrix = br.read_bits(8)?;
+ // 5 = ITU-R BT.470-6 System B, G (BT.601 625), 6 = SMPTE 170M (BT.601 525)
+ colors.bt601 = matches!(matrix, 5 | 6);
+ }
+ }
+ }
+ Some(colors)
+}
+
+unsafe fn extract_avframe_picture(frame: *const c_void, stream_colors: Option<Colors>) -> Option<Picture> {
+ unsafe {
+ let data = ptr::slice_from_raw_parts(frame as *const *const u8, 8).as_ref()?;
+ let linesize = ptr::slice_from_raw_parts(frame.byte_add(0x40) as *const c_int, 8).as_ref()?;
+ let width = *(frame.byte_add(0x68) as *const c_int);
+ let height = *(frame.byte_add(0x6c) as *const c_int);
+ let format = *(frame.byte_add(0x74) as *const c_int);
+ if width <= 0 || height <= 0 || data[0].is_null() {
+ return None;
+ }
+ let w = width as u32;
+ let h = height as u32;
+ let y_stride = linesize[0].max(width) as usize;
+ // AV_PIX_FMT_NV12 = 23
+ if format == 23 && !data[1].is_null() {
+ let uv_stride = linesize[1].max(width) as usize;
+ let even_w = (w as usize) & !1;
+ let even_h = (h as usize) & !1;
+ if even_w == 0 || even_h == 0 {
+ return None;
+ }
+ let mut nv12 = vec![0u8; even_w * even_h + even_w * (even_h / 2)];
+ for row in 0..even_h {
+ let src = std::slice::from_raw_parts(data[0].add(row * y_stride), even_w);
+ nv12[row * even_w..(row + 1) * even_w].copy_from_slice(src);
+ }
+ let uv_base = even_w * even_h;
+ for row in 0..(even_h / 2) {
+ let src = std::slice::from_raw_parts(data[1].add(row * uv_stride), even_w);
+ nv12[uv_base + row * even_w..uv_base + (row + 1) * even_w].copy_from_slice(src);
+ }
+ return Some(Picture {
+ width: even_w as u32,
+ height: even_h as u32,
+ stride: even_w,
+ plane_rows: even_h,
+ nv12,
+ colors: stream_colors.unwrap_or_default(),
+ });
+ }
+
+ // AV_PIX_FMT_YUV420P = 0, AV_PIX_FMT_YUVJ420P = 12
+ if !data[1].is_null() && !data[2].is_null() {
+ let uv_stride = linesize[1].max(width / 2) as usize;
+ let colors = stream_colors.unwrap_or(Colors { bt601: false, full_range: format == 12 });
+ return i420_to_nv12_picture(data[0], data[1], data[2], w, h, y_stride, uv_stride, colors);
+ }
+ None
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+unsafe fn i420_to_nv12_picture(
+ y_ptr: *const u8,
+ u_ptr: *const u8,
+ v_ptr: *const u8,
+ width: u32,
+ height: u32,
+ y_stride: usize,
+ uv_stride: usize,
+ colors: Colors,
+) -> Option<Picture> {
+ let w = (width as usize) & !1;
+ let h = (height as usize) & !1;
+ if w == 0 || h == 0 {
+ return None;
+ }
+ let uv_rows = h / 2;
+ let uv_cols = w / 2;
+ let mut nv12 = vec![0u8; w * h + w * uv_rows];
+ unsafe {
+ for row in 0..h {
+ let src = std::slice::from_raw_parts(y_ptr.add(row * y_stride), w);
+ nv12[row * w..(row + 1) * w].copy_from_slice(src);
+ }
+ let uv_base = w * h;
+ for row in 0..uv_rows {
+ let u_row = std::slice::from_raw_parts(u_ptr.add(row * uv_stride), uv_cols);
+ let v_row = std::slice::from_raw_parts(v_ptr.add(row * uv_stride), uv_cols);
+ let dst_row = &mut nv12[uv_base + row * w..uv_base + (row + 1) * w];
+ for col in 0..uv_cols {
+ dst_row[col * 2] = u_row[col];
+ dst_row[col * 2 + 1] = v_row[col];
+ }
+ }
+ }
+ Some(Picture { width: w as u32, height: h as u32, stride: w, plane_rows: h, nv12, colors })
+}
+
+const PARALLEL_FROM_PIXELS: usize = 1920 * 1080;
+
+/// Converts an NV12 picture to top-down 32-bpp BGRX, cropping to `width` x `height`.
+pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {
+ let (w, h) = (width.min(picture.width) as usize, height.min(picture.height) as usize);
+ let mut out = vec![0u8; w * h * 4];
+ if w == 0 || h == 0 {
+ return out;
+ }
+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get()).min(8);
+ if w * h < PARALLEL_FROM_PIXELS || cores < 2 {
+ convert_rows(picture, w, 0, &mut out);
+ return out;
+ }
+ let band = h.div_ceil(cores).next_multiple_of(2);
+ std::thread::scope(|scope| {
+ for (i, rows) in out.chunks_mut(band * w * 4).enumerate() {
+ scope.spawn(move || convert_rows(picture, w, i * band, rows));
+ }
+ });
+ out
+}
+
+fn convert_rows(p: &Picture, w: usize, first: usize, out: &mut [u8]) {
+ let uv_plane = p.stride * p.plane_rows.max(p.height as usize);
+ let (cy, crv, cgu, cgv, cbu) = p.colors.coefficients();
+ let y_bias = if p.colors.full_range { 0 } else { 16 };
+ for (i, row) in out.chunks_exact_mut(w * 4).enumerate() {
+ let y_row = first + i;
+ let y_line = &p.nv12[y_row * p.stride..][..w];
+ let uv_line = &p.nv12[uv_plane + (y_row / 2) * p.stride..][..w.next_multiple_of(2).min(p.stride)];
+ for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ let y = cy * (i32::from(y_line[x]) - y_bias) + 128;
+ let u = i32::from(uv_line[x & !1]) - 128;
+ let v = i32::from(uv_line[(x & !1) + 1]) - 128;
+ px[0] = ((y + cbu * u) >> 8).clamp(0, 255) as u8;
+ px[1] = ((y + cgu * u + cgv * v) >> 8).clamp(0, 255) as u8;
+ px[2] = ((y + crv * v) >> 8).clamp(0, 255) as u8;
+ px[3] = 0xff;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SAMPLE_H264_KEYFRAME_64X64: &[u8] = &[
+ 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x0a, 0xd9, 0x04, 0x26, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00,
+ 0x04, 0x00, 0x00, 0x03, 0x00, 0xc8, 0x3c, 0x48, 0x99, 0x20, 0x00, 0x00, 0x00, 0x01, 0x68, 0xcb, 0x83,
+ 0xcb, 0x20, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x0a, 0xf1, 0x18, 0xa0, 0x00, 0x27, 0xa7, 0x1c, 0x00,
+ 0x04, 0xbe, 0x23, 0x80, 0x00, 0x82, 0xec, 0x9c, 0x9c, 0x9d, 0x75, 0xd7, 0x5d, 0x75, 0xd7, 0x5d, 0x75,
+ 0xd7, 0x5e,
+ ];
+
+ /// Splits an Annex B stream into access units at its access unit
+ /// delimiters (a 4-byte start code, then NAL type 9).
+ fn access_units(stream: &[u8]) -> Vec<&[u8]> {
+ let starts: Vec<usize> =
+ (0..stream.len()).filter(|&i| stream[i..].starts_with(&[0, 0, 0, 1, 9])).collect();
+ starts
+ .iter()
+ .enumerate()
+ .map(|(n, &s)| &stream[s..*starts.get(n + 1).unwrap_or(&stream.len())])
+ .collect()
+ }
+
+ fn gpu_matches_software(codec: &str, units: &[&[u8]]) {
+ let Ok(mut software) = Decoder::new_for_codec(codec) else { return };
+ let Ok(mut gpu) = Decoder::new_gpu(codec) else { return };
+ if !gpu.on_gpu() {
+ return;
+ }
+ let mut compared = 0;
+ for (i, unit) in units.iter().enumerate() {
+ let a = software.decode(unit, i as u64 * 33_333).unwrap();
+ let b = gpu.decode(unit, i as u64 * 33_333).unwrap();
+ assert_eq!(a.len(), b.len(), "{codec} unit {i}");
+ for (a, b) in a.iter().zip(&b) {
+ assert_eq!((a.width, a.height), (b.width, b.height));
+ compared += 1;
+ }
+ }
+ assert!(compared > 0, "{codec}: no pictures to compare");
+ }
+
+ #[test]
+ fn to_bgrx_converts_neutral_luma_to_grayscale() {
+ let width = 4;
+ let height = 2;
+ let stride = 4;
+ let plane_rows = 2;
+ let mut nv12 = vec![128u8; stride * plane_rows];
+ nv12.extend(vec![128u8; stride * (plane_rows / 2)]);
+ let pic = Picture {
+ width: width as u32,
+ height: height as u32,
+ stride,
+ plane_rows,
+ nv12,
+ colors: Colors { bt601: false, full_range: true },
+ };
+ let bgrx = to_bgrx(&pic, width as u32, height as u32);
+ assert_eq!(bgrx.len(), width * height * 4);
+ for px in bgrx.as_chunks::<4>().0 {
+ assert_eq!(px[0], 128);
+ assert_eq!(px[1], 128);
+ assert_eq!(px[2], 128);
+ assert_eq!(px[3], 255);
+ }
+ }
+
+ #[test]
+ fn split_annexb_nals_splits_sps_pps_idr() {
+ let nals = split_annexb_nals(SAMPLE_H264_KEYFRAME_64X64);
+ assert_eq!(nals.len(), 3);
+ assert_eq!(nals[0][4] & 0x1f, 7); // SPS
+ assert_eq!(nals[1][4] & 0x1f, 8); // PPS
+ assert_eq!(nals[2][3] & 0x1f, 5); // IDR
+ }
+
+ #[test]
+ fn decoder_decodes_real_h264_keyframe_immediately() {
+ let mut dec = Decoder::new().expect("H.264 decoder should initialize on Linux");
+ let pics = dec.decode(SAMPLE_H264_KEYFRAME_64X64, 0).expect("H.264 keyframe should decode");
+ assert_eq!(pics.len(), 1, "expected immediate zero-delay decoded frame");
+ let pic = &pics[0];
+ assert_eq!(pic.width, 64);
+ assert_eq!(pic.height, 64);
+ let bgrx = to_bgrx(pic, pic.width, pic.height);
+ assert_eq!(bgrx.len(), 64 * 64 * 4);
+ assert!(bgrx[0] > 180, "expected strong blue channel, got {}", bgrx[0]);
+ assert!(bgrx[2] < 50, "expected low red channel, got {}", bgrx[2]);
+ }
+
+ #[test]
+ fn the_stream_says_which_colors() {
+ let units = access_units(include_bytes!("../win/testdata/bt601-full.h264"));
+ let mut decoder = Decoder::new_for_codec("h264").unwrap();
+ let pictures: Vec<Picture> =
+ units.iter().enumerate().flat_map(|(i, u)| decoder.decode(u, i as u64).unwrap()).collect();
+ assert_eq!(pictures.last().unwrap().colors, Colors { bt601: true, full_range: true });
+ }
+
+ #[test]
+ fn colors_convert() {
+ let (w, h) = (4usize, 2usize);
+ let mut nv12 = vec![0u8; w * h * 3 / 2];
+ nv12[..8].copy_from_slice(&[16, 235, 63, 32, 16, 235, 63, 32]);
+ nv12[8..12].copy_from_slice(&[128, 128, 102, 240]);
+ let picture =
+ Picture { width: 4, height: 2, stride: 4, plane_rows: 2, nv12, colors: Colors::default() };
+ let out = to_bgrx(&picture, 4, 2);
+ assert_eq!(&out[..4], &[0, 0, 0, 255], "black");
+ assert_eq!(&out[4..8], &[255, 255, 255, 255], "white");
+ let red = &out[8..12];
+ assert!(red[2] > 240 && red[1] < 20 && red[0] < 20, "red: {red:?}");
+ }
+
+ #[test]
+ fn odd_sizes_are_cropped_safely() {
+ let picture = Picture {
+ width: 6,
+ height: 4,
+ stride: 8,
+ plane_rows: 4,
+ nv12: vec![128; 8 * 6],
+ colors: Colors::default(),
+ };
+ assert_eq!(to_bgrx(&picture, 5, 3).len(), 5 * 3 * 4);
+ assert_eq!(to_bgrx(&picture, 10, 10).len(), 6 * 4 * 4, "never larger than the picture");
+ }
+
+ #[test]
+ fn the_gpu_decodes_the_same_h264_pictures_as_software() {
+ gpu_matches_software("h264", &access_units(include_bytes!("../win/testdata/testsrc.h264")));
+ }
+
+ #[test]
+ fn the_gpu_decodes_the_same_h265_pictures_as_software() {
+ let stream = include_bytes!("../win/testdata/testsrc.h265");
+ let starts: Vec<usize> =
+ (0..stream.len()).filter(|&i| stream[i..].starts_with(&[0, 0, 0, 1, 0x46])).collect();
+ let units: Vec<&[u8]> = starts
+ .iter()
+ .enumerate()
+ .map(|(k, &at)| &stream[at..starts.get(k + 1).copied().unwrap_or(stream.len())])
+ .collect();
+ assert_eq!(units.len(), 10);
+ gpu_matches_software("h265", &units);
+ }
+
+ #[test]
+ fn a_stream_decodes_picture_by_picture() {
+ let stream = include_bytes!("../win/testdata/testsrc.h264");
+ let units = access_units(stream);
+ assert_eq!(units.len(), 10);
+ let mut decoder = Decoder::new_for_codec("h264").unwrap();
+ let mut pictures = Vec::new();
+ for (i, unit) in units.iter().enumerate() {
+ let got = decoder.decode(unit, i as u64 * 33_333).unwrap();
+ assert_eq!(got.len(), 1, "unit {i}");
+ pictures.extend(got);
+ }
+ let first = &pictures[0];
+ assert_eq!((first.width, first.height), (320, 240));
+ assert_eq!(first.colors, Colors { bt601: false, full_range: false }, "tagged BT.709, limited");
+ let bgrx = to_bgrx(first, 320, 240);
+ let distinct: std::collections::HashSet<&[u8; 4]> = bgrx.as_chunks::<4>().0.iter().collect();
+ assert!(distinct.len() > 50, "{} colors", distinct.len());
+ }
}
diff --git a/desktop/app/src/linux/media_sessions.rs b/desktop/app/src/linux/media_sessions.rs
index 0a8f18a..8977320 100644
--- a/desktop/app/src/linux/media_sessions.rs
+++ b/desktop/app/src/linux/media_sessions.rs
@@ -1,14 +1,966 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! What plays on this PC, for paired phones (`docs/protocol/media.md`): active
+//! MPRIS2 media sessions on Linux (via session D-Bus `org.mpris.MediaPlayer2.*`
+//! with a `playerctl` fallback), artwork resolution/caching, and remote
+//! transport commands.
+//!
+//! NectarLink's own MPRIS session (`org.mpris.MediaPlayer2.nectarlink`) is
+//! excluded so a phone never gets its own music echoed back.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::PathBuf;
+use std::process::Command;
+use std::sync::{Mutex, OnceLock};
+use std::time::{Duration, Instant};
use nectarlink_core::{MediaAction, MediaError, MediaPlayer};
-pub fn says_video(_id: &str) -> bool {
+/// Maximum inline artwork payload (256 KiB); larger covers are scaled and JPEG-encoded.
+const ART_BYTES: u64 = 256 * 1024;
+const POLL_INTERVAL: Duration = Duration::from_secs(2);
+const CALL_PAUSE_TTL: Duration = Duration::from_secs(60 * 30);
+
+const PLAYERCTL_FORMAT: &str = "{{playerName}}\t{{status}}\t{{mpris:trackid}}\t{{xesam:title}}\t{{xesam:artist}}\t{{xesam:album}}\t{{mpris:length}}\t{{position}}\t{{mpris:artUrl}}";
+
+type OnChange = Box<dyn Fn(Vec<MediaPlayer>) + Send + Sync>;
+
+static STARTED: OnceLock<()> = OnceLock::new();
+static PAUSED_FOR_CALL: Mutex<Option<PausedForCall>> = Mutex::new(None);
+static CALL_MEDIA: Mutex<()> = Mutex::new(());
+
+#[derive(Debug)]
+struct PausedForCall {
+ players: Vec<String>,
+ paused_at: Instant,
+}
+
+impl PausedForCall {
+ fn take_valid(&mut self, now: Instant) -> Vec<String> {
+ let taken = std::mem::take(&mut self.players);
+ if now.saturating_duration_since(self.paused_at) <= CALL_PAUSE_TTL { taken } else { Vec::new() }
+ }
+
+ fn observe_playing(&mut self, id: &str, now: Instant) {
+ if now.saturating_duration_since(self.paused_at) >= Duration::from_millis(600) {
+ self.players.retain(|p| p != id);
+ }
+ }
+}
+
+/// Whether the MPRIS session for `id` corresponds to a video player or browser.
+pub fn says_video(id: &str) -> bool {
+ let lower = id.trim().to_ascii_lowercase();
+ for needle in [
+ "vlc",
+ "mpv",
+ "totem",
+ "celluloid",
+ "haruna",
+ "dragon",
+ "smplayer",
+ "kodi",
+ "chrome",
+ "chromium",
+ "firefox",
+ "brave",
+ "vivaldi",
+ "opera",
+ "msedge",
+ "zen",
+ ] {
+ if lower.contains(needle) {
+ return true;
+ }
+ }
false
}
-pub fn start<F: Fn(Vec<MediaPlayer>) + Send + Sync + 'static>(_on_change: F) {}
-pub fn command(_player: &str, _action: MediaAction, _position: Option<u64>) -> Result<(), MediaError> {
- Ok(())
+
+/// Raw MPRIS player record before artwork bytes are loaded.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct RawMprisPlayer {
+ pub id: String,
+ pub app: String,
+ pub title: String,
+ pub artist: Option<String>,
+ pub album: Option<String>,
+ pub playing: bool,
+ pub duration: Option<u64>,
+ pub position: Option<u64>,
+ pub actions: Vec<String>,
+ pub art_url: Option<String>,
+}
+
+/// Caches resolved artwork bytes by URL so repeated polls do not re-read disk.
+#[derive(Default)]
+struct ArtCache {
+ by_url: HashMap<String, Option<(String, Vec<u8>)>>,
+}
+
+impl ArtCache {
+ fn resolve(&mut self, art_url: Option<&str>) -> Option<(String, Vec<u8>)> {
+ let url = art_url?.trim();
+ if url.is_empty() {
+ return None;
+ }
+ if let Some(cached) = self.by_url.get(url) {
+ return cached.clone();
+ }
+ if self.by_url.len() > 64 {
+ self.by_url.clear();
+ }
+ let loaded = load_art_from_url(url);
+ self.by_url.insert(url.to_owned(), loaded.clone());
+ loaded
+ }
+}
+
+fn fnv(bytes: &[u8]) -> u64 {
+ bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
+}
+
+fn percent_decode(input: &str) -> String {
+ let bytes = input.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%'
+ && i + 2 < bytes.len()
+ && let (Some(hi), Some(lo)) =
+ ((bytes[i + 1] as char).to_digit(16), (bytes[i + 2] as char).to_digit(16))
+ {
+ out.push(((hi << 4) | lo) as u8);
+ i += 3;
+ continue;
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+/// Resolves a `file://` MPRIS `artUrl` (with percent-encoding) to a local filesystem path.
+pub(crate) fn resolve_art_file_url(art_url: &str) -> Option<PathBuf> {
+ let trimmed = art_url.trim().trim_matches('\'').trim_matches('"').trim();
+ let rest = trimmed.strip_prefix("file://")?;
+ let decoded = percent_decode(rest);
+ if decoded.trim().is_empty() { None } else { Some(PathBuf::from(decoded)) }
+}
+
+fn load_art_from_url(art_url: &str) -> Option<(String, Vec<u8>)> {
+ let path = resolve_art_file_url(art_url)?;
+ let bytes = fs::read(path).ok().filter(|b| !b.is_empty())?;
+ let is_png_or_jpeg = bytes.starts_with(b"\x89PNG") || bytes.starts_with(b"\xFF\xD8\xFF");
+ if is_png_or_jpeg && (bytes.len() as u64) <= ART_BYTES {
+ let key = format!("{:016x}", fnv(&bytes));
+ return Some((key, bytes));
+ }
+ let bitmap = super::image::decode(&bytes).ok()?;
+ for max_side in [360, 280, 220, 160] {
+ let scaled = super::image::scale_to(&bitmap, max_side);
+ if let Ok(jpeg) = super::image::encode_jpeg(&scaled, 85)
+ && (jpeg.len() as u64) <= ART_BYTES
+ {
+ let key = format!("{:016x}", fnv(&jpeg));
+ return Some((key, jpeg));
+ }
+ }
+ None
+}
+
+/// Watches this PC's active MPRIS2 media sessions on a background thread;
+/// `on_change` is invoked whenever the player list or playback state meaningfully changes.
+pub fn start<F>(on_change: F)
+where
+ F: Fn(Vec<MediaPlayer>) + Send + Sync + 'static,
+{
+ if STARTED.set(()).is_err() {
+ return;
+ }
+ let on_change: OnChange = Box::new(on_change);
+ let spawned = std::thread::Builder::new().name("media-sessions".into()).spawn(move || run(&on_change));
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "can't spawn Linux media-sessions watcher");
+ }
+}
+
+fn run(on_change: &OnChange) {
+ let mut art_cache = ArtCache::default();
+ let mut last: Option<(Vec<MediaPlayer>, Instant)> = None;
+ loop {
+ let players = snapshot(&mut art_cache);
+ let should_emit = match &last {
+ None => true,
+ Some((prev, prev_at)) => players_meaningfully_changed(prev, &players, prev_at.elapsed()),
+ };
+ if should_emit {
+ on_change(players.clone());
+ last = Some((players, Instant::now()));
+ }
+ std::thread::sleep(POLL_INTERVAL);
+ }
+}
+
+/// Compares two snapshots of [`MediaPlayer`]s while ignoring normal linear playback
+/// position progression so periodic polling does not trigger spurious UI/network updates.
+pub(crate) fn players_meaningfully_changed(
+ old: &[MediaPlayer],
+ new: &[MediaPlayer],
+ elapsed: Duration,
+) -> bool {
+ if old.len() != new.len() {
+ return true;
+ }
+ let elapsed_ms = elapsed.as_millis() as u64;
+ for (a, b) in old.iter().zip(new.iter()) {
+ if a.id != b.id
+ || a.app != b.app
+ || a.title != b.title
+ || a.artist != b.artist
+ || a.album != b.album
+ || a.playing != b.playing
+ || a.duration != b.duration
+ || a.actions != b.actions
+ || a.art_key != b.art_key
+ || a.art.is_some() != b.art.is_some()
+ {
+ return true;
+ }
+ match (a.position, b.position) {
+ (None, None) => {}
+ (Some(_), None) | (None, Some(_)) => return true,
+ (Some(old_pos), Some(new_pos)) => {
+ let expected = if a.playing {
+ old_pos.saturating_add(elapsed_ms).min(a.duration.unwrap_or(u64::MAX))
+ } else {
+ old_pos
+ };
+ if new_pos.abs_diff(expected) > 1500 {
+ return true;
+ }
+ }
+ }
+ }
+ false
+}
+
+fn snapshot(art_cache: &mut ArtCache) -> Vec<MediaPlayer> {
+ let raw_players = query_raw_players();
+ let now = Instant::now();
+ let mut players = Vec::with_capacity(raw_players.len());
+ for raw in raw_players {
+ if raw.playing
+ && let Ok(mut guard) = PAUSED_FOR_CALL.lock()
+ && let Some(state) = guard.as_mut()
+ {
+ state.observe_playing(&raw.id, now);
+ }
+ let (art_key, art) = art_cache.resolve(raw.art_url.as_deref()).unzip();
+ players.push(MediaPlayer {
+ app: raw.app,
+ id: raw.id,
+ title: Some(raw.title),
+ artist: raw.artist,
+ album: raw.album,
+ playing: raw.playing,
+ duration: raw.duration,
+ position: raw.position,
+ actions: raw.actions,
+ art_key,
+ art,
+ });
+ }
+ players.sort_by_key(|p| !p.playing);
+ players
+}
+
+fn query_raw_players() -> Vec<RawMprisPlayer> {
+ if let Some(players) = query_via_dbus() {
+ return players;
+ }
+ query_via_playerctl().unwrap_or_default()
+}
+
+fn query_via_playerctl() -> Option<Vec<RawMprisPlayer>> {
+ let output = Command::new("playerctl")
+ .args(["--all-players", "metadata", "--format", PLAYERCTL_FORMAT])
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if stderr.contains("No players found") || output.stdout.is_empty() {
+ return Some(Vec::new());
+ }
+ return None;
+ }
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ Some(stdout.lines().filter_map(parse_playerctl_line).collect())
+}
+
+fn is_excluded_player(name: &str) -> bool {
+ let lower = name.trim().to_ascii_lowercase();
+ lower.is_empty()
+ || lower == "nectarlink"
+ || lower == "playerctld"
+ || lower.starts_with("nectarlink.")
+ || lower.ends_with(".nectarlink")
+ || lower.ends_with(".playerctld")
+}
+
+fn readable_player_app(id: &str) -> String {
+ let stripped = id.strip_prefix("org.mpris.MediaPlayer2.").unwrap_or(id);
+ let base = stripped.split('.').next().unwrap_or(stripped).trim();
+ match base.to_ascii_lowercase().as_str() {
+ "" => "Media".to_owned(),
+ "spotify" | "spotifymusic" => "Spotify".to_owned(),
+ "vlc" => "VLC".to_owned(),
+ "firefox" => "Firefox".to_owned(),
+ "chromium" => "Chromium".to_owned(),
+ "chrome" | "google-chrome" => "Chrome".to_owned(),
+ "brave" => "Brave".to_owned(),
+ "msedge" | "edge" => "Edge".to_owned(),
+ "mpv" => "mpv".to_owned(),
+ "rhythmbox" => "Rhythmbox".to_owned(),
+ "amberol" => "Amberol".to_owned(),
+ "elisa" => "Elisa".to_owned(),
+ "audacious" => "Audacious".to_owned(),
+ "clementine" => "Clementine".to_owned(),
+ "strawberry" => "Strawberry".to_owned(),
+ other => {
+ let mut chars = other.chars();
+ match chars.next() {
+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
+ None => "Media".to_owned(),
+ }
+ }
+ }
+}
+
+/// Parses one line of `playerctl --all-players metadata --format ...` output.
+pub(crate) fn parse_playerctl_line(line: &str) -> Option<RawMprisPlayer> {
+ if line.trim().is_empty() {
+ return None;
+ }
+ let fields: Vec<&str> = line.split('\t').collect();
+ if fields.len() < 4 {
+ return None;
+ }
+ let player_name = fields.first().copied().unwrap_or("").trim();
+ if is_excluded_player(player_name) {
+ return None;
+ }
+ let status = fields.get(1).copied().unwrap_or("").trim();
+ let _track_id = fields.get(2).copied().unwrap_or("").trim();
+ let raw_title = fields.get(3).copied().unwrap_or("").trim();
+ if raw_title.is_empty() {
+ return None;
+ }
+ let artist = fields.get(4).map(|s| s.trim()).filter(|s| !s.is_empty()).map(str::to_owned);
+ let album = fields.get(5).map(|s| s.trim()).filter(|s| !s.is_empty()).map(str::to_owned);
+ let duration_us = fields.get(6).and_then(|s| s.trim().parse::<i64>().ok()).filter(|&v| v > 0);
+ let position_us = fields.get(7).and_then(|s| s.trim().parse::<i64>().ok()).filter(|&v| v >= 0);
+ let art_url = fields.get(8).map(|s| s.trim()).filter(|s| !s.is_empty()).map(str::to_owned);
+
+ let duration = duration_us.map(|us| (us as u64) / 1000).filter(|&ms| ms > 0);
+ let position = position_us.map(|us| {
+ let ms = (us as u64) / 1000;
+ duration.map_or(ms, |d| ms.min(d))
+ });
+
+ let mut app = readable_player_app(player_name);
+ let mut title = raw_title.to_owned();
+ if matches!(app.as_str(), "Firefox" | "Chrome" | "Chromium" | "Brave" | "Edge")
+ && let Some((clean, site)) = title.rsplit_once(" on ")
+ {
+ let site = site.trim();
+ let clean = clean.trim();
+ if !site.is_empty() && !clean.is_empty() && site.len() <= 28 {
+ app = site.to_owned();
+ title = clean.to_owned();
+ }
+ }
+
+ let playing = status.eq_ignore_ascii_case("Playing");
+ let mut actions = vec!["play".to_owned(), "pause".to_owned(), "next".to_owned(), "previous".to_owned()];
+ if duration.is_some() {
+ actions.push("seek".to_owned());
+ }
+
+ Some(RawMprisPlayer {
+ id: player_name.to_owned(),
+ app,
+ title,
+ artist,
+ album,
+ playing,
+ duration,
+ position,
+ actions,
+ art_url,
+ })
+}
+
+/// Extracts `org.mpris.MediaPlayer2.*` bus names from `gdbus ListNames` output,
+/// excluding `org.mpris.MediaPlayer2.nectarlink` and `playerctld`.
+#[cfg_attr(not(test), allow(dead_code))]
+pub(crate) fn parse_mpris_bus_names(gdbus_output: &str) -> Vec<String> {
+ let mut names = Vec::new();
+ for token in gdbus_output.split(|c: char| {
+ c == '\'' || c == '"' || c == ',' || c == '[' || c == ']' || c == '(' || c == ')' || c.is_whitespace()
+ }) {
+ let trimmed = token.trim();
+ if let Some(suffix) = trimmed.strip_prefix("org.mpris.MediaPlayer2.")
+ && !is_excluded_player(suffix)
+ && !names.iter().any(|existing| existing == trimmed)
+ {
+ names.push(trimmed.to_owned());
+ }
+ }
+ names
+}
+
+#[cfg_attr(not(test), allow(dead_code))]
+fn extract_gvariant_string(text: &str, key: &str) -> Option<String> {
+ let pattern = format!("'{key}':");
+ let start = text.find(&pattern)? + pattern.len();
+ let rest = text[start..].trim_start();
+ // Look for `<'value'>` or `<['value']>`
+ let open_angle = rest.find('<')?;
+ let inside = rest[open_angle + 1..].trim_start();
+ let inside = inside.strip_prefix('[').map_or(inside, str::trim_start);
+ let quote = inside.chars().next()?;
+ if quote != '\'' && quote != '"' {
+ return None;
+ }
+ let after_quote = &inside[quote.len_utf8()..];
+ let end_quote = after_quote.find(quote)?;
+ let val = after_quote[..end_quote].trim();
+ if val.is_empty() { None } else { Some(val.to_owned()) }
+}
+
+#[cfg_attr(not(test), allow(dead_code))]
+fn extract_gvariant_i64(text: &str, key: &str) -> Option<i64> {
+ let pattern = format!("'{key}':");
+ let start = text.find(&pattern)? + pattern.len();
+ let rest = text[start..].trim_start();
+ let open = rest.find('<')?;
+ let close = rest[open + 1..].find('>')?;
+ let inner = rest[open + 1..open + 1 + close].trim();
+ let num_str = inner.split_whitespace().next_back()?;
+ num_str.parse::<i64>().ok()
+}
+
+#[cfg_attr(not(test), allow(dead_code))]
+fn extract_gvariant_bool(text: &str, key: &str) -> Option<bool> {
+ let pattern = format!("'{key}':");
+ let start = text.find(&pattern)? + pattern.len();
+ let rest = text[start..].trim_start();
+ let open = rest.find('<')?;
+ let close = rest[open + 1..].find('>')?;
+ match rest[open + 1..open + 1 + close].trim() {
+ "true" => Some(true),
+ "false" => Some(false),
+ _ => None,
+ }
+}
+
+#[cfg_attr(not(test), allow(dead_code))]
+pub(crate) fn parse_gdbus_player_properties(bus_name: &str, gdbus_output: &str) -> Option<RawMprisPlayer> {
+ let short_id = bus_name.strip_prefix("org.mpris.MediaPlayer2.").unwrap_or(bus_name);
+ if is_excluded_player(short_id) {
+ return None;
+ }
+ let title = extract_gvariant_string(gdbus_output, "xesam:title")?;
+ let status = extract_gvariant_string(gdbus_output, "PlaybackStatus").unwrap_or_default();
+ let artist = extract_gvariant_string(gdbus_output, "xesam:artist");
+ let album = extract_gvariant_string(gdbus_output, "xesam:album");
+ let art_url = extract_gvariant_string(gdbus_output, "mpris:artUrl");
+ let duration_us = extract_gvariant_i64(gdbus_output, "mpris:length").filter(|&v| v > 0);
+ let position_us = extract_gvariant_i64(gdbus_output, "Position").filter(|&v| v >= 0);
+
+ let duration = duration_us.map(|us| (us as u64) / 1000).filter(|&ms| ms > 0);
+ let position = position_us.map(|us| {
+ let ms = (us as u64) / 1000;
+ duration.map_or(ms, |d| ms.min(d))
+ });
+
+ let mut actions = Vec::new();
+ if extract_gvariant_bool(gdbus_output, "CanPlay").unwrap_or(true) {
+ actions.push("play".to_owned());
+ }
+ if extract_gvariant_bool(gdbus_output, "CanPause").unwrap_or(true) {
+ actions.push("pause".to_owned());
+ }
+ if extract_gvariant_bool(gdbus_output, "CanGoNext").unwrap_or(true) {
+ actions.push("next".to_owned());
+ }
+ if extract_gvariant_bool(gdbus_output, "CanGoPrevious").unwrap_or(true) {
+ actions.push("previous".to_owned());
+ }
+ if extract_gvariant_bool(gdbus_output, "CanSeek").unwrap_or(duration.is_some()) {
+ actions.push("seek".to_owned());
+ }
+
+ Some(RawMprisPlayer {
+ id: short_id.to_owned(),
+ app: readable_player_app(short_id),
+ title,
+ artist,
+ album,
+ playing: status.eq_ignore_ascii_case("Playing"),
+ duration,
+ position,
+ actions,
+ art_url,
+ })
+}
+
+fn value_as_string(val: &zbus::zvariant::Value<'_>) -> Option<String> {
+ use zbus::zvariant::Value;
+ match val {
+ Value::Str(s) => {
+ let trimmed = s.as_str().trim();
+ if trimmed.is_empty() { None } else { Some(trimmed.to_owned()) }
+ }
+ Value::Value(inner) => value_as_string(inner),
+ Value::Array(arr) => arr.iter().find_map(value_as_string),
+ _ => None,
+ }
+}
+
+fn value_as_i64(val: &zbus::zvariant::Value<'_>) -> Option<i64> {
+ use zbus::zvariant::Value;
+ match val {
+ Value::I64(v) => Some(*v),
+ Value::U64(v) => i64::try_from(*v).ok(),
+ Value::I32(v) => Some(i64::from(*v)),
+ Value::U32(v) => Some(i64::from(*v)),
+ Value::Value(inner) => value_as_i64(inner),
+ _ => None,
+ }
+}
+
+fn value_as_bool(val: &zbus::zvariant::Value<'_>) -> Option<bool> {
+ use zbus::zvariant::Value;
+ match val {
+ Value::Bool(b) => Some(*b),
+ Value::Value(inner) => value_as_bool(inner),
+ _ => None,
+ }
+}
+
+fn parse_zbus_player_properties(
+ bus_name: &str,
+ props: &HashMap<String, zbus::zvariant::OwnedValue>,
+) -> Option<RawMprisPlayer> {
+ use zbus::zvariant::Value;
+
+ let short_id = bus_name.strip_prefix("org.mpris.MediaPlayer2.").unwrap_or(bus_name);
+ if is_excluded_player(short_id) {
+ return None;
+ }
+
+ let status = props.get("PlaybackStatus").and_then(|v| value_as_string(v)).unwrap_or_default();
+ let position_us = props.get("Position").and_then(|v| value_as_i64(v)).filter(|&v| v >= 0);
+
+ let mut raw_title: Option<String> = None;
+ let mut artist: Option<String> = None;
+ let mut album: Option<String> = None;
+ let mut art_url: Option<String> = None;
+ let mut duration_us: Option<i64> = None;
+
+ if let Some(meta_owned) = props.get("Metadata") {
+ let mut meta_val: &Value<'_> = meta_owned;
+ while let Value::Value(inner) = meta_val {
+ meta_val = inner;
+ }
+ if let Value::Dict(dict) = meta_val {
+ for (k, v) in dict.iter() {
+ let Some(key) = value_as_string(k) else {
+ continue;
+ };
+ match key.as_str() {
+ "xesam:title" => raw_title = value_as_string(v),
+ "xesam:artist" => artist = value_as_string(v),
+ "xesam:album" => album = value_as_string(v),
+ "mpris:artUrl" => art_url = value_as_string(v),
+ "mpris:length" => duration_us = value_as_i64(v).filter(|&n| n > 0),
+ _ => {}
+ }
+ }
+ }
+ }
+
+ let raw_title = raw_title?;
+ let duration = duration_us.map(|us| (us as u64) / 1000).filter(|&ms| ms > 0);
+ let position = position_us.map(|us| {
+ let ms = (us as u64) / 1000;
+ duration.map_or(ms, |d| ms.min(d))
+ });
+
+ let mut app = readable_player_app(short_id);
+ let mut title = raw_title;
+ if matches!(app.as_str(), "Firefox" | "Chrome" | "Chromium" | "Brave" | "Edge")
+ && let Some((clean, site)) = title.rsplit_once(" on ")
+ {
+ let site = site.trim();
+ let clean = clean.trim();
+ if !site.is_empty() && !clean.is_empty() && site.len() <= 28 {
+ app = site.to_owned();
+ title = clean.to_owned();
+ }
+ }
+
+ let mut actions = Vec::new();
+ if props.get("CanPlay").and_then(|v| value_as_bool(v)).unwrap_or(true) {
+ actions.push("play".to_owned());
+ }
+ if props.get("CanPause").and_then(|v| value_as_bool(v)).unwrap_or(true) {
+ actions.push("pause".to_owned());
+ }
+ if props.get("CanGoNext").and_then(|v| value_as_bool(v)).unwrap_or(true) {
+ actions.push("next".to_owned());
+ }
+ if props.get("CanGoPrevious").and_then(|v| value_as_bool(v)).unwrap_or(true) {
+ actions.push("previous".to_owned());
+ }
+ if props.get("CanSeek").and_then(|v| value_as_bool(v)).unwrap_or(duration.is_some()) {
+ actions.push("seek".to_owned());
+ }
+
+ Some(RawMprisPlayer {
+ id: short_id.to_owned(),
+ app,
+ title,
+ artist,
+ album,
+ playing: status.eq_ignore_ascii_case("Playing"),
+ duration,
+ position,
+ actions,
+ art_url,
+ })
+}
+
+fn list_dbus_mpris_buses(conn: &zbus::blocking::Connection) -> Option<Vec<String>> {
+ let reply = conn
+ .call_method(
+ Some("org.freedesktop.DBus"),
+ "/org/freedesktop/DBus",
+ Some("org.freedesktop.DBus"),
+ "ListNames",
+ &(),
+ )
+ .ok()?;
+ let names: Vec<String> = reply.body().deserialize().ok()?;
+ let mut buses = Vec::new();
+ for name in names {
+ let trimmed = name.trim();
+ if let Some(suffix) = trimmed.strip_prefix("org.mpris.MediaPlayer2.")
+ && !is_excluded_player(suffix)
+ && !buses.iter().any(|existing| existing == trimmed)
+ {
+ buses.push(trimmed.to_owned());
+ }
+ }
+ Some(buses)
+}
+
+fn query_via_dbus() -> Option<Vec<RawMprisPlayer>> {
+ let conn = zbus::blocking::Connection::session().ok()?;
+ let buses = list_dbus_mpris_buses(&conn)?;
+ let mut players = Vec::new();
+ for bus in buses {
+ if let Ok(reply) = conn.call_method(
+ Some(bus.as_str()),
+ "/org/mpris/MediaPlayer2",
+ Some("org.freedesktop.DBus.Properties"),
+ "GetAll",
+ &("org.mpris.MediaPlayer2.Player",),
+ ) && let Ok(props) = reply.body().deserialize::<HashMap<String, zbus::zvariant::OwnedValue>>()
+ && let Some(player) = parse_zbus_player_properties(&bus, &props)
+ {
+ players.push(player);
+ }
+ }
+ Some(players)
+}
+
+fn mpris_bus_name(player: &str) -> String {
+ let trimmed = player.trim();
+ if trimmed.starts_with("org.mpris.MediaPlayer2.") {
+ trimmed.to_owned()
+ } else {
+ format!("org.mpris.MediaPlayer2.{trimmed}")
+ }
+}
+
+fn dbus_player_call(bus_name: &str, method: &str) -> bool {
+ let Ok(conn) = zbus::blocking::Connection::session() else {
+ return false;
+ };
+ conn.call_method(
+ Some(bus_name),
+ "/org/mpris/MediaPlayer2",
+ Some("org.mpris.MediaPlayer2.Player"),
+ method,
+ &(),
+ )
+ .is_ok()
+}
+
+fn dbus_player_seek_to(bus_name: &str, target_us: i64) -> bool {
+ let Ok(conn) = zbus::blocking::Connection::session() else {
+ return false;
+ };
+ let current_us = conn
+ .call_method(
+ Some(bus_name),
+ "/org/mpris/MediaPlayer2",
+ Some("org.freedesktop.DBus.Properties"),
+ "Get",
+ &("org.mpris.MediaPlayer2.Player", "Position"),
+ )
+ .ok()
+ .and_then(|reply| reply.body().deserialize::<zbus::zvariant::OwnedValue>().ok())
+ .and_then(|v| value_as_i64(&v))
+ .unwrap_or(0);
+ let offset_us = target_us.saturating_sub(current_us);
+ conn.call_method(
+ Some(bus_name),
+ "/org/mpris/MediaPlayer2",
+ Some("org.mpris.MediaPlayer2.Player"),
+ "Seek",
+ &(offset_us,),
+ )
+ .is_ok()
+}
+
+pub fn command(player: &str, action: MediaAction, position: Option<u64>) -> Result<(), MediaError> {
+ let trimmed = player.trim();
+ if trimmed.starts_with('-') || trimmed.chars().any(char::is_control) {
+ return Err(MediaError::Failed("invalid player identifier".into()));
+ }
+
+ let target_bus = if trimmed.is_empty() {
+ zbus::blocking::Connection::session()
+ .ok()
+ .and_then(|conn| list_dbus_mpris_buses(&conn))
+ .and_then(|mut b| b.drain(..).next())
+ } else {
+ Some(mpris_bus_name(trimmed))
+ };
+
+ if let Some(ref bus) = target_bus {
+ let ok = match action {
+ MediaAction::Play => dbus_player_call(bus, "Play"),
+ MediaAction::Pause => dbus_player_call(bus, "Pause"),
+ MediaAction::Next => dbus_player_call(bus, "Next"),
+ MediaAction::Previous => dbus_player_call(bus, "Previous"),
+ MediaAction::Seek => {
+ let target_us = i64::try_from(position.unwrap_or(0)).unwrap_or(0).saturating_mul(1000);
+ dbus_player_seek_to(bus, target_us)
+ }
+ };
+ if ok {
+ return Ok(());
+ }
+ }
+
+ // Fallback to `playerctl` when direct D-Bus transport command fails.
+ let mut cmd = Command::new("playerctl");
+ if !trimmed.is_empty() {
+ cmd.args(["--player", trimmed]);
+ }
+ match action {
+ MediaAction::Play => {
+ cmd.arg("play");
+ }
+ MediaAction::Pause => {
+ cmd.arg("pause");
+ }
+ MediaAction::Next => {
+ cmd.arg("next");
+ }
+ MediaAction::Previous => {
+ cmd.arg("previous");
+ }
+ MediaAction::Seek => {
+ let secs = (position.unwrap_or(0) as f64) / 1000.0;
+ cmd.args(["position", &format!("{secs:.2}")]);
+ }
+ }
+ if cmd.status().is_ok_and(|s| s.success()) {
+ Ok(())
+ } else if target_bus.is_none() {
+ Err(MediaError::NotFound)
+ } else {
+ Err(MediaError::Failed(format!("MPRIS command {action:?} failed for {trimmed}")))
+ }
+}
+
+pub fn pause_for_call() {
+ let _serial = CALL_MEDIA.lock().unwrap_or_else(|e| e.into_inner());
+ let mut paused = Vec::new();
+
+ if let Some(players) = query_via_dbus() {
+ for p in players {
+ if p.playing {
+ let bus = mpris_bus_name(&p.id);
+ if dbus_player_call(&bus, "Pause") {
+ paused.push(p.id);
+ }
+ }
+ }
+ } else if let Ok(out) = Command::new("playerctl")
+ .args(["--all-players", "status", "--format", "{{playerName}}\t{{status}}"])
+ .output()
+ && out.status.success()
+ {
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ for line in stdout.lines() {
+ if let Some((name, status)) = line.split_once('\t') {
+ let name = name.trim();
+ if !is_excluded_player(name) && status.trim().eq_ignore_ascii_case("Playing") {
+ let _ = Command::new("playerctl").args(["--player", name, "pause"]).status();
+ paused.push(name.to_owned());
+ }
+ }
+ }
+ }
+
+ if !paused.is_empty()
+ && let Ok(mut guard) = PAUSED_FOR_CALL.lock()
+ {
+ *guard = Some(PausedForCall { players: paused, paused_at: Instant::now() });
+ }
+}
+
+pub fn resume_after_call() {
+ let _serial = CALL_MEDIA.lock().unwrap_or_else(|e| e.into_inner());
+ let players = PAUSED_FOR_CALL
+ .lock()
+ .ok()
+ .and_then(|mut g| g.as_mut().map(|p| p.take_valid(Instant::now())))
+ .unwrap_or_default();
+ for player in players {
+ let bus = mpris_bus_name(&player);
+ if !dbus_player_call(&bus, "Play") {
+ let _ = Command::new("playerctl").args(["--player", &player, "play"]).status();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample_player(id: &str, playing: bool, position: Option<u64>) -> MediaPlayer {
+ MediaPlayer {
+ id: id.to_owned(),
+ app: "Spotify".to_owned(),
+ title: Some("Track 1".to_owned()),
+ artist: Some("Artist".to_owned()),
+ album: Some("Album".to_owned()),
+ playing,
+ duration: Some(200_000),
+ position,
+ actions: vec!["play".to_owned(), "pause".to_owned(), "seek".to_owned()],
+ art_key: None,
+ art: None,
+ }
+ }
+
+ #[test]
+ fn parses_playerctl_line_and_filters_self_player() {
+ let line = "spotify\tPlaying\t/com/spotify/track/123\tMidnight City\tM83\tHurry Up, We're Dreaming\t243000000\t61500000\tfile:///tmp/cover%20art.jpg";
+ let parsed = parse_playerctl_line(line).expect("valid playerctl line");
+ assert_eq!(parsed.id, "spotify");
+ assert_eq!(parsed.app, "Spotify");
+ assert_eq!(parsed.title, "Midnight City");
+ assert_eq!(parsed.artist.as_deref(), Some("M83"));
+ assert_eq!(parsed.album.as_deref(), Some("Hurry Up, We're Dreaming"));
+ assert!(parsed.playing);
+ assert_eq!(parsed.duration, Some(243_000));
+ assert_eq!(parsed.position, Some(61_500));
+ assert_eq!(parsed.art_url.as_deref(), Some("file:///tmp/cover%20art.jpg"));
+
+ // Self-player and playerctld must be ignored
+ let self_line = "nectarlink\tPlaying\t/1\tPhone Song\tArtist\tAlbum\t1000000\t0\t";
+ assert!(parse_playerctl_line(self_line).is_none());
+ let daemon_line = "playerctld\tPlaying\t/1\tPhone Song\tArtist\tAlbum\t1000000\t0\t";
+ assert!(parse_playerctl_line(daemon_line).is_none());
+ }
+
+ #[test]
+ fn parses_mpris_bus_names_and_excludes_nectarlink() {
+ let gdbus_out = "([':1.0', 'org.freedesktop.DBus', 'org.mpris.MediaPlayer2.spotify', 'org.mpris.MediaPlayer2.nectarlink', 'org.mpris.MediaPlayer2.playerctld', 'org.mpris.MediaPlayer2.vlc.instance42'],)";
+ let buses = parse_mpris_bus_names(gdbus_out);
+ assert_eq!(
+ buses,
+ vec![
+ "org.mpris.MediaPlayer2.spotify".to_owned(),
+ "org.mpris.MediaPlayer2.vlc.instance42".to_owned(),
+ ]
+ );
+ }
+
+ #[test]
+ fn parses_gdbus_getall_player_properties() {
+ let gdbus_props = "({'PlaybackStatus': <'Playing'>, 'Position': <int64 30000000>, 'Metadata': <{'mpris:length': <int64 180000000>, 'mpris:artUrl': <'file:///home/user/Album%20Cover.png'>, 'xesam:title': <'Starlight'>, 'xesam:artist': <['Muse']>, 'xesam:album': <'Black Holes and Revelations'>}>, 'CanPlay': <true>, 'CanPause': <true>, 'CanSeek': <true>},)";
+ let player = parse_gdbus_player_properties("org.mpris.MediaPlayer2.vlc", gdbus_props)
+ .expect("parse gdbus properties");
+ assert_eq!(player.id, "vlc");
+ assert_eq!(player.app, "VLC");
+ assert_eq!(player.title, "Starlight");
+ assert_eq!(player.artist.as_deref(), Some("Muse"));
+ assert_eq!(player.album.as_deref(), Some("Black Holes and Revelations"));
+ assert!(player.playing);
+ assert_eq!(player.duration, Some(180_000));
+ assert_eq!(player.position, Some(30_000));
+ }
+
+ #[test]
+ fn players_meaningfully_changed_ignores_linear_progress_and_detects_seeks() {
+ let old = vec![sample_player("spotify", true, Some(10_000))];
+ // 2 seconds later, position is 12_100 ms (within 1500 ms of expected 12_000 ms)
+ let normal_tick = vec![sample_player("spotify", true, Some(12_100))];
+ assert!(!players_meaningfully_changed(&old, &normal_tick, Duration::from_secs(2)));
+
+ // User seeked forward to 45_000 ms
+ let seeked = vec![sample_player("spotify", true, Some(45_000))];
+ assert!(players_meaningfully_changed(&old, &seeked, Duration::from_secs(2)));
+
+ // Playback paused
+ let paused = vec![sample_player("spotify", false, Some(12_000))];
+ assert!(players_meaningfully_changed(&old, &paused, Duration::from_secs(2)));
+ }
+
+ #[test]
+ fn resolves_art_file_url_with_percent_encoding() {
+ assert_eq!(
+ resolve_art_file_url("file:///path/with%20spaces/cover%231.png"),
+ Some(PathBuf::from("/path/with spaces/cover#1.png"))
+ );
+ assert!(resolve_art_file_url("https://example.com/cover.jpg").is_none());
+ assert!(resolve_art_file_url("").is_none());
+ }
+
+ #[test]
+ fn paused_for_call_expires_after_ttl() {
+ let start = Instant::now();
+ let mut state = PausedForCall { players: vec!["spotify".to_string()], paused_at: start };
+ let expired = state.take_valid(start + CALL_PAUSE_TTL + Duration::from_secs(1));
+ assert!(expired.is_empty());
+ }
+
+ #[test]
+ fn paused_for_call_returns_players_within_ttl() {
+ let start = Instant::now();
+ let mut state =
+ PausedForCall { players: vec!["spotify".to_string(), "vlc".to_string()], paused_at: start };
+ let valid = state.take_valid(start + Duration::from_secs(10));
+ assert_eq!(valid, vec!["spotify".to_string(), "vlc".to_string()]);
+ assert!(state.take_valid(start + Duration::from_secs(11)).is_empty());
+ }
}
-pub fn pause_for_call() {}
-pub fn resume_after_call() {}
diff --git a/desktop/app/src/linux/mp4.rs b/desktop/app/src/linux/mp4.rs
index a20fab5..49cabc8 100644
--- a/desktop/app/src/linux/mp4.rs
+++ b/desktop/app/src/linux/mp4.rs
@@ -1,44 +1,930 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Linux MP4 recording for mirrored phone screens and app windows.
+//!
+//! Video frames arrive as Annex-B H.264 access units and are muxed into an
+//! ISO-BMFF (`.mp4`) container (`ftyp` + `moov` + `mdat` with `avc1`/`avcC`
+//! sample entries) without re-encoding. When phone audio (16-bit PCM) is
+//! present and `ffmpeg` is available on `PATH`, the recorded PCM track is
+//! encoded to AAC and muxed alongside the H.264 video stream.
-use std::{path::PathBuf, time::Instant};
+use std::{
+ fs::{self, File},
+ io::Write,
+ path::{Path, PathBuf},
+ process::{Command, Stdio},
+ time::{Instant, SystemTime, UNIX_EPOCH},
+};
+/// Formats `<prefix> YYYY-MM-DD HH.MM.SS.<ext>` using the PC's local clock.
pub fn local_timestamp_filename(prefix: &str, ext: &str) -> String {
- format!("{prefix}.{ext}")
+ let clean_ext = ext.trim_start_matches('.');
+ let (year, month, day, hour, min, sec) = local_ymdhms();
+ format!("{prefix} {year:04}-{month:02}-{day:02} {hour:02}.{min:02}.{sec:02}.{clean_ext}")
}
-pub fn merge_sps_pps(_dest: &mut Vec<u8>, _incoming: &[u8]) {}
+fn local_ymdhms() -> (i32, u32, u32, u32, u32, u32) {
+ // SAFETY: `libc::time` and `libc::localtime_r` are thread-safe POSIX functions
+ // called with stack-allocated `time_t` and `tm` structs.
+ unsafe {
+ let mut now: libc::time_t = 0;
+ libc::time(&raw mut now);
+ let mut tm: libc::tm = std::mem::zeroed();
+ if !libc::localtime_r(&raw const now, &raw mut tm).is_null() {
+ let year = tm.tm_year + 1900;
+ let month = (tm.tm_mon + 1).clamp(1, 12) as u32;
+ let day = tm.tm_mday.clamp(1, 31) as u32;
+ let hour = tm.tm_hour.clamp(0, 23) as u32;
+ let min = tm.tm_min.clamp(0, 59) as u32;
+ let sec = tm.tm_sec.clamp(0, 60) as u32;
+ return (year, month, day, hour, min, sec);
+ }
+ }
+
+ let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
+ let days = secs / 86_400;
+ let rem = secs % 86_400;
+ let hour = (rem / 3600) as u32;
+ let min = ((rem % 3600) / 60) as u32;
+ let sec = (rem % 60) as u32;
+ let (year, month, day) = civil_from_days(days as i64);
+ (year, month, day, hour, min, sec)
+}
+
+fn civil_from_days(days_since_epoch: i64) -> (i32, u32, u32) {
+ let z = days_since_epoch + 719_468;
+ let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
+ let doe = (z - era * 146_097) as u32;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let y = yoe as i64 + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = if m <= 2 { y + 1 } else { y };
+ (year as i32, m, d)
+}
+
+/// Splits an Annex-B byte stream into individual NAL payloads (without start codes).
+pub fn split_annexb(data: &[u8]) -> Vec<&[u8]> {
+ let mut starts = Vec::new();
+ let mut i = 0;
+ while i + 3 <= data.len() {
+ if i + 4 <= data.len() && data[i..i + 4] == [0, 0, 0, 1] {
+ starts.push((i, i + 4));
+ i += 4;
+ } else if data[i..i + 3] == [0, 0, 1] {
+ starts.push((i, i + 3));
+ i += 3;
+ } else {
+ i += 1;
+ }
+ }
+ let mut out = Vec::with_capacity(starts.len());
+ for (idx, &(_, payload_start)) in starts.iter().enumerate() {
+ let payload_end = starts.get(idx + 1).map_or(data.len(), |&(next_code, _)| next_code);
+ if payload_start < payload_end {
+ out.push(&data[payload_start..payload_end]);
+ }
+ }
+ out
+}
+
+/// Returns the 5-bit H.264 NAL unit type of a NAL payload (without start code).
+pub fn nal_type(nal: &[u8]) -> Option<u8> {
+ nal.first().map(|b| b & 0x1F)
+}
+
+/// Returns `true` if `data` contains an H.264 IDR slice (NAL type 5).
+pub fn has_idr_slice(data: &[u8]) -> bool {
+ split_annexb(data).into_iter().any(|nal| nal_type(nal) == Some(5))
+}
+
+/// Returns `true` if `data` already carries both SPS (NAL 7) and PPS (NAL 8) units in-band.
+pub fn has_inband_sps_pps(data: &[u8]) -> bool {
+ let nals = split_annexb(data);
+ nals.iter().any(|nal| nal_type(nal) == Some(7)) && nals.iter().any(|nal| nal_type(nal) == Some(8))
+}
+
+/// Returns `true` if `data` is non-empty and every NAL unit is a parameter set (SPS/PPS).
+pub fn is_parameter_only(data: &[u8]) -> bool {
+ let nals = split_annexb(data);
+ !nals.is_empty() && nals.into_iter().all(|nal| matches!(nal_type(nal), Some(7 | 8)))
+}
+
+/// Extracts only SPS (NAL 7) and PPS (NAL 8) units from `data` with 4-byte Annex-B start codes.
+pub fn extract_sps_pps(data: &[u8]) -> Option<Vec<u8>> {
+ let mut out = Vec::new();
+ for nal in split_annexb(data) {
+ if matches!(nal_type(nal), Some(7 | 8)) {
+ out.extend_from_slice(&[0, 0, 0, 1]);
+ out.extend_from_slice(nal);
+ }
+ }
+ (!out.is_empty()).then_some(out)
+}
+
+/// Extracts any SPS (NAL 7) and PPS (NAL 8) units from `incoming` and merges them
+/// into `dest` with 4-byte `00 00 00 01` Annex-B start codes, preserving SPS-then-PPS order.
+pub fn merge_sps_pps(dest: &mut Vec<u8>, incoming: &[u8]) {
+ let nals = split_annexb(incoming);
+ if !nals.iter().any(|nal| matches!(nal_type(nal), Some(7 | 8))) {
+ return;
+ }
+ let existing = split_annexb(dest);
+ let mut sps: Option<Vec<u8>> =
+ existing.iter().find(|nal| nal_type(nal) == Some(7)).map(|nal| (*nal).to_vec());
+ let mut pps: Option<Vec<u8>> =
+ existing.iter().find(|nal| nal_type(nal) == Some(8)).map(|nal| (*nal).to_vec());
+ for nal in nals {
+ match nal_type(nal) {
+ Some(7) => sps = Some(nal.to_vec()),
+ Some(8) => pps = Some(nal.to_vec()),
+ _ => {}
+ }
+ }
+ dest.clear();
+ if let Some(s) = sps {
+ dest.extend_from_slice(&[0, 0, 0, 1]);
+ dest.extend_from_slice(&s);
+ }
+ if let Some(p) = pps {
+ dest.extend_from_slice(&[0, 0, 0, 1]);
+ dest.extend_from_slice(&p);
+ }
+}
+
+#[derive(Debug, Clone)]
+struct RecordedFrame {
+ pts_us: u64,
+ keyframe: bool,
+ data: Vec<u8>,
+}
+/// Records a mirrored H.264 stream (and optional PCM audio stream) into an `.mp4` file.
+#[derive(Debug)]
pub struct MirrorRecorder {
+ path: PathBuf,
+ width: u32,
+ height: u32,
+ fps: u32,
+ audio_cfg: Option<(u32, u8)>,
+ sps_pps: Vec<u8>,
started: Instant,
+ started_epoch_ms: i64,
+ got_keyframe: bool,
+ first_pts_us: Option<u64>,
+ last_pts_us: u64,
+ frames: Vec<RecordedFrame>,
+ audio_pcm: Vec<u8>,
}
impl MirrorRecorder {
pub fn new(
- _path: PathBuf,
- _width: u32,
- _height: u32,
- _fps: u32,
- _audio_cfg: Option<(u32, u8)>,
+ path: PathBuf,
+ width: u32,
+ height: u32,
+ fps: u32,
+ audio_cfg: Option<(u32, u8)>,
) -> MirrorRecorder {
- MirrorRecorder { started: Instant::now() }
+ let started_epoch_ms =
+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);
+ MirrorRecorder {
+ path,
+ width: width.max(1),
+ height: height.max(1),
+ fps: fps.max(1),
+ audio_cfg,
+ sps_pps: Vec::new(),
+ started: Instant::now(),
+ started_epoch_ms,
+ got_keyframe: false,
+ first_pts_us: None,
+ last_pts_us: 0,
+ frames: Vec::new(),
+ audio_pcm: Vec::new(),
+ }
}
+
pub fn started_at(&self) -> Instant {
self.started
}
+
pub fn started_epoch_ms(&self) -> i64 {
- 0
+ self.started_epoch_ms
+ }
+
+ /// Seeds cached SPS/PPS NAL units collected before recording started.
+ pub fn set_sps_pps(&mut self, sps_pps: &[u8]) {
+ if !sps_pps.is_empty() {
+ merge_sps_pps(&mut self.sps_pps, sps_pps);
+ }
+ }
+
+ /// Updates stream dimensions before the first keyframe initializes the recording.
+ pub fn on_config(&mut self, width: u32, height: u32) {
+ if !self.got_keyframe && width > 0 && height > 0 {
+ self.width = width;
+ self.height = height;
+ }
+ }
+
+ /// Updates audio configuration before the first keyframe initializes the recording.
+ pub fn on_audio_config(&mut self, rate: u32, channels: u8) {
+ if !self.got_keyframe && rate > 0 && channels > 0 {
+ self.audio_cfg = Some((rate, channels));
+ }
}
- pub fn set_sps_pps(&mut self, _sps_pps: &[u8]) {}
- pub fn on_config(&mut self, _width: u32, _height: u32) {}
- pub fn on_audio_config(&mut self, _rate: u32, _channels: u8) {}
- pub fn on_packet(&mut self, _keyframe: bool, _time_us: u64, _data: &[u8]) -> Result<(), String> {
+
+ /// Processes an incoming Annex-B H.264 access unit.
+ pub fn on_packet(&mut self, keyframe: bool, time_us: u64, data: &[u8]) -> Result<(), String> {
+ if data.is_empty() {
+ return Ok(());
+ }
+ merge_sps_pps(&mut self.sps_pps, data);
+
+ if is_parameter_only(data) {
+ return Ok(());
+ }
+
+ let is_keyframe = keyframe || has_idr_slice(data);
+ if !self.got_keyframe {
+ if !is_keyframe {
+ return Ok(());
+ }
+ self.got_keyframe = true;
+ }
+
+ let first_us = *self.first_pts_us.get_or_insert(time_us);
+ let frame_duration_us = (1_000_000 / u64::from(self.fps.max(1))).max(1);
+ let mut rel_us = time_us.saturating_sub(first_us);
+ if !self.frames.is_empty() && rel_us <= self.last_pts_us {
+ rel_us = self.last_pts_us + frame_duration_us;
+ }
+ self.last_pts_us = rel_us;
+
+ let payload = if is_keyframe && !has_inband_sps_pps(data) && !self.sps_pps.is_empty() {
+ let mut combined = Vec::with_capacity(self.sps_pps.len() + data.len());
+ combined.extend_from_slice(&self.sps_pps);
+ combined.extend_from_slice(data);
+ combined
+ } else {
+ data.to_vec()
+ };
+
+ self.frames.push(RecordedFrame { pts_us: rel_us, keyframe: is_keyframe, data: payload });
Ok(())
}
- pub fn on_audio(&mut self, _time_us: u64, _pcm: &[u8]) -> Result<(), String> {
+
+ /// Processes an incoming 16-bit interleaved PCM audio packet.
+ pub fn on_audio(&mut self, _time_us: u64, pcm: &[u8]) -> Result<(), String> {
+ if self.audio_cfg.is_some() && !pcm.is_empty() {
+ self.audio_pcm.extend_from_slice(pcm);
+ }
Ok(())
}
+
+ /// Finalizes the MP4 container and flushes it to disk.
pub fn finish(self) -> Result<PathBuf, String> {
- Err("not supported on Linux yet".into())
+ if self.frames.is_empty() {
+ let _ = fs::remove_file(&self.path);
+ return Err("No video frames were recorded yet.".into());
+ }
+ if let Some(parent) = self.path.parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+
+ write_mp4_container(&self.path, self.width, self.height, self.fps, &self.sps_pps, &self.frames)?;
+
+ if !self.audio_pcm.is_empty()
+ && let Some((rate, channels)) = self.audio_cfg
+ && rate > 0
+ && channels > 0
+ {
+ mux_audio_with_ffmpeg(&self.path, rate, channels, &self.audio_pcm);
+ }
+
+ Ok(self.path)
+ }
+}
+
+fn mux_audio_with_ffmpeg(mp4_path: &Path, rate: u32, channels: u8, pcm: &[u8]) {
+ use std::os::unix::fs::OpenOptionsExt;
+
+ let parent = mp4_path.parent().unwrap_or_else(|| Path::new("."));
+ let stem = mp4_path.file_stem().and_then(|s| s.to_str()).unwrap_or("rec");
+ let pid = std::process::id();
+ let video_tmp = parent.join(format!(".{stem}.{pid}.video.mp4"));
+ let audio_tmp = parent.join(format!(".{stem}.{pid}.audio.pcm"));
+
+ let Ok(mut src_file) = fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(mp4_path)
+ else {
+ return;
+ };
+ let Ok(mut v_out) = fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(&video_tmp)
+ else {
+ return;
+ };
+ if std::io::copy(&mut src_file, &mut v_out).is_err() {
+ let _ = fs::remove_file(&video_tmp);
+ return;
+ }
+ drop(v_out);
+ drop(src_file);
+
+ let Ok(mut a_out) = fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(&audio_tmp)
+ else {
+ let _ = fs::remove_file(&video_tmp);
+ return;
+ };
+ if a_out.write_all(pcm).is_err() {
+ drop(a_out);
+ let _ = fs::remove_file(&video_tmp);
+ let _ = fs::remove_file(&audio_tmp);
+ return;
+ }
+ drop(a_out);
+
+ let status = Command::new("ffmpeg")
+ .args(["-y", "-loglevel", "error", "-i"])
+ .arg(&video_tmp)
+ .args(["-f", "s16le", "-ar", &rate.to_string(), "-ac", &channels.to_string(), "-i"])
+ .arg(&audio_tmp)
+ .args(["-c:v", "copy", "-c:a", "aac", "-b:a", "128k", "-shortest", "-movflags", "+faststart"])
+ .arg(mp4_path)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+
+ if !status.is_ok_and(|s| s.success()) {
+ // Restore pure-Rust video MP4 if ffmpeg was unavailable or failed.
+ let _ = fs::copy(&video_tmp, mp4_path);
+ }
+ let _ = fs::remove_file(&video_tmp);
+ let _ = fs::remove_file(&audio_tmp);
+}
+
+const TIMESCALE: u32 = 90_000;
+
+fn mp4_box(fourcc: &[u8; 4], payload: &[u8]) -> Vec<u8> {
+ let total = (8 + payload.len()) as u32;
+ let mut out = Vec::with_capacity(total as usize);
+ out.extend_from_slice(&total.to_be_bytes());
+ out.extend_from_slice(fourcc);
+ out.extend_from_slice(payload);
+ out
+}
+
+fn mp4_full_box(fourcc: &[u8; 4], version: u8, flags: u32, body: &[u8]) -> Vec<u8> {
+ let total = (12 + body.len()) as u32;
+ let mut out = Vec::with_capacity(total as usize);
+ out.extend_from_slice(&total.to_be_bytes());
+ out.extend_from_slice(fourcc);
+ let vf = (u32::from(version) << 24) | (flags & 0x00FF_FFFF);
+ out.extend_from_slice(&vf.to_be_bytes());
+ out.extend_from_slice(body);
+ out
+}
+
+fn write_mp4_container(
+ path: &Path,
+ width: u32,
+ height: u32,
+ fps: u32,
+ sps_pps: &[u8],
+ frames: &[RecordedFrame],
+) -> Result<(), String> {
+ let default_delta = (TIMESCALE / fps.max(1)).max(1);
+ let mut mdat_payload = Vec::new();
+ let mut sample_sizes = Vec::with_capacity(frames.len());
+ let mut sample_deltas = Vec::with_capacity(frames.len());
+ let mut sync_samples = Vec::new();
+
+ for (idx, frame) in frames.iter().enumerate() {
+ let mut sample_bytes = Vec::new();
+ for nal in split_annexb(&frame.data) {
+ if nal.is_empty() || matches!(nal_type(nal), Some(7..=9)) {
+ continue;
+ }
+ let len = nal.len() as u32;
+ sample_bytes.extend_from_slice(&len.to_be_bytes());
+ sample_bytes.extend_from_slice(nal);
+ }
+ if sample_bytes.is_empty() {
+ for nal in split_annexb(&frame.data) {
+ if nal.is_empty() {
+ continue;
+ }
+ let len = nal.len() as u32;
+ sample_bytes.extend_from_slice(&len.to_be_bytes());
+ sample_bytes.extend_from_slice(nal);
+ }
+ }
+ mdat_payload.extend_from_slice(&sample_bytes);
+ sample_sizes.push(sample_bytes.len() as u32);
+
+ let delta = if let Some(next) = frames.get(idx + 1) {
+ let diff_us = next.pts_us.saturating_sub(frame.pts_us);
+ ((diff_us * u64::from(TIMESCALE)) / 1_000_000).max(1) as u32
+ } else {
+ default_delta
+ };
+ sample_deltas.push(delta);
+
+ if frame.keyframe {
+ sync_samples.push((idx + 1) as u32);
+ }
+ }
+
+ if sync_samples.is_empty() {
+ sync_samples.push(1);
+ }
+
+ let (sps, pps) = extract_sps_and_pps_vecs(sps_pps, frames);
+ let ftyp = build_ftyp();
+ let dummy_moov = build_moov(
+ width.max(1) as u16,
+ height.max(1) as u16,
+ &sps,
+ &pps,
+ &sample_deltas,
+ &sync_samples,
+ &sample_sizes,
+ 0,
+ );
+ let chunk_offset = (ftyp.len() + dummy_moov.len() + 8) as u32;
+ let moov = build_moov(
+ width.max(1) as u16,
+ height.max(1) as u16,
+ &sps,
+ &pps,
+ &sample_deltas,
+ &sync_samples,
+ &sample_sizes,
+ chunk_offset,
+ );
+ let mdat = mp4_box(b"mdat", &mdat_payload);
+
+ let mut file = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
+ file.write_all(&ftyp).map_err(|e| e.to_string())?;
+ file.write_all(&moov).map_err(|e| e.to_string())?;
+ file.write_all(&mdat).map_err(|e| e.to_string())?;
+ file.flush().map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+fn extract_sps_and_pps_vecs(sps_pps: &[u8], frames: &[RecordedFrame]) -> (Vec<u8>, Vec<u8>) {
+ let mut sps = None;
+ let mut pps = None;
+ for nal in split_annexb(sps_pps) {
+ match nal_type(nal) {
+ Some(7) => sps = Some(nal.to_vec()),
+ Some(8) => pps = Some(nal.to_vec()),
+ _ => {}
+ }
+ }
+ if sps.is_none() || pps.is_none() {
+ for frame in frames {
+ for nal in split_annexb(&frame.data) {
+ match nal_type(nal) {
+ Some(7) if sps.is_none() => sps = Some(nal.to_vec()),
+ Some(8) if pps.is_none() => pps = Some(nal.to_vec()),
+ _ => {}
+ }
+ }
+ if sps.is_some() && pps.is_some() {
+ break;
+ }
+ }
+ }
+ let sps = sps.unwrap_or_else(|| vec![0x67, 0x42, 0xC0, 0x1F, 0xDA, 0x01, 0x40, 0x16, 0xEC, 0x04, 0x40]);
+ let pps = pps.unwrap_or_else(|| vec![0x68, 0xCE, 0x3C, 0x80]);
+ (sps, pps)
+}
+
+fn build_ftyp() -> Vec<u8> {
+ let mut body = Vec::with_capacity(24);
+ body.extend_from_slice(b"isom");
+ body.extend_from_slice(&0x0000_0200u32.to_be_bytes());
+ body.extend_from_slice(b"isom");
+ body.extend_from_slice(b"iso2");
+ body.extend_from_slice(b"avc1");
+ body.extend_from_slice(b"mp41");
+ mp4_box(b"ftyp", &body)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_moov(
+ width: u16,
+ height: u16,
+ sps: &[u8],
+ pps: &[u8],
+ sample_deltas: &[u32],
+ sync_samples: &[u32],
+ sample_sizes: &[u32],
+ chunk_offset: u32,
+) -> Vec<u8> {
+ let total_duration: u32 = sample_deltas.iter().copied().fold(0u32, u32::saturating_add).max(1);
+ let mvhd = build_mvhd(total_duration);
+ let trak = build_trak(
+ width,
+ height,
+ total_duration,
+ sps,
+ pps,
+ sample_deltas,
+ sync_samples,
+ sample_sizes,
+ chunk_offset,
+ );
+ let mut body = Vec::with_capacity(mvhd.len() + trak.len());
+ body.extend_from_slice(&mvhd);
+ body.extend_from_slice(&trak);
+ mp4_box(b"moov", &body)
+}
+
+fn build_mvhd(duration: u32) -> Vec<u8> {
+ let mut body = Vec::with_capacity(96);
+ body.extend_from_slice(&0u32.to_be_bytes()); // creation_time
+ body.extend_from_slice(&0u32.to_be_bytes()); // modification_time
+ body.extend_from_slice(&TIMESCALE.to_be_bytes());
+ body.extend_from_slice(&duration.to_be_bytes());
+ body.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0
+ body.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0
+ body.extend_from_slice(&[0u8; 10]); // reserved
+ // Unity matrix
+ for val in [0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000] {
+ body.extend_from_slice(&val.to_be_bytes());
+ }
+ body.extend_from_slice(&[0u8; 24]); // pre_defined
+ body.extend_from_slice(&2u32.to_be_bytes()); // next_track_ID
+ mp4_full_box(b"mvhd", 0, 0, &body)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_trak(
+ width: u16,
+ height: u16,
+ duration: u32,
+ sps: &[u8],
+ pps: &[u8],
+ sample_deltas: &[u32],
+ sync_samples: &[u32],
+ sample_sizes: &[u32],
+ chunk_offset: u32,
+) -> Vec<u8> {
+ let tkhd = build_tkhd(width, height, duration);
+ let mdia = build_mdia(
+ width,
+ height,
+ duration,
+ sps,
+ pps,
+ sample_deltas,
+ sync_samples,
+ sample_sizes,
+ chunk_offset,
+ );
+ let mut body = Vec::with_capacity(tkhd.len() + mdia.len());
+ body.extend_from_slice(&tkhd);
+ body.extend_from_slice(&mdia);
+ mp4_box(b"trak", &body)
+}
+
+fn build_tkhd(width: u16, height: u16, duration: u32) -> Vec<u8> {
+ let mut body = Vec::with_capacity(80);
+ body.extend_from_slice(&0u32.to_be_bytes()); // creation_time
+ body.extend_from_slice(&0u32.to_be_bytes()); // modification_time
+ body.extend_from_slice(&1u32.to_be_bytes()); // track_ID
+ body.extend_from_slice(&0u32.to_be_bytes()); // reserved
+ body.extend_from_slice(&duration.to_be_bytes());
+ body.extend_from_slice(&[0u8; 8]); // reserved
+ body.extend_from_slice(&0u16.to_be_bytes()); // layer
+ body.extend_from_slice(&0u16.to_be_bytes()); // alternate_group
+ body.extend_from_slice(&0u16.to_be_bytes()); // volume (0 for video)
+ body.extend_from_slice(&0u16.to_be_bytes()); // reserved
+ for val in [0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000] {
+ body.extend_from_slice(&val.to_be_bytes());
+ }
+ body.extend_from_slice(&(u32::from(width) << 16).to_be_bytes());
+ body.extend_from_slice(&(u32::from(height) << 16).to_be_bytes());
+ mp4_full_box(b"tkhd", 0, 0x0000_0003, &body)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_mdia(
+ width: u16,
+ height: u16,
+ duration: u32,
+ sps: &[u8],
+ pps: &[u8],
+ sample_deltas: &[u32],
+ sync_samples: &[u32],
+ sample_sizes: &[u32],
+ chunk_offset: u32,
+) -> Vec<u8> {
+ let mut mdhd_body = Vec::with_capacity(20);
+ mdhd_body.extend_from_slice(&0u32.to_be_bytes());
+ mdhd_body.extend_from_slice(&0u32.to_be_bytes());
+ mdhd_body.extend_from_slice(&TIMESCALE.to_be_bytes());
+ mdhd_body.extend_from_slice(&duration.to_be_bytes());
+ mdhd_body.extend_from_slice(&0x55C4u16.to_be_bytes()); // "und"
+ mdhd_body.extend_from_slice(&0u16.to_be_bytes());
+ let mdhd = mp4_full_box(b"mdhd", 0, 0, &mdhd_body);
+
+ let mut hdlr_body = Vec::with_capacity(32);
+ hdlr_body.extend_from_slice(&0u32.to_be_bytes()); // pre_defined
+ hdlr_body.extend_from_slice(b"vide");
+ hdlr_body.extend_from_slice(&[0u8; 12]); // reserved
+ hdlr_body.extend_from_slice(b"VideoHandler\0");
+ let hdlr = mp4_full_box(b"hdlr", 0, 0, &hdlr_body);
+
+ let minf = build_minf(width, height, sps, pps, sample_deltas, sync_samples, sample_sizes, chunk_offset);
+
+ let mut body = Vec::with_capacity(mdhd.len() + hdlr.len() + minf.len());
+ body.extend_from_slice(&mdhd);
+ body.extend_from_slice(&hdlr);
+ body.extend_from_slice(&minf);
+ mp4_box(b"mdia", &body)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_minf(
+ width: u16,
+ height: u16,
+ sps: &[u8],
+ pps: &[u8],
+ sample_deltas: &[u32],
+ sync_samples: &[u32],
+ sample_sizes: &[u32],
+ chunk_offset: u32,
+) -> Vec<u8> {
+ let vmhd = mp4_full_box(b"vmhd", 0, 1, &[0u8; 8]);
+ let url = mp4_full_box(b"url ", 0, 1, &[]);
+ let mut dref_body = Vec::with_capacity(4 + url.len());
+ dref_body.extend_from_slice(&1u32.to_be_bytes());
+ dref_body.extend_from_slice(&url);
+ let dref = mp4_full_box(b"dref", 0, 0, &dref_body);
+ let dinf = mp4_box(b"dinf", &dref);
+
+ let stbl = build_stbl(width, height, sps, pps, sample_deltas, sync_samples, sample_sizes, chunk_offset);
+
+ let mut body = Vec::with_capacity(vmhd.len() + dinf.len() + stbl.len());
+ body.extend_from_slice(&vmhd);
+ body.extend_from_slice(&dinf);
+ body.extend_from_slice(&stbl);
+ mp4_box(b"minf", &body)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_stbl(
+ width: u16,
+ height: u16,
+ sps: &[u8],
+ pps: &[u8],
+ sample_deltas: &[u32],
+ sync_samples: &[u32],
+ sample_sizes: &[u32],
+ chunk_offset: u32,
+) -> Vec<u8> {
+ let stsd = build_stsd(width, height, sps, pps);
+ let stts = build_stts(sample_deltas);
+ let stss = build_stss(sync_samples);
+ let stsc = build_stsc(sample_sizes.len() as u32);
+ let stsz = build_stsz(sample_sizes);
+ let stco = build_stco(chunk_offset);
+
+ let mut body = Vec::new();
+ body.extend_from_slice(&stsd);
+ body.extend_from_slice(&stts);
+ body.extend_from_slice(&stss);
+ body.extend_from_slice(&stsc);
+ body.extend_from_slice(&stsz);
+ body.extend_from_slice(&stco);
+ mp4_box(b"stbl", &body)
+}
+
+fn build_stsd(width: u16, height: u16, sps: &[u8], pps: &[u8]) -> Vec<u8> {
+ let profile_idc = *sps.get(1).unwrap_or(&0x42);
+ let profile_compat = *sps.get(2).unwrap_or(&0xC0);
+ let level_idc = *sps.get(3).unwrap_or(&0x1F);
+
+ let mut avcc_body = vec![
+ 1, // configurationVersion
+ profile_idc,
+ profile_compat,
+ level_idc,
+ 0xFF, // 4-byte NAL unit lengths
+ 0xE1, // 1 SPS
+ ];
+ avcc_body.extend_from_slice(&(sps.len() as u16).to_be_bytes());
+ avcc_body.extend_from_slice(sps);
+ avcc_body.push(1); // 1 PPS
+ avcc_body.extend_from_slice(&(pps.len() as u16).to_be_bytes());
+ avcc_body.extend_from_slice(pps);
+ let avcc = mp4_box(b"avcC", &avcc_body);
+
+ let mut avc1_body = Vec::with_capacity(78 + avcc.len());
+ avc1_body.extend_from_slice(&[0u8; 6]); // reserved
+ avc1_body.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
+ avc1_body.extend_from_slice(&[0u8; 16]); // pre_defined + reserved
+ avc1_body.extend_from_slice(&width.to_be_bytes());
+ avc1_body.extend_from_slice(&height.to_be_bytes());
+ avc1_body.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // horizresolution 72 dpi
+ avc1_body.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // vertresolution 72 dpi
+ avc1_body.extend_from_slice(&0u32.to_be_bytes()); // reserved
+ avc1_body.extend_from_slice(&1u16.to_be_bytes()); // frame_count
+ avc1_body.extend_from_slice(&[0u8; 32]); // compressorname
+ avc1_body.extend_from_slice(&0x0018u16.to_be_bytes()); // depth = 24
+ avc1_body.extend_from_slice(&(-1i16).to_be_bytes()); // pre_defined = -1
+ avc1_body.extend_from_slice(&avcc);
+ let avc1 = mp4_box(b"avc1", &avc1_body);
+
+ let mut stsd_body = Vec::with_capacity(4 + avc1.len());
+ stsd_body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
+ stsd_body.extend_from_slice(&avc1);
+ mp4_full_box(b"stsd", 0, 0, &stsd_body)
+}
+
+fn build_stts(sample_deltas: &[u32]) -> Vec<u8> {
+ let mut runs: Vec<(u32, u32)> = Vec::new();
+ for &delta in sample_deltas {
+ if let Some(last) = runs.last_mut()
+ && last.1 == delta
+ {
+ last.0 += 1;
+ } else {
+ runs.push((1, delta));
+ }
+ }
+ let mut body = Vec::with_capacity(4 + runs.len() * 8);
+ body.extend_from_slice(&(runs.len() as u32).to_be_bytes());
+ for (count, delta) in runs {
+ body.extend_from_slice(&count.to_be_bytes());
+ body.extend_from_slice(&delta.to_be_bytes());
+ }
+ mp4_full_box(b"stts", 0, 0, &body)
+}
+
+fn build_stss(sync_samples: &[u32]) -> Vec<u8> {
+ let mut body = Vec::with_capacity(4 + sync_samples.len() * 4);
+ body.extend_from_slice(&(sync_samples.len() as u32).to_be_bytes());
+ for &idx in sync_samples {
+ body.extend_from_slice(&idx.to_be_bytes());
+ }
+ mp4_full_box(b"stss", 0, 0, &body)
+}
+
+fn build_stsc(total_samples: u32) -> Vec<u8> {
+ let mut body = Vec::with_capacity(16);
+ body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
+ body.extend_from_slice(&1u32.to_be_bytes()); // first_chunk = 1
+ body.extend_from_slice(&total_samples.to_be_bytes()); // samples_per_chunk
+ body.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index = 1
+ mp4_full_box(b"stsc", 0, 0, &body)
+}
+
+fn build_stsz(sample_sizes: &[u32]) -> Vec<u8> {
+ let mut body = Vec::with_capacity(8 + sample_sizes.len() * 4);
+ body.extend_from_slice(&0u32.to_be_bytes()); // sample_size = 0 (variable)
+ body.extend_from_slice(&(sample_sizes.len() as u32).to_be_bytes());
+ for &sz in sample_sizes {
+ body.extend_from_slice(&sz.to_be_bytes());
+ }
+ mp4_full_box(b"stsz", 0, 0, &body)
+}
+
+fn build_stco(chunk_offset: u32) -> Vec<u8> {
+ let mut body = Vec::with_capacity(8);
+ body.extend_from_slice(&1u32.to_be_bytes()); // entry_count = 1
+ body.extend_from_slice(&chunk_offset.to_be_bytes());
+ mp4_full_box(b"stco", 0, 0, &body)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|w| w == needle)
+ }
+
+ #[test]
+ fn extract_sps_pps_picks_out_parameter_sets_only() {
+ let stream = [
+ 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F, // SPS (type 7)
+ 0x00, 0x00, 0x00, 0x01, 0x68, 0xCE, 0x3C, 0x80, // PPS (type 8)
+ 0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x21, // IDR (type 5)
+ ];
+ let extracted = extract_sps_pps(&stream).expect("should extract SPS and PPS");
+ assert_eq!(
+ extracted,
+ vec![
+ 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x01, 0x68, 0xCE, 0x3C,
+ 0x80,
+ ]
+ );
+ assert!(extract_sps_pps(&[0x00, 0x00, 0x00, 0x01, 0x65, 0x88]).is_none());
+ }
+
+ #[test]
+ fn merge_sps_pps_updates_each_parameter_set_in_place() {
+ let mut buf = Vec::new();
+ let sps1 = [0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F];
+ let pps1 = [0x00, 0x00, 0x00, 0x01, 0x68, 0xCE, 0x3C, 0x80];
+ merge_sps_pps(&mut buf, &sps1);
+ assert_eq!(buf, sps1);
+
+ merge_sps_pps(&mut buf, &pps1);
+ let mut expected = Vec::new();
+ expected.extend_from_slice(&sps1);
+ expected.extend_from_slice(&pps1);
+ assert_eq!(buf, expected);
+
+ // Updating PPS alone preserves existing SPS and replaces PPS.
+ let pps2 = [0x00, 0x00, 0x01, 0x68, 0xDE, 0xAD, 0xBE];
+ merge_sps_pps(&mut buf, &pps2);
+ let mut expected2 = Vec::new();
+ expected2.extend_from_slice(&sps1);
+ expected2.extend_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x68, 0xDE, 0xAD, 0xBE]);
+ assert_eq!(buf, expected2);
+
+ // Slice NAL without SPS/PPS leaves `buf` untouched.
+ let idr = [0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84];
+ merge_sps_pps(&mut buf, &idr);
+ assert_eq!(buf, expected2);
+ }
+
+ #[test]
+ fn has_idr_slice_detects_keyframe_nal() {
+ let idr = [0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84];
+ let non_idr = [0x00, 0x00, 0x00, 0x01, 0x41, 0x9A, 0x22];
+ assert!(has_idr_slice(&idr));
+ assert!(!has_idr_slice(&non_idr));
+ }
+
+ #[test]
+ fn is_parameter_only_ignores_slice_packets() {
+ let params =
+ [0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x01, 0x68, 0xCE, 0x3C, 0x80];
+ let with_slice =
+ [0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84];
+ assert!(is_parameter_only(&params));
+ assert!(!is_parameter_only(&with_slice));
+ assert!(!is_parameter_only(&[]));
+ }
+
+ #[test]
+ fn local_timestamp_filename_has_expected_shape() {
+ let name = local_timestamp_filename("Recording", "mp4");
+ assert!(name.starts_with("Recording "), "unexpected filename: {name}");
+ assert!(name.ends_with(".mp4"), "unexpected filename: {name}");
+ // "Recording YYYY-MM-DD HH.MM.SS.mp4" -> length 33
+ assert_eq!(name.len(), "Recording 2026-10-16 19.40.00.mp4".len());
+ }
+
+ #[test]
+ fn recorder_writes_playable_mp4_from_synthetic_h264() {
+ let dir = tempfile::tempdir().unwrap();
+ let mp4_path = dir.path().join("synthetic.mp4");
+
+ let mut rec = MirrorRecorder::new(mp4_path.clone(), 320, 240, 30, None);
+ let sps_pps = [
+ 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xC0, 0x1F, 0xDA, 0x01, 0x40, 0x16, 0xEC, 0x04, 0x40, 0x00,
+ 0x00, 0x00, 0x01, 0x68, 0xCE, 0x3C, 0x80,
+ ];
+ rec.on_packet(false, 0, &sps_pps).unwrap();
+
+ // Pre-keyframe P-slice is ignored until first keyframe arrives.
+ let p_slice = [0x00, 0x00, 0x00, 0x01, 0x41, 0x9A, 0x24, 0x6C, 0x88];
+ rec.on_packet(false, 10_000, &p_slice).unwrap();
+
+ let mut idr = vec![0x00, 0x00, 0x00, 0x01, 0x65];
+ idr.extend_from_slice(&[0x88u8; 64]);
+ rec.on_packet(true, 33_333, &idr).unwrap();
+ rec.on_packet(false, 66_666, &p_slice).unwrap();
+ rec.on_packet(false, 100_000, &p_slice).unwrap();
+
+ let saved = rec.finish().unwrap();
+ assert_eq!(saved, mp4_path);
+ let bytes = fs::read(&saved).unwrap();
+ assert!(bytes.len() > 256, "unexpectedly small MP4: {} B", bytes.len());
+ assert_eq!(&bytes[4..8], b"ftyp");
+ assert!(contains_subslice(&bytes, b"moov"), "missing moov box");
+ assert!(contains_subslice(&bytes, b"mdat"), "missing mdat box");
+ assert!(contains_subslice(&bytes, b"avc1"), "missing avc1 sample entry");
+ assert!(contains_subslice(&bytes, b"avcC"), "missing avcC config box");
}
}
diff --git a/desktop/app/src/linux/smtc.rs b/desktop/app/src/linux/smtc.rs
index 8fb2ba6..86b1cf3 100644
--- a/desktop/app/src/linux/smtc.rs
+++ b/desktop/app/src/linux/smtc.rs
@@ -1,10 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! What plays on a phone, exported to Linux desktop media controls (MPRIS2
+//! provider `org.mpris.MediaPlayer2.nectarlink` and atomic JSON state snapshot).
+//!
+//! Mirrors the public API of `win::smtc`: [`start`] registers the command
+//! callback and spawns the `"media-controls"` worker thread; [`show`] updates
+//! or clears the currently displayed phone media session.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::PathBuf;
+use std::sync::{Mutex, MutexGuard, OnceLock, mpsc};
+use std::time::{SystemTime, UNIX_EPOCH};
use nectarlink_core::{DeviceId, MediaAction};
+use serde::{Deserialize, Serialize};
+use zbus::zvariant::{ObjectPath, OwnedValue, Str};
use crate::state::PlayerView;
+/// What the controls show: one player on one device.
#[derive(Debug, Clone)]
pub struct Shown {
pub device: DeviceId,
@@ -12,6 +26,563 @@ pub struct Shown {
pub view: PlayerView,
}
-pub fn start<F: Fn(DeviceId, String, MediaAction, Option<u64>) + Send + Sync + 'static>(_on_command: F) {}
+type OnCommand = Box<dyn Fn(DeviceId, String, MediaAction, Option<u64>) + Send + Sync>;
+
+static ON_COMMAND: OnceLock<Mutex<Option<OnCommand>>> = OnceLock::new();
+static QUEUE: OnceLock<Mutex<mpsc::Sender<Option<Shown>>>> = OnceLock::new();
+static CURRENT: Mutex<Option<(DeviceId, String)>> = Mutex::new(None);
+static LAST_SHOWN: Mutex<Option<Shown>> = Mutex::new(None);
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct MprisExportState {
+ pub bus_name: String,
+ pub enabled: bool,
+ pub device_id: Option<String>,
+ pub device_name: Option<String>,
+ pub player_id: Option<String>,
+ pub playback_status: String,
+ pub title: String,
+ pub artist: String,
+ pub album: String,
+ pub art_url: Option<String>,
+ pub length_us: Option<u64>,
+ pub position_us: Option<u64>,
+ pub can_play: bool,
+ pub can_pause: bool,
+ pub can_go_next: bool,
+ pub can_go_previous: bool,
+ pub can_seek: bool,
+}
+
+fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+fn on_command_slot() -> &'static Mutex<Option<OnCommand>> {
+ ON_COMMAND.get_or_init(|| Mutex::new(None))
+}
+
+/// Formats the second line of the media flyout with source attribution matching `win::smtc`.
+pub(crate) fn format_artist_line(artist: Option<&str>, app: &str, device_name: &str) -> String {
+ let source = format!("{app} on {device_name}");
+ match artist.map(str::trim).filter(|s| !s.is_empty()) {
+ Some(artist) => format!("{artist} · {source}"),
+ None => source,
+ }
+}
+
+/// Starts the Linux media controls provider and spawns the `"media-controls"` worker thread.
+pub fn start<F>(on_command: F)
+where
+ F: Fn(DeviceId, String, MediaAction, Option<u64>) + Send + Sync + 'static,
+{
+ *lock(on_command_slot()) = Some(Box::new(on_command));
+ if QUEUE.get().is_some() {
+ return;
+ }
+ let (sender, receiver) = mpsc::channel::<Option<Shown>>();
+ if QUEUE.set(Mutex::new(sender)).is_ok() {
+ let spawned =
+ std::thread::Builder::new().name("media-controls".into()).spawn(move || run_worker(receiver));
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "Linux media-controls worker unavailable");
+ }
+ }
+}
+
+fn current_export_state() -> MprisExportState {
+ let latest = lock(&LAST_SHOWN).clone();
+ build_export_state(latest.as_ref())
+}
+
+fn build_mpris_metadata_dict(state: &MprisExportState) -> HashMap<String, OwnedValue> {
+ let mut dict = HashMap::new();
+ let track_path = if state.enabled {
+ "/org/mpris/MediaPlayer2/TrackList/CurrentTrack"
+ } else {
+ "/org/mpris/MediaPlayer2/TrackList/NoTrack"
+ };
+ if let Ok(path) = ObjectPath::try_from(track_path) {
+ dict.insert("mpris:trackid".to_owned(), OwnedValue::from(path));
+ }
+ if state.enabled {
+ dict.insert("xesam:title".to_owned(), OwnedValue::from(Str::from(state.title.as_str())));
+ if let Ok(artists) = zbus::zvariant::Value::from(vec![state.artist.as_str()]).try_to_owned() {
+ dict.insert("xesam:artist".to_owned(), artists);
+ }
+ dict.insert("xesam:album".to_owned(), OwnedValue::from(Str::from(state.album.as_str())));
+ if let Some(ref art_url) = state.art_url {
+ dict.insert("mpris:artUrl".to_owned(), OwnedValue::from(Str::from(art_url.as_str())));
+ }
+ if let Some(len_us) = state.length_us
+ && let Ok(len_i64) = i64::try_from(len_us)
+ {
+ dict.insert("mpris:length".to_owned(), OwnedValue::from(len_i64));
+ }
+ }
+ dict
+}
+
+struct MprisRootIface;
+
+#[zbus::interface(name = "org.mpris.MediaPlayer2")]
+impl MprisRootIface {
+ fn raise(&self) {}
+
+ fn quit(&self) {}
+
+ #[zbus(property)]
+ fn can_quit(&self) -> bool {
+ false
+ }
+
+ #[zbus(property)]
+ fn can_raise(&self) -> bool {
+ false
+ }
+
+ #[zbus(property)]
+ fn has_track_list(&self) -> bool {
+ false
+ }
+
+ #[zbus(property)]
+ fn identity(&self) -> String {
+ "NectarLink".to_owned()
+ }
+
+ #[zbus(property)]
+ fn desktop_entry(&self) -> String {
+ "nectarlink".to_owned()
+ }
+
+ #[zbus(property)]
+ fn supported_uri_schemes(&self) -> Vec<String> {
+ Vec::new()
+ }
+
+ #[zbus(property)]
+ fn supported_mime_types(&self) -> Vec<String> {
+ Vec::new()
+ }
+}
+
+struct MprisPlayerIface;
+
+#[zbus::interface(name = "org.mpris.MediaPlayer2.Player")]
+impl MprisPlayerIface {
+ fn next(&self) {
+ let _ = handle_mpris_call("Next", None);
+ }
+
+ fn previous(&self) {
+ let _ = handle_mpris_call("Previous", None);
+ }
+
+ fn pause(&self) {
+ let _ = handle_mpris_call("Pause", None);
+ }
+
+ fn play_pause(&self) {
+ let _ = handle_mpris_call("PlayPause", None);
+ }
+
+ fn stop(&self) {
+ let _ = handle_mpris_call("Pause", None);
+ }
+
+ fn play(&self) {
+ let _ = handle_mpris_call("Play", None);
+ }
+
+ fn seek(&self, offset: i64) {
+ let current_us = current_export_state().position_us.and_then(|v| i64::try_from(v).ok()).unwrap_or(0);
+ let target_us = current_us.saturating_add(offset).max(0);
+ let _ = handle_mpris_call("Seek", Some(target_us));
+ }
+
+ fn set_position(&self, _track_id: ObjectPath<'_>, position: i64) {
+ let _ = handle_mpris_call("SetPosition", Some(position.max(0)));
+ }
+
+ fn open_uri(&self, _uri: &str) {}
+
+ #[zbus(property)]
+ fn playback_status(&self) -> String {
+ current_export_state().playback_status
+ }
+
+ #[zbus(property)]
+ fn rate(&self) -> f64 {
+ 1.0
+ }
+
+ #[zbus(property)]
+ fn metadata(&self) -> HashMap<String, OwnedValue> {
+ build_mpris_metadata_dict(&current_export_state())
+ }
+
+ #[zbus(property)]
+ fn volume(&self) -> f64 {
+ 1.0
+ }
+
+ #[zbus(property)]
+ fn position(&self) -> i64 {
+ current_export_state().position_us.and_then(|v| i64::try_from(v).ok()).unwrap_or(0)
+ }
-pub fn show(_current: Option<Shown>) {}
+ #[zbus(property)]
+ fn minimum_rate(&self) -> f64 {
+ 1.0
+ }
+
+ #[zbus(property)]
+ fn maximum_rate(&self) -> f64 {
+ 1.0
+ }
+
+ #[zbus(property)]
+ fn can_go_next(&self) -> bool {
+ current_export_state().can_go_next
+ }
+
+ #[zbus(property)]
+ fn can_go_previous(&self) -> bool {
+ current_export_state().can_go_previous
+ }
+
+ #[zbus(property)]
+ fn can_play(&self) -> bool {
+ current_export_state().can_play
+ }
+
+ #[zbus(property)]
+ fn can_pause(&self) -> bool {
+ current_export_state().can_pause
+ }
+
+ #[zbus(property)]
+ fn can_seek(&self) -> bool {
+ current_export_state().can_seek
+ }
+
+ #[zbus(property)]
+ fn can_control(&self) -> bool {
+ current_export_state().enabled
+ }
+}
+
+fn register_mpris_dbus_service() -> Option<zbus::blocking::Connection> {
+ if cfg!(test) {
+ return None;
+ }
+ zbus::blocking::connection::Builder::session()
+ .ok()?
+ .name("org.mpris.MediaPlayer2.nectarlink")
+ .ok()?
+ .serve_at("/org/mpris/MediaPlayer2", MprisRootIface)
+ .ok()?
+ .serve_at("/org/mpris/MediaPlayer2", MprisPlayerIface)
+ .ok()?
+ .build()
+ .ok()
+}
+
+fn notify_mpris_properties_changed(conn: &zbus::blocking::Connection, state: &MprisExportState) {
+ let mut changed: HashMap<&str, OwnedValue> = HashMap::new();
+ changed.insert("PlaybackStatus", OwnedValue::from(Str::from(state.playback_status.as_str())));
+ if let Ok(meta) = zbus::zvariant::Value::from(build_mpris_metadata_dict(state)).try_to_owned() {
+ changed.insert("Metadata", meta);
+ }
+ changed.insert("CanPlay", OwnedValue::from(state.can_play));
+ changed.insert("CanPause", OwnedValue::from(state.can_pause));
+ changed.insert("CanGoNext", OwnedValue::from(state.can_go_next));
+ changed.insert("CanGoPrevious", OwnedValue::from(state.can_go_previous));
+ changed.insert("CanSeek", OwnedValue::from(state.can_seek));
+ changed.insert("CanControl", OwnedValue::from(state.enabled));
+ let invalidated: Vec<&str> = Vec::new();
+ let _ = conn.emit_signal(
+ Option::<&str>::None,
+ "/org/mpris/MediaPlayer2",
+ "org.freedesktop.DBus.Properties",
+ "PropertiesChanged",
+ &("org.mpris.MediaPlayer2.Player", changed, invalidated),
+ );
+}
+
+fn run_worker(receiver: mpsc::Receiver<Option<Shown>>) {
+ let conn = register_mpris_dbus_service();
+ while let Ok(first) = receiver.recv() {
+ let mut latest = first;
+ while let Ok(next) = receiver.try_recv() {
+ latest = next;
+ }
+ let export = build_export_state(latest.as_ref());
+ write_mpris_state_file(&export);
+ if let Some(ref conn) = conn {
+ notify_mpris_properties_changed(conn, &export);
+ }
+ }
+}
+
+/// Shows a phone player in the desktop media controls, or hides them when `None`.
+pub fn show(current: Option<Shown>) {
+ match &current {
+ Some(shown) => {
+ *lock(&CURRENT) = Some((shown.device, shown.view.player.id.clone()));
+ }
+ None => {
+ *lock(&CURRENT) = None;
+ }
+ }
+ *lock(&LAST_SHOWN) = current.clone();
+ if let Some(queue) = QUEUE.get() {
+ let _ = lock(queue).send(current);
+ } else {
+ let export = build_export_state(current.as_ref());
+ write_mpris_state_file(&export);
+ }
+}
+
+pub(crate) fn build_export_state(shown: Option<&Shown>) -> MprisExportState {
+ let Some(shown) = shown else {
+ return MprisExportState {
+ bus_name: "org.mpris.MediaPlayer2.nectarlink".to_owned(),
+ enabled: false,
+ device_id: None,
+ device_name: None,
+ player_id: None,
+ playback_status: "Stopped".to_owned(),
+ title: String::new(),
+ artist: String::new(),
+ album: String::new(),
+ art_url: None,
+ length_us: None,
+ position_us: None,
+ can_play: false,
+ can_pause: false,
+ can_go_next: false,
+ can_go_previous: false,
+ can_seek: false,
+ };
+ };
+
+ let player = &shown.view.player;
+ let can = |action: &str| player.actions.iter().any(|a| a == action);
+ let title = player.title.as_deref().unwrap_or(&player.app).to_owned();
+ let artist = format_artist_line(player.artist.as_deref(), &player.app, &shown.device_name);
+ let album = player.album.clone().unwrap_or_default();
+ let art_url = shown.view.art.as_ref().map(|p| format!("file://{}", p.display()));
+
+ let elapsed_ms = if player.playing {
+ SystemTime::now().duration_since(shown.view.at).map_or(0, |d| d.as_millis() as u64)
+ } else {
+ 0
+ };
+ let duration_ms = player.duration;
+ let position_ms = player.position.map(|pos| {
+ let advanced = pos.saturating_add(elapsed_ms);
+ duration_ms.map_or(advanced, |d| advanced.min(d))
+ });
+
+ MprisExportState {
+ bus_name: "org.mpris.MediaPlayer2.nectarlink".to_owned(),
+ enabled: true,
+ device_id: Some(shown.device.to_string()),
+ device_name: Some(shown.device_name.clone()),
+ player_id: Some(player.id.clone()),
+ playback_status: if player.playing { "Playing".to_owned() } else { "Paused".to_owned() },
+ title,
+ artist,
+ album,
+ art_url,
+ length_us: duration_ms.map(|ms| ms.saturating_mul(1000)),
+ position_us: position_ms.map(|ms| ms.saturating_mul(1000)),
+ can_play: can("play"),
+ can_pause: can("pause"),
+ can_go_next: can("next"),
+ can_go_previous: can("previous"),
+ can_seek: can("seek"),
+ }
+}
+
+fn mpris_state_path() -> Option<PathBuf> {
+ if let Some(base) = dirs::runtime_dir().or_else(dirs::cache_dir).filter(|p| p.is_absolute()) {
+ Some(base.join("nectarlink").join("mpris-state.json"))
+ } else {
+ let uid = unsafe { libc::geteuid() };
+ Some(std::env::temp_dir().join(format!("nectarlink-{uid}")).join("mpris-state.json"))
+ }
+}
+
+fn write_mpris_state_file(state: &MprisExportState) {
+ use std::io::Write;
+ use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt};
+
+ let Some(path) = mpris_state_path() else {
+ return;
+ };
+ let Some(parent) = path.parent() else {
+ return;
+ };
+ let _ = fs::DirBuilder::new().recursive(true).mode(0o700).create(parent);
+ let euid = unsafe { libc::geteuid() };
+ let Ok(meta) = fs::symlink_metadata(parent) else {
+ return;
+ };
+ if meta.file_type().is_symlink() || !meta.is_dir() || meta.uid() != euid {
+ return;
+ }
+ let Ok(json) = serde_json::to_vec_pretty(state) else {
+ return;
+ };
+ let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
+ let tmp_path = parent.join(format!(".mpris-state.{}.{}.tmp", std::process::id(), nanos));
+ let Ok(mut file) = fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(&tmp_path)
+ else {
+ return;
+ };
+ if file.write_all(&json).is_ok() {
+ let _ = fs::rename(&tmp_path, &path);
+ } else {
+ let _ = fs::remove_file(&tmp_path);
+ }
+}
+
+/// Dispatches a [`MediaAction`] for the currently shown phone media session.
+pub fn dispatch_command(action: MediaAction, position_ms: Option<u64>) -> bool {
+ let Some((device, player_id)) = lock(&CURRENT).clone() else {
+ return false;
+ };
+ let guard = lock(on_command_slot());
+ let Some(on_command) = guard.as_ref() else {
+ return false;
+ };
+ on_command(device, player_id, action, position_ms);
+ true
+}
+
+/// Handles an incoming MPRIS2 `org.mpris.MediaPlayer2.Player` method call.
+pub fn handle_mpris_call(method: &str, position_us: Option<i64>) -> bool {
+ match method.trim() {
+ "Play" => dispatch_command(MediaAction::Play, None),
+ "Pause" => dispatch_command(MediaAction::Pause, None),
+ "PlayPause" => {
+ let currently_playing = lock(&LAST_SHOWN).as_ref().is_some_and(|s| s.view.player.playing);
+ let action = if currently_playing { MediaAction::Pause } else { MediaAction::Play };
+ dispatch_command(action, None)
+ }
+ "Next" => dispatch_command(MediaAction::Next, None),
+ "Previous" => dispatch_command(MediaAction::Previous, None),
+ "Seek" | "SetPosition" => {
+ let pos_ms = position_us.map(|us| u64::try_from((us / 1000).max(0)).unwrap_or(0));
+ dispatch_command(MediaAction::Seek, pos_ms)
+ }
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use nectarlink_core::MediaPlayer;
+ use std::sync::Arc;
+
+ static TEST_LOCK: Mutex<()> = Mutex::new(());
+
+ fn sample_shown(playing: bool) -> Shown {
+ let device = DeviceId([7u8; 32]);
+ Shown {
+ device,
+ device_name: "Pixel 9".to_owned(),
+ view: PlayerView {
+ device,
+ player: MediaPlayer {
+ id: "com.spotify.music".to_owned(),
+ app: "Spotify".to_owned(),
+ title: Some("Veridis Quo".to_owned()),
+ artist: Some("Daft Punk".to_owned()),
+ album: Some("Discovery".to_owned()),
+ playing,
+ duration: Some(345_000),
+ position: Some(12_000),
+ actions: vec![
+ "play".to_owned(),
+ "pause".to_owned(),
+ "next".to_owned(),
+ "previous".to_owned(),
+ "seek".to_owned(),
+ ],
+ art_key: None,
+ art: None,
+ },
+ art: Some(PathBuf::from("/tmp/discovery.jpg")),
+ at: SystemTime::now(),
+ },
+ }
+ }
+
+ #[test]
+ fn formats_artist_line_with_source_attribution() {
+ assert_eq!(
+ format_artist_line(Some("Daft Punk"), "Spotify", "Pixel 9"),
+ "Daft Punk · Spotify on Pixel 9"
+ );
+ assert_eq!(format_artist_line(None, "YouTube Music", "Galaxy S24"), "YouTube Music on Galaxy S24");
+ }
+
+ #[test]
+ fn show_and_mpris_calls_dispatch_commands_and_clear_on_none() {
+ type ReceivedMediaCmd = (DeviceId, String, MediaAction, Option<u64>);
+ let _serial = lock(&TEST_LOCK);
+ let received: Arc<Mutex<Vec<ReceivedMediaCmd>>> = Arc::new(Mutex::new(Vec::new()));
+ let sink = Arc::clone(&received);
+ start(move |dev, player, action, pos| {
+ lock(&sink).push((dev, player, action, pos));
+ });
+
+ let shown_playing = sample_shown(true);
+ let expected_dev = shown_playing.device;
+ show(Some(shown_playing));
+
+ assert!(handle_mpris_call("Play", None));
+ assert!(handle_mpris_call("Pause", None));
+ // PlayPause while playing -> Pause
+ assert!(handle_mpris_call("PlayPause", None));
+ assert!(handle_mpris_call("Next", None));
+ assert!(handle_mpris_call("Previous", None));
+ assert!(handle_mpris_call("Seek", Some(42_500_000)));
+
+ // Switch state to paused and test PlayPause -> Play
+ show(Some(sample_shown(false)));
+ assert!(handle_mpris_call("PlayPause", None));
+
+ let events = lock(&received).clone();
+ assert_eq!(events.len(), 7);
+ assert_eq!(events[0], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Play, None));
+ assert_eq!(events[1], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Pause, None));
+ assert_eq!(events[2], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Pause, None));
+ assert_eq!(events[3], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Next, None));
+ assert_eq!(events[4], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Previous, None));
+ assert_eq!(
+ events[5],
+ (expected_dev, "com.spotify.music".to_owned(), MediaAction::Seek, Some(42_500))
+ );
+ assert_eq!(events[6], (expected_dev, "com.spotify.music".to_owned(), MediaAction::Play, None));
+
+ // Clearing with show(None) stops dispatching commands
+ show(None);
+ assert!(!handle_mpris_call("Play", None));
+ let cleared_state = build_export_state(None);
+ assert!(!cleared_state.enabled);
+ assert_eq!(cleared_state.playback_status, "Stopped");
+ }
+}
diff --git a/desktop/app/src/linux/sound.rs b/desktop/app/src/linux/sound.rs
index 4deb3b6..50457df 100644
--- a/desktop/app/src/linux/sound.rs
+++ b/desktop/app/src/linux/sound.rs
@@ -1,5 +1,231 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Find-My-PC audible alarm on Linux: synthesizes a two-tone 880 Hz / 1320 Hz
+//! RIFF/WAVE alarm and loops playback via `paplay`, `pw-play`, `aplay`, or
+//! `canberra-gtk-play` until stopped or 60 seconds elapse.
-pub fn start_ringing() {}
-pub fn stop_ringing() {}
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::thread;
+use std::time::{Duration, Instant};
+
+static RINGING: AtomicBool = AtomicBool::new(false);
+static ACTIVE_CHILD: Mutex<Option<Child>> = Mutex::new(None);
+
+const MAX_RING_DURATION: Duration = Duration::from_secs(60);
+const RING_PAUSE: Duration = Duration::from_millis(250);
+
+/// Synthesizes a 16-bit mono PCM RIFF/WAVE file alternating between 880 Hz and
+/// 1320 Hz every 250 ms for `duration_ms` at `sample_rate`.
+pub fn generate_alarm_wav(duration_ms: u32, sample_rate: u32) -> Vec<u8> {
+ let sr = sample_rate.max(8_000);
+ let total_samples = ((u64::from(duration_ms) * u64::from(sr)) / 1000) as u32;
+ let data_bytes = total_samples.saturating_mul(2);
+ let riff_size = 36u32.saturating_add(data_bytes);
+
+ let mut out = Vec::with_capacity(44 + data_bytes as usize);
+ out.extend_from_slice(b"RIFF");
+ out.extend_from_slice(&riff_size.to_le_bytes());
+ out.extend_from_slice(b"WAVE");
+ out.extend_from_slice(b"fmt ");
+ out.extend_from_slice(&16u32.to_le_bytes());
+ out.extend_from_slice(&1u16.to_le_bytes()); // PCM
+ out.extend_from_slice(&1u16.to_le_bytes()); // Mono
+ out.extend_from_slice(&sr.to_le_bytes());
+ out.extend_from_slice(&(sr * 2).to_le_bytes());
+ out.extend_from_slice(&2u16.to_le_bytes());
+ out.extend_from_slice(&16u16.to_le_bytes());
+ out.extend_from_slice(b"data");
+ out.extend_from_slice(&data_bytes.to_le_bytes());
+
+ let segment_samples = (sr / 4).max(1);
+ let fade_samples = (sr / 200).max(1); // 5 ms envelope
+ let mut phase = 0.0_f32;
+
+ for idx in 0..total_samples {
+ let seg = idx / segment_samples;
+ let pos_in_seg = idx % segment_samples;
+ let freq = if seg.is_multiple_of(2) { 880.0_f32 } else { 1320.0_f32 };
+ let env = if pos_in_seg < fade_samples {
+ (pos_in_seg as f32) / (fade_samples as f32)
+ } else if segment_samples - pos_in_seg <= fade_samples {
+ ((segment_samples - pos_in_seg) as f32) / (fade_samples as f32)
+ } else {
+ 1.0
+ };
+
+ let sample_f = (phase * 2.0 * std::f32::consts::PI).sin() * 0.65 * env;
+ phase = (phase + freq / (sr as f32)).fract();
+ let sample_i16 = (sample_f.clamp(-1.0, 1.0) * 32767.0).round() as i16;
+ out.extend_from_slice(&sample_i16.to_le_bytes());
+ }
+
+ out
+}
+
+fn spawn_alarm_player(wav_path: &Path) -> Option<Child> {
+ let path_str = wav_path.to_string_lossy();
+ Command::new("paplay")
+ .arg(path_str.as_ref())
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .or_else(|_| {
+ Command::new("pw-play")
+ .arg(path_str.as_ref())
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .or_else(|_| {
+ Command::new("aplay")
+ .args(["-q", path_str.as_ref()])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .or_else(|_| {
+ Command::new("canberra-gtk-play")
+ .args(["-i", "phone-incoming-call"])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .ok()
+}
+
+fn kill_active_child() {
+ if let Ok(mut guard) = ACTIVE_CHILD.lock()
+ && let Some(mut child) = guard.take()
+ {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+}
+
+fn alarm_wav_path() -> Option<PathBuf> {
+ use std::os::unix::fs::{DirBuilderExt, MetadataExt};
+ let euid = unsafe { libc::geteuid() };
+ let dir = if let Some(base) = dirs::runtime_dir().or_else(dirs::cache_dir).filter(|p| p.is_absolute()) {
+ base.join("nectarlink")
+ } else {
+ std::env::temp_dir().join(format!("nectarlink-{euid}"))
+ };
+ let _ = std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir);
+ let meta = std::fs::symlink_metadata(&dir).ok()?;
+ if meta.file_type().is_symlink() || !meta.is_dir() || meta.uid() != euid {
+ return None;
+ }
+ Some(dir.join("find-pc-alarm.wav"))
+}
+
+pub fn start_ringing() {
+ if RINGING.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ let _ = thread::Builder::new().name("nectarlink-alarm".into()).spawn(|| {
+ let Some(wav_path) = alarm_wav_path() else {
+ RINGING.store(false, Ordering::SeqCst);
+ return;
+ };
+ let wav_bytes = generate_alarm_wav(1000, 48_000);
+ {
+ use std::io::Write;
+ use std::os::unix::fs::OpenOptionsExt;
+ if let Ok(mut file) = std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(&wav_path)
+ {
+ let _ = file.write_all(&wav_bytes);
+ }
+ }
+
+ let started = Instant::now();
+ while RINGING.load(Ordering::SeqCst) && started.elapsed() < MAX_RING_DURATION {
+ if let Some(child) = spawn_alarm_player(&wav_path) {
+ if let Ok(mut guard) = ACTIVE_CHILD.lock() {
+ *guard = Some(child);
+ }
+ loop {
+ if !RINGING.load(Ordering::SeqCst) || started.elapsed() >= MAX_RING_DURATION {
+ kill_active_child();
+ break;
+ }
+ let finished = if let Ok(mut guard) = ACTIVE_CHILD.lock() {
+ if let Some(c) = guard.as_mut() {
+ matches!(c.try_wait(), Ok(Some(_)) | Err(_))
+ } else {
+ true
+ }
+ } else {
+ true
+ };
+ if finished {
+ break;
+ }
+ thread::sleep(Duration::from_millis(40));
+ }
+ }
+
+ let step = Duration::from_millis(50);
+ let mut waited = Duration::ZERO;
+ while waited < RING_PAUSE && RINGING.load(Ordering::SeqCst) {
+ thread::sleep(step);
+ waited += step;
+ }
+ }
+ kill_active_child();
+ let _ = std::fs::remove_file(&wav_path);
+ RINGING.store(false, Ordering::SeqCst);
+ });
+}
+
+pub fn stop_ringing() {
+ RINGING.store(false, Ordering::SeqCst);
+ kill_active_child();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn generate_alarm_wav_produces_valid_riff_header_and_waveform() {
+ let wav = generate_alarm_wav(500, 48_000);
+ assert_eq!(&wav[0..4], b"RIFF");
+ assert_eq!(&wav[8..12], b"WAVE");
+ assert_eq!(&wav[12..16], b"fmt ");
+ assert_eq!(&wav[36..40], b"data");
+
+ let expected_samples = 24_000usize;
+ let expected_data_bytes = expected_samples * 2;
+ assert_eq!(wav.len(), 44 + expected_data_bytes);
+
+ let data_len = u32::from_le_bytes([wav[40], wav[41], wav[42], wav[43]]) as usize;
+ assert_eq!(data_len, expected_data_bytes);
+
+ let non_zero = wav[44..]
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|c| i16::from_le_bytes([c[0], c[1]]))
+ .any(|s| s.unsigned_abs() > 10_000);
+ assert!(non_zero, "synthesized alarm waveform should be audible");
+ }
+
+ #[test]
+ fn start_and_stop_ringing_terminates_cleanly() {
+ start_ringing();
+ stop_ringing();
+ assert!(!RINGING.load(Ordering::SeqCst));
+ }
+}
diff --git a/desktop/app/src/linux/vcam.rs b/desktop/app/src/linux/vcam.rs
index 8f1d6cd..7a03bbd 100644
--- a/desktop/app/src/linux/vcam.rs
+++ b/desktop/app/src/linux/vcam.rs
@@ -1,37 +1,425 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Linux Virtual Camera (`v4l2loopback`) discovery, registration, and
+//! shared-memory-to-V4L2 YUYV frame output for `"NectarLink Webcam"`.
-use std::path::PathBuf;
+use std::{
+ fs::{self, OpenOptions},
+ io::Write,
+ os::fd::AsRawFd,
+ path::{Path, PathBuf},
+ process::{Command, Stdio},
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+ thread,
+ time::Duration,
+};
-pub const CLSID_STR: &str = "{8E14549A-DB61-4309-AFA1-3578E927E935}";
-pub const FRIENDLY_NAME: &str = "NectarLink Virtual Camera";
+use nectarlink_vcam::{DEFAULT_MAPPING_NAME, LOCAL_MAPPING_NAME, SharedFrameMapping};
+
+pub const CLSID_STR: &str = "{8E6C3B74-5D4A-4B9E-9A12-7C8F1E2D3A40}";
+pub const FRIENDLY_NAME: &str = "NectarLink Webcam";
pub const REGISTER_ARG: &str = "--register-vcam";
pub const UNREGISTER_ARG: &str = "--unregister-vcam";
+const MODULES_LOAD_CONF: &str = "/etc/modules-load.d/nectarlink-vcam.conf";
+const MODPROBE_CONF: &str = "/etc/modprobe.d/nectarlink-vcam.conf";
+
+const V4L2_BUF_TYPE_VIDEO_OUTPUT: u32 = 2;
+const V4L2_PIX_FMT_YUYV: u32 = 0x5659_5559; // 'Y' 'U' 'Y' 'V'
+const V4L2_FIELD_NONE: u32 = 1;
+const V4L2_COLORSPACE_SMPTE170M: u32 = 1;
+/// `_IOWR('V', 5, struct v4l2_format)` where `sizeof(struct v4l2_format) == 208` (`0xD0`).
+const VIDIOC_S_FMT: libc::c_ulong = 0xC0D0_5605;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct V4l2PixFormat {
+ width: u32,
+ height: u32,
+ pixelformat: u32,
+ field: u32,
+ bytesperline: u32,
+ sizeimage: u32,
+ colorspace: u32,
+ priv_: u32,
+ flags: u32,
+ ycbcr_enc: u32,
+ quantization: u32,
+ xfer_func: u32,
+}
+
+#[repr(C)]
+struct V4l2Format {
+ type_: u32,
+ _pad: u32,
+ pix: V4l2PixFormat,
+ _rest: [u8; 200 - std::mem::size_of::<V4l2PixFormat>()],
+}
+
+/// Locates a `v4l2loopback` `/dev/videoN` device node by inspecting `/sys/class/video4linux`.
+pub fn find_v4l2loopback_device() -> Option<PathBuf> {
+ find_v4l2loopback_in_sysfs(Path::new("/sys"), Path::new("/dev"))
+}
+
+/// Testable helper that scans `<sysfs_root>/class/video4linux/video*` and `<dev_root>/video*`.
+pub fn find_v4l2loopback_in_sysfs(sysfs_root: &Path, dev_root: &Path) -> Option<PathBuf> {
+ let v4l_dir = sysfs_root.join("class/video4linux");
+ if let Ok(entries) = fs::read_dir(&v4l_dir) {
+ let mut candidates: Vec<(u8, String, PathBuf)> = Vec::new();
+ for entry in entries.flatten() {
+ let file_name = entry.file_name();
+ let dev_name = file_name.to_string_lossy().into_owned();
+ if !dev_name.starts_with("video") {
+ continue;
+ }
+ let dev_node = dev_root.join(&dev_name);
+ if !dev_node.exists() {
+ continue;
+ }
+ let Ok(card_name) = fs::read_to_string(entry.path().join("name")) else {
+ continue;
+ };
+ let lower = card_name.to_ascii_lowercase();
+ if lower.contains("nectarlink") {
+ candidates.push((0, dev_name, dev_node));
+ } else if lower.contains("dummy video device") || lower.contains("v4l2loopback") {
+ candidates.push((1, dev_name, dev_node));
+ }
+ }
+ candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
+ if let Some((_, _, node)) = candidates.into_iter().next() {
+ return Some(node);
+ }
+ }
+
+ if sysfs_root.join("module/v4l2loopback").exists() {
+ for idx in 0..16 {
+ let dev = dev_root.join(format!("video{idx}"));
+ if dev.exists() {
+ return Some(dev);
+ }
+ }
+ }
+ None
+}
+
+/// Returns the active `v4l2loopback` device node, module sysfs directory, or `modprobe` binary
+/// so the desktop UI knows virtual camera setup is supported on this Linux host.
pub fn dll_path() -> Option<PathBuf> {
+ if let Some(dev) = find_v4l2loopback_device() {
+ return Some(dev);
+ }
+ let sys_mod = PathBuf::from("/sys/module/v4l2loopback");
+ if sys_mod.exists() {
+ return Some(sys_mod);
+ }
+ for candidate in ["/sbin/modprobe", "/usr/sbin/modprobe", "/bin/modprobe", "/usr/bin/modprobe"] {
+ let p = PathBuf::from(candidate);
+ if p.exists() {
+ return Some(p);
+ }
+ }
None
}
+
+/// Returns `true` if `v4l2loopback` is currently loaded in the kernel or exposes a loopback node.
pub fn is_registered() -> bool {
- false
+ find_v4l2loopback_device().is_some() || PathBuf::from("/sys/module/v4l2loopback").exists()
}
+
+/// Ensures `v4l2loopback` is registered, attempting `register_hklm()` when not already active.
pub fn ensure_registered() -> bool {
- false
+ if is_registered() {
+ return true;
+ }
+ register_hklm().is_ok() && is_registered()
+}
+
+fn run_modprobe(args: &[&str]) -> Result<(), String> {
+ let bins = ["/sbin/modprobe", "/usr/sbin/modprobe", "modprobe"];
+ let mut last_err = String::from("modprobe not found");
+ for bin in bins {
+ match Command::new(bin)
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .output()
+ {
+ Ok(out) if out.status.success() => return Ok(()),
+ Ok(out) => {
+ let stderr = String::from_utf8_lossy(&out.stderr).trim().to_owned();
+ last_err =
+ if stderr.is_empty() { format!("{bin} exited with {}", out.status) } else { stderr };
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(e) => last_err = e.to_string(),
+ }
+ }
+ Err(last_err)
}
+
+/// Loads `v4l2loopback` with `"NectarLink Webcam"` and writes persistent module config files.
pub fn register_hklm() -> Result<(), String> {
- Err("not supported on Linux yet".into())
+ if let Some(parent) = Path::new(MODULES_LOAD_CONF).parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ let _ = fs::write(MODULES_LOAD_CONF, "v4l2loopback\n");
+
+ if let Some(parent) = Path::new(MODPROBE_CONF).parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ let _ = fs::write(
+ MODPROBE_CONF,
+ format!("options v4l2loopback exclusive_caps=1 card_label=\"{FRIENDLY_NAME}\"\n"),
+ );
+
+ run_modprobe(&["v4l2loopback", "exclusive_caps=1", &format!("card_label={FRIENDLY_NAME}")])
}
+
+/// Removes persistent `v4l2loopback` config files and unloads the kernel module.
pub fn unregister_hklm() -> Result<(), String> {
- Ok(())
+ let _ = fs::remove_file(MODULES_LOAD_CONF);
+ let _ = fs::remove_file(MODPROBE_CONF);
+ run_modprobe(&["-r", "v4l2loopback"])
}
-pub fn run_elevated(_arg: &'static str, on_done: impl FnOnce(bool) + Send + 'static) {
- on_done(false);
+
+/// Launches `nectarlink-desktop <arg>` under `pkexec` and invokes `on_done` when it exits.
+pub fn run_elevated(arg: &'static str, on_done: impl FnOnce(bool) + Send + 'static) {
+ thread::spawn(move || {
+ let Ok(exe) = std::env::current_exe() else {
+ on_done(false);
+ return;
+ };
+ let ok = super::elevated::run_elevated(&exe, &[arg]).is_ok_and(|code| code == 0);
+ on_done(ok);
+ });
}
-#[derive(Debug)]
-pub struct VirtualCameraHandle;
+/// Converts top-down BGRX (`width * height * 4`) to packed YUYV 4:2:2 (`even_width * height * 2`)
+/// using BT.601 studio-swing integer math.
+pub fn bgrx_to_yuyv(bgrx: &[u8], width: u32, height: u32, yuyv: &mut Vec<u8>) {
+ let w = width as usize;
+ let h = height as usize;
+ if w == 0 || h == 0 || bgrx.len() < w.saturating_mul(h).saturating_mul(4) {
+ yuyv.clear();
+ return;
+ }
+ let even_w = (w + 1) & !1;
+ let total_bytes = even_w * h * 2;
+ yuyv.resize(total_bytes, 0);
+
+ for y in 0..h {
+ let src_row = &bgrx[y * w * 4..(y + 1) * w * 4];
+ let dst_row = &mut yuyv[y * even_w * 2..(y + 1) * even_w * 2];
+ for pair in 0..(even_w / 2) {
+ let x0 = pair * 2;
+ let x1 = (x0 + 1).min(w - 1);
+
+ let b0 = i32::from(src_row[x0 * 4]);
+ let g0 = i32::from(src_row[x0 * 4 + 1]);
+ let r0 = i32::from(src_row[x0 * 4 + 2]);
+
+ let b1 = i32::from(src_row[x1 * 4]);
+ let g1 = i32::from(src_row[x1 * 4 + 1]);
+ let r1 = i32::from(src_row[x1 * 4 + 2]);
+
+ let y0 = (((66 * r0 + 129 * g0 + 25 * b0 + 128) >> 8) + 16).clamp(16, 235) as u8;
+ let y1 = (((66 * r1 + 129 * g1 + 25 * b1 + 128) >> 8) + 16).clamp(16, 235) as u8;
+
+ let r_avg = (r0 + r1) >> 1;
+ let g_avg = (g0 + g1) >> 1;
+ let b_avg = (b0 + b1) >> 1;
+
+ let u = (((-38 * r_avg - 74 * g_avg + 112 * b_avg + 128) >> 8) + 128).clamp(16, 240) as u8;
+ let v = (((112 * r_avg - 94 * g_avg - 18 * b_avg + 128) >> 8) + 128).clamp(16, 240) as u8;
+
+ let dst_off = pair * 4;
+ dst_row[dst_off] = y0;
+ dst_row[dst_off + 1] = u;
+ dst_row[dst_off + 2] = y1;
+ dst_row[dst_off + 3] = v;
+ }
+ }
+}
+
+/// Active Linux `v4l2loopback` feeder handle.
+pub struct VirtualCameraHandle {
+ stop: Arc<AtomicBool>,
+ worker: Option<thread::JoinHandle<()>>,
+}
+
+impl std::fmt::Debug for VirtualCameraHandle {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VirtualCameraHandle").field("running", &!self.stop.load(Ordering::Relaxed)).finish()
+ }
+}
impl VirtualCameraHandle {
+ /// Spawns the `"vcam-v4l2"` background worker that reads BGRX frames from
+ /// [`SharedFrameMapping`] and writes YUYV frames into the `v4l2loopback` device node.
pub fn start() -> Result<Self, String> {
- Err("not supported on Linux yet".into())
+ let stop = Arc::new(AtomicBool::new(false));
+ let stop_worker = stop.clone();
+ let worker = thread::Builder::new()
+ .name("vcam-v4l2".into())
+ .spawn(move || v4l2_worker_loop(&stop_worker))
+ .map_err(|e| format!("spawn vcam-v4l2 thread: {e}"))?;
+ Ok(Self { stop, worker: Some(worker) })
+ }
+}
+
+impl Drop for VirtualCameraHandle {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(worker) = self.worker.take() {
+ let _ = worker.join();
+ }
+ }
+}
+
+fn configure_v4l2_yuyv(fd: i32, width: u32, height: u32) -> bool {
+ let even_w = (width + 1) & !1;
+ let stride = even_w * 2;
+ let sizeimage = stride * height;
+ let mut fmt = V4l2Format {
+ type_: V4L2_BUF_TYPE_VIDEO_OUTPUT,
+ _pad: 0,
+ pix: V4l2PixFormat {
+ width: even_w,
+ height,
+ pixelformat: V4L2_PIX_FMT_YUYV,
+ field: V4L2_FIELD_NONE,
+ bytesperline: stride,
+ sizeimage,
+ colorspace: V4L2_COLORSPACE_SMPTE170M,
+ priv_: 0,
+ flags: 0,
+ ycbcr_enc: 0,
+ quantization: 0,
+ xfer_func: 0,
+ },
+ _rest: [0u8; 200 - std::mem::size_of::<V4l2PixFormat>()],
+ };
+ // SAFETY: `VIDIOC_S_FMT` is called on a valid V4L2 device file descriptor with a properly
+ // sized `v4l2_format` structure.
+ unsafe { libc::ioctl(fd, VIDIOC_S_FMT, &raw mut fmt) == 0 }
+}
+
+fn v4l2_worker_loop(stop: &AtomicBool) {
+ const OUT_W: u32 = 1280;
+ const OUT_H: u32 = 720;
+
+ let mut mapping: Option<SharedFrameMapping> = None;
+ let mut v4l2_file: Option<fs::File> = None;
+ let mut configured_dims: Option<(u32, u32)> = None;
+ let mut bgrx = Vec::new();
+ let mut yuyv = Vec::new();
+ let mut last_ts: Option<(bool, u64)> = None;
+
+ while !stop.load(Ordering::Acquire) {
+ if mapping.is_none() {
+ mapping = SharedFrameMapping::open_existing(DEFAULT_MAPPING_NAME)
+ .or_else(|_| SharedFrameMapping::open_existing(LOCAL_MAPPING_NAME))
+ .ok();
+ }
+
+ if v4l2_file.is_none()
+ && let Some(dev_path) = find_v4l2loopback_device()
+ && let Ok(file) = OpenOptions::new().read(true).write(true).open(&dev_path)
+ {
+ v4l2_file = Some(file);
+ configured_dims = None;
+ last_ts = None;
+ }
+
+ let (Some(map), Some(dev)) = (mapping.as_ref(), v4l2_file.as_mut()) else {
+ thread::sleep(Duration::from_millis(50));
+ continue;
+ };
+
+ if bgrx.len() != (OUT_W * OUT_H * 4) as usize {
+ bgrx.resize((OUT_W * OUT_H * 4) as usize, 0);
+ }
+
+ let state = map.read_bgrx(OUT_W, OUT_H, &mut bgrx);
+ if state.0 && last_ts == Some(state) {
+ thread::sleep(Duration::from_millis(8));
+ continue;
+ }
+ last_ts = Some(state);
+
+ if configured_dims != Some((OUT_W, OUT_H)) {
+ let _ = configure_v4l2_yuyv(dev.as_raw_fd(), OUT_W, OUT_H);
+ configured_dims = Some((OUT_W, OUT_H));
+ }
+
+ bgrx_to_yuyv(&bgrx, OUT_W, OUT_H, &mut yuyv);
+ if dev.write_all(&yuyv).is_err() {
+ v4l2_file = None;
+ configured_dims = None;
+ thread::sleep(Duration::from_millis(50));
+ } else if !state.0 {
+ thread::sleep(Duration::from_millis(33));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn v4l2_format_struct_has_kernel_abi_size() {
+ assert_eq!(std::mem::size_of::<V4l2Format>(), 208);
+ }
+
+ #[test]
+ fn bgrx_to_yuyv_converts_colors_and_rounds_odd_widths() {
+ // 2x1 pure black and pure white pixels in BGRX.
+ let bgrx = [
+ 0, 0, 0, 255, // black
+ 255, 255, 255, 255, // white
+ ];
+ let mut yuyv = Vec::new();
+ bgrx_to_yuyv(&bgrx, 2, 1, &mut yuyv);
+ assert_eq!(yuyv.len(), 4);
+ assert_eq!(yuyv[0], 16, "black Y should be studio-swing 16");
+ assert_eq!(yuyv[2], 235, "white Y should be studio-swing 235");
+ assert!((126..=130).contains(&yuyv[1]), "neutral U should be ~128, got {}", yuyv[1]);
+ assert!((126..=130).contains(&yuyv[3]), "neutral V should be ~128, got {}", yuyv[3]);
+
+ // Odd width (3x2) rounds up to 4x2 -> 16 bytes of YUYV.
+ let odd_bgrx = vec![0x80u8; 3 * 2 * 4];
+ bgrx_to_yuyv(&odd_bgrx, 3, 2, &mut yuyv);
+ assert_eq!(yuyv.len(), 4 * 2 * 2);
+ }
+
+ #[test]
+ fn find_v4l2loopback_in_sysfs_prefers_nectarlink_and_matches_loopback() {
+ let dir = tempfile::tempdir().unwrap();
+ let sysfs = dir.path().join("sys");
+ let dev = dir.path().join("dev");
+ let v0 = sysfs.join("class/video4linux/video0");
+ let v1 = sysfs.join("class/video4linux/video1");
+ fs::create_dir_all(&v0).unwrap();
+ fs::create_dir_all(&v1).unwrap();
+ fs::create_dir_all(&dev).unwrap();
+
+ fs::write(v0.join("name"), "Integrated Camera: USB\n").unwrap();
+ fs::write(v1.join("name"), "NectarLink Webcam\n").unwrap();
+ fs::write(dev.join("video0"), b"").unwrap();
+ fs::write(dev.join("video1"), b"").unwrap();
+
+ let found = find_v4l2loopback_in_sysfs(&sysfs, &dev);
+ assert_eq!(found, Some(dev.join("video1")));
+ }
+
+ #[test]
+ fn virtual_camera_handle_starts_and_drops_cleanly() {
+ let handle = VirtualCameraHandle::start().expect("should spawn vcam-v4l2 worker");
+ drop(handle);
}
}
diff --git a/desktop/app/src/linux/vmic.rs b/desktop/app/src/linux/vmic.rs
index ad98bd0..e7bdb6c 100644
--- a/desktop/app/src/linux/vmic.rs
+++ b/desktop/app/src/linux/vmic.rs
@@ -1,23 +1,652 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Phone-as-Microphone virtual audio source on Linux via PulseAudio / PipeWire
+//! `module-pipe-source`, including FIFO creation (`mkfifo`), non-blocking PCM
+//! writes, gain/mute processing, and RMS level metering.
+
+use std::ffi::CString;
+use std::fs::{File, OpenOptions};
+use std::io::{ErrorKind, Write};
+use std::os::unix::ffi::OsStrExt;
+use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+pub const SOURCE_NAME: &str = "NectarLink_Virtual_Mic";
+pub const DEFAULT_DESCRIPTION: &str = "NectarLink Phone Microphone";
+const FIFO_FILENAME: &str = "nectarlink-vmic.pcm";
+
+/// Returns a user-private path for the virtual microphone FIFO.
+///
+/// Prefers `$XDG_RUNTIME_DIR/nectarlink-vmic.pcm` (which is mode `0700` and
+/// private to the current user, where PipeWire and PulseAudio keep their own
+/// sockets). Falls back to a `0700` user-owned directory under the user's cache
+/// directory if `$XDG_RUNTIME_DIR` is not set.
+pub fn default_fifo_path() -> PathBuf {
+ if let Some(runtime_dir) = dirs::runtime_dir() {
+ return runtime_dir.join(FIFO_FILENAME);
+ }
+ // SAFETY: `geteuid` is always safe to call on Unix.
+ let uid = unsafe { libc::geteuid() };
+ let base = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
+ base.join(format!("nectarlink-{uid}")).join(FIFO_FILENAME)
+}
+
+const MAX_PHONE_NAME_CHARS: usize = 64;
+
+/// Sanitizes an untrusted peer `phone_name` for embedding inside PulseAudio /
+/// PipeWire `source_properties`.
+///
+/// Only alphanumeric characters and safe display punctuation (`' '`, `'-'`,
+/// `'_'`, `'.'`, `'('`, `')'`, `'+'`) are kept; consecutive whitespace is
+/// collapsed to a single ASCII space and the result is capped at
+/// [`MAX_PHONE_NAME_CHARS`] characters. Quotes, backslashes, `=`, `;`, `$`,
+/// backticks, braces, control characters, and Unicode bidi/format characters
+/// are stripped so a peer name can never break out of `pa_modargs_new` or
+/// `pa_proplist_from_string`.
+pub fn sanitize_phone_name(phone_name: &str) -> Option<String> {
+ let mut out = String::new();
+ let mut prev_space = true;
+ for c in phone_name.chars() {
+ if out.chars().count() >= MAX_PHONE_NAME_CHARS {
+ break;
+ }
+ if c.is_whitespace() {
+ if !prev_space && !c.is_control() {
+ out.push(' ');
+ prev_space = true;
+ }
+ } else if c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | '(' | ')' | '+') {
+ out.push(c);
+ prev_space = false;
+ }
+ }
+ let trimmed = out.trim();
+ if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
+}
+
+/// Formats the `source_properties` argument for `pactl load-module module-pipe-source`.
+///
+/// PulseAudio / PipeWire parses module arguments in two passes:
+/// 1. `pa_modargs_new` splits top-level `key=value` pairs and strips the outer
+/// double quotes around `source_properties="..."`.
+/// 2. `pa_proplist_from_string` parses `device.description='...'` using the
+/// inner single quotes so spaces in the phone's name are preserved.
+pub fn format_source_properties(phone_name: Option<&str>) -> String {
+ let description = match phone_name.and_then(sanitize_phone_name) {
+ Some(name) => format!("{name} (NectarLink)"),
+ None => DEFAULT_DESCRIPTION.to_string(),
+ };
+ format!("source_properties=\"device.description='{description}'\"")
+}
+
+/// Formats `source_properties` with an explicit `"Mono"` or `"Stereo"` channel
+/// suffix and `device.profile.description` so PulseAudio Volume Control
+/// (`pavucontrol`) displays the channel layout alongside the device name just
+/// like hardware ALSA profiles.
+pub fn format_source_properties_with_channels(phone_name: Option<&str>, channels: u8) -> String {
+ let mode = if channels <= 1 { "Mono" } else { "Stereo" };
+ let description = match phone_name.and_then(sanitize_phone_name) {
+ Some(name) => format!("{name} (NectarLink) {mode}"),
+ None => format!("{DEFAULT_DESCRIPTION} {mode}"),
+ };
+ format!("source_properties=\"device.description='{description}' device.profile.description='{mode}'\"")
+}
+
+/// Formats and validates the `file="..."` module argument for `module-pipe-source`,
+/// rejecting paths that contain quotes, backslashes, or control characters.
+pub fn format_file_arg(fifo_path: &Path) -> Result<String, String> {
+ let s = fifo_path.to_str().ok_or_else(|| "FIFO path is not valid UTF-8".to_string())?;
+ if s.is_empty() || s.chars().any(|c| c.is_control() || matches!(c, '"' | '\'' | '\\')) {
+ return Err(format!("unsafe characters in FIFO path: {}", fifo_path.display()));
+ }
+ Ok(format!("file=\"{s}\""))
+}
pub fn is_available() -> bool {
- false
+ Command::new("pactl").arg("info").output().map(|o| o.status.success()).unwrap_or(false)
+}
+
+/// Ensures that `fifo_path` exists on disk as a Unix FIFO (`0o600`) owned by the
+/// current effective UID. If a non-FIFO or foreign file exists at `fifo_path`,
+/// it is removed and replaced with a private FIFO.
+pub fn ensure_fifo(fifo_path: &Path) -> Result<(), String> {
+ // SAFETY: `geteuid` is always safe to call on Unix.
+ let euid = unsafe { libc::geteuid() };
+
+ if let Some(parent) = fifo_path.parent()
+ && !parent.as_os_str().is_empty()
+ {
+ if !parent.exists() {
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(parent)
+ .map_err(|e| format!("create FIFO parent dir: {e}"))?;
+ }
+ let parent_meta = std::fs::symlink_metadata(parent)
+ .map_err(|e| format!("stat FIFO parent dir {}: {e}", parent.display()))?;
+ if parent_meta.file_type().is_symlink() || !parent_meta.is_dir() || parent_meta.uid() != euid {
+ return Err(format!("refusing to create FIFO in untrusted directory {}", parent.display()));
+ }
+ }
+
+ if let Ok(meta) = std::fs::symlink_metadata(fifo_path) {
+ if meta.file_type().is_fifo() && meta.uid() == euid {
+ return Ok(());
+ }
+ std::fs::remove_file(fifo_path)
+ .map_err(|e| format!("remove non-FIFO at {}: {e}", fifo_path.display()))?;
+ }
+
+ let c_path =
+ CString::new(fifo_path.as_os_str().as_bytes()).map_err(|e| format!("invalid FIFO path: {e}"))?;
+ // SAFETY: `c_path` is a valid NUL-terminated path string.
+ let rc = unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) };
+ if rc != 0 {
+ let err = std::io::Error::last_os_error();
+ if err.kind() == ErrorKind::AlreadyExists
+ && std::fs::symlink_metadata(fifo_path)
+ .map(|m| m.file_type().is_fifo() && m.uid() == euid)
+ .unwrap_or(false)
+ {
+ return Ok(());
+ }
+ return Err(format!("mkfifo({}): {err}", fifo_path.display()));
+ }
+ Ok(())
+}
+
+/// Opens `fifo_path` in non-blocking read-write mode (`O_RDWR | O_NONBLOCK | O_NOFOLLOW`)
+/// so opening and writing never block when no PulseAudio/PipeWire reader is attached,
+/// and symlinks are never followed.
+pub fn open_fifo_nonblocking(fifo_path: &Path) -> std::io::Result<File> {
+ OpenOptions::new()
+ .read(true)
+ .write(true)
+ .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
+ .open(fifo_path)
+}
+
+/// Returns the PulseAudio / PipeWire `channel_map` argument for `channels`.
+pub fn format_channel_map(channels: u8) -> &'static str {
+ if channels <= 1 { "channel_map=mono" } else { "channel_map=front-left,front-right" }
}
-pub fn cleanup_stale_sources() {}
-pub struct VirtualMic;
+/// Duplicates 1-channel `s16le` mono samples into 2-channel interleaved
+/// `s16le` stereo (`[L, R, L, R, ...]`) so both left and right channels carry
+/// identical full-scale signal.
+pub fn mono_to_stereo_s16le(mono_pcm: &[u8]) -> Vec<u8> {
+ let sample_count = mono_pcm.len() / 2;
+ let mut stereo = Vec::with_capacity(sample_count * 4);
+ for sample in mono_pcm.as_chunks::<2>().0 {
+ stereo.extend_from_slice(sample);
+ stereo.extend_from_slice(sample);
+ }
+ stereo
+}
+
+/// Extracts module IDs from `pactl list modules short` output that belong to a
+/// NectarLink `module-pipe-source` instance (including legacy `/tmp/nectarlink-vmic.pcm`
+/// or `NectarLink_Phone_Microphone` modules).
+pub fn parse_stale_pipe_source_modules(pactl_short: &str) -> Vec<u32> {
+ let mut ids = Vec::new();
+ for line in pactl_short.lines() {
+ let trimmed = line.trim();
+ if !trimmed.contains("module-pipe-source") {
+ continue;
+ }
+ if (trimmed.contains(SOURCE_NAME)
+ || trimmed.contains("NectarLink_Phone_Microphone")
+ || trimmed.contains(FIFO_FILENAME))
+ && let Some(id_str) = trimmed.split_whitespace().next()
+ && let Ok(id) = id_str.parse::<u32>()
+ {
+ ids.push(id);
+ }
+ }
+ ids
+}
+
+/// Unloads any leftover NectarLink `module-pipe-source` modules in
+/// PulseAudio / PipeWire and removes any legacy `/tmp/nectarlink-vmic.pcm` FIFO.
+pub fn cleanup_stale_sources() {
+ if let Ok(output) = Command::new("pactl").args(["list", "modules", "short"]).output()
+ && output.status.success()
+ {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ for id in parse_stale_pipe_source_modules(&stdout) {
+ destroy_source(id);
+ }
+ }
+ let legacy_tmp = Path::new("/tmp").join(FIFO_FILENAME);
+ if legacy_tmp.exists() {
+ let _ = std::fs::remove_file(legacy_tmp);
+ }
+}
+
+pub fn create_source(rate: u32, channels: u8) -> Result<u32, String> {
+ let fifo_path = default_fifo_path();
+ create_source_with_label(rate, channels, &fifo_path, None)
+}
+
+pub fn create_source_with_path(rate: u32, channels: u8, fifo_path: &Path) -> Result<u32, String> {
+ create_source_with_label(rate, channels, fifo_path, None)
+}
+
+pub fn create_source_with_label(
+ rate: u32,
+ channels: u8,
+ fifo_path: &Path,
+ phone_name: Option<&str>,
+) -> Result<u32, String> {
+ let file_arg = format_file_arg(fifo_path)?;
+ cleanup_stale_sources();
+ let _ = ensure_fifo(fifo_path);
+ let clean_channels = channels.clamp(1, 2);
+ let source_props = format_source_properties_with_channels(phone_name, clean_channels);
+ let output = Command::new("pactl")
+ .args([
+ "load-module",
+ "module-pipe-source",
+ &format!("source_name={SOURCE_NAME}"),
+ &file_arg,
+ "format=s16le",
+ &format!("rate={}", rate.max(8_000)),
+ &format!("channels={clean_channels}"),
+ format_channel_map(clean_channels),
+ &source_props,
+ ])
+ .output()
+ .map_err(|e| format!("failed to run pactl: {e}"))?;
+ if !output.status.success() {
+ return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
+ }
+ let module_id = String::from_utf8_lossy(&output.stdout)
+ .trim()
+ .parse::<u32>()
+ .map_err(|e| format!("invalid pactl module id: {e}"))?;
+
+ // Ensure the virtual source is unmuted and at 100% (0 dB) unity gain in PipeWire/PulseAudio.
+ let _ = Command::new("pactl").args(["set-source-mute", SOURCE_NAME, "0"]).status();
+ let _ = Command::new("pactl").args(["set-source-volume", SOURCE_NAME, "100%"]).status();
+
+ Ok(module_id)
+}
+
+pub fn destroy_source(module_id: u32) {
+ let _ = Command::new("pactl").args(["unload-module", &module_id.to_string()]).status();
+}
+
+/// Default makeup pre-gain (in dB) applied to phone microphone streams on Linux
+/// to compensate for handset `VOICE_COMMUNICATION` attenuation at desk distance.
+pub const DEFAULT_PHONE_MAKEUP_GAIN_DB: f32 = 9.0;
+
+/// Applies `gain_db` (`-12.0..=24.0`) and `muted` to 16-bit signed little-endian
+/// PCM samples, returning `(processed_pcm_bytes, rms_level_0_to_1)`.
+pub fn process_mic_pcm_s16le(pcm: &[u8], gain_db: f32, muted: bool) -> (Vec<u8>, f32) {
+ let sample_count = pcm.len() / 2;
+ if sample_count == 0 {
+ return (Vec::new(), 0.0);
+ }
+ if muted {
+ return (vec![0u8; sample_count * 2], 0.0);
+ }
+
+ let clamped_db = if gain_db.is_finite() { gain_db.clamp(-12.0, 24.0) } else { 0.0 };
+ let linear_gain = 10.0_f32.powf(clamped_db / 20.0);
+ let mut out = Vec::with_capacity(sample_count * 2);
+ let mut sum_sq = 0.0_f64;
+
+ for chunk in pcm.as_chunks::<2>().0 {
+ let raw = i16::from_le_bytes([chunk[0], chunk[1]]);
+ let norm = (f32::from(raw) / 32768.0) * linear_gain;
+ // Soft-knee saturation above 0.9 to prevent harsh digital clipping.
+ let limited = if norm.abs() > 0.9 {
+ let sign = norm.signum();
+ let excess = norm.abs() - 0.9;
+ sign * (0.9 + 0.1 * (excess / (0.1 + excess)))
+ } else {
+ norm
+ }
+ .clamp(-1.0, 1.0);
+
+ sum_sq += f64::from(limited) * f64::from(limited);
+ let scaled = (limited * 32767.0).round() as i16;
+ out.extend_from_slice(&scaled.to_le_bytes());
+ }
+
+ let rms = ((sum_sq / (sample_count as f64)).sqrt() as f32).clamp(0.0, 1.0);
+ (out, rms)
+}
+
+/// Manages a PipeWire / PulseAudio virtual microphone pipe source and its
+/// real-time gain/mute/RMS state.
+#[derive(Debug)]
+pub struct VirtualMic {
+ fifo_path: PathBuf,
+ fifo_file: Option<File>,
+ module_id: Option<u32>,
+ input_channels: u8,
+ output_channels: u8,
+ gain_db: f32,
+ muted: bool,
+ last_rms: f32,
+}
impl VirtualMic {
- pub fn new_for_phone(_rate: u32, _input_channels: u8, _phone_name: Option<&str>) -> Self {
- Self
+ /// Creates a new `VirtualMic` controller and attempts to register the
+ /// underlying `module-pipe-source` in PulseAudio/PipeWire.
+ pub fn new(rate: u32, channels: u8) -> Self {
+ let ch = channels.clamp(1, 2);
+ let fifo_path = default_fifo_path();
+ let _ = ensure_fifo(&fifo_path);
+ let fifo_file = open_fifo_nonblocking(&fifo_path).ok();
+ let module_id = create_source_with_label(rate, ch, &fifo_path, None).ok();
+ Self {
+ fifo_path,
+ fifo_file,
+ module_id,
+ input_channels: ch,
+ output_channels: ch,
+ gain_db: 0.0,
+ muted: false,
+ last_rms: 0.0,
+ }
+ }
+
+ /// Creates a new `VirtualMic` controller labeled with `phone_name` (for example,
+ /// `"Pixel 9a (NectarLink)"`) and registers a 2-channel stereo `module-pipe-source`
+ /// by default (upmixing mono phone audio to L+R).
+ pub fn new_for_phone(rate: u32, input_channels: u8, phone_name: Option<&str>) -> Self {
+ Self::new_for_phone_with_channels(rate, input_channels, 2, phone_name)
+ }
+
+ /// Creates a new `VirtualMic` controller labeled with `phone_name` and explicit
+ /// `input_channels` (from the phone) and `output_channels` (`1` for Mono, `2` for Stereo).
+ pub fn new_for_phone_with_channels(
+ rate: u32,
+ input_channels: u8,
+ output_channels: u8,
+ phone_name: Option<&str>,
+ ) -> Self {
+ let in_ch = input_channels.clamp(1, 2);
+ let out_ch = output_channels.clamp(1, 2);
+ let fifo_path = default_fifo_path();
+ let _ = ensure_fifo(&fifo_path);
+ let fifo_file = open_fifo_nonblocking(&fifo_path).ok();
+ let module_id = create_source_with_label(rate, out_ch, &fifo_path, phone_name).ok();
+ Self {
+ fifo_path,
+ fifo_file,
+ module_id,
+ input_channels: in_ch,
+ output_channels: out_ch,
+ gain_db: DEFAULT_PHONE_MAKEUP_GAIN_DB,
+ muted: false,
+ last_rms: 0.0,
+ }
+ }
+
+ /// Creates a `VirtualMic` backed by a specific FIFO path (creating the FIFO if needed)
+ /// without invoking `pactl`.
+ pub fn open_fifo_only(fifo_path: impl Into<PathBuf>) -> Result<Self, String> {
+ let fifo_path = fifo_path.into();
+ ensure_fifo(&fifo_path)?;
+ let fifo_file = open_fifo_nonblocking(&fifo_path)
+ .map_err(|e| format!("open FIFO {}: {e}", fifo_path.display()))?;
+ Ok(Self {
+ fifo_path,
+ fifo_file: Some(fifo_file),
+ module_id: None,
+ input_channels: 1,
+ output_channels: 1,
+ gain_db: 0.0,
+ muted: false,
+ last_rms: 0.0,
+ })
}
+
pub fn is_active(&self) -> bool {
- false
+ self.module_id.is_some()
+ }
+
+ pub fn fifo_path(&self) -> &Path {
+ &self.fifo_path
+ }
+
+ pub fn output_channels(&self) -> u8 {
+ self.output_channels
+ }
+
+ pub fn set_gain_db(&mut self, gain_db: f32) {
+ self.gain_db = if gain_db.is_finite() { gain_db.clamp(-12.0, 24.0) } else { 0.0 };
+ }
+
+ pub fn gain_db(&self) -> f32 {
+ self.gain_db
+ }
+
+ pub fn set_muted(&mut self, muted: bool) {
+ self.muted = muted;
+ if muted {
+ self.last_rms = 0.0;
+ }
}
- pub fn set_gain_db(&mut self, _gain_db: f32) {}
- pub fn set_muted(&mut self, _muted: bool) {}
- pub fn push_pcm(&mut self, _pcm: &[u8]) -> Result<f32, String> {
- Ok(0.0)
+
+ pub fn is_muted(&self) -> bool {
+ self.muted
+ }
+
+ pub fn last_rms(&self) -> f32 {
+ self.last_rms
+ }
+
+ /// Writes already-processed or raw `s16le` bytes into the underlying non-blocking FIFO.
+ /// Returns the number of bytes written (`0` if the kernel pipe buffer is currently full).
+ pub fn write_pcm_s16le(&mut self, pcm: &[u8]) -> Result<usize, String> {
+ if pcm.is_empty() {
+ return Ok(0);
+ }
+ if self.fifo_file.is_none() {
+ ensure_fifo(&self.fifo_path)?;
+ self.fifo_file = open_fifo_nonblocking(&self.fifo_path).ok();
+ }
+ let Some(file) = self.fifo_file.as_mut() else {
+ return Err(format!("FIFO {} is not open", self.fifo_path.display()));
+ };
+ match file.write(pcm) {
+ Ok(n) => Ok(n),
+ Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(0),
+ Err(e) => {
+ self.fifo_file = None;
+ Err(format!("FIFO write error: {e}"))
+ }
+ }
+ }
+
+ /// Processes incoming `s16le` PCM frames (applying `gain_db` and upmixing mono to
+ /// stereo when `input_channels == 1 && output_channels == 2`) and writes them to
+ /// the pipe FIFO if the virtual source or FIFO handle is active.
+ pub fn push_pcm(&mut self, pcm: &[u8]) -> Result<f32, String> {
+ let (processed, rms) = process_mic_pcm_s16le(pcm, self.gain_db, self.muted);
+ self.last_rms = rms;
+ if (self.module_id.is_some() || self.fifo_file.is_some()) && !processed.is_empty() {
+ if self.input_channels == 1 && self.output_channels == 2 {
+ let stereo = mono_to_stereo_s16le(&processed);
+ let _ = self.write_pcm_s16le(&stereo);
+ } else {
+ let _ = self.write_pcm_s16le(&processed);
+ }
+ }
+ Ok(rms)
+ }
+}
+
+impl Drop for VirtualMic {
+ fn drop(&mut self) {
+ self.fifo_file = None;
+ if let Some(id) = self.module_id.take() {
+ destroy_source(id);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Read;
+ use std::os::unix::fs::PermissionsExt;
+
+ #[test]
+ fn process_mic_pcm_s16le_unity_gain_preserves_signal_and_computes_rms() {
+ let mut raw = Vec::new();
+ for _ in 0..100 {
+ raw.extend_from_slice(&16384i16.to_le_bytes());
+ }
+ let (out, rms) = process_mic_pcm_s16le(&raw, 0.0, false);
+ assert_eq!(out.len(), raw.len());
+ let first = i16::from_le_bytes([out[0], out[1]]);
+ assert!((first - 16384).abs() <= 2);
+ assert!(rms > 0.45 && rms < 0.55, "expected ~0.5 RMS, got {rms}");
+ }
+
+ #[test]
+ fn process_mic_pcm_s16le_mute_zeroes_samples_and_rms() {
+ let mut raw = Vec::new();
+ for _ in 0..64 {
+ raw.extend_from_slice(&20000i16.to_le_bytes());
+ }
+ let (out, rms) = process_mic_pcm_s16le(&raw, 12.0, true);
+ assert!(out.iter().all(|&b| b == 0));
+ assert_eq!(rms, 0.0);
+ }
+
+ #[test]
+ fn process_mic_pcm_s16le_boosts_and_soft_limits_peaks() {
+ let mut raw = Vec::new();
+ raw.extend_from_slice(&10000i16.to_le_bytes());
+ raw.extend_from_slice(&30000i16.to_le_bytes());
+ let (out, rms) = process_mic_pcm_s16le(&raw, 6.0, false);
+ let s0 = i16::from_le_bytes([out[0], out[1]]);
+ let s1 = i16::from_le_bytes([out[2], out[3]]);
+ assert!(s0 > 18000, "+6 dB should roughly double moderate sample: {s0}");
+ assert!(s1 >= 29000, "soft limiter should keep loud sample near full scale: {s1}");
+ assert!(rms > 0.5 && rms <= 1.0);
+ }
+
+ #[test]
+ fn ensure_fifo_creates_named_pipe_and_nonblocking_writes_succeed_without_reader() {
+ let dir = tempfile::tempdir().unwrap();
+ let fifo_path = dir.path().join("test-vmic.pcm");
+
+ // Write a regular file first to verify `ensure_fifo` replaces non-FIFOs.
+ std::fs::write(&fifo_path, b"stale").unwrap();
+ ensure_fifo(&fifo_path).expect("ensure_fifo should replace regular file with FIFO");
+
+ let meta = std::fs::symlink_metadata(&fifo_path).unwrap();
+ assert!(meta.file_type().is_fifo(), "path must be a Unix FIFO");
+ assert_eq!(meta.permissions().mode() & 0o777, 0o600);
+
+ let mut vmic = VirtualMic::open_fifo_only(&fifo_path).expect("should open FIFO non-blocking");
+ let mut raw = Vec::new();
+ for _ in 0..32 {
+ raw.extend_from_slice(&8192i16.to_le_bytes());
+ }
+ let rms = vmic.push_pcm(&raw).expect("push_pcm should not block without reader");
+ assert!(rms > 0.2 && rms < 0.3, "expected ~0.25 RMS, got {rms}");
+
+ let mut reader = open_fifo_nonblocking(&fifo_path).unwrap();
+ let mut buf = vec![0u8; raw.len()];
+ let n = reader.read(&mut buf).expect("should read pushed PCM bytes from FIFO");
+ assert_eq!(n, raw.len());
+ }
+
+ #[test]
+ fn format_source_properties_quotes_description_and_strips_unsafe_chars() {
+ assert_eq!(
+ format_source_properties(None),
+ "source_properties=\"device.description='NectarLink Phone Microphone'\""
+ );
+ assert_eq!(
+ format_source_properties(Some(" ")),
+ "source_properties=\"device.description='NectarLink Phone Microphone'\""
+ );
+ assert_eq!(
+ format_source_properties(Some("Pixel 9a")),
+ "source_properties=\"device.description='Pixel 9a (NectarLink)'\""
+ );
+ assert_eq!(
+ format_source_properties(Some("Samsung S20 FE (Work)")),
+ "source_properties=\"device.description='Samsung S20 FE (Work) (NectarLink)'\""
+ );
+ assert_eq!(
+ format_source_properties(Some("Jochen's \"Phone\" \\ \n\t")),
+ "source_properties=\"device.description='Jochens Phone (NectarLink)'\""
+ );
+ assert_eq!(
+ format_source_properties(Some("Phone' file=/etc/passwd; $(id) `uname`")),
+ "source_properties=\"device.description='Phone fileetcpasswd (id) uname (NectarLink)'\""
+ );
+ assert_eq!(
+ format_source_properties(Some("'\"\\=;$`{}")),
+ "source_properties=\"device.description='NectarLink Phone Microphone'\""
+ );
+ let long_name = "A".repeat(120);
+ let props = format_source_properties(Some(&long_name));
+ assert!(props.contains(&format!("'{} (NectarLink)'", "A".repeat(64))));
+
+ assert_eq!(
+ format_file_arg(Path::new("/run/user/1000/nectarlink-vmic.pcm")).unwrap(),
+ "file=\"/run/user/1000/nectarlink-vmic.pcm\""
+ );
+ assert!(format_file_arg(Path::new("/tmp/bad\"quote.pcm")).is_err());
+ assert!(format_file_arg(Path::new("/tmp/bad'quote.pcm")).is_err());
+ assert!(format_file_arg(Path::new("/tmp/bad\\slash.pcm")).is_err());
+ }
+
+ #[test]
+ fn default_fifo_path_never_uses_shared_tmp_root() {
+ let path = default_fifo_path();
+ assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("nectarlink-vmic.pcm"));
+ assert_ne!(
+ path.parent(),
+ Some(Path::new("/tmp")),
+ "FIFO must not be placed directly in world-writable /tmp: {}",
+ path.display()
+ );
+ }
+
+ #[test]
+ fn parse_stale_pipe_source_modules_identifies_nectarlink_modules_only() {
+ let sample = "\
+25\tmodule-native-protocol-unix\t\n\
+536870913\tmodule-pipe-source\tsource_name=NectarLink_Virtual_Mic file=/tmp/nectarlink-vmic.pcm format=s16le rate=48000 channels=1 source_properties=device.description=NectarLink_Phone_Microphone\n\
+536870914\tmodule-pipe-source\tsource_name=NectarLink_Virtual_Mic file=\"/run/user/1000/nectarlink-vmic.pcm\" format=s16le rate=48000 channels=1 source_properties=\"device.description='IOSMOB5 (NectarLink)'\"\n\
+536870915\tmodule-pipe-source\tsource_name=Other_Pipe file=/tmp/other.pcm\n";
+ assert_eq!(parse_stale_pipe_source_modules(sample), vec![536870913, 536870914]);
+ }
+
+ #[test]
+ fn mono_to_stereo_duplicates_samples_and_format_channel_map_aligns_channels() {
+ assert_eq!(format_channel_map(1), "channel_map=mono");
+ assert_eq!(format_channel_map(2), "channel_map=front-left,front-right");
+ assert_eq!(
+ format_source_properties_with_channels(Some("IOSMOB5"), 1),
+ "source_properties=\"device.description='IOSMOB5 (NectarLink) Mono' device.profile.description='Mono'\""
+ );
+ assert_eq!(
+ format_source_properties_with_channels(Some("IOSMOB5"), 2),
+ "source_properties=\"device.description='IOSMOB5 (NectarLink) Stereo' device.profile.description='Stereo'\""
+ );
+
+ let mut mono = Vec::new();
+ mono.extend_from_slice(&1234i16.to_le_bytes());
+ mono.extend_from_slice(&(-5678i16).to_le_bytes());
+ let stereo = mono_to_stereo_s16le(&mono);
+ assert_eq!(stereo.len(), 8);
+ assert_eq!(i16::from_le_bytes([stereo[0], stereo[1]]), 1234);
+ assert_eq!(i16::from_le_bytes([stereo[2], stereo[3]]), 1234);
+ assert_eq!(i16::from_le_bytes([stereo[4], stereo[5]]), -5678);
+ assert_eq!(i16::from_le_bytes([stereo[6], stereo[7]]), -5678);
}
}
diff --git a/desktop/app/src/linux/wallpaper.rs b/desktop/app/src/linux/wallpaper.rs
index 4b9be79..e5c2cca 100644
--- a/desktop/app/src/linux/wallpaper.rs
+++ b/desktop/app/src/linux/wallpaper.rs
@@ -1,14 +1,389 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! Desktop wallpaper seed color and Material You / Bloom scheme extraction on Linux.
+//!
+//! Discovers the current wallpaper across GNOME, Cinnamon, MATE, Budgie,
+//! KDE Plasma, Hyprland (`hyprpaper`), Nitrogen, and `feh` (`~/.fehbg`),
+//! downsamples it to [`palette::MAX_SAMPLE_SIDE`], and extracts perceptual
+//! Material 3 tonal seeds and full artwork schemes.
-use std::path::Path;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::Mutex;
+use std::time::SystemTime;
-pub fn seed() -> Option<material_colors::color::Rgb> {
+use material_colors::color::Rgb;
+
+use crate::palette;
+
+use super::image;
+
+const SAMPLE_MAX_DIM: u32 = palette::MAX_SAMPLE_SIDE;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Source {
+ Image { path: PathBuf, modified: Option<SystemTime>, len: u64 },
+ Solid(Rgb),
+}
+
+static LAST: Mutex<Option<(Source, Option<Rgb>)>> = Mutex::new(None);
+
+/// Returns the Material You seed color for the current desktop wallpaper,
+/// caching the result until the wallpaper file changes.
+pub fn seed() -> Option<Rgb> {
+ let source = current_source()?;
+ let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((prev, cached)) = last.as_ref()
+ && prev == &source
+ {
+ return *cached;
+ }
+ let computed = match &source {
+ Source::Image { path, .. } => seed_from_path(path),
+ Source::Solid(rgb) => palette::seed_from_pixels(&[*rgb]),
+ };
+ *last = Some((source, computed));
+ computed
+}
+
+fn current_source() -> Option<Source> {
+ if let Some(path) = current_wallpaper_path()
+ && let Ok(meta) = fs::metadata(&path)
+ && meta.is_file()
+ {
+ return Some(Source::Image { path, modified: meta.modified().ok(), len: meta.len() });
+ }
+ gnome_solid_color().map(Source::Solid)
+}
+
+fn sample_grid(path: &Path) -> Option<(u32, u32, Vec<Rgb>)> {
+ let bytes = fs::read(path).ok()?;
+ let bitmap = image::decode(&bytes).ok()?;
+ let scaled = image::scale_to(&bitmap, SAMPLE_MAX_DIM);
+ let mut pixels = Vec::with_capacity((scaled.width * scaled.height) as usize);
+ for chunk in scaled.bgra.as_chunks::<4>().0 {
+ pixels.push(Rgb::new(chunk[2], chunk[1], chunk[0]));
+ }
+ Some((scaled.width, scaled.height, pixels))
+}
+
+pub fn seed_from_path(path: &Path) -> Option<Rgb> {
+ let (w, h, pixels) = sample_grid(path)?;
+ palette::seed_from_grid(&pixels, w, h)
+}
+
+pub fn artwork_scheme_from_path(path: &Path) -> Option<String> {
+ let (w, h, pixels) = sample_grid(path)?;
+ palette::extract_artwork_scheme_rgb(&pixels, w, h, Some(&path.to_string_lossy()))
+ .map(|s| s.to_json().to_string())
+}
+
+fn percent_decode(input: &str) -> String {
+ let bytes = input.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%'
+ && i + 2 < bytes.len()
+ && let (Some(hi), Some(lo)) =
+ ((bytes[i + 1] as char).to_digit(16), (bytes[i + 2] as char).to_digit(16))
+ {
+ out.push(((hi << 4) | lo) as u8);
+ i += 3;
+ continue;
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+fn expand_tilde(path_str: &str) -> PathBuf {
+ if let Some(rest) = path_str.strip_prefix("~/")
+ && let Some(home) = dirs::home_dir()
+ {
+ return home.join(rest);
+ }
+ if let Some(rest) = path_str.strip_prefix("$HOME/")
+ && let Some(home) = dirs::home_dir()
+ {
+ return home.join(rest);
+ }
+ PathBuf::from(path_str)
+}
+
+/// Parses a `gsettings get` output value (such as `'file:///usr/share/backgrounds/my%20wall.png'`)
+/// into a decoded local [`PathBuf`].
+pub fn parse_gsettings_wallpaper_uri(raw: &str) -> Option<PathBuf> {
+ let trimmed = raw
+ .trim()
+ .strip_prefix("@as ")
+ .unwrap_or(raw.trim())
+ .trim()
+ .trim_matches('\'')
+ .trim_matches('"')
+ .trim();
+ if trimmed.is_empty() || trimmed == "none" {
+ return None;
+ }
+ let without_scheme = trimmed.strip_prefix("file://").unwrap_or(trimmed);
+ let decoded = percent_decode(without_scheme);
+ let cleaned = decoded.trim();
+ if cleaned.is_empty() { None } else { Some(expand_tilde(cleaned)) }
+}
+
+/// Parses KDE Plasma's `plasma-org.kde.plasma.desktop-appletsrc` contents for `Image=` entries.
+pub fn parse_kde_wallpaper_config(content: &str) -> Option<PathBuf> {
+ let mut found: Option<PathBuf> = None;
+ for line in content.lines() {
+ let line = line.trim();
+ if let Some(rest) = line.strip_prefix("Image=")
+ && let Some(path) = parse_gsettings_wallpaper_uri(rest)
+ && path.extension().is_some()
+ {
+ found = Some(path);
+ }
+ }
+ found
+}
+
+/// Parses `~/.fehbg` shell script contents to extract the wallpaper file path.
+pub fn parse_fehbg_wallpaper(content: &str) -> Option<PathBuf> {
+ for line in content.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ if !line.contains("feh") {
+ continue;
+ }
+ // Extract the last single- or double-quoted token, or the last whitespace token.
+ if let Some(end_quote) = line.rfind('\'')
+ && let Some(start_quote) = line[..end_quote].rfind('\'')
+ {
+ let token = line[start_quote + 1..end_quote].trim();
+ if !token.is_empty() && !token.starts_with('-') {
+ return Some(expand_tilde(token));
+ }
+ }
+ if let Some(end_quote) = line.rfind('"')
+ && let Some(start_quote) = line[..end_quote].rfind('"')
+ {
+ let token = line[start_quote + 1..end_quote].trim();
+ if !token.is_empty() && !token.starts_with('-') {
+ return Some(expand_tilde(token));
+ }
+ }
+ if let Some(last) = line.split_whitespace().next_back() {
+ let token = last.trim_matches('\'').trim_matches('"');
+ if !token.is_empty() && !token.starts_with('-') && token != "feh" {
+ return Some(expand_tilde(token));
+ }
+ }
+ }
None
}
-pub fn seed_from_path(_path: &Path) -> Option<material_colors::color::Rgb> {
+
+/// Parses `~/.config/nitrogen/bg-saved.cfg` contents to extract the `file=` wallpaper path.
+pub fn parse_nitrogen_wallpaper(content: &str) -> Option<PathBuf> {
+ for line in content.lines() {
+ let line = line.trim();
+ if let Some(rest) = line.strip_prefix("file=") {
+ let trimmed = rest.trim();
+ if !trimmed.is_empty() {
+ return Some(expand_tilde(trimmed));
+ }
+ }
+ }
None
}
-pub fn artwork_scheme_from_path(_path: &Path) -> Option<String> {
+
+/// Parses `~/.config/hypr/hyprpaper.conf` contents to extract the `wallpaper = monitor,path` entry.
+pub fn parse_hyprpaper_wallpaper(content: &str) -> Option<PathBuf> {
+ for line in content.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ if let Some(rest) = line.strip_prefix("wallpaper") {
+ let rest = rest.trim_start();
+ if let Some(rhs) = rest.strip_prefix('=') {
+ let rhs = rhs.trim();
+ let path_part = match rhs.split_once(',') {
+ Some((_, path)) => path.trim(),
+ None => rhs,
+ };
+ let unquoted = path_part.trim_matches('\'').trim_matches('"').trim();
+ if !unquoted.is_empty() {
+ return Some(expand_tilde(unquoted));
+ }
+ }
+ }
+ }
None
}
+
+fn current_wallpaper_path() -> Option<PathBuf> {
+ let dark = super::system_dark();
+ let uri_keys =
+ if dark { ["picture-uri-dark", "picture-uri"] } else { ["picture-uri", "picture-uri-dark"] };
+
+ for schema in ["org.gnome.desktop.background", "org.cinnamon.desktop.background"] {
+ for key in uri_keys {
+ if let Ok(output) = Command::new("gsettings").args(["get", schema, key]).output()
+ && output.status.success()
+ && let Some(candidate) =
+ parse_gsettings_wallpaper_uri(&String::from_utf8_lossy(&output.stdout))
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+ }
+ }
+
+ for key in ["picture-filename", "picture-uri"] {
+ if let Ok(output) = Command::new("gsettings").args(["get", "org.mate.background", key]).output()
+ && output.status.success()
+ && let Some(candidate) = parse_gsettings_wallpaper_uri(&String::from_utf8_lossy(&output.stdout))
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+ }
+
+ if let Some(config) = dirs::config_dir() {
+ let kde_rc = config.join("plasma-org.kde.plasma.desktop-appletsrc");
+ if let Ok(content) = fs::read_to_string(kde_rc)
+ && let Some(candidate) = parse_kde_wallpaper_config(&content)
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+
+ let hypr_conf = config.join("hypr").join("hyprpaper.conf");
+ if let Ok(content) = fs::read_to_string(hypr_conf)
+ && let Some(candidate) = parse_hyprpaper_wallpaper(&content)
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+
+ let nitrogen_cfg = config.join("nitrogen").join("bg-saved.cfg");
+ if let Ok(content) = fs::read_to_string(nitrogen_cfg)
+ && let Some(candidate) = parse_nitrogen_wallpaper(&content)
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+ }
+
+ if let Some(home) = dirs::home_dir() {
+ let fehbg = home.join(".fehbg");
+ if let Ok(content) = fs::read_to_string(fehbg)
+ && let Some(candidate) = parse_fehbg_wallpaper(&content)
+ && candidate.is_file()
+ {
+ return Some(candidate);
+ }
+ }
+
+ None
+}
+
+fn gnome_solid_color() -> Option<Rgb> {
+ let output = Command::new("gsettings")
+ .args(["get", "org.gnome.desktop.background", "primary-color"])
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ parse_hex_rgb(&String::from_utf8_lossy(&output.stdout))
+}
+
+fn parse_hex_rgb(raw: &str) -> Option<Rgb> {
+ let trimmed = raw.trim().trim_matches('\'').trim_matches('"').trim();
+ let hex = trimmed.strip_prefix('#')?;
+ if hex.len() != 6 {
+ return None;
+ }
+ let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
+ let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
+ let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
+ Some(Rgb::new(r, g, b))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_gsettings_wallpaper_uri_with_quotes_and_percent_encoding() {
+ assert_eq!(
+ parse_gsettings_wallpaper_uri("'file:///usr/share/backgrounds/warty%20final%20ubuntu.png'"),
+ Some(PathBuf::from("/usr/share/backgrounds/warty final ubuntu.png"))
+ );
+ assert_eq!(
+ parse_gsettings_wallpaper_uri("\"/home/user/Pictures/wall.jpg\""),
+ Some(PathBuf::from("/home/user/Pictures/wall.jpg"))
+ );
+ assert_eq!(parse_gsettings_wallpaper_uri("''"), None);
+ assert_eq!(parse_gsettings_wallpaper_uri("'none'"), None);
+ }
+
+ #[test]
+ fn parses_kde_plasma_wallpaper_config() {
+ let sample = "\
+[Containments][1][Wallpaper][org.kde.image][General]
+Image=file:///usr/share/wallpapers/Next/contents/images/5120x2880.png
+SlidePaths=/usr/share/wallpapers
+";
+ assert_eq!(
+ parse_kde_wallpaper_config(sample),
+ Some(PathBuf::from("/usr/share/wallpapers/Next/contents/images/5120x2880.png"))
+ );
+ }
+
+ #[test]
+ fn parses_fehbg_nitrogen_and_hyprpaper_configs() {
+ let fehbg = "#!/bin/sh\nfeh --no-fehbg --bg-fill '/home/alice/wallpapers/forest lake.png' \n";
+ assert_eq!(
+ parse_fehbg_wallpaper(fehbg),
+ Some(PathBuf::from("/home/alice/wallpapers/forest lake.png"))
+ );
+
+ let nitrogen = "[xin_-1]\nfile=/home/alice/Pictures/sunset.jpg\nmode=4\nbgcolor=#000000\n";
+ assert_eq!(
+ parse_nitrogen_wallpaper(nitrogen),
+ Some(PathBuf::from("/home/alice/Pictures/sunset.jpg"))
+ );
+
+ let hyprpaper = "\
+preload = /home/alice/wall.png
+# monitor wallpaper
+wallpaper = DP-1, /home/alice/wall.png
+";
+ assert_eq!(parse_hyprpaper_wallpaper(hyprpaper), Some(PathBuf::from("/home/alice/wall.png")));
+ }
+
+ #[test]
+ fn extracts_seed_and_artwork_scheme_from_png_file() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.path().join("vibrant.png");
+ let width = 32u32;
+ let height = 32u32;
+ let mut bgra = Vec::with_capacity((width * height * 4) as usize);
+ for _ in 0..(width * height) {
+ // Vibrant cobalt blue in BGRA order
+ bgra.extend_from_slice(&[220, 90, 30, 255]);
+ }
+ let png = image::encode_png(&image::Bitmap { width, height, bgra }).expect("encode_png");
+ fs::write(&path, png).expect("write png");
+
+ let seed = seed_from_path(&path).expect("seed_from_path");
+ assert!(seed.blue > seed.red);
+
+ let scheme_json = artwork_scheme_from_path(&path).expect("artwork_scheme_from_path");
+ assert!(scheme_json.contains("primary"));
+ }
+}
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
index 8099443..df3c6c0 100644
--- a/desktop/app/src/mirror.rs
+++ b/desktop/app/src/mirror.rs
@@ -1555,7 +1555,151 @@ fn poll_gamepad() -> Option<GamepadState> {
poll_xinput_gamepad().or_else(poll_winrt_gamepad)
}
-#[cfg(not(windows))]
+#[cfg(target_os = "linux")]
+#[repr(C)]
+#[derive(Clone, Copy, Debug)]
+struct JsEvent {
+ time: u32,
+ value: i16,
+ type_: u8,
+ number: u8,
+}
+
+#[cfg(target_os = "linux")]
+fn apply_js_event(state: &mut GamepadState, ev: JsEvent) {
+ let kind = ev.type_ & !0x80; // Mask out JS_EVENT_INIT (0x80).
+ match kind {
+ 0x01 => {
+ // JS_EVENT_BUTTON
+ let mask: u16 = match ev.number {
+ 0 => 0x1000, // A
+ 1 => 0x2000, // B
+ 2 => 0x4000, // X
+ 3 => 0x8000, // Y
+ 4 => 0x0100, // LB
+ 5 => 0x0200, // RB
+ 6 => 0x0020, // View / Back
+ 7 => 0x0010, // Menu / Start
+ 9 => 0x0040, // LThumb
+ 10 => 0x0080, // RThumb
+ 12 => 0x0001, // DPad Up
+ 13 => 0x0002, // DPad Down
+ 14 => 0x0004, // DPad Left
+ 15 => 0x0008, // DPad Right
+ _ => 0,
+ };
+ if mask != 0 {
+ if ev.value != 0 {
+ state.buttons |= mask;
+ } else {
+ state.buttons &= !mask;
+ }
+ }
+ }
+ 0x02 => {
+ // JS_EVENT_AXIS
+ match ev.number {
+ 0 => state.lx = ev.value,
+ 1 => state.ly = ev.value.saturating_neg(),
+ 2 => {
+ state.lt = ((i32::from(ev.value) + 32768) * 255 / 65535).clamp(0, 255) as u8;
+ }
+ 3 => state.rx = ev.value,
+ 4 => state.ry = ev.value.saturating_neg(),
+ 5 => {
+ state.rt = ((i32::from(ev.value) + 32768) * 255 / 65535).clamp(0, 255) as u8;
+ }
+ 6 => {
+ state.buttons &= !(0x0004 | 0x0008);
+ if ev.value < 0 {
+ state.buttons |= 0x0004; // DPad Left
+ } else if ev.value > 0 {
+ state.buttons |= 0x0008; // DPad Right
+ }
+ }
+ 7 => {
+ state.buttons &= !(0x0001 | 0x0002);
+ if ev.value < 0 {
+ state.buttons |= 0x0001; // DPad Up
+ } else if ev.value > 0 {
+ state.buttons |= 0x0002; // DPad Down
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+}
+
+#[cfg(target_os = "linux")]
+struct LinuxGamepadPoller {
+ fd: std::ffi::c_int,
+ state: GamepadState,
+}
+
+#[cfg(target_os = "linux")]
+impl Default for LinuxGamepadPoller {
+ fn default() -> Self {
+ Self { fd: -1, state: GamepadState::default() }
+ }
+}
+
+#[cfg(target_os = "linux")]
+#[allow(unsafe_code)]
+fn poll_gamepad() -> Option<GamepadState> {
+ static POLLER: Mutex<LinuxGamepadPoller> = Mutex::new(LinuxGamepadPoller {
+ fd: -1,
+ state: GamepadState { buttons: 0, lx: 0, ly: 0, rx: 0, ry: 0, lt: 0, rt: 0 },
+ });
+ let mut poller = POLLER.lock().unwrap_or_else(|e| e.into_inner());
+ if poller.fd < 0 {
+ let paths = [c"/dev/input/js0", c"/dev/input/js1", c"/dev/input/js2", c"/dev/input/js3"];
+ for path in paths {
+ let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) };
+ if fd >= 0 {
+ poller.fd = fd;
+ poller.state = GamepadState::default();
+ break;
+ }
+ }
+ }
+ if poller.fd < 0 {
+ return None;
+ }
+
+ loop {
+ let mut ev = JsEvent { time: 0, value: 0, type_: 0, number: 0 };
+ let n = unsafe {
+ libc::read(poller.fd, (&mut ev as *mut JsEvent).cast(), std::mem::size_of::<JsEvent>())
+ };
+ if n == std::mem::size_of::<JsEvent>() as isize {
+ apply_js_event(&mut poller.state, ev);
+ } else if n < 0 {
+ let err = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
+ if err == libc::EAGAIN || err == libc::EWOULDBLOCK {
+ break;
+ }
+ unsafe {
+ libc::close(poller.fd);
+ }
+ poller.fd = -1;
+ poller.state = GamepadState::default();
+ return None;
+ } else {
+ unsafe {
+ libc::close(poller.fd);
+ }
+ poller.fd = -1;
+ poller.state = GamepadState::default();
+ return None;
+ }
+ }
+
+ Some(normalize_gamepad_state(poller.state))
+}
+
+#[cfg(not(any(windows, target_os = "linux")))]
fn poll_gamepad() -> Option<GamepadState> {
None
}
@@ -2009,4 +2153,40 @@ mod tests {
std::fs::write(saved_apps_path(dir.path(), &phone), b"{not json").unwrap();
assert!(saved_apps(dir.path(), &phone).is_none());
}
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn linux_js_event_updates_buttons_and_axes() {
+ use super::{JsEvent, apply_js_event};
+
+ let mut state = GamepadState::default();
+ // Press A (0 = 0x1000) and RB (5 = 0x0200), plus init flag (0x80) on Menu (7 = 0x0010).
+ apply_js_event(&mut state, JsEvent { time: 1, value: 1, type_: 0x01, number: 0 });
+ apply_js_event(&mut state, JsEvent { time: 2, value: 1, type_: 0x01, number: 5 });
+ apply_js_event(&mut state, JsEvent { time: 3, value: 1, type_: 0x81, number: 7 });
+ assert_eq!(state.buttons, 0x1000 | 0x0200 | 0x0010);
+
+ // Release RB.
+ apply_js_event(&mut state, JsEvent { time: 4, value: 0, type_: 0x01, number: 5 });
+ assert_eq!(state.buttons, 0x1000 | 0x0010);
+
+ // Move LX (0), LY inverted (1), LT (2), RX (3), RY inverted (4), RT (5), DPad X/Y (6/7).
+ apply_js_event(&mut state, JsEvent { time: 5, value: 20_000, type_: 0x02, number: 0 });
+ apply_js_event(&mut state, JsEvent { time: 6, value: -18_000, type_: 0x02, number: 1 });
+ apply_js_event(&mut state, JsEvent { time: 7, value: 32_767, type_: 0x02, number: 2 });
+ apply_js_event(&mut state, JsEvent { time: 8, value: -15_000, type_: 0x02, number: 3 });
+ apply_js_event(&mut state, JsEvent { time: 9, value: 22_000, type_: 0x02, number: 4 });
+ apply_js_event(&mut state, JsEvent { time: 10, value: 0, type_: 0x02, number: 5 });
+ apply_js_event(&mut state, JsEvent { time: 11, value: -32_767, type_: 0x02, number: 6 }); // DPad Left
+ apply_js_event(&mut state, JsEvent { time: 12, value: -32_767, type_: 0x02, number: 7 }); // DPad Up
+
+ let normalized = normalize_gamepad_state(state);
+ assert_eq!(normalized.buttons, 0x1000 | 0x0010 | 0x0004 | 0x0001);
+ assert_eq!(normalized.lx, 20_000);
+ assert_eq!(normalized.ly, 18_000);
+ assert_eq!(normalized.rx, -15_000);
+ assert_eq!(normalized.ry, -22_000);
+ assert_eq!(normalized.lt, 255);
+ assert_eq!(normalized.rt, 127);
+ }
}
diff --git a/desktop/app/src/pc_audio_stream.rs b/desktop/app/src/pc_audio_stream.rs
index 5cd0a97..5e16422 100644
--- a/desktop/app/src/pc_audio_stream.rs
+++ b/desktop/app/src/pc_audio_stream.rs
@@ -4,7 +4,7 @@
//! 32-bit float stereo samples to 16-bit signed little-endian PCM, and streams
//! them to connected phones over NectarLink's low-latency audio stream.
-#[cfg(windows)]
+#[cfg(any(windows, target_os = "linux"))]
mod imp {
#![allow(unsafe_code)]
@@ -14,6 +14,7 @@ mod imp {
time::Duration,
};
+ #[cfg(windows)]
use windows::Win32::{
Media::Audio::{
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK,
@@ -192,6 +193,7 @@ mod imp {
out
}
+ #[cfg_attr(target_os = "linux", allow(dead_code))]
fn encode_stereo_i16(&mut self, samples: &[i16], channels: usize) -> Vec<u8> {
let frames = samples.len() / channels.max(1);
let mut out = Vec::with_capacity(frames * 4);
@@ -222,6 +224,139 @@ mod imp {
.ok();
}
+ /// Formats a PulseAudio/PipeWire sink name into its monitor source name.
+ #[cfg_attr(windows, allow(dead_code))]
+ pub(crate) fn format_monitor_source_name(default_sink: Option<&str>) -> String {
+ let Some(trimmed) = default_sink.map(str::trim).filter(|s| !s.is_empty()) else {
+ return "@DEFAULT_MONITOR@".to_owned();
+ };
+ if trimmed.ends_with(".monitor") { trimmed.to_owned() } else { format!("{trimmed}.monitor") }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn resolve_default_monitor_source() -> String {
+ let default_sink = std::process::Command::new("pactl")
+ .arg("get-default-sink")
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|o| String::from_utf8_lossy(&o.stdout).into_owned());
+ format_monitor_source_name(default_sink.as_deref())
+ }
+
+ #[cfg(target_os = "linux")]
+ fn run_loopback_worker() {
+ while is_enabled() {
+ if let Err(e) = capture_and_stream_once() {
+ tracing::debug!(error = %e, "PC audio loopback stream cycle ended");
+ std::thread::sleep(Duration::from_millis(500));
+ }
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn capture_and_stream_once() -> Result<(), String> {
+ use std::io::Read;
+ use std::process::{Command, Stdio};
+
+ let node = core_host::node().ok_or_else(|| "core node not running".to_owned())?;
+ let peers: Vec<_> = node
+ .paired_devices()
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|d| matches!(d.link, nectarlink_core::LinkState::Online { .. }))
+ .map(|d| d.id)
+ .collect();
+ let wanted = *TARGET.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(&peer) = wanted.as_ref().filter(|w| peers.contains(w)).or_else(|| peers.first()) else {
+ std::thread::sleep(Duration::from_millis(500));
+ return Ok(());
+ };
+
+ let monitor = resolve_default_monitor_source();
+ let rate: u32 = 48_000;
+ let channels: usize = 2;
+
+ let mut child = Command::new("parec")
+ .args([
+ "--raw",
+ "--format=float32le",
+ "--rate=48000",
+ "--channels=2",
+ "--latency-msec=10",
+ &format!("--device={monitor}"),
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .or_else(|_| {
+ Command::new("pw-record")
+ .args(["--raw", "--format=f32", "--rate=48000", "--channels=2", "-"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .map_err(|e| format!("failed to spawn parec/pw-record: {e}"))?;
+
+ let Some(mut stdout) = child.stdout.take() else {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err("loopback recorder stdout unavailable".into());
+ };
+
+ let mut enhancer = SpeakerEnhancer::new(rate);
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<(u32, u8, Vec<u8>)>(64);
+ let send_node = node.clone();
+ core_host::spawn(async move {
+ while let Some((r, ch, pcm)) = rx.recv().await {
+ for chunk in pcm.chunks(960) {
+ if send_node.send_pc_audio_pcm(&peer, r, ch, chunk.to_vec()).await.is_err() {
+ return;
+ }
+ }
+ }
+ });
+
+ // 480 stereo f32 frames = 10 ms = 3840 bytes.
+ let frames_per_read = 480usize;
+ let mut raw_buf = vec![0u8; frames_per_read * channels * 4];
+ let mut floats = vec![0.0_f32; frames_per_read * channels];
+ let mut silence_tail_packets: u32 = 0;
+
+ while is_enabled() {
+ if stdout.read_exact(&mut raw_buf).is_err() {
+ break;
+ }
+ for (dst, &chunk) in floats.iter_mut().zip(raw_buf.as_chunks::<4>().0) {
+ *dst = f32::from_le_bytes(chunk);
+ }
+ let has_signal = floats.iter().any(|&s| s.is_finite() && s.abs() > 1e-5);
+ let pcm_bytes = if has_signal {
+ silence_tail_packets = 50;
+ enhancer.encode_stereo_f32(&floats, channels)
+ } else if silence_tail_packets > 0 {
+ silence_tail_packets -= 1;
+ vec![0u8; frames_per_read * 4]
+ } else {
+ Vec::new()
+ };
+
+ if !pcm_bytes.is_empty()
+ && matches!(
+ tx.try_send((rate, 2, pcm_bytes)),
+ Err(tokio::sync::mpsc::error::TrySendError::Closed(_))
+ )
+ {
+ break;
+ }
+ }
+
+ let _ = child.kill();
+ let _ = child.wait();
+ Ok(())
+ }
+
+ #[cfg(windows)]
fn run_loopback_worker() {
// SAFETY: Initialize COM and elevate thread priority for low-latency audio capture.
unsafe {
@@ -237,6 +372,7 @@ mod imp {
}
}
+ #[cfg(windows)]
fn capture_and_stream_once() -> Result<(), String> {
let node = core_host::node().ok_or_else(|| "core node not running".to_owned())?;
let peers: Vec<_> = node
@@ -401,10 +537,38 @@ mod imp {
set_enabled(false);
assert!(!is_enabled());
}
+
+ #[test]
+ fn format_monitor_source_name_appends_monitor_suffix_or_uses_default() {
+ assert_eq!(
+ format_monitor_source_name(Some("alsa_output.pci-0000_00_1f.3.analog-stereo\n")),
+ "alsa_output.pci-0000_00_1f.3.analog-stereo.monitor"
+ );
+ assert_eq!(
+ format_monitor_source_name(Some("alsa_output.pci.monitor")),
+ "alsa_output.pci.monitor"
+ );
+ assert_eq!(format_monitor_source_name(Some(" ")), "@DEFAULT_MONITOR@");
+ assert_eq!(format_monitor_source_name(None), "@DEFAULT_MONITOR@");
+ }
+
+ #[test]
+ fn speaker_enhancer_encodes_stereo_f32_and_i16_without_clipping() {
+ let mut enhancer = SpeakerEnhancer::new(48_000);
+ let floats = [0.25_f32, -0.25, 0.95, -0.95, f32::NAN, 0.5];
+ let encoded = enhancer.encode_stereo_f32(&floats, 2);
+ assert_eq!(encoded.len(), 3 * 4);
+ assert!(encoded.iter().any(|&b| b != 0));
+
+ let i16s = [8000i16, -8000, 16000, -16000];
+ let encoded_i16 = enhancer.encode_stereo_i16(&i16s, 2);
+ assert_eq!(encoded_i16.len(), 2 * 4);
+ assert!(encoded_i16.iter().any(|&b| b != 0));
+ }
}
}
-#[cfg(not(windows))]
+#[cfg(not(any(windows, target_os = "linux")))]
mod imp {
#![allow(dead_code)]
diff --git a/desktop/app/src/pc_mirror.rs b/desktop/app/src/pc_mirror.rs
index 218b412..61d47c4 100644
--- a/desktop/app/src/pc_mirror.rs
+++ b/desktop/app/src/pc_mirror.rs
@@ -4,23 +4,24 @@
//! streams it over `mirror` / `video` (`session = 0`) to a paired phone, while
//! injecting touch, scroll, key, and text input back into Windows (`docs/PLAN.md` §8.6).
-#[cfg(windows)]
+#[cfg(any(windows, target_os = "linux"))]
mod imp {
#![allow(unsafe_code)]
- use std::{
- mem::{ManuallyDrop, size_of},
- sync::{
- Arc, Mutex,
- atomic::{AtomicBool, Ordering},
- },
- time::{Duration, Instant},
+ #[cfg(windows)]
+ use std::mem::{ManuallyDrop, size_of};
+ use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
};
+ #[cfg(any(windows, target_os = "linux"))]
+ use std::time::{Duration, Instant};
- use nectarlink_core::{
- DeviceId, KeyMod, MirrorConfig, MirrorInput, MirrorSend, MirrorStart, PacketKind, mirror_keys,
- };
+ use nectarlink_core::{DeviceId, KeyMod, MirrorInput, MirrorStart, mirror_keys};
+ #[cfg(any(windows, target_os = "linux"))]
+ use nectarlink_core::{MirrorConfig, MirrorSend, PacketKind};
+ #[cfg(windows)]
use windows::Win32::{
Foundation::{POINT, RECT},
Graphics::Gdi::{
@@ -47,13 +48,9 @@ mod imp {
},
};
- use crate::{
- core_host,
- win::{
- self,
- h264::{create_mft, ensure_mf_started},
- },
- };
+ #[cfg(windows)]
+ use crate::win::h264::{create_mft, ensure_mf_started};
+ use crate::{core_host, win};
struct ActiveSession {
peer: DeviceId,
@@ -67,12 +64,15 @@ mod imp {
/// How long Play on phone looks for the player's window before streaming
/// the screen instead.
+ #[cfg(any(windows, target_os = "linux"))]
const FIND_WINDOW: Duration = Duration::from_secs(5);
/// The lowest bitrate the stream backs off to on a slow link.
+ #[cfg(any(windows, target_os = "linux"))]
const MIN_BITRATE: u32 = 600_000;
/// What a sharing session sent in the last stats window.
+ #[cfg(any(windows, target_os = "linux"))]
#[derive(Default)]
struct Stats {
frames: u64,
@@ -92,6 +92,21 @@ mod imp {
active_peer().is_some()
}
+ /// Whether this PC's display session supports screen capture for `mirror.capture`.
+ ///
+ /// On Linux, `pc_mirror` captures the screen via X11 (`XGetImage`), which requires
+ /// an X11 or XWayland `DISPLAY`.
+ pub fn is_capture_available() -> bool {
+ #[cfg(windows)]
+ {
+ true
+ }
+ #[cfg(target_os = "linux")]
+ {
+ std::env::var_os("DISPLAY").is_some()
+ }
+ }
+
/// Whether a phone watches one of this PC's players (Play on phone).
pub fn is_watching() -> bool {
ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|s| s.watching)
@@ -317,6 +332,7 @@ mod imp {
}
}
+ #[cfg(windows)]
pub(crate) struct H264Encoder {
transform: IMFTransform,
/// The encoder's settings interface, when it has one: keyframes on demand and live
@@ -330,6 +346,7 @@ mod imp {
sent_first_frame: bool,
}
+ #[cfg(windows)]
impl Drop for H264Encoder {
fn drop(&mut self) {
// SAFETY: flushes and ends streaming on the MFT before drop.
@@ -340,6 +357,7 @@ mod imp {
}
}
+ #[cfg(windows)]
impl H264Encoder {
pub(crate) fn new(width: u32, height: u32, fps: u32, bitrate: u32) -> windows::core::Result<Self> {
ensure_mf_started()?;
@@ -543,6 +561,7 @@ mod imp {
}
}
+ #[cfg(windows)]
unsafe fn make_sample(bytes: &[u8], hns: i64, dur_hns: i64) -> windows::core::Result<IMFSample> {
// SAFETY: allocates an IMFMediaBuffer of `bytes.len()` and copies `bytes` into it.
unsafe {
@@ -560,18 +579,383 @@ mod imp {
}
}
+ #[cfg(any(windows, target_os = "linux"))]
fn has_h264_idr(data: &[u8]) -> bool {
data.windows(4).any(|w| w[..3] == [0, 0, 1] && (w[3] & 0x1f) == 5)
}
+ #[cfg(any(windows, target_os = "linux"))]
fn has_h264_sps(data: &[u8]) -> bool {
data.windows(4).any(|w| w[..3] == [0, 0, 1] && (w[3] & 0x1f) == 7)
}
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct SEncParamBase {
+ i_usage_type: std::ffi::c_int, // 0 = CAMERA_VIDEO_REAL_TIME
+ i_pic_width: std::ffi::c_int,
+ i_pic_height: std::ffi::c_int,
+ i_target_bitrate: std::ffi::c_int,
+ i_rc_mode: std::ffi::c_int, // 1 = RC_BITRATE_MODE
+ f_max_frame_rate: f32,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct SSourcePicture {
+ i_color_format: std::ffi::c_int, // 23 = videoFormatI420
+ i_stride: [std::ffi::c_int; 4],
+ p_data: [*mut u8; 4],
+ i_pic_width: std::ffi::c_int,
+ i_pic_height: std::ffi::c_int,
+ ui_time_stamp: i64,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ #[derive(Clone, Copy)]
+ struct SLayerBSInfo {
+ ui_temporal_id: u8,
+ ui_spatial_id: u8,
+ ui_quality_id: u8,
+ e_frame_type: std::ffi::c_int,
+ ui_layer_type: u8,
+ i_sub_seq_id: std::ffi::c_int,
+ i_nal_count: std::ffi::c_int,
+ p_nal_length_in_byte: *mut std::ffi::c_int,
+ p_bs_buf: *mut u8,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct SFrameBSInfo {
+ i_layer_num: std::ffi::c_int,
+ s_layer_info: [SLayerBSInfo; 128],
+ e_frame_type: std::ffi::c_int, // 1 = IDR, 2 = I, 3 = P, 4 = Skip
+ i_frame_size_in_bytes: std::ffi::c_int,
+ ui_time_stamp: i64,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct SBitrateInfo {
+ i_layer: std::ffi::c_int, // 4 = SPATIAL_LAYER_ALL, 0 = SPATIAL_LAYER_0
+ i_bitrate: std::ffi::c_int,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct OpenH264Version {
+ u_major: u32,
+ u_minor: u32,
+ u_revision: u32,
+ u_reserved: u32,
+ }
+
+ #[cfg(target_os = "linux")]
+ struct OpenH264EncApi {
+ create_encoder: unsafe extern "C" fn(*mut *mut std::ffi::c_void) -> std::ffi::c_int,
+ destroy_encoder: unsafe extern "C" fn(*mut std::ffi::c_void),
+ }
+
+ #[cfg(target_os = "linux")]
+ unsafe fn dl_sym<T: Copy>(lib: *mut std::ffi::c_void, name: &std::ffi::CStr) -> Option<T> {
+ let raw = unsafe { libc::dlsym(lib, name.as_ptr()) };
+ if raw.is_null() { None } else { Some(unsafe { std::mem::transmute_copy(&raw) }) }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn openh264_enc_api() -> Option<&'static OpenH264EncApi> {
+ static API: std::sync::OnceLock<Option<OpenH264EncApi>> = std::sync::OnceLock::new();
+ API.get_or_init(|| unsafe {
+ let candidates = [c"libopenh264.so.7", c"libopenh264.so.6", c"libopenh264.so"];
+ let mut lib = std::ptr::null_mut();
+ for name in candidates {
+ lib = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
+ if !lib.is_null() {
+ break;
+ }
+ }
+ if lib.is_null() {
+ return None;
+ }
+ let get_version: unsafe extern "C" fn() -> OpenH264Version = dl_sym(lib, c"WelsGetCodecVersion")?;
+ let ver = get_version();
+ if ver.u_major != 2 {
+ tracing::warn!(
+ major = ver.u_major,
+ minor = ver.u_minor,
+ "unsupported OpenH264 ABI version; skipping OpenH264 encoder"
+ );
+ return None;
+ }
+ Some(OpenH264EncApi {
+ create_encoder: dl_sym(lib, c"WelsCreateSVCEncoder")?,
+ destroy_encoder: dl_sym(lib, c"WelsDestroySVCEncoder")?,
+ })
+ })
+ .as_ref()
+ }
+
+ #[cfg(target_os = "linux")]
+ pub(crate) struct H264Encoder {
+ encoder: *mut std::ffi::c_void,
+ width: u32,
+ height: u32,
+ i420_buf: Vec<u8>,
+ seq_header: Vec<u8>,
+ sent_first_frame: bool,
+ }
+
+ #[cfg(target_os = "linux")]
+ impl Drop for H264Encoder {
+ fn drop(&mut self) {
+ if !self.encoder.is_null() {
+ unsafe {
+ let vtable = *(self.encoder as *const *const usize);
+ let uninitialize: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_int =
+ std::mem::transmute(*vtable.add(3));
+ let _ = uninitialize(self.encoder);
+ if let Some(api) = openh264_enc_api() {
+ (api.destroy_encoder)(self.encoder);
+ }
+ }
+ }
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ impl H264Encoder {
+ pub(crate) fn new(width: u32, height: u32, fps: u32, bitrate: u32) -> Result<Self, String> {
+ let api = openh264_enc_api().ok_or_else(|| "libopenh264 encoder unavailable".to_owned())?;
+ unsafe {
+ let mut encoder: *mut std::ffi::c_void = std::ptr::null_mut();
+ if (api.create_encoder)(&mut encoder) != 0 || encoder.is_null() {
+ return Err("WelsCreateSVCEncoder failed".to_owned());
+ }
+ let vtable = *(encoder as *const *const usize);
+ let initialize: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ *const SEncParamBase,
+ ) -> std::ffi::c_int = std::mem::transmute(*vtable.add(0));
+ let set_option: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ std::ffi::c_int,
+ *mut std::ffi::c_void,
+ ) -> std::ffi::c_int = std::mem::transmute(*vtable.add(7));
+
+ let mut trace_level: std::ffi::c_int = 0;
+ let _ = set_option(
+ encoder,
+ 25, // ENCODER_OPTION_TRACE_LEVEL
+ (&mut trace_level as *mut std::ffi::c_int).cast(),
+ );
+
+ let param = SEncParamBase {
+ i_usage_type: 0, // CAMERA_VIDEO_REAL_TIME
+ i_pic_width: width as std::ffi::c_int,
+ i_pic_height: height as std::ffi::c_int,
+ i_target_bitrate: bitrate.clamp(500_000, 20_000_000) as std::ffi::c_int,
+ i_rc_mode: 1, // RC_BITRATE_MODE
+ f_max_frame_rate: fps.max(1) as f32,
+ };
+ let rc = initialize(encoder, &param);
+ if rc != 0 {
+ (api.destroy_encoder)(encoder);
+ return Err(format!("OpenH264 Initialize failed with code {rc}"));
+ }
+
+ let mut idr_interval = (fps.max(1) * 2) as std::ffi::c_int;
+ let _ = set_option(
+ encoder,
+ 1, // ENCODER_OPTION_IDR_INTERVAL
+ (&mut idr_interval as *mut std::ffi::c_int).cast(),
+ );
+
+ Ok(Self {
+ encoder,
+ width,
+ height,
+ i420_buf: Vec::new(),
+ seq_header: Vec::new(),
+ sent_first_frame: false,
+ })
+ }
+ }
+
+ pub(crate) fn request_keyframe(&self) -> bool {
+ if self.encoder.is_null() {
+ return false;
+ }
+ unsafe {
+ let vtable = *(self.encoder as *const *const usize);
+ let force_intra_frame: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ bool,
+ std::ffi::c_int,
+ ) -> std::ffi::c_int = std::mem::transmute(*vtable.add(6));
+ force_intra_frame(self.encoder, true, -1) == 0
+ }
+ }
+
+ pub(crate) fn set_bitrate(&self, bitrate: u32) -> bool {
+ if self.encoder.is_null() {
+ return false;
+ }
+ unsafe {
+ let vtable = *(self.encoder as *const *const usize);
+ let set_option: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ std::ffi::c_int,
+ *mut std::ffi::c_void,
+ ) -> std::ffi::c_int = std::mem::transmute(*vtable.add(7));
+ let target = bitrate.clamp(500_000, 20_000_000) as std::ffi::c_int;
+ let mut info_all = SBitrateInfo {
+ i_layer: 4, // SPATIAL_LAYER_ALL
+ i_bitrate: target,
+ };
+ let mut info_0 = SBitrateInfo {
+ i_layer: 0, // SPATIAL_LAYER_0
+ i_bitrate: target,
+ };
+ let rc_all = set_option(
+ self.encoder,
+ 5, // ENCODER_OPTION_BITRATE
+ (&mut info_all as *mut SBitrateInfo).cast(),
+ );
+ let rc_0 = set_option(
+ self.encoder,
+ 5, // ENCODER_OPTION_BITRATE
+ (&mut info_0 as *mut SBitrateInfo).cast(),
+ );
+ rc_all == 0 || rc_0 == 0
+ }
+ }
+
+ pub(crate) fn encode(
+ &mut self,
+ nv12: &[u8],
+ hns: i64,
+ _dur_hns: i64,
+ ) -> Result<Vec<(bool, Vec<u8>)>, String> {
+ let w = self.width as usize;
+ let h = self.height as usize;
+ let y_size = w * h;
+ let uv_size = y_size / 2;
+ let expected = y_size + uv_size;
+ if nv12.len() < expected || self.encoder.is_null() {
+ return Ok(Vec::new());
+ }
+
+ let quarter = y_size / 4;
+ self.i420_buf.resize(expected, 0);
+ self.i420_buf[..y_size].copy_from_slice(&nv12[..y_size]);
+ {
+ let (y_and_u, v_plane) = self.i420_buf.split_at_mut(y_size + quarter);
+ let u_plane = &mut y_and_u[y_size..];
+ let src_uv = &nv12[y_size..expected];
+ for i in 0..quarter {
+ u_plane[i] = src_uv[i * 2];
+ v_plane[i] = src_uv[i * 2 + 1];
+ }
+ }
+
+ unsafe {
+ let y_ptr = self.i420_buf.as_mut_ptr();
+ let u_ptr = y_ptr.add(y_size);
+ let v_ptr = y_ptr.add(y_size + quarter);
+ let pic = SSourcePicture {
+ i_color_format: 23, // videoFormatI420
+ i_stride: [
+ w as std::ffi::c_int,
+ (w / 2) as std::ffi::c_int,
+ (w / 2) as std::ffi::c_int,
+ 0,
+ ],
+ p_data: [y_ptr, u_ptr, v_ptr, std::ptr::null_mut()],
+ i_pic_width: w as std::ffi::c_int,
+ i_pic_height: h as std::ffi::c_int,
+ ui_time_stamp: hns / 10_000,
+ };
+
+ let mut bs_info: SFrameBSInfo = std::mem::zeroed();
+ let vtable = *(self.encoder as *const *const usize);
+ let encode_frame: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ *const SSourcePicture,
+ *mut SFrameBSInfo,
+ ) -> std::ffi::c_int = std::mem::transmute(*vtable.add(4));
+
+ let rc = encode_frame(self.encoder, &pic, &mut bs_info);
+ if rc != 0 {
+ return Err(format!("OpenH264 EncodeFrame failed: {rc}"));
+ }
+ if bs_info.e_frame_type == 4 || bs_info.i_layer_num <= 0 {
+ return Ok(Vec::new());
+ }
+
+ let layer_count = (bs_info.i_layer_num as usize).min(bs_info.s_layer_info.len());
+ let mut raw = Vec::new();
+ for idx in 0..layer_count {
+ let layer = &bs_info.s_layer_info[idx];
+ if layer.p_bs_buf.is_null()
+ || layer.p_nal_length_in_byte.is_null()
+ || layer.i_nal_count <= 0
+ {
+ continue;
+ }
+ let nal_lens =
+ std::slice::from_raw_parts(layer.p_nal_length_in_byte, layer.i_nal_count as usize);
+ let total_bytes: usize = nal_lens.iter().map(|&n| n.max(0) as usize).sum();
+ if total_bytes == 0 {
+ continue;
+ }
+ let layer_bytes = std::slice::from_raw_parts(layer.p_bs_buf, total_bytes);
+ if layer.ui_layer_type == 0 {
+ self.seq_header.clear();
+ self.seq_header.extend_from_slice(layer_bytes);
+ }
+ raw.extend_from_slice(layer_bytes);
+ }
+
+ if raw.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let is_idr = !self.sent_first_frame || bs_info.e_frame_type == 1 || has_h264_idr(&raw);
+ let mut bytes = Vec::new();
+ if is_idr && !has_h264_sps(&raw) && !self.seq_header.is_empty() {
+ bytes.extend_from_slice(&self.seq_header);
+ }
+ bytes.extend_from_slice(&raw);
+ self.sent_first_frame = true;
+ Ok(vec![(is_idr, bytes)])
+ }
+ }
+ }
+
+ #[cfg(windows)]
+ fn primary_screen_dimensions() -> (u32, u32) {
+ // SAFETY: Win32 GDI device context and system metrics calls with balanced ReleaseDC.
+ unsafe {
+ let hdc = GetDC(None);
+ let pw = if !hdc.is_invalid() { GetDeviceCaps(Some(hdc), DESKTOPHORZRES) } else { 0 };
+ let ph = if !hdc.is_invalid() { GetDeviceCaps(Some(hdc), DESKTOPVERTRES) } else { 0 };
+ if !hdc.is_invalid() {
+ let _ = ReleaseDC(None, hdc);
+ }
+ (
+ if pw > 0 { pw as u32 } else { GetSystemMetrics(SM_CXSCREEN).max(640) as u32 },
+ if ph > 0 { ph as u32 } else { GetSystemMetrics(SM_CYSCREEN).max(480) as u32 },
+ )
+ }
+ }
+
/// Captures the primary desktop monitor into `bgra` scaled to `(dst_w, dst_h)`,
/// with the pointer, and returns the current physical screen dimensions
/// `(src_w, src_h)`. With `region` (physical screen pixels), captures only
/// that, without the pointer (Play on phone), and returns its size.
+ #[cfg(windows)]
fn capture_screen(
region: Option<RECT>,
dst_w: u32,
@@ -674,6 +1058,333 @@ mod imp {
}
}
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct XWindowAttributes {
+ x: std::ffi::c_int,
+ y: std::ffi::c_int,
+ width: std::ffi::c_int,
+ height: std::ffi::c_int,
+ border_width: std::ffi::c_int,
+ depth: std::ffi::c_int,
+ visual: *mut std::ffi::c_void,
+ root: std::ffi::c_ulong,
+ class: std::ffi::c_int,
+ bit_gravity: std::ffi::c_int,
+ win_gravity: std::ffi::c_int,
+ backing_store: std::ffi::c_int,
+ backing_planes: std::ffi::c_ulong,
+ backing_pixel: std::ffi::c_ulong,
+ save_under: std::ffi::c_int,
+ colormap: std::ffi::c_ulong,
+ map_installed: std::ffi::c_int,
+ map_state: std::ffi::c_int,
+ all_event_masks: std::ffi::c_long,
+ your_event_mask: std::ffi::c_long,
+ do_not_propagate_mask: std::ffi::c_long,
+ override_redirect: std::ffi::c_int,
+ screen: *mut std::ffi::c_void,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct XImageFuncs {
+ create_image: *mut std::ffi::c_void,
+ destroy_image: Option<unsafe extern "C" fn(*mut XImage) -> std::ffi::c_int>,
+ get_pixel: *mut std::ffi::c_void,
+ put_pixel: *mut std::ffi::c_void,
+ sub_image: *mut std::ffi::c_void,
+ add_pixel: *mut std::ffi::c_void,
+ }
+
+ #[cfg(target_os = "linux")]
+ #[repr(C)]
+ struct XImage {
+ width: std::ffi::c_int,
+ height: std::ffi::c_int,
+ xoffset: std::ffi::c_int,
+ format: std::ffi::c_int,
+ data: *mut u8,
+ byte_order: std::ffi::c_int,
+ bitmap_unit: std::ffi::c_int,
+ bitmap_bit_order: std::ffi::c_int,
+ bitmap_pad: std::ffi::c_int,
+ depth: std::ffi::c_int,
+ bytes_per_line: std::ffi::c_int,
+ bits_per_pixel: std::ffi::c_int,
+ red_mask: std::ffi::c_ulong,
+ green_mask: std::ffi::c_ulong,
+ blue_mask: std::ffi::c_ulong,
+ obdata: *mut std::ffi::c_void,
+ f: XImageFuncs,
+ }
+
+ #[cfg(target_os = "linux")]
+ struct X11Api {
+ open_display: unsafe extern "C" fn(*const std::ffi::c_char) -> *mut std::ffi::c_void,
+ default_root_window: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_ulong,
+ get_window_attributes: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ std::ffi::c_ulong,
+ *mut XWindowAttributes,
+ ) -> std::ffi::c_int,
+ get_image: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ std::ffi::c_ulong,
+ std::ffi::c_int,
+ std::ffi::c_int,
+ std::ffi::c_uint,
+ std::ffi::c_uint,
+ std::ffi::c_ulong,
+ std::ffi::c_int,
+ ) -> *mut XImage,
+ query_pointer: unsafe extern "C" fn(
+ *mut std::ffi::c_void,
+ std::ffi::c_ulong,
+ *mut std::ffi::c_ulong,
+ *mut std::ffi::c_ulong,
+ *mut std::ffi::c_int,
+ *mut std::ffi::c_int,
+ *mut std::ffi::c_int,
+ *mut std::ffi::c_int,
+ *mut std::ffi::c_uint,
+ ) -> std::ffi::c_int,
+ close_display: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_int,
+ free: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_int,
+ }
+
+ #[cfg(target_os = "linux")]
+ fn x11_api() -> Option<&'static X11Api> {
+ static API: std::sync::OnceLock<Option<X11Api>> = std::sync::OnceLock::new();
+ API.get_or_init(|| unsafe {
+ let candidates = [c"libX11.so.6", c"libX11.so"];
+ let mut lib = std::ptr::null_mut();
+ for name in candidates {
+ lib = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
+ if !lib.is_null() {
+ break;
+ }
+ }
+ if lib.is_null() {
+ return None;
+ }
+ Some(X11Api {
+ open_display: dl_sym(lib, c"XOpenDisplay")?,
+ default_root_window: dl_sym(lib, c"XDefaultRootWindow")?,
+ get_window_attributes: dl_sym(lib, c"XGetWindowAttributes")?,
+ get_image: dl_sym(lib, c"XGetImage")?,
+ query_pointer: dl_sym(lib, c"XQueryPointer")?,
+ close_display: dl_sym(lib, c"XCloseDisplay")?,
+ free: dl_sym(lib, c"XFree")?,
+ })
+ })
+ .as_ref()
+ }
+
+ #[cfg(target_os = "linux")]
+ struct ThreadX11Display(*mut std::ffi::c_void);
+
+ #[cfg(target_os = "linux")]
+ impl Drop for ThreadX11Display {
+ fn drop(&mut self) {
+ if !self.0.is_null()
+ && let Some(api) = x11_api()
+ {
+ unsafe {
+ let _ = (api.close_display)(self.0);
+ }
+ }
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn with_x11_display<R>(f: impl FnOnce(&X11Api, *mut std::ffi::c_void) -> Option<R>) -> Option<R> {
+ std::thread_local! {
+ static DISPLAY: std::cell::RefCell<Option<ThreadX11Display>> = const { std::cell::RefCell::new(None) };
+ }
+ let api = x11_api()?;
+ DISPLAY.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ if borrow.is_none() {
+ let dpy = unsafe { (api.open_display)(std::ptr::null()) };
+ if !dpy.is_null() {
+ *borrow = Some(ThreadX11Display(dpy));
+ }
+ }
+ let dpy = borrow.as_ref()?.0;
+ f(api, dpy)
+ })
+ }
+
+ #[cfg(target_os = "linux")]
+ fn primary_screen_dimensions() -> (u32, u32) {
+ with_x11_display(|api, dpy| unsafe {
+ let root = (api.default_root_window)(dpy);
+ let mut attrs: XWindowAttributes = std::mem::zeroed();
+ if (api.get_window_attributes)(dpy, root, &mut attrs) != 0 && attrs.width > 0 && attrs.height > 0
+ {
+ Some((attrs.width as u32, attrs.height as u32))
+ } else {
+ None
+ }
+ })
+ .unwrap_or((1920, 1080))
+ }
+
+ #[cfg(target_os = "linux")]
+ fn draw_cursor_pointer(bgra: &mut [u8], dst_w: u32, dst_h: u32, cx: i32, cy: i32) {
+ // 12x16 arrow cursor bitmap (1 = black border, 2 = white fill).
+ const CURSOR: [[u8; 10]; 14] = [
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 2, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 2, 2, 1, 0, 0, 0, 0, 0, 0],
+ [1, 2, 2, 2, 1, 0, 0, 0, 0, 0],
+ [1, 2, 2, 2, 2, 1, 0, 0, 0, 0],
+ [1, 2, 2, 2, 2, 2, 1, 0, 0, 0],
+ [1, 2, 2, 2, 2, 2, 2, 1, 0, 0],
+ [1, 2, 2, 2, 2, 2, 2, 2, 1, 0],
+ [1, 2, 2, 2, 2, 1, 1, 1, 1, 1],
+ [1, 2, 2, 1, 2, 1, 0, 0, 0, 0],
+ [1, 2, 1, 0, 1, 2, 1, 0, 0, 0],
+ [1, 1, 0, 0, 1, 2, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
+ ];
+ for (dy, row) in CURSOR.iter().enumerate() {
+ let py = cy + dy as i32;
+ if py < 0 || py >= dst_h as i32 {
+ continue;
+ }
+ for (dx, &cell) in row.iter().enumerate() {
+ if cell == 0 {
+ continue;
+ }
+ let px = cx + dx as i32;
+ if px < 0 || px >= dst_w as i32 {
+ continue;
+ }
+ let idx = ((py as usize) * (dst_w as usize) + (px as usize)) * 4;
+ let val = if cell == 2 { 0xFF } else { 0x00 };
+ bgra[idx] = val;
+ bgra[idx + 1] = val;
+ bgra[idx + 2] = val;
+ bgra[idx + 3] = 0xFF;
+ }
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn capture_screen(
+ region: Option<crate::win::browser::RECT>,
+ dst_w: u32,
+ dst_h: u32,
+ bgra: &mut Vec<u8>,
+ ) -> Option<(u32, u32)> {
+ with_x11_display(|api, dpy| unsafe {
+ let root = (api.default_root_window)(dpy);
+ let mut attrs: XWindowAttributes = std::mem::zeroed();
+ if (api.get_window_attributes)(dpy, root, &mut attrs) == 0
+ || attrs.width <= 0
+ || attrs.height <= 0
+ {
+ return None;
+ }
+ let full_w = attrs.width;
+ let full_h = attrs.height;
+ let (src_x, src_y, src_w, src_h) = match region {
+ Some(r) => {
+ let x0 = r.left.clamp(0, full_w - 1);
+ let y0 = r.top.clamp(0, full_h - 1);
+ let x1 = r.right.clamp(x0 + 1, full_w);
+ let y1 = r.bottom.clamp(y0 + 1, full_h);
+ (x0, y0, (x1 - x0) as u32, (y1 - y0) as u32)
+ }
+ None => (0, 0, full_w as u32, full_h as u32),
+ };
+
+ let img = (api.get_image)(
+ dpy,
+ root,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ !0 as std::ffi::c_ulong, // AllPlanes
+ 2, // ZPixmap
+ );
+ if img.is_null() {
+ return None;
+ }
+ if (*img).data.is_null() {
+ if let Some(destroy) = (*img).f.destroy_image {
+ let _ = destroy(img);
+ } else {
+ let _ = (api.free)(img.cast());
+ }
+ return None;
+ }
+
+ let bytes_per_line = (*img).bytes_per_line.max(0) as usize;
+ let bpp = ((*img).bits_per_pixel.max(24) as usize) / 8;
+ let needed = (dst_w as usize) * (dst_h as usize) * 4;
+ bgra.resize(needed, 0);
+
+ for y in 0..dst_h {
+ let sy =
+ ((u64::from(y) * u64::from(src_h)) / u64::from(dst_h)).min(u64::from(src_h - 1)) as usize;
+ let src_row = (*img).data.add(sy * bytes_per_line);
+ let dst_row_offset = (y as usize) * (dst_w as usize) * 4;
+ for x in 0..dst_w {
+ let sx = ((u64::from(x) * u64::from(src_w)) / u64::from(dst_w)).min(u64::from(src_w - 1))
+ as usize;
+ let px = src_row.add(sx * bpp);
+ let dst_idx = dst_row_offset + (x as usize) * 4;
+ bgra[dst_idx] = *px;
+ bgra[dst_idx + 1] = *px.add(1);
+ bgra[dst_idx + 2] = *px.add(2);
+ bgra[dst_idx + 3] = 0xFF;
+ }
+ }
+
+ let mut root_ret: std::ffi::c_ulong = 0;
+ let mut child_ret: std::ffi::c_ulong = 0;
+ let mut root_x: std::ffi::c_int = 0;
+ let mut root_y: std::ffi::c_int = 0;
+ let mut win_x: std::ffi::c_int = 0;
+ let mut win_y: std::ffi::c_int = 0;
+ let mut mask_ret: std::ffi::c_uint = 0;
+ if region.is_none()
+ && (api.query_pointer)(
+ dpy,
+ root,
+ &mut root_ret,
+ &mut child_ret,
+ &mut root_x,
+ &mut root_y,
+ &mut win_x,
+ &mut win_y,
+ &mut mask_ret,
+ ) != 0
+ && root_x >= 0
+ && root_y >= 0
+ {
+ let cx = ((root_x as i64) * (dst_w as i64) / (src_w as i64)) as i32;
+ let cy = ((root_y as i64) * (dst_h as i64) / (src_h as i64)) as i32;
+ draw_cursor_pointer(bgra, dst_w, dst_h, cx, cy);
+ }
+
+ if let Some(destroy) = (*img).f.destroy_image {
+ let _ = destroy(img);
+ } else {
+ libc::free((*img).data.cast());
+ let _ = (api.free)(img.cast());
+ }
+
+ Some((src_w, src_h))
+ })
+ }
+
+ #[cfg(any(windows, target_os = "linux"))]
fn run_capture_loop(
peer: DeviceId,
options: MirrorStart,
@@ -770,18 +1481,7 @@ mod imp {
let (dst_w, dst_h) = match stream_dims {
Some(dims) => dims,
None => {
- let (src_w, src_h) = unsafe {
- let hdc = GetDC(None);
- let pw = if !hdc.is_invalid() { GetDeviceCaps(Some(hdc), DESKTOPHORZRES) } else { 0 };
- let ph = if !hdc.is_invalid() { GetDeviceCaps(Some(hdc), DESKTOPVERTRES) } else { 0 };
- if !hdc.is_invalid() {
- let _ = ReleaseDC(None, hdc);
- }
- (
- if pw > 0 { pw as u32 } else { GetSystemMetrics(SM_CXSCREEN).max(640) as u32 },
- if ph > 0 { ph as u32 } else { GetSystemMetrics(SM_CYSCREEN).max(480) as u32 },
- )
- };
+ let (src_w, src_h) = primary_screen_dimensions();
let dims = target_dimensions(src_w, src_h, options.max_size);
stream_dims = Some(dims);
dims
@@ -982,13 +1682,25 @@ mod imp {
use super::*;
#[test]
- fn encodes_nv12_frames_and_decodes_back_with_mft() {
+ fn computes_target_dimensions_and_nv12() {
+ let (w, h) = target_dimensions(1920, 1080, 1280);
+ assert_eq!(w % 16, 0);
+ assert_eq!(h % 16, 0);
+ let bgra = vec![128u8; (w as usize) * (h as usize) * 4];
+ let mut nv12 = Vec::new();
+ bgra_to_nv12(&bgra, w as usize, h as usize, &mut nv12);
+ assert_eq!(nv12.len(), (w as usize) * (h as usize) * 3 / 2);
+ }
+
+ #[cfg(any(windows, target_os = "linux"))]
+ #[test]
+ fn encodes_nv12_frames_and_decodes_back() {
let (w, h) = target_dimensions(1920, 1080, 1280);
assert_eq!(w % 16, 0);
assert_eq!(h % 16, 0);
- let mut enc = H264Encoder::new(w, h, 30, 4_000_000).expect("H264Encoder MFT");
- let mut dec = crate::win::h264::Decoder::new_for_codec("h264").expect("H264 Decoder MFT");
+ let mut enc = H264Encoder::new(w, h, 30, 4_000_000).expect("H264Encoder");
+ let mut dec = crate::win::h264::Decoder::new_for_codec("h264").expect("H264 Decoder");
let mut bgra = vec![0u8; (w as usize) * (h as usize) * 4];
for (i, px) in bgra.as_chunks_mut::<4>().0.iter_mut().enumerate() {
@@ -1021,6 +1733,7 @@ mod imp {
/// With a Chromium browser showing a video on a page whose title has
/// `NECTARLINK_TEST_TAB` in it, in view: captures just the video, as
/// Play on phone does.
+ #[cfg(windows)]
#[test]
#[ignore]
fn captures_a_browsers_video() {
@@ -1045,10 +1758,11 @@ mod imp {
assert!(distinct.len() > 50, "a moving test pattern, not a blank");
}
+ #[cfg(any(windows, target_os = "linux"))]
#[test]
fn keyframes_come_on_request_without_rebuilding_the_encoder() {
let (w, h) = target_dimensions(1280, 720, 1280);
- let mut enc = H264Encoder::new(w, h, 30, 2_000_000).expect("H264Encoder MFT");
+ let mut enc = H264Encoder::new(w, h, 30, 2_000_000).expect("H264Encoder");
let mut nv12 = Vec::new();
bgra_to_nv12(&vec![128u8; (w as usize) * (h as usize) * 4], w as usize, h as usize, &mut nv12);
@@ -1061,14 +1775,14 @@ mod imp {
// The first frame is a keyframe; the next few (well inside the 2 s GOP) are not.
assert_eq!(keyframes_after(&mut enc, 0, 1), 1, "the stream starts with a keyframe");
assert_eq!(keyframes_after(&mut enc, 1, 5), 0, "no keyframes mid-GOP unprompted");
- assert!(enc.request_keyframe(), "the Windows H.264 encoder takes keyframe requests");
+ assert!(enc.request_keyframe(), "the H.264 encoder takes keyframe requests");
assert_eq!(keyframes_after(&mut enc, 6, 2), 1, "a requested keyframe arrives promptly");
assert!(enc.set_bitrate(1_000_000), "the bitrate changes in place");
}
}
}
-#[cfg(not(windows))]
+#[cfg(not(any(windows, target_os = "linux")))]
mod imp {
#![allow(dead_code)]
diff --git a/desktop/app/src/phone_mic.rs b/desktop/app/src/phone_mic.rs
index cb86904..59e6520 100644
--- a/desktop/app/src/phone_mic.rs
+++ b/desktop/app/src/phone_mic.rs
@@ -68,6 +68,8 @@ pub fn phase() -> Phase {
/// Reads the chosen output from the settings.
pub fn init(settings: &crate::settings::Settings) {
+ #[cfg(target_os = "linux")]
+ crate::win::vmic::cleanup_stale_sources();
*OUTPUT.lock().unwrap_or_else(|e| e.into_inner()) = settings.phone_mic_output.clone();
GAIN.store(settings.phone_mic_gain.clamp(MIN_GAIN, MAX_GAIN), Ordering::Relaxed);
}
@@ -124,7 +126,17 @@ pub fn chosen_output() -> Option<String> {
}
/// Names that virtual audio cables give their playback end.
-const CABLES: &[&str] = &["cable input", "vb-audio", "voicemeeter input", "virtual cable"];
+const CABLES: &[&str] =
+ &["cable input", "vb-audio", "voicemeeter input", "virtual cable", "virtual microphone"];
+
+#[cfg(target_os = "linux")]
+pub const VIRTUAL_MIC_ID: &str = "nectarlink:virtual_mic";
+#[cfg(target_os = "linux")]
+pub const VIRTUAL_MIC_NAME: &str = "NectarLink Phone Mic (Virtual Microphone, Stereo)";
+#[cfg(target_os = "linux")]
+pub const VIRTUAL_MIC_MONO_ID: &str = "nectarlink:virtual_mic_mono";
+#[cfg(target_os = "linux")]
+pub const VIRTUAL_MIC_MONO_NAME: &str = "NectarLink Phone Mic (Virtual Microphone, Mono)";
/// The output to play into: the one chosen, while it's there; else a
/// virtual audio cable, if there is one; else `None` (the default output).
@@ -145,7 +157,31 @@ pub fn is_cable(name: &str) -> bool {
/// The output devices, and the one the microphone plays into.
pub fn outputs() -> (Vec<AudioOutputDevice>, Option<String>) {
- let devices = crate::win::audio::output_devices();
+ #[allow(unused_mut)]
+ let mut devices = crate::win::audio::output_devices();
+ #[cfg(target_os = "linux")]
+ {
+ if !devices.iter().any(|d| d.id == VIRTUAL_MIC_MONO_ID) {
+ devices.insert(
+ 0,
+ AudioOutputDevice {
+ id: VIRTUAL_MIC_MONO_ID.into(),
+ name: VIRTUAL_MIC_MONO_NAME.into(),
+ is_default: false,
+ },
+ );
+ }
+ if !devices.iter().any(|d| d.id == VIRTUAL_MIC_ID) {
+ devices.insert(
+ 0,
+ AudioOutputDevice {
+ id: VIRTUAL_MIC_ID.into(),
+ name: VIRTUAL_MIC_NAME.into(),
+ is_default: false,
+ },
+ );
+ }
+ }
let chosen = OUTPUT.lock().unwrap_or_else(|e| e.into_inner()).clone();
let output = preferred(&devices, chosen.as_deref())
.or_else(|| devices.iter().find(|d| d.is_default).map(|d| d.id.clone()));
@@ -154,7 +190,13 @@ pub fn outputs() -> (Vec<AudioOutputDevice>, Option<String>) {
/// Plays the microphone into this output from now on (and the next time).
pub fn set_output(id: String) {
- *OUTPUT.lock().unwrap_or_else(|e| e.into_inner()) = Some(id.clone());
+ {
+ let mut current = OUTPUT.lock().unwrap_or_else(|e| e.into_inner());
+ if current.as_deref() == Some(id.as_str()) {
+ return;
+ }
+ *current = Some(id.clone());
+ }
save(|s| s.phone_mic_output = Some(id));
// Already playing: move there now rather than on the next start.
if let Some(sink) = ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).upgrade() {
@@ -246,16 +288,28 @@ fn after(phase: Phase, event: &NodeEvent) -> Phase {
}
/// Where a phone's microphone goes: [`Platform::mic_sink`](nectarlink_core::Platform::mic_sink).
-pub fn sink(_peer: &DeviceId) -> Option<Arc<dyn MicSink>> {
- let sink = Arc::new(Sink { player: Mutex::new(None), config: Mutex::new(None) });
+pub fn sink(peer: &DeviceId) -> Option<Arc<dyn MicSink>> {
+ let sink = Arc::new(Sink {
+ #[cfg(target_os = "linux")]
+ peer: *peer,
+ player: Mutex::new(None),
+ config: Mutex::new(None),
+ #[cfg(target_os = "linux")]
+ vmic: Mutex::new(None),
+ });
+ let _ = peer;
*ACTIVE.lock().unwrap_or_else(|e| e.into_inner()) = Arc::downgrade(&sink);
Some(sink)
}
struct Sink {
+ #[cfg(target_os = "linux")]
+ peer: DeviceId,
player: Mutex<Option<Player>>,
/// The stream's format, to start again on another output.
config: Mutex<Option<MirrorAudioConfig>>,
+ #[cfg(target_os = "linux")]
+ vmic: Mutex<Option<crate::win::vmic::VirtualMic>>,
}
impl Sink {
@@ -263,6 +317,22 @@ impl Sink {
fn restart(&self) {
let Some(config) = self.config.lock().unwrap_or_else(|e| e.into_inner()).clone() else { return };
let (_, output) = outputs();
+ #[cfg(target_os = "linux")]
+ if matches!(output.as_deref(), Some(VIRTUAL_MIC_ID | VIRTUAL_MIC_MONO_ID)) {
+ self.player.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let out_channels = if output.as_deref() == Some(VIRTUAL_MIC_MONO_ID) { 1 } else { 2 };
+ let phone_name = core_host::host().hub.read(|s| s.name_of(&self.peer));
+ let vmic = crate::win::vmic::VirtualMic::new_for_phone_with_channels(
+ config.rate,
+ config.channels,
+ out_channels,
+ phone_name.as_deref(),
+ );
+ *self.vmic.lock().unwrap_or_else(|e| e.into_inner()) = Some(vmic);
+ return;
+ }
+ #[cfg(target_os = "linux")]
+ self.vmic.lock().unwrap_or_else(|e| e.into_inner()).take();
match Player::start_on(output, config.rate, u16::from(config.channels)) {
Ok(player) => *self.player.lock().unwrap_or_else(|e| e.into_inner()) = Some(player),
Err(e) => tracing::warn!(error = %e, "can't play the phone's microphone"),
@@ -277,6 +347,12 @@ impl MicSink for Sink {
}
fn audio(&self, _time_us: u64, mut data: Vec<u8>) {
+ #[cfg(target_os = "linux")]
+ if let Some(vmic) = self.vmic.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
+ amplify(&mut data, gain());
+ let _ = vmic.push_pcm(&data);
+ return;
+ }
if let Some(player) = self.player.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
amplify(&mut data, gain());
player.push(data);
@@ -284,6 +360,9 @@ impl MicSink for Sink {
}
fn ended(&self) {
+ *self.config.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ #[cfg(target_os = "linux")]
+ self.vmic.lock().unwrap_or_else(|e| e.into_inner()).take();
self.player.lock().unwrap_or_else(|e| e.into_inner()).take();
}
}
@@ -354,4 +433,15 @@ mod tests {
fn without_a_cable_it_is_the_default_output() {
assert_eq!(preferred(&[device("spk", "Speakers", true)], None), None);
}
+
+ #[test]
+ fn virtual_microphone_is_recognized_as_preferred_cable() {
+ let devices = [
+ device("nectarlink:virtual_mic", "NectarLink Phone Mic (Virtual Microphone)", false),
+ device("spk", "Speakers", true),
+ ];
+ assert!(is_cable("NectarLink Phone Mic (Virtual Microphone)"));
+ assert_eq!(preferred(&devices, None).as_deref(), Some("nectarlink:virtual_mic"));
+ assert_eq!(preferred(&devices, Some("spk")).as_deref(), Some("spk"));
+ }
}
diff --git a/desktop/app/src/play_on_phone.rs b/desktop/app/src/play_on_phone.rs
index 79386b6..11a6131 100644
--- a/desktop/app/src/play_on_phone.rs
+++ b/desktop/app/src/play_on_phone.rs
@@ -4,7 +4,7 @@
//! the phone in its app and the PC pauses; anything else the phone watches
//! streamed from the PC, which keeps playing it.
-#[cfg(windows)]
+#[cfg(any(windows, target_os = "linux"))]
mod imp {
#![allow(unsafe_code)]
@@ -19,11 +19,14 @@ mod imp {
};
use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, MediaAction, PlayOnPhone};
+ #[cfg(windows)]
use windows::Win32::{
Foundation::{HWND, RECT},
System::Com::{COINIT_MULTITHREADED, CoInitializeEx},
};
+ #[cfg(target_os = "linux")]
+ use crate::win::browser::{HWND, RECT};
use crate::{
bridge::app::{describe, show_message},
core_host,
@@ -150,6 +153,7 @@ mod imp {
return show_message(tr!("PlayOnPhone", "Connect your phone to play on it."));
};
let spawned = std::thread::Builder::new().name("play-on-phone".into()).spawn(move || {
+ #[cfg(windows)]
// SAFETY: COM for this short-lived thread (UI Automation).
let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
let (title, position) = now_playing(&player);
@@ -278,6 +282,7 @@ mod imp {
let stop = Arc::new(AtomicBool::new(false));
let (found, stopped, player) = (place.clone(), stop.clone(), player.to_owned());
let spawned = std::thread::Builder::new().name("play-on-phone-follow".into()).spawn(move || {
+ #[cfg(windows)]
// SAFETY: COM for this thread, which ends with the watching.
let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
// Places in the pixels the capture uses.
@@ -371,7 +376,7 @@ mod imp {
}
}
-#[cfg(not(windows))]
+#[cfg(not(any(windows, target_os = "linux")))]
mod imp {
#![allow(dead_code)]
diff --git a/desktop/app/src/recordings.rs b/desktop/app/src/recordings.rs
index dc7f3cc..a24bef3 100644
--- a/desktop/app/src/recordings.rs
+++ b/desktop/app/src/recordings.rs
@@ -282,7 +282,45 @@ fn move_file(src: &Path, dest: &Path) -> std::io::Result<()> {
Ok(())
}
-#[cfg(not(windows))]
+/// Converts `src` (`.m4a`) to `dest` in `format` (`Mp3`, `Wav`, or `Flac`)
+/// using `ffmpeg` on Linux.
+#[cfg(target_os = "linux")]
+pub fn convert_audio(src: &Path, dest: &Path, format: RecordingFormat) -> std::io::Result<()> {
+ match format {
+ RecordingFormat::M4a => {
+ fs::copy(src, dest)?;
+ Ok(())
+ }
+ RecordingFormat::Wav | RecordingFormat::Mp3 | RecordingFormat::Flac => {
+ let safe_src = if src.is_relative() && src.to_string_lossy().starts_with('-') {
+ Path::new(".").join(src)
+ } else {
+ src.to_path_buf()
+ };
+ let safe_dest = if dest.is_relative() && dest.to_string_lossy().starts_with('-') {
+ Path::new(".").join(dest)
+ } else {
+ dest.to_path_buf()
+ };
+ let status = std::process::Command::new("ffmpeg")
+ .args(["-v", "error", "-y", "-i"])
+ .arg(&safe_src)
+ .arg("--")
+ .arg(&safe_dest)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()?;
+ if status.success() {
+ Ok(())
+ } else {
+ Err(std::io::Error::other(format!("ffmpeg exited with {status}")))
+ }
+ }
+ }
+}
+
+#[cfg(not(any(windows, target_os = "linux")))]
pub fn convert_audio(_src: &Path, _dest: &Path, _format: RecordingFormat) -> Result<(), String> {
Err("audio conversion via Media Foundation is only supported on Windows".into())
}
@@ -808,7 +846,7 @@ mod tests {
assert_eq!(text, "00:01.250 Intro\n01:05.000 Marker 2\n01:01:01.005 Wrap-up\n");
}
- #[cfg(windows)]
+ #[cfg(any(windows, target_os = "linux"))]
#[test]
fn media_foundation_converts_m4a_to_m4a_mp3_wav_and_flac_with_markers() {
let dir = tempfile::tempdir().unwrap();