Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Phone as microphone on the PC
Bee41c70c21821b
diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 8aab16e..abd5b50 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -269,6 +269,7 @@ fn main() {"src/bridge/mirror.rs","src/bridge/notifications.rs","src/bridge/pairing.rs",+ "src/bridge/phone_mic.rs","src/bridge/photos.rs","src/bridge/prefs.rs","src/bridge/setup.rs",diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 6d5e946..457b50b 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -1557,6 +1557,42 @@ Item {Divider { width: parent.width }+ // Phone as microphone: its sound plays into an output; a+ // virtual audio cable's other end is a microphone apps can pick.+ ListRow {+ width: parent.width+ iconPath: Icons.mic+ title: qsTr("Phone as microphone")+ description: PhoneMic.phase === "live"+ ? qsTr("Live from %1, playing into %2.").arg(PhoneMic.deviceName).arg(PhoneMic.outputName)+ : PhoneMic.phase === "asking"+ ? qsTr("Tap Start on %1.").arg(PhoneMic.deviceName)+ : PhoneMic.cable+ ? qsTr("Plays into %1, so apps can pick its other end as a microphone.").arg(PhoneMic.outputName)+ : qsTr("Plays into %1. To use it as a microphone in other apps, install a virtual audio cable such as VB-CABLE.").arg(PhoneMic.outputName)+ Row {+ spacing: 8+ Button {+ variant: "outline"+ size: "sm"+ text: qsTr("Output")+ onClicked: {+ PhoneMic.refresh()+ micOutputSheet.open()+ }+ }+ Button {+ size: "sm"+ variant: PhoneMic.phase === "off" ? "fill" : "tonal"+ enabled: PhoneMic.phase !== "off" || PhoneMic.device !== ""+ text: PhoneMic.phase === "off" ? qsTr("Start") : qsTr("Stop")+ onClicked: PhoneMic.phase === "off" ? PhoneMic.start(PhoneMic.device) : PhoneMic.stop()+ }+ }+ }++ Divider { width: parent.width }+// Row 2: Virtual camera add-onListRow {width: parent.width@@ -3127,6 +3163,34 @@ Item {Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }}+ Sheet {+ id: micOutputSheet+ cardWidth: 440+ Column {+ width: parent.width+ spacing: 12+ Txt { width: parent.width; text: qsTr("Play the phone's microphone into"); role: "headline"; wrapMode: Text.WordWrap }+ Repeater {+ model: { try { return JSON.parse(PhoneMic.outputs) } catch (e) { return [] } }+ delegate: Button {+ required property var modelData+ width: parent.width+ variant: modelData.id === PhoneMic.output ? "tonal" : "text"+ iconPath: modelData.id === PhoneMic.output ? Icons.check : Icons.speaker+ text: modelData.name+ onClicked: {+ PhoneMic.chooseOutput(modelData.id)+ micOutputSheet.close()+ }+ }+ }+ Row {+ anchors.right: parent.right+ Button { variant: "text"; text: qsTr("Close"); onClicked: micOutputSheet.close() }+ }+ }+ }+Sheet {id: unpairSheetproperty string deviceIddiff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rsindex 3d935b0..96470f2 100644--- a/desktop/app/src/bridge/mod.rs+++ b/desktop/app/src/bridge/mod.rs@@ -28,6 +28,8 @@ pub mod notifications;#[allow(unsafe_code)]pub mod pairing;#[allow(unsafe_code)]+pub mod phone_mic;+#[allow(unsafe_code)]pub mod photos;#[allow(unsafe_code)]pub mod prefs;diff --git a/desktop/app/src/bridge/phone_mic.rs b/desktop/app/src/bridge/phone_mic.rsnew file mode 100644index 0000000..6498e27--- /dev/null+++ b/desktop/app/src/bridge/phone_mic.rs@@ -0,0 +1,117 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! `PhoneMic`: QML singleton for Phone as microphone (crate::phone_mic):+//! whether a phone's microphone is off, asked for or live, and which output+//! it plays into.++use std::pin::Pin;++use cxx_qt::Threading;+use cxx_qt_lib::QString;++use crate::{+ phone_mic::{self, Phase},+ state::Changes,+};++#[cxx_qt::bridge]+pub mod qobject {+ unsafe extern "C++" {+ include!("cxx-qt-lib/qstring.h");+ type QString = cxx_qt_lib::QString;+ }++ unsafe extern "RustQt" {+ #[qobject]+ #[qml_element]+ #[qml_singleton]+ /// "off", "asking" (waiting for the phone's user) or "live".+ #[qproperty(QString, phase)]+ /// The phone it asks or listens to, else the one it would ask ("" when none).+ #[qproperty(QString, device)]+ #[qproperty(QString, device_name, cxx_name = "deviceName")]+ /// The output devices, as JSON: `[{ "id", "name" }]`.+ #[qproperty(QString, outputs)]+ /// The output it plays into (an ID from `outputs`).+ #[qproperty(QString, output)]+ #[qproperty(QString, output_name, cxx_name = "outputName")]+ /// Whether `output` is a virtual audio cable (apps see it as a microphone).+ #[qproperty(bool, cable)]+ type PhoneMic = super::PhoneMicRust;+ }++ impl cxx_qt::Threading for PhoneMic {}+ impl cxx_qt::Initialize for PhoneMic {}++ unsafe extern "RustQt" {+ #[qinvokable]+ fn start(self: &PhoneMic, device: &QString);+ #[qinvokable]+ fn stop(self: &PhoneMic);+ #[qinvokable]+ #[cxx_name = "chooseOutput"]+ fn choose_output(self: &PhoneMic, id: &QString);+ /// Lists the outputs again (one may have been plugged in).+ #[qinvokable]+ fn refresh(self: Pin<&mut PhoneMic>);+ }+}++#[derive(Default)]+pub struct PhoneMicRust {+ phase: QString,+ device: QString,+ device_name: QString,+ outputs: QString,+ output: QString,+ output_name: QString,+ cable: bool,+}++impl cxx_qt::Initialize for qobject::PhoneMic {+ fn initialize(self: Pin<&mut Self>) {+ super::subscribe(+ self.qt_thread(),+ Changes::MIC | Changes::DEVICES | Changes::CAPABILITIES,+ Self::refresh,+ );+ }+}++impl qobject::PhoneMic {+ pub fn refresh(mut self: Pin<&mut Self>) {+ let phase = match phone_mic::phase() {+ Phase::Off => "off",+ Phase::Asking(_) => "asking",+ Phase::Live(_) => "live",+ };+ let (device, device_name) =+ phone_mic::phone().map(|(id, name)| (id.to_string(), name)).unwrap_or_default();+ let (devices, output) = phone_mic::outputs();+ let list: Vec<_> =+ devices.iter().map(|d| serde_json::json!({ "id": d.id, "name": d.name })).collect();+ let chosen = output.as_deref().and_then(|id| devices.iter().find(|d| d.id == id));+ let name = chosen.map(|d| d.name.clone()).unwrap_or_default();+ let cable = chosen.is_some_and(|d| phone_mic::is_cable(&d.name));+ self.as_mut().set_phase(QString::from(phase));+ self.as_mut().set_device(QString::from(&device));+ self.as_mut().set_device_name(QString::from(&device_name));+ self.as_mut().set_outputs(QString::from(&serde_json::Value::Array(list).to_string()));+ self.as_mut().set_output(QString::from(output.unwrap_or_default().as_str()));+ self.as_mut().set_output_name(QString::from(&name));+ self.as_mut().set_cable(cable);+ }++ pub fn start(&self, device: &QString) {+ if let Some(id) = super::parse_device(device) {+ phone_mic::start(id);+ }+ }++ pub fn stop(&self) {+ phone_mic::stop();+ }++ pub fn choose_output(&self, id: &QString) {+ phone_mic::set_output(String::from(id));+ }+}diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rsindex d53448d..f7d7689 100644--- a/desktop/app/src/bridge/prefs.rs+++ b/desktop/app/src/bridge/prefs.rs@@ -877,6 +877,7 @@ impl qobject::Preferences {webcam_height: crate::webcam::height(),webcam_mirror: crate::webcam::mirror(),webcam_camera: crate::webcam::camera().to_owned(),+ phone_mic_output: crate::phone_mic::chosen_output(),timeline_retention_days: p.timeline_retention_days.max(0) as u32,continuity_photo_hotkey: String::from(&p.continuity_photo_hotkey),continuity_scan_hotkey: String::from(&p.continuity_scan_hotkey),diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex a0b514a..9128a2b 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -119,6 +119,7 @@ pub fn compute_capabilities(node: Option<&Node>) -> Vec<String> {nectarlink_core::STORAGE_WRITE.into(),nectarlink_core::WEBCAM_VIRTUAL.into(),nectarlink_core::MEDIA_STREAM.into(),+ nectarlink_core::MIC_LISTEN.into(),];let mut pc_mirror_enabled = crate::pc_mirror::is_active();let mut remote_input_enabled = false;@@ -312,6 +313,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {crate::battery::on_event(&event);crate::storage::on_event(&event);crate::webcam::on_event(&event);+ crate::phone_mic::on_event(&event);crate::automations::on_event(&event);crate::bridge::app::on_home_event(&event);}diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 613f283..17af192 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -37,6 +37,7 @@ mod pc_audio_stream;mod pc_mirror;mod pc_notifications;mod pc_storage;+mod phone_mic;mod photos;mod play_on_phone;mod qr;@@ -142,6 +143,12 @@ impl Platform for DesktopPlatform {) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {mirror::sink(peer, session)}+ fn mic_sink(+ &self,+ peer: &nectarlink_core::DeviceId,+ ) -> Option<std::sync::Arc<dyn nectarlink_core::MicSink>> {+ phone_mic::sink(peer)+ }fn webcam_sink(&self,peer: &nectarlink_core::DeviceId,@@ -550,6 +557,7 @@ fn main() -> ExitCode {storage::start();folder_sync::start_poller();webcam::init(&settings);+ phone_mic::init(&settings);local_api::init(&settings);win::widget::write_state_snapshot(&data_dir);win::tray::update_hotkeys(diff --git a/desktop/app/src/phone_mic.rs b/desktop/app/src/phone_mic.rsnew file mode 100644index 0000000..f46c551--- /dev/null+++ b/desktop/app/src/phone_mic.rs@@ -0,0 +1,223 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! Phone as microphone (docs/protocol/mic.md), on this PC: asks a phone for+//! its microphone and plays it into an output device. Played into a virtual+//! audio cable (VB-Audio's CABLE Input, Voicemeeter), the cable's other end+//! is a microphone every app can pick; played to the speakers, it's for+//! listening in. A virtual microphone of NectarLink's own needs an audio+//! driver and is a later, separate step (GitHub #7).++use std::sync::{Arc, Mutex};++use nectarlink_core::{AudioOutputDevice, DeviceId, Error, LinkState, MicSink, MirrorAudioConfig, NodeEvent};++use crate::{+ bridge::app::{describe, show_message},+ core_host,+ state::Changes,+ win::audio_out::Player,+};++/// Where the phone's microphone is.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum Phase {+ #[default]+ Off,+ /// Asked; waiting for the phone's user to tap Start.+ Asking(DeviceId),+ /// Its sound is arriving.+ Live(DeviceId),+}++static PHASE: Mutex<Phase> = Mutex::new(Phase::Off);+/// The output device chosen in Settings (an endpoint ID), if any.+static OUTPUT: Mutex<Option<String>> = Mutex::new(None);++fn set_phase(phase: Phase) {+ let mut current = PHASE.lock().unwrap_or_else(|e| e.into_inner());+ if *current != phase {+ tracing::info!(?phase, "phone microphone");+ *current = phase;+ drop(current);+ core_host::host().hub.changed(Changes::MIC);+ }+}++pub fn phase() -> Phase {+ *PHASE.lock().unwrap_or_else(|e| e.into_inner())+}++/// Reads the chosen output from the settings.+pub fn init(settings: &crate::settings::Settings) {+ *OUTPUT.lock().unwrap_or_else(|e| e.into_inner()) = settings.phone_mic_output.clone();+}++/// The output chosen in Settings, if any (kept when other settings save).+pub fn chosen_output() -> Option<String> {+ OUTPUT.lock().unwrap_or_else(|e| e.into_inner()).clone()+}++/// Names that virtual audio cables give their playback end.+const CABLES: &[&str] = &["cable input", "vb-audio", "voicemeeter input", "virtual cable"];++/// 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).+pub(crate) fn preferred(devices: &[AudioOutputDevice], chosen: Option<&str>) -> Option<String> {+ if let Some(id) = chosen+ && devices.iter().any(|d| d.id == id)+ {+ return Some(id.to_owned());+ }+ devices.iter().find(|d| is_cable(&d.name)).map(|d| d.id.clone())+}++/// Whether an output with this name is a virtual audio cable.+pub fn is_cable(name: &str) -> bool {+ let name = name.to_lowercase();+ CABLES.iter().any(|cable| name.contains(cable))+}++/// The output devices, and the one the microphone plays into.+pub fn outputs() -> (Vec<AudioOutputDevice>, Option<String>) {+ let devices = crate::win::audio::output_devices();+ 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()));+ (devices, output)+}++/// 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 dir = &core_host::host().data_dir;+ let mut settings = crate::settings::Settings::load(dir);+ settings.phone_mic_output = Some(id);+ if let Err(e) = settings.save(dir) {+ tracing::warn!(error = %e, "can't save the microphone's output");+ }+ core_host::host().hub.changed(Changes::MIC);+}++/// The phone whose microphone to use: the one asked or listened to, else+/// the first online one that can lend it, else the first online one (which+/// says so if it can't).+pub fn phone() -> Option<(DeviceId, String)> {+ let current = match phase() {+ Phase::Asking(id) | Phase::Live(id) => Some(id),+ Phase::Off => None,+ };+ core_host::host().hub.read(|s| {+ let can = |id: &DeviceId| {+ s.matrices.get(id).and_then(|m| m.state("media.phone_mic"))+ == Some(nectarlink_core::FeatureState::Available)+ };+ s.devices+ .iter()+ .find(|d| Some(d.id) == current)+ .or_else(|| s.devices.iter().find(|d| matches!(d.link, LinkState::Online { .. }) && can(&d.id)))+ .or_else(|| s.devices.iter().find(|d| matches!(d.link, LinkState::Online { .. })))+ .map(|d| (d.id, d.info.name.clone()))+ })+}++/// Asks `phone` for its microphone; its user taps Start there.+pub fn start(phone: DeviceId) {+ let Some(node) = core_host::node() else { return };+ let name = core_host::host().hub.read(|s| s.name_of(&phone)).unwrap_or_else(|| "your phone".into());+ set_phase(Phase::Asking(phone));+ core_host::spawn(async move {+ match node.mic_start(phone).await {+ Ok(()) => show_message(format!("Tap Start on {name} to use its microphone.")),+ Err(e) => {+ set_phase(Phase::Off);+ show_message(match e {+ Error::Unsupported => format!("Update NectarLink on {name} to use its microphone."),+ Error::Denied => format!("The microphone is turned off for this PC on {name}."),+ other => describe(&other),+ });+ }+ }+ });+}++/// Stops listening (and asking).+pub fn stop() {+ let (Phase::Asking(phone) | Phase::Live(phone)) = phase() else { return };+ set_phase(Phase::Off);+ if let Some(node) = core_host::node() {+ core_host::spawn(async move { node.mic_stop(phone).await });+ }+}++pub fn on_event(event: &NodeEvent) {+ match event {+ NodeEvent::Mic { device, on: true } => set_phase(Phase::Live(*device)),+ NodeEvent::Mic { device, on: false } if phase() == Phase::Live(*device) => set_phase(Phase::Off),+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } }+ | NodeEvent::DeviceRemoved(device)+ if matches!(phase(), Phase::Asking(d) | Phase::Live(d) if d == *device) =>+ {+ set_phase(Phase::Off)+ }+ _ => {}+ }+}++/// Where a phone's microphone goes: [`Platform::mic_sink`](nectarlink_core::Platform::mic_sink).+pub fn sink(_peer: &DeviceId) -> Option<Arc<dyn MicSink>> {+ Some(Arc::new(Sink { player: Mutex::new(None) }))+}++struct Sink {+ player: Mutex<Option<Player>>,+}++impl MicSink for Sink {+ fn config(&self, config: MirrorAudioConfig) {+ let (_, output) = outputs();+ 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"),+ }+ }++ fn audio(&self, _time_us: u64, data: Vec<u8>) {+ if let Some(player) = self.player.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {+ player.push(data);+ }+ }++ fn ended(&self) {+ self.player.lock().unwrap_or_else(|e| e.into_inner()).take();+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn device(id: &str, name: &str, is_default: bool) -> AudioOutputDevice {+ AudioOutputDevice { id: id.into(), name: name.into(), is_default }+ }++ #[test]+ fn a_virtual_cable_is_preferred_until_another_output_is_chosen() {+ let devices = [+ device("spk", "Speakers (Realtek Audio)", true),+ device("cable", "CABLE Input (VB-Audio Virtual Cable)", false),+ ];+ assert_eq!(preferred(&devices, None).as_deref(), Some("cable"));+ assert_eq!(preferred(&devices, Some("spk")).as_deref(), Some("spk"));+ // The chosen one was unplugged: the cable again.+ assert_eq!(preferred(&devices, Some("usb-headset")).as_deref(), Some("cable"));+ assert_eq!(+ preferred(&[device("vm", "Voicemeeter Input (VB-Audio Voicemeeter VAIO)", false)], None)+ .as_deref(),+ Some("vm")+ );+ }++ #[test]+ fn without_a_cable_it_is_the_default_output() {+ assert_eq!(preferred(&[device("spk", "Speakers", true)], None), None);+ }+}diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rsindex 1778505..3a7fe18 100644--- a/desktop/app/src/settings.rs+++ b/desktop/app/src/settings.rs@@ -325,6 +325,10 @@ pub struct Settings {/// Horizontally mirror the webcam video.#[serde(alias = "webcam_mirror")]pub webcam_mirror: bool,+ /// Where a phone's microphone plays (an output endpoint ID; `None`: a+ /// virtual audio cable if there is one, else the default output).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub phone_mic_output: Option<String>,/// Which phone camera lens to stream (`"back"` or `"front"`).#[serde(default = "default_webcam_camera", alias = "webcam_camera")]pub webcam_camera: String,@@ -438,6 +442,7 @@ impl Default for Settings {webcam_height: 720,webcam_mirror: false,webcam_camera: default_webcam_camera(),+ phone_mic_output: None,timeline_retention_days: 90,continuity_photo_hotkey: "Ctrl+Alt+C".into(),continuity_scan_hotkey: "Ctrl+Alt+D".into(),@@ -587,6 +592,7 @@ mod tests {webcam_height: 2160,webcam_mirror: true,webcam_camera: "front".into(),+ phone_mic_output: Some("{0.0.0.00000000}.{cable}".into()),timeline_retention_days: 30,continuity_photo_hotkey: "Ctrl+Alt+P".into(),continuity_scan_hotkey: "Ctrl+Alt+S".into(),diff --git a/desktop/app/src/win/audio_out.rs b/desktop/app/src/win/audio_out.rsindex ed95d09..56a3805 100644--- a/desktop/app/src/win/audio_out.rs+++ b/desktop/app/src/win/audio_out.rs@@ -47,13 +47,20 @@ impl Player {/// Starts playing `channels` × 16-bit PCM at `rate` on the default/// output device.pub fn start(rate: u32, channels: u16) -> std::io::Result<Player> {+ Self::start_on(None, rate, channels)+ }++ /// As [`Player::start`], on the output device with this endpoint ID+ /// (from [`super::audio::output_devices`]), or the default one when+ /// it's `None` or gone.+ pub fn start_on(device: Option<String>, rate: u32, channels: u16) -> std::io::Result<Player> {let (queue, packets) = sync_channel(QUEUE);std::thread::Builder::new().name("mirror-sound".into()).spawn(move || {let mut attempts = 0;// The device can go away (headphones unplugged): start over on// the new default, a few times.while attempts < 5 {- match play(rate, channels, &packets) {+ match play(device.as_deref(), rate, channels, &packets) {Ok(()) => return,Err(e) => {tracing::warn!(error = %e, "the sound stopped; trying the default device again");@@ -144,18 +151,29 @@ impl Jitter {}/// Plays until the sender is gone (`Ok`) or the device fails (`Err`).-fn play(rate: u32, channels: u16, packets: &Receiver<Vec<u8>>) -> windows::core::Result<()> {+fn play(+ device: Option<&str>,+ rate: u32,+ channels: u16,+ packets: &Receiver<Vec<u8>>,+) -> windows::core::Result<()> {// SAFETY: balanced below; this thread is ours and uses only the MTA.unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok()?;let event = Event::new()?;- let result = render(rate, channels, packets, event.0);+ let result = render(device, rate, channels, packets, event.0);drop(event);// SAFETY: pairs with CoInitializeEx above; every COM object is gone.unsafe { CoUninitialize() };result}-fn render(rate: u32, channels: u16, packets: &Receiver<Vec<u8>>, event: HANDLE) -> windows::core::Result<()> {+fn render(+ device: Option<&str>,+ rate: u32,+ channels: u16,+ packets: &Receiver<Vec<u8>>,+ event: HANDLE,+) -> windows::core::Result<()> {let block = 2 * channels;let format = WAVEFORMATEX {wFormatTag: WAVE_FORMAT_PCM as u16,@@ -171,7 +189,11 @@ fn render(rate: u32, channels: u16, packets: &Receiver<Vec<u8>>, event: HANDLE)// GetBuffer and ReleaseBuffer.unsafe {let devices: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;- let device = devices.GetDefaultAudioEndpoint(eRender, eConsole)?;+ let chosen = device.and_then(|id| devices.GetDevice(&windows::core::HSTRING::from(id)).ok());+ let device = match chosen {+ Some(device) => device,+ None => devices.GetDefaultAudioEndpoint(eRender, eConsole)?,+ };let client: IAudioClient = device.Activate(CLSCTX_ALL, None)?;// Windows converts the rate and channels to the device's own.client.Initialize(