Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Phone as microphone: the protocol, the core and the phone
Beed3a73b3c9771
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 3e96634..f9d7cfe 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -319,6 +319,20 @@android:exported="false"android:foregroundServiceType="microphone" />+ <!-- Phone as microphone. -->+ <service+ android:name=".mic.MicService"+ android:exported="false"+ android:foregroundServiceType="microphone" />++ <activity+ android:name=".mic.MicStartActivity"+ android:exported="false"+ android:excludeFromRecents="true"+ android:noHistory="true"+ android:taskAffinity=""+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />+<serviceandroid:name=".webcam.WebcamService"android:exported="false"diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex 2c48c95..404cf3f 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -97,6 +97,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerringer,phoneMedia,onLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },+ onMic = { pc ->+ app.nectarlink.android.mic.MicRequests.show(this.context, pc, _state.value.nameOf(pc).orEmpty())+ },onWatch = { pc, player, title ->app.nectarlink.android.media.WatchOffers.show(this.context,@@ -933,6 +936,23 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}}+ /** Opens this phone's microphone stream to [pcId] (docs/protocol/mic.md); null if it can't. */+ suspend fun micOpen(pcId: String): MirrorStream? {+ startJob?.join()+ val node = node ?: return null+ return try {+ node.micOpen(pcId)+ } catch (e: NectarlinkException) {+ _messages.tryEmit(describe(e))+ null+ }+ }++ /** Stops this phone's microphone stream to [pcId] and tells the PC. */+ fun micStop(pcId: String) {+ command { it.micStop(pcId) }+ }+fun clearWebcamRequest(pcId: String? = null) {if (pcId != null) WebcamRequests.dismiss(context, pcId)_state.update { s ->@@ -1603,6 +1623,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerCLIPBOARD_CAPABILITIES +// Play on phone: shows a PC's playback, streamed from the PC.listOf("media.watch") ++ // Phone as microphone: asks for the permission when a PC first wants it.+ (if (context.packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) listOf("mic.stream") else emptyList()) +toggles.capabilities() +(if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()) +(if (notificationAccess && NotificationListener.canReadSensitive(context)) listOf("notify.sensitive") else emptyList()) +diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 3c38c3d..1b222e4 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -63,6 +63,8 @@ internal class PhonePlatform(private val onLink: (String, String) -> Boolean,/** Shows a PC's Play on phone offer: (PC's ID, player, title) → shown. */private val onWatch: (String, String, String?) -> Boolean,+ /** Asks the user to start the microphone for a PC: PC's ID → asked. */+ private val onMic: (String) -> Boolean,/** Shows or updates a watched task from a PC: (PC's ID, task) → shown. */private val onTask: (String, TaskNotify) -> Boolean,/** The phone's calls (created after this). */@@ -202,6 +204,13 @@ internal class PhonePlatform(return onWebcam(pcId, request)}+ override fun micRequested(pcId: String): Boolean = onMic(pcId)++ override fun micStopRequested(pcId: String) {+ app.nectarlink.android.mic.MicRequests.dismiss(context, pcId)+ app.nectarlink.android.mic.MicService.stop(context)+ }+override fun webcamStopRequested(pcId: String) {WebcamRequests.dismiss(context, pcId)WebcamService.stopForPc(context, pcId)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mic/MicRequests.kt b/android/app/src/main/kotlin/app/nectarlink/android/mic/MicRequests.ktnew file mode 100644index 0000000..53a6c7d--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mic/MicRequests.kt@@ -0,0 +1,96 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mic++import android.Manifest+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import app.nectarlink.android.R++/**+ * A PC asking for this phone's microphone (`mic.start`). The microphone only turns on when+ * the user taps: the notification opens [MicStartActivity], which asks for the microphone+ * permission if needed and starts [MicService] from the foreground, as Android requires.+ */+object MicRequests {+ private const val CHANNEL = "mic_requests"+ private const val TAG = "mic_req"+ private const val REQUEST_TIMEOUT_MS = 2 * 60 * 1000L++ /** Shows the request; false if notifications are off. */+ fun show(context: Context, pcId: String, pcName: String): Boolean {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=+ PackageManager.PERMISSION_GRANTED+ ) {+ return false+ }+ context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(+ NotificationChannel(CHANNEL, context.getString(R.string.channel_mic_requests), NotificationManager.IMPORTANCE_HIGH),+ )+ val start = PendingIntent.getActivity(+ context,+ pcId.hashCode(),+ Intent(context, MicStartActivity::class.java)+ .putExtra(MicStartActivity.EXTRA_PC, pcId)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val from = pcName.ifEmpty { context.getString(R.string.your_pc) }+ val notification = NotificationCompat.Builder(context, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(context.getString(R.string.mic_request_title, from))+ .setContentText(context.getString(R.string.mic_request_text))+ .setContentIntent(start)+ .addAction(0, context.getString(R.string.mic_request_start), start)+ .setAutoCancel(true)+ .setTimeoutAfter(REQUEST_TIMEOUT_MS)+ .setCategory(NotificationCompat.CATEGORY_CALL)+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .build()+ return runCatching { NotificationManagerCompat.from(context).notify(TAG, pcId.hashCode(), notification) }.isSuccess+ }++ fun dismiss(context: Context, pcId: String) {+ runCatching { NotificationManagerCompat.from(context).cancel(TAG, pcId.hashCode()) }+ }+}++/** Starts the microphone for a PC after the user tapped its request; shows nothing itself. */+class MicStartActivity : ComponentActivity() {+ private var pcId: String? = null++ private val permission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ if (granted) pcId?.let { MicService.start(this, it) }+ finish()+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ val pc = intent.getStringExtra(EXTRA_PC)+ if (pc == null) {+ finish()+ return+ }+ pcId = pc+ MicRequests.dismiss(this, pc)+ if (MicService.hasPermission(this)) {+ MicService.start(this, pc)+ finish()+ } else if (savedInstanceState == null) {+ permission.launch(Manifest.permission.RECORD_AUDIO)+ }+ }++ companion object {+ const val EXTRA_PC = "mic_pc"+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mic/MicService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mic/MicService.ktnew file mode 100644index 0000000..4f113bf--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mic/MicService.kt@@ -0,0 +1,218 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mic++import android.Manifest+import android.annotation.SuppressLint+import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.content.pm.ServiceInfo+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.MediaRecorder+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.ServiceCompat+import androidx.core.content.ContextCompat+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import app.nectarlink.core.MirrorSendResult+import app.nectarlink.core.VideoPacketKind+import app.nectarlink.core.mirrorAudioConfig+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/**+ * Phone as microphone (docs/protocol/mic.md): streams the microphone to a PC as 48 kHz mono+ * 16-bit PCM, 10 ms at a time, in a foreground service of type `microphone` so it keeps going+ * with the screen off. It records for calls (echo cancellation and noise suppression where the+ * phone has them) and stops when the PC stops listening, the connection ends, or the user taps+ * Stop.+ */+class MicService : Service() {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var job: Job? = null++ @Volatile+ private var running = false++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ when (intent?.action) {+ ACTION_START -> {+ val pcId = intent.getStringExtra(EXTRA_PC)+ if (pcId != null && !running) start(pcId) else if (pcId == null) stopSelf()+ }+ ACTION_STOP -> {+ val pcId = _streaming.value+ running = false+ // The phone's user stopped it: tell the PC.+ if (intent.getBooleanExtra(EXTRA_FROM_USER, false) && pcId != null) {+ (application as NectarlinkApplication).core.micStop(pcId)+ }+ if (job == null) stopSelf()+ }+ }+ return START_NOT_STICKY+ }++ @SuppressLint("MissingPermission")+ private fun start(pcId: String) {+ if (!hasPermission(this)) {+ stopSelf()+ return+ }+ createChannel(this)+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE+ } else {+ 0+ }+ ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(pcId), type)+ running = true+ _streaming.value = pcId+ val core = (application as NectarlinkApplication).core+ job = scope.launch {+ try {+ val stream = core.micOpen(pcId) ?: return@launch+ val minimum = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)+ val recorder = AudioRecord(+ MediaRecorder.AudioSource.VOICE_COMMUNICATION,+ RATE,+ AudioFormat.CHANNEL_IN_MONO,+ AudioFormat.ENCODING_PCM_16BIT,+ maxOf(minimum, CHUNK_BYTES * 4),+ )+ if (recorder.state != AudioRecord.STATE_INITIALIZED) {+ Log.w(TAG, "microphone not available")+ recorder.release()+ stream.end()+ stream.close()+ core.micStop(pcId)+ return@launch+ }+ try {+ if (stream.send(VideoPacketKind.CONFIG, 0u, mirrorAudioConfig(RATE.toUInt(), 1u)) ==+ MirrorSendResult.CLOSED+ ) {+ return@launch+ }+ recorder.startRecording()+ val chunk = ByteArray(CHUNK_BYTES)+ var samples = 0L+ while (running) {+ val read = recorder.read(chunk, 0, chunk.size)+ if (read <= 0) continue+ val timeUs = samples * 1_000_000L / RATE+ samples += read / 2+ // Dropped packets (a slow link) only lose that moment; a closed stream ends it.+ if (stream.send(VideoPacketKind.FRAME, timeUs.toULong(), chunk.copyOf(read)) ==+ MirrorSendResult.CLOSED+ ) {+ break+ }+ }+ } finally {+ runCatching { recorder.stop() }+ recorder.release()+ stream.end()+ stream.close()+ }+ } catch (e: Exception) {+ Log.w(TAG, "microphone stream failed", e)+ } finally {+ running = false+ _streaming.value = null+ job = null+ ServiceCompat.stopForeground(this@MicService, ServiceCompat.STOP_FOREGROUND_REMOVE)+ stopSelf()+ }+ }+ }++ private fun notification(pcId: String): Notification {+ val core = (application as NectarlinkApplication).core+ val pcName = core.state.value.nameOf(pcId).orEmpty().ifEmpty { getString(R.string.your_pc) }+ val stop = PendingIntent.getService(+ this,+ 1,+ Intent(this, MicService::class.java).setAction(ACTION_STOP).putExtra(EXTRA_FROM_USER, true),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ return NotificationCompat.Builder(this, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(getString(R.string.mic_notification_title, pcName))+ .setContentText(getString(R.string.mic_notification_text))+ .setOngoing(true)+ .setSilent(true)+ .setOnlyAlertOnce(true)+ .setCategory(NotificationCompat.CATEGORY_SERVICE)+ .addAction(0, getString(R.string.action_stop), stop)+ .build()+ }++ override fun onDestroy() {+ running = false+ scope.cancel()+ _streaming.value = null+ super.onDestroy()+ }++ companion object {+ private const val TAG = "MicService"+ private const val CHANNEL = "mic"+ private const val NOTIFICATION_ID = 9+ private const val RATE = 48_000++ /** 10 ms of 16-bit mono at [RATE]. */+ private const val CHUNK_BYTES = RATE / 100 * 2++ private const val ACTION_START = "app.nectarlink.android.mic.START"+ private const val ACTION_STOP = "app.nectarlink.android.mic.STOP"+ private const val EXTRA_PC = "pc"+ private const val EXTRA_FROM_USER = "from_user"++ private val _streaming = MutableStateFlow<String?>(null)++ /** The PC this phone's microphone streams to, if any. */+ val streaming: StateFlow<String?> = _streaming.asStateFlow()++ fun hasPermission(context: Context): Boolean =+ ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==+ PackageManager.PERMISSION_GRANTED++ /** Starts streaming to [pcId]; only from the foreground (Android's rule for the mic). */+ fun start(context: Context, pcId: String) {+ val intent = Intent(context, MicService::class.java).setAction(ACTION_START).putExtra(EXTRA_PC, pcId)+ ContextCompat.startForegroundService(context, intent)+ }++ /** The PC stopped listening. */+ fun stop(context: Context) {+ if (_streaming.value == null) return+ context.startService(Intent(context, MicService::class.java).setAction(ACTION_STOP))+ }++ private fun createChannel(context: Context) {+ context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(+ NotificationChannel(CHANNEL, context.getString(R.string.channel_mic), NotificationManager.IMPORTANCE_LOW)+ .apply { setShowBadge(false) },+ )+ }+ }+}diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xmlindex 6a593f7..0d5ce07 100644--- a/android/app/src/main/res/values-zh-rCN/strings.xml+++ b/android/app/src/main/res/values-zh-rCN/strings.xml@@ -348,6 +348,13 @@<string name="pc_mirror_viewport_desc">%1$s 屏幕</string><string name="action_record_pc">录制</string><string name="channel_recorder">录音机</string>+ <string name="channel_mic">电脑麦克风</string>+ <string name="channel_mic_requests">麦克风请求</string>+ <string name="mic_notification_title">正在为 %1$s 使用麦克风</string>+ <string name="mic_notification_text">电脑正在接收此手机的麦克风。</string>+ <string name="mic_request_title">%1$s 想使用此手机的麦克风</string>+ <string name="mic_request_text">轻触即可开始。在你或电脑停止之前会一直开启。</string>+ <string name="mic_request_start">开始</string><string name="recorder_notification_recording">正在为 %1$s 录音</string><string name="recorder_notification_paused">录音已暂停(%1$s)</string><string name="recorder_permission_title">允许使用麦克风</string>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex fe5ebe5..194c5aa 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -363,6 +363,14 @@<!-- Voice recorder to PC --><string name="action_record_pc">Record</string><string name="channel_recorder">Voice recorder</string>+ <!-- Phone as microphone. -->+ <string name="channel_mic">Microphone for your PC</string>+ <string name="channel_mic_requests">Microphone requests</string>+ <string name="mic_notification_title">Microphone on for %1$s</string>+ <string name="mic_notification_text">Your PC hears this phone\'s microphone.</string>+ <string name="mic_request_title">%1$s wants this phone\'s microphone</string>+ <string name="mic_request_text">Tap to start. It stays on until you or the PC stop it.</string>+ <string name="mic_request_start">Start</string><string name="recorder_notification_recording">Recording for %1$s</string><string name="recorder_notification_paused">Recording paused (%1$s)</string><string name="recorder_permission_title">Allow microphone access</string>diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex b8a7ce9..0764854 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -439,6 +439,21 @@ pub trait Platform: Send + Sync + 'static {Err("this device doesn't stream a camera".into())}+ /// Where a phone's microphone goes on this PC when it starts streaming+ /// (`docs/protocol/mic.md`). `None` refuses the stream.+ fn mic_sink(&self, _peer: &nectarlink_protocol::DeviceId) -> Option<std::sync::Arc<dyn crate::MicSink>> {+ None+ }++ /// A paired PC asked for this phone's microphone: ask the user, then+ /// stream with [`Node::mic_open`](crate::Node::mic_open).+ fn mic_requested(&self, _peer: &nectarlink_protocol::DeviceId) -> Result<(), String> {+ Err("this device doesn't stream its microphone".into())+ }++ /// The PC stopped listening to this phone's microphone: stop recording.+ fn mic_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}+/// The PC stopped using this phone's webcam: stop streaming.fn webcam_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 8165974..b3a3166 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -220,6 +220,11 @@ pub enum NodeEvent {device: DeviceId,on: bool,},+ /// A paired phone's microphone started or stopped arriving on this PC.+ Mic {+ device: DeviceId,+ on: bool,+ },/// A paired PC requested a Continuity Camera capture on this phone.CameraCaptureRequested {device: DeviceId,diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 7e4e4e8..624aa4f 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -345,6 +345,8 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[("pc_actions", true),("mirroring", true),("webcam", true),+ // The phone asks its user each time a PC wants its microphone.+ ("mic", true),// Browsing the phone's storage on a PC is opt-in.("storage", false),// Viewing this PC's screen on a phone is opt-in.@@ -872,6 +874,12 @@ pub const FEATURES: &[FeatureDef] = &[],partial: None,},+ FeatureDef {+ id: "media.phone_mic",+ group: FeatureGroup::Media,+ requires: &[phone("mic.stream", UPDATE), desktop("mic.listen", UPDATE), DeviceToggle("mic")],+ partial: None,+ },FeatureDef {id: "camera.continuity",group: FeatureGroup::Camera,diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 4f5a8ed..367808d 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -22,6 +22,7 @@ pub mod handoff;mod identity;pub mod localsend;mod media;+pub mod mic;mod mirror;mod node;mod notifications;@@ -73,6 +74,7 @@ pub use localsend::{peer_device_id as localsend_peer_device_id,};pub use media::{MediaAction, MediaError};+pub use mic::{MicSink, TOGGLE as MIC_TOGGLE};pub use mirror::{MirrorSend, MirrorSink, MirrorStream, PC_MIRROR_TOGGLE};pub use nectarlink_protocol::messages::clip::{IMAGE_TYPES as CLIP_IMAGE_TYPES, MAX_IMAGE_BYTES as CLIP_MAX_IMAGE_BYTES,@@ -103,6 +105,7 @@ pub use nectarlink_protocol::{format_mac, ipv4_broadcast, is_package_name, is_valid_storage_dir_path, is_valid_storage_id,is_valid_storage_name, is_valid_storage_path, magic_packet,media_watch::{STREAM as MEDIA_STREAM, WATCH as MEDIA_WATCH},+ mic::{LISTEN as MIC_LISTEN, STREAM as MIC_STREAM},mirror::{AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, AV1 as MIRROR_AV1,CAPTURE as MIRROR_CAPTURE, H264 as MIRROR_H264, H265 as MIRROR_H265, INPUT as MIRROR_INPUT,diff --git a/core/nectarlink-core/src/mic.rs b/core/nectarlink-core/src/mic.rsnew file mode 100644index 0000000..42118f6--- /dev/null+++ b/core/nectarlink-core/src/mic.rs@@ -0,0 +1,203 @@+// SPDX-License-Identifier: MPL-2.0+//! Phone as microphone (`docs/protocol/mic.md`): a phone streams its+//! microphone as 16-bit PCM on a dedicated QUIC stream (`mic/pcm`), after+//! its user accepts a PC's `mic.start` (or starts it on the phone).++use std::sync::Arc;++use iroh::endpoint::{RecvStream, SendStream, VarInt};+use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode, PacketKind,+ messages::{MirrorAudioConfig, StreamHeader, mic, types},+ read_video_packet, write_frame,+};++use crate::{Error, MirrorStream, Result, events::NodeEvent, node::Shared, session::Session};++/// The device toggle that allows a device's microphone on this PC (or this+/// phone's microphone for a PC).+pub const TOGGLE: &str = "mic";++/// What the PC's app gets of a phone's microphone. Called from the core's+/// threads; must return quickly.+pub trait MicSink: Send + Sync {+ /// The sound's format: first, and again if it changes.+ fn config(&self, config: MirrorAudioConfig);+ /// Sound, in that format.+ fn audio(&self, time_us: u64, data: Vec<u8>);+ /// The stream ended (the phone stopped, or the connection dropped).+ fn ended(&self);+}++impl std::fmt::Debug for dyn MicSink {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("MicSink")+ }+}++// ---- The PC ----++pub(crate) async fn start(shared: &Shared, session: &Session) -> Result<()> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ if !shared.store.get_peer(&session.peer)?.is_some_and(|p| p.caps.contains(mic::STREAM)) {+ return Err(Error::Unsupported);+ }+ let env = Envelope::empty(types::MIC_START);+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}++pub(crate) async fn stop(session: &Session) -> Result<()> {+ session.send(Envelope::empty(types::MIC_STOP)).await+}++/// A phone opened a `mic/pcm` stream (its stream header already read).+pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut recv: RecvStream) {+ let refuse = |mut send: SendStream, mut recv: RecvStream| {+ let _ = send.reset(VarInt::from_u32(mic::STOPPED));+ let _ = recv.stop(VarInt::from_u32(mic::STOPPED));+ };+ let listens = shared.local_capabilities().iter().any(|c| c == mic::LISTEN);+ if !listens || !shared.toggle_on(&peer, TOGGLE) {+ return refuse(send, recv);+ }+ let first = match read_video_packet(&mut recv).await {+ Ok(Some(p)) if p.kind == PacketKind::Config => {+ MirrorAudioConfig::from_cbor(&p.data).ok().filter(MirrorAudioConfig::is_valid)+ }+ _ => None,+ };+ let Some(config) = first else {+ tracing::warn!("a phone sent a microphone format this PC can't play");+ return refuse(send, recv);+ };+ let Some(sink) = shared.platform.mic_sink(&peer) else {+ return refuse(send, recv);+ };+ let stopped = shared.new_mic_stop(&peer);+ shared.emit(NodeEvent::Mic { device: peer, on: true });+ sink.config(config);+ loop {+ let packet = tokio::select! {+ _ = stopped.notified() => break,+ packet = read_video_packet(&mut recv) => packet,+ };+ match packet {+ Ok(Some(p)) if p.kind == PacketKind::Config => match MirrorAudioConfig::from_cbor(&p.data) {+ Ok(config) if config.is_valid() => sink.config(config),+ _ => {+ tracing::warn!("a phone sent a microphone format this PC can't play");+ break;+ }+ },+ Ok(Some(p)) => sink.audio(p.time_us, p.data),+ Ok(None) => break,+ Err(e) => {+ tracing::debug!(error = %e, "microphone stream ended");+ break;+ }+ }+ }+ let _ = recv.stop(VarInt::from_u32(mic::STOPPED));+ let _ = send.finish();+ sink.ended();+ if shared.clear_mic_stop(&peer, &stopped) {+ shared.emit(NodeEvent::Mic { device: peer, on: false });+ }+}++// ---- The phone ----++pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ let peer = session.peer;+ let platform = shared.platform.clone();+ match env.t.as_str() {+ types::MIC_START => {+ let reply = if !shared.toggle_on(&peer, TOGGLE) {+ Envelope::error(ErrorCode::Denied, "the microphone is off for this device")+ } else if !shared.local_capabilities().iter().any(|c| c == mic::STREAM) {+ Envelope::error(ErrorCode::Unsupported, "this device doesn't stream its microphone")+ } else {+ match tokio::task::spawn_blocking(move || platform.mic_requested(&peer))+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ {+ Ok(()) => Envelope::empty(types::OK),+ Err(reason) => {+ tracing::warn!(reason, "can't ask to start the microphone");+ Envelope::error(ErrorCode::Internal, "the phone couldn't ask")+ }+ }+ };+ session.send(reply.reply_to(env.id)).await?;+ }+ types::MIC_STOP => {+ // The PC's side: stop listening; the phone's: stop recording.+ shared.stop_mic(&peer);+ tokio::task::spawn_blocking(move || platform.mic_stop_requested(&peer));+ if env.id.is_some() {+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;+ }+ }+ _ => return Ok(false),+ }+ Ok(true)+}++/// Opens this phone's microphone stream to a connected PC: write a config+/// packet first, then the sound.+pub(crate) async fn open(shared: &Arc<Shared>, session: &Session) -> Result<MirrorStream> {+ if !shared.toggle_on(&session.peer, TOGGLE) {+ return Err(Error::Denied);+ }+ let (mut send, recv) = session.conn.open_bi().await.map_err(crate::error::net)?;+ let header = StreamHeader { svc: mic::SERVICE.into(), op: mic::OP_PCM.into(), v: mic::VERSION };+ write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;+ let on_end = shared+ .record_timeline(crate::timeline::NewTimelineEntry {+ kind: crate::TimelineKind::Session,+ device_id: session.peer,+ device_name: shared.peer_name(&session.peer),+ incoming: false,+ timestamp: crate::now_unix(),+ title: "Phone microphone".into(),+ detail: String::new(),+ target: "mic".into(),+ size_bytes: 0,+ duration_secs: 0,+ ref_id: None,+ })+ .map(|id| (shared.clone(), id, std::time::Instant::now()));+ Ok(MirrorStream::spawn_stream(send, recv, true, on_end))+}++impl Shared {+ fn new_mic_stop(&self, peer: &DeviceId) -> Arc<tokio::sync::Notify> {+ let signal = Arc::new(tokio::sync::Notify::new());+ if let Some(prev) =+ self.mic_stops.lock().unwrap_or_else(|e| e.into_inner()).insert(*peer, signal.clone())+ {+ prev.notify_one();+ }+ signal+ }++ fn clear_mic_stop(&self, peer: &DeviceId, signal: &Arc<tokio::sync::Notify>) -> bool {+ let mut stops = self.mic_stops.lock().unwrap_or_else(|e| e.into_inner());+ if stops.get(peer).is_some_and(|cur| Arc::ptr_eq(cur, signal)) {+ stops.remove(peer);+ true+ } else {+ false+ }+ }++ pub(crate) fn stop_mic(&self, peer: &DeviceId) {+ if let Some(signal) = self.mic_stops.lock().unwrap_or_else(|e| e.into_inner()).remove(peer) {+ signal.notify_one();+ self.emit(NodeEvent::Mic { device: *peer, on: false });+ }+ }+}diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 9862c7d..4ee51cd 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -154,6 +154,8 @@ pub(crate) struct Shared {pub(crate) watch_offers: Mutex<HashMap<DeviceId, (String, std::time::Instant)>>,/// Stop signals for phone webcam streams arriving here, by phone.pub(crate) webcam_stops: Mutex<HashMap<DeviceId, Arc<tokio::sync::Notify>>>,+ /// Stop signals for phone microphone streams arriving here, by phone.+ pub(crate) mic_stops: Mutex<HashMap<DeviceId, Arc<tokio::sync::Notify>>>,/// Per-peer rate limiters and prompt state for remote input.pub(crate) remote: Mutex<crate::remote::RemoteState>,/// Per-peer prompt state and open folders for the storage service.@@ -1411,6 +1413,7 @@ impl Node {pc_mirror_sessions: Mutex::new(std::collections::HashSet::new()),watch_offers: Mutex::new(HashMap::new()),webcam_stops: Mutex::new(HashMap::new()),+ mic_stops: Mutex::new(HashMap::new()),remote: Mutex::new(Default::default()),storage: Mutex::new(Default::default()),clipboard_history,@@ -1801,6 +1804,16 @@ impl Node {});}}+ if toggle == crate::mic::TOGGLE && !enabled {+ self.shared.stop_mic(&peer);+ let platform = self.shared.platform.clone();+ drop(self.shared.runtime.spawn_blocking(move || platform.mic_stop_requested(&peer)));+ if let Some(session) = self.shared.session(&peer) {+ self.shared.runtime.spawn(async move {+ let _ = crate::mic::stop(&session).await;+ });+ }+ }if toggle == crate::webcam::TOGGLE && !enabled {self.shared.stop_webcam(&peer);let platform = self.shared.platform.clone();@@ -2500,6 +2513,29 @@ impl Node {crate::webcam::open(&self.shared, &session).await}+ // ---- Phone as microphone (docs/protocol/mic.md) ----++ /// Asks a paired phone to stream its microphone; the phone asks its+ /// user. Sound then arrives through [`Platform::mic_sink`](crate::Platform::mic_sink).+ pub async fn mic_start(&self, peer: DeviceId) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::mic::start(&self.shared, &session).await+ }++ /// Stops a microphone stream with `peer` (either direction) and tells `peer`.+ pub async fn mic_stop(&self, peer: DeviceId) {+ self.shared.stop_mic(&peer);+ if let Ok(session) = self.connected(&peer) {+ let _ = crate::mic::stop(&session).await;+ }+ }++ /// Opens this phone's microphone stream to a paired PC.+ pub async fn mic_open(&self, peer: DeviceId) -> Result<crate::MirrorStream> {+ let session = self.connected(&peer)?;+ crate::mic::open(&self.shared, &session).await+ }+// ---- Continuity Camera (docs/protocol/v0.md §Continuity Camera) ----/// Asks a paired phone to capture a photo or scan a document and stream the result back.diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 1f9cc27..a9e8a7a 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -491,6 +491,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}t if t.starts_with("webcam.") && crate::webcam::handle(shared, session, &env).await? => {}+ t if t.starts_with("mic.") && crate::mic::handle(shared, session, &env).await? => {}t if t.starts_with("camera.capture.")&& crate::continuity_camera::handle(shared, session, &env).await? => {}t if t.starts_with("remote.") && crate::remote::handle(shared, session, &env).await? => {}diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rsindex 9f727c3..6fc3db2 100644--- a/core/nectarlink-core/src/transfer.rs+++ b/core/nectarlink-core/src/transfer.rs@@ -1462,6 +1462,13 @@ pub(crate) async fn accept_stream(Some(h) if h.svc == mirror::SERVICE && h.op == mirror::OP_AUDIO && h.v == mirror::VERSION => {crate::mirror::receive_audio(shared, session.peer, send, recv).await;}+ Some(h)+ if h.svc == nectarlink_protocol::messages::mic::SERVICE+ && h.op == nectarlink_protocol::messages::mic::OP_PCM+ && h.v == nectarlink_protocol::messages::mic::VERSION =>+ {+ crate::mic::receive(shared, session.peer, send, recv).await;+ }Some(h)if h.svc == nectarlink_protocol::messages::webcam::SERVICE&& h.op == nectarlink_protocol::messages::webcam::OP_VIDEOdiff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 4f57f60..744fc64 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -41,6 +41,8 @@ struct RecordingPlatform {mirror_asks: Mutex<Vec<String>>,mirror_reject: std::sync::atomic::AtomicBool,watch_offers: Mutex<Vec<String>>,+ mic_asks: Mutex<Vec<String>>,+ mic: Arc<TestMicSink>,/// What a PC got of a phone's screen.screen: Arc<ScreenSink>,webcam_asks: Mutex<Vec<String>>,@@ -171,6 +173,16 @@ impl Platform for RecordingPlatform {) {self.mirror_asks.lock().unwrap().push(format!("{input:?} on {session}"));}+ fn mic_sink(&self, _peer: &nectarlink_core::DeviceId) -> Option<Arc<dyn nectarlink_core::MicSink>> {+ Some(self.mic.clone())+ }+ fn mic_requested(&self, _peer: &nectarlink_core::DeviceId) -> Result<(), String> {+ self.mic_asks.lock().unwrap().push("start".into());+ Ok(())+ }+ fn mic_stop_requested(&self, _peer: &nectarlink_core::DeviceId) {+ self.mic_asks.lock().unwrap().push("stop".into());+ }fn webcam_sink(&self, _peer: &nectarlink_core::DeviceId) -> Option<Arc<dyn nectarlink_core::WebcamSink>> {self.webcam_asks.lock().unwrap().push("sink".into());Some(self.webcam.clone())@@ -596,6 +608,23 @@ impl nectarlink_core::WebcamSink for TestWebcamSink {}}+#[derive(Debug, Default)]+struct TestMicSink {+ got: Mutex<Vec<String>>,+}++impl nectarlink_core::MicSink for TestMicSink {+ fn config(&self, config: nectarlink_core::MirrorAudioConfig) {+ self.got.lock().unwrap().push(format!("config {} Hz x{}", config.rate, config.channels));+ }+ fn audio(&self, _time_us: u64, data: Vec<u8>) {+ self.got.lock().unwrap().push(format!("audio {}", data.len()));+ }+ fn ended(&self) {+ self.got.lock().unwrap().push("ended".into());+ }+}+struct TestDevice {node: Node,events: Receiver<NodeEvent>,@@ -5659,3 +5688,74 @@ async fn play_on_phone_needs_a_phone_that_can_watch() {pc.node.shutdown().await;phone.node.shutdown().await;}++#[tokio::test(flavor = "multi_thread")]+async fn a_phone_streams_its_microphone_when_its_user_agrees() {+ use nectarlink_core::{MIC_LISTEN, MIC_STREAM, MirrorAudioConfig, MirrorSend, PacketKind};++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[MIC_LISTEN]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[MIC_STREAM]).await;+ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // The PC asks; the phone asks its user (the platform), nothing streams yet.+ with_timeout("mic_start", pc.node.mic_start(phone_id)).await.unwrap();+ assert_eq!(*phone.platform.mic_asks.lock().unwrap(), ["start"]);++ // The user agreed: the phone streams 48 kHz mono.+ let stream = Arc::new(with_timeout("mic_open", phone.node.mic_open(pc_id)).await.unwrap());+ let config = MirrorAudioConfig { codec: nectarlink_core::MIRROR_PCM.into(), rate: 48_000, channels: 1 };+ let sender = stream.clone();+ let sent = tokio::task::spawn_blocking(move || {+ [+ sender.send(PacketKind::Config, 0, config.to_cbor()),+ sender.send(PacketKind::Frame, 10_000, vec![0u8; 960]),+ sender.send(PacketKind::Frame, 20_000, vec![1u8; 960]),+ ]+ })+ .await+ .unwrap();+ assert!(sent.iter().all(|s| *s == MirrorSend::Queued), "{sent:?}");+ wait_for(&mut pc, "mic on", |e| matches!(e, NodeEvent::Mic { on: true, .. }).then_some(())).await;+ let deadline = std::time::Instant::now() + WAIT;+ while pc.platform.mic.got.lock().unwrap().len() < 3 {+ assert!(std::time::Instant::now() < deadline, "{:?}", pc.platform.mic.got.lock().unwrap());+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ assert_eq!(pc.platform.mic.got.lock().unwrap()[..3], ["config 48000 Hz x1", "audio 960", "audio 960"]);++ // The PC stops listening: the phone is told to stop recording.+ pc.node.mic_stop(phone_id).await;+ wait_for(&mut pc, "mic off", |e| matches!(e, NodeEvent::Mic { on: false, .. }).then_some(())).await;+ let deadline = std::time::Instant::now() + WAIT;+ while !phone.platform.mic_asks.lock().unwrap().contains(&"stop".to_owned()) {+ assert!(std::time::Instant::now() < deadline, "the phone wasn't told to stop");+ tokio::time::sleep(Duration::from_millis(20)).await;+ }++ // With the microphone off for the PC on the phone, the PC's ask is refused.+ phone.node.set_device_toggle(pc_id, "mic", false).unwrap();+ let denied = pc.node.mic_start(phone_id).await;+ assert!(matches!(denied, Err(Error::Denied)), "{denied:?}");+ assert_eq!(phone.platform.mic_asks.lock().unwrap().iter().filter(|a| *a == "start").count(), 1);++ pc.node.shutdown().await;+ phone.node.shutdown().await;+}++#[tokio::test(flavor = "multi_thread")]+async fn a_pc_without_mic_listen_refuses_a_phones_microphone() {+ use nectarlink_core::{MIC_STREAM, MirrorAudioConfig, PacketKind};++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[MIC_STREAM]).await;+ pair_qr(&mut pc, &mut phone).await;+ let stream = Arc::new(with_timeout("mic_open", phone.node.mic_open(pc.node.device_id())).await.unwrap());+ let config = MirrorAudioConfig { codec: nectarlink_core::MIRROR_PCM.into(), rate: 48_000, channels: 1 };+ let sender = stream.clone();+ tokio::task::spawn_blocking(move || sender.send(PacketKind::Config, 0, config.to_cbor())).await.unwrap();+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(pc.platform.mic.got.lock().unwrap().is_empty());+ pc.node.shutdown().await;+ phone.node.shutdown().await;+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 3c0b849..bc74ace 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -2406,7 +2406,9 @@ impl Event {NodeEvent::CameraCaptureRequested { .. }| NodeEvent::CameraCaptureReceived { .. }| NodeEvent::CameraCaptureCancelled { .. }- | NodeEvent::PcMirrorRequested { .. } => return None,+ | NodeEvent::PcMirrorRequested { .. }+ // A phone's microphone arrives on PCs only.+ | NodeEvent::Mic { .. } => return None,NodeEvent::RemoteInputRequested { device } => {Event::RemoteInputRequested { id: device.to_string() }}@@ -2644,6 +2646,11 @@ pub trait Platform: Send + Sync {fn webcam_requested(&self, pc_id: String, options: WebcamOptions) -> bool;/// The PC stopped watching the webcam stream.fn webcam_stop_requested(&self, pc_id: String);+ /// A PC asked for this phone's microphone (`docs/protocol/mic.md`): ask+ /// the user, then stream with `mic_open`. False if it couldn't ask.+ fn mic_requested(&self, pc_id: String) -> bool;+ /// The PC stopped listening to this phone's microphone: stop recording.+ fn mic_stop_requested(&self, pc_id: String);/// The PC needs a fresh H.264 keyframe on the webcam stream.fn webcam_keyframe_requested(&self, pc_id: String);/// A PC asked this phone to capture a photo or scan a document (`mode` is@@ -2856,6 +2863,12 @@ impl core::Platform for PlatformAdapter {fn webcam_stop_requested(&self, peer: &DeviceId) {self.0.webcam_stop_requested(peer.to_string());}+ fn mic_requested(&self, peer: &DeviceId) -> Result<(), String> {+ if self.0.mic_requested(peer.to_string()) { Ok(()) } else { Err("not asked".into()) }+ }+ fn mic_stop_requested(&self, peer: &DeviceId) {+ self.0.mic_stop_requested(peer.to_string());+ }fn webcam_keyframe_requested(&self, peer: &DeviceId) {self.0.webcam_keyframe_requested(peer.to_string());}@@ -3949,6 +3962,25 @@ impl NectarlinkNode {self.run(async move { Ok(Arc::new(MirrorStream(node.webcam_open(id).await?))) }).await}+ /// Opens this phone's microphone stream to a paired PC (`docs/protocol/mic.md`):+ /// a config packet (`mirror_audio_config`) first, then 16-bit PCM.+ pub async fn mic_open(&self, pc_id: String) -> Result<Arc<MirrorStream>> {+ let id = parse_id(&pc_id)?;+ let node = self.node.clone();+ self.run(async move { Ok(Arc::new(MirrorStream(node.mic_open(id).await?))) }).await+ }++ /// Stops this phone's microphone stream to a paired PC and tells the PC.+ pub async fn mic_stop(&self, pc_id: String) -> Result<()> {+ let id = parse_id(&pc_id)?;+ let node = self.node.clone();+ self.run(async move {+ node.mic_stop(id).await;+ Ok(())+ })+ .await+ }+/// Stops this phone's webcam stream to a paired PC and tells the PC.pub async fn webcam_stop(&self, pc_id: String) -> Result<()> {let id = parse_id(&pc_id)?;diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex c2e9218..091f101 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -91,6 +91,8 @@ pub mod types {pub const STORAGE_RENAME: &str = "storage.rename";pub const STORAGE_DELETE: &str = "storage.delete";pub const STORAGE_CHANGED: &str = "storage.changed";+ pub const MIC_START: &str = "mic.start";+ pub const MIC_STOP: &str = "mic.stop";pub const WEBCAM_START: &str = "webcam.start";pub const WEBCAM_STOP: &str = "webcam.stop";pub const WEBCAM_KEYFRAME: &str = "webcam.keyframe";@@ -1567,6 +1569,19 @@ impl MirrorAudioConfig {// ---- Phone as webcam (docs/protocol/webcam.md) ----+/// Phone as microphone (`docs/protocol/mic.md`).+pub mod mic {+ /// Offered by phones that stream their microphone.+ pub const STREAM: &str = "mic.stream";+ /// Offered by PCs that take a phone's microphone.+ pub const LISTEN: &str = "mic.listen";+ pub const SERVICE: &str = "mic";+ pub const OP_PCM: &str = "pcm";+ pub const VERSION: u32 = 1;+ /// Stream reset code: the microphone stopped.+ pub const STOPPED: u32 = 13;+}+pub mod webcam {/// Offered by phones that stream their camera as a webcam.pub const STREAM: &str = "camera.stream";diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex f8661a0..5234a40 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -71,6 +71,8 @@ impl Changes {pub const DEVICE_METRICS: Changes = Changes(1 << 27);/// Offline send queue items changed.pub const QUEUE: Changes = Changes(1 << 28);+ /// Phone as microphone state or output (kept by crate::phone_mic).+ pub const MIC: Changes = Changes(1 << 29);pub fn is_empty(self) -> bool {self.0 == 0@@ -541,6 +543,7 @@ impl AppState {| NodeEvent::StorageRequested { .. }| NodeEvent::StorageChanged { .. }| NodeEvent::Webcam { .. }+ | NodeEvent::Mic { .. }| NodeEvent::PcAudioFrame { .. }| NodeEvent::CameraCaptureRequested { .. }| NodeEvent::CameraCaptureCancelled { .. } => Changes::NONE,diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.mdindex bd8b829..ba6e489 100644--- a/docs/architecture/capabilities.md+++ b/docs/architecture/capabilities.md@@ -137,6 +137,8 @@ Available. Everything else in the matrix is identical on both devices.| `mirroring.control` | phone `mirror.capture`, `mirror.input` (Assist) | None | Locked → Assist · ~1 min || `mirroring.app_windows` | phone `mirror.virtual_display` (Elevated), Elevated, Android ≥ 11 | None | Locked → Elevated || `camera.webcam` | phone `camera.stream` (camera permission), desktop `camera.virtual`, desktop `addon.vcam`, Windows build ≥ 22000, toggle `webcam` | None | Locked → install virtual camera · ~1 min |+| `media.play_on_phone` | desktop `media.stream`, phone `media.watch`, toggle `media` | None | Available |+| `media.phone_mic` | phone `mic.stream`, desktop `mic.listen`, toggle `mic` | None | Available |The full registry is `FEATURES` in `core/nectarlink-core/src/features.rs`.diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex e329e81..d26d442 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -70,6 +70,8 @@ capability is missing.| `storage.read` | Lists folders and reads files in shared storage or picked SAF folders ([storage](storage.md)) | All files access or picked SAF folder || `storage.write` | Creates folders, writes/uploads files, renames and deletes entries in shared storage or picked SAF folders ([storage](storage.md)) | All files access or picked SAF folder || `camera.stream` | Streams a camera for webcam use ([webcam](webcam.md)) | camera permission |+| `mic.stream` | Streams its microphone when its user agrees ([mic](mic.md)) | app update (asks for the microphone permission when first used) |+| `media.watch` | Shows a PC's playback streamed to it (Play on phone, [media](media.md) §4) | app update || `camera.capture` | Captures a photo or document scan on request ([Continuity Camera](v0.md#12-continuity-camera-cameracapture)) | camera permission |## Desktop@@ -92,6 +94,8 @@ capability is missing.| `deck.actions` | Shares its Deck layout and live tile state and runs Deck actions ([deck](deck.md)) | app update || `pc.audio` | Reports active audio output devices in `deck.state` and accepts `pc.audio.set` volume/mute changes ([deck](deck.md)) | app update || `camera.virtual` | Receives and decodes a phone's camera stream ([webcam](webcam.md)) | app update |+| `mic.listen` | Takes a phone's microphone and plays it into an output ([mic](mic.md)) | app update |+| `media.stream` | Streams a player's picture and sound to a phone that watches (Play on phone, [media](media.md) §4) | app update || `addon.vcam` | The virtual camera add-on is installed ([webcam](webcam.md)) | installing the add-on || `camera.continuity` | Requests and receives Continuity Camera photos and document scans ([Continuity Camera](v0.md#12-continuity-camera-cameracapture)) | app update |diff --git a/docs/protocol/mic.md b/docs/protocol/mic.mdnew file mode 100644index 0000000..3e7c037--- /dev/null+++ b/docs/protocol/mic.md@@ -0,0 +1,63 @@+# Phone as microphone (v1)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++Uses a paired phone's microphone on a PC. Control messages travel on the+session's control stream ([protocol v0](v0.md) §4); the sound travels on a+dedicated bidirectional QUIC stream (`{ svc: "mic", op: "pcm", v: 1 }`).++This is the streaming half of GitHub #7. The PC plays the sound into an+output device; played into a virtual audio cable, the cable's other end is+a microphone every app can pick. A virtual microphone of NectarLink's own+needs an audio driver and is a separate step.++## 1. Capabilities and toggle++| Capability | Offered by | Meaning |+|---|---|---|+| `mic.stream` | Phone | Streams its microphone when its user agrees (it asks for the microphone permission then, if needed) |+| `mic.listen` | PC | Takes a phone's microphone stream |++Both devices have a `mic` per-device toggle (on by default). When it's off+for a peer, `mic.start` is refused with `DENIED`, incoming `mic` streams are+reset with code `13`, and a running stream with that peer stops.++A phone **never** turns its microphone on silently: it streams only after+its user taps Start on the PC's request, and shows an ongoing notification+with a **Stop** button the whole time. Android only lets the microphone+start from the foreground, which the tap provides.++## 2. Starting and stopping++```+t = "mic.start" id = n // PC to phone+t = "ok" re = n+t = "mic.stop" [id = n] // either way+t = "ok" re = n // when it had an id+```++**`mic.start`** asks the phone to ask its user. The phone answers `ok` once+it has asked (not when the user agrees): the stream follows if the user+taps Start. Errors: `DENIED` when the microphone is off for the PC,+`UNSUPPORTED` without `mic.stream`.++**`mic.stop`** ends it: from the PC, the phone stops recording; from the+phone (its user tapped Stop), the PC stops listening. Ending the stream+itself (either side) means the same.++## 3. The sound stream++The phone opens a bidirectional stream with the header+`{ svc: "mic", op: "pcm", v: 1 }`, then writes the framed packets of the+[webcam stream](webcam.md) §3:++| `kind` | Name | Payload |+|---|---|---|+| `0` | `Config` | CBOR `{ codec: "pcm_s16le", rate: uint, channels: uint }` (as mirroring's sound, [mirror.md](mirror.md) §5): first, and again if the format changes |+| `1` | `Frame` | 16-bit little-endian PCM in that format, interleaved |++Phones send 48 kHz mono, 10 ms a packet, recorded for voice calls (echo+cancellation and noise suppression where the phone has them). The PC keeps+a short jitter buffer (about 40 ms) and drops the oldest sound rather than+fall behind. The PC writes nothing; it stops reading to end the stream.