Skip to content

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

Phone as a webcam

Bee45b56812e0b9
diff --git a/Cargo.lock b/Cargo.lock
index b5c692f..707c3c4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2351,6 +2351,7 @@ dependencies = [
"hostname",
"material-colors",
"nectarlink-core",
+ "nectarlink-vcam",
"qrcode",
"serde",
"serde_json",
@@ -2390,6 +2391,14 @@ dependencies = [
"url",
]
+[[package]]
+name = "nectarlink-vcam"
+version = "0.0.1"
+dependencies = [
+ "windows",
+ "windows-core",
+]
+
[[package]]
name = "netdev"
version = "0.45.1"
diff --git a/Cargo.toml b/Cargo.toml
index 39b58a3..94707bf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,6 +6,7 @@ members = [
"core/nectarlink-cli",
"core/nectarlink-ffi",
"desktop/app",
+ "desktop/vcam",
"tools/xtask",
"spikes/s1-qt-rust",
]
@@ -25,6 +26,7 @@ name = "Pollen"
[workspace.dependencies]
nectarlink-protocol = { path = "core/nectarlink-protocol", version = "0.0.1" }
nectarlink-core = { path = "core/nectarlink-core", version = "0.0.1" }
+nectarlink-vcam = { path = "desktop/vcam", version = "0.0.1" }
anyhow = "1"
ciborium = "0.2"
diff --git a/README.md b/README.md
index c65ea29..cc7d819 100644
--- a/README.md
+++ b/README.md
@@ -172,6 +172,14 @@ tests; there are no releases yet.
file beside it when you add markers and a notification to open the recording
or its folder. If the PC is offline, the recording waits on the phone and
goes out as soon as it reconnects.
+- **Phone as a webcam**: use the phone's camera in video calls on the PC (Zoom,
+ Teams, Meet, OBS and the Windows Camera app) as **Nectarlink Webcam**. Start
+ it from the phone or ask from the PC (the phone always confirms before the
+ camera opens), switch between back and front cameras, toggle the flashlight,
+ zoom (`1×`/`2×` or continuous slider), choose 720p or 1080p at 30 fps, and
+ horizontally mirror the image on the PC. Includes a live preview in Settings
+ even before the Windows 11 virtual camera add-on (`MFCreateVirtualCamera`
+ media source) is set up.
- **Phone controls on the PC**: see and change the phone's Do Not Disturb,
ringer mode (Ring, Vibrate, Silent), flashlight, media volume, screen
brightness, Wi‑Fi (with a confirmation before turning it off) and Bluetooth
@@ -262,7 +270,9 @@ core/
nectarlink-core/ Identity, trust store, pairing, sessions, features (MPL-2.0)
nectarlink-ffi/ UniFFI bindings used by the Android app (MPL-2.0)
nectarlink-cli/ Command-line client for development and testing (GPL)
-desktop/app/ Windows app: Rust host, cxx-qt bridge, QML UI (GPL)
+desktop/
+ app/ Windows app: Rust host, cxx-qt bridge, QML UI (GPL)
+ vcam/ Windows 11 virtual camera Media Foundation DLL (GPL)
android/ Android app: Kotlin and Jetpack Compose (GPL)
assets/fonts/ Fonts both apps ship with (OFL-1.1)
tools/xtask/ Code generation (theme tokens) and checks
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index ee411ee..ac0715e 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -18,6 +18,8 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<!-- Voice recorder to PC while the screen is off or the app is in the background. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
+ <!-- Streaming the camera to a PC as a webcam while the app is in the background. -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<!-- Voice recordings and voice typing for a PC (asked in context) and the
phone's sound while mirrored (playback capture, with the screen share's consent). -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -254,6 +256,11 @@
android:exported="false"
android:foregroundServiceType="microphone" />
+ <service
+ android:name=".webcam.WebcamService"
+ android:exported="false"
+ android:foregroundServiceType="camera" />
+
<service
android:name=".service.ConnectionService"
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.kt
index 18d4205..7b77838 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
@@ -32,6 +32,8 @@ import app.nectarlink.android.service.ConnectionService
import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.android.storage.PhoneStorage
import app.nectarlink.android.toggles.PhoneToggles
+import app.nectarlink.android.webcam.WebcamRequests
+import app.nectarlink.android.webcam.WebcamService
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
import app.nectarlink.core.FileToSend
@@ -88,6 +90,17 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
onMirror = { pc, request ->
MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())
},
+ onWebcam = { pc, request ->
+ val session = WebcamService.session.value
+ if (session.active && session.pcId == pc && WebcamService.hasPermission(this.context)) {
+ WebcamService.start(this.context, pc, request.height, request.fps, request.camera)
+ true
+ } else {
+ _state.update { it.copy(webcamRequest = request) }
+ WebcamRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())
+ true
+ }
+ },
appWindows = AppWindows(this.context, scope, open = { pc -> mirrorOpen(pc) }, nameOf = { pc -> _state.value.nameOf(pc).orEmpty() }),
)
private val storage = PhoneStorage(this.context) { path ->
@@ -495,6 +508,30 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
return node.mirrorOpenAudio(pcId)
}
+ /** Opens this phone's camera stream to a PC (`webcam`), or emits a message on failure. */
+ suspend fun webcamOpenOrMessage(pcId: String): MirrorStream? {
+ startJob?.join()
+ val node = node ?: return null
+ return try {
+ node.webcamOpen(pcId)
+ } catch (e: NectarlinkException) {
+ val name = _state.value.nameOf(pcId).orEmpty()
+ val msg = when (e) {
+ is NectarlinkException.Denied -> context.getString(R.string.webcam_denied_text, name)
+ else -> describe(e)
+ }
+ _messages.tryEmit(msg)
+ null
+ }
+ }
+
+ fun clearWebcamRequest(pcId: String? = null) {
+ if (pcId != null) WebcamRequests.dismiss(context, pcId)
+ _state.update { s ->
+ if (pcId == null || s.webcamRequest?.pcId == pcId) s.copy(webcamRequest = null) else s
+ }
+ }
+
/**
* Sends picked or shared files to a PC; problems arrive as messages.
* The files are opened right away: Android's permission to read a
@@ -603,6 +640,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +
(if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) +
PhoneStorage.capabilities(context) +
+ (if (WebcamService.hasPermission(context)) listOf("webcam.h264") else emptyList()) +
(if (InputService.running || Elevated.running) listOf("mirror.input") else emptyList()) +
// Apps in windows of their own run on displays the Elevated helper makes.
(if (Elevated.running && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) listOf("mirror.virtual_display") else emptyList()) +
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index d16c667..dd0669c 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package app.nectarlink.android.core
+import app.nectarlink.android.webcam.WebcamRequest
import app.nectarlink.core.DiscoveredDevice
import app.nectarlink.core.Event
import app.nectarlink.core.Feature
@@ -105,6 +106,8 @@ data class CoreState(
val storageSafFolders: List<String> = emptyList(),
/** ID of a paired PC that asked to browse this phone's storage while `storage` is off. */
val storageRequestedFrom: String? = null,
+ /** Pending request from a paired PC asking to use this phone's camera as a webcam. */
+ val webcamRequest: WebcamRequest? = null,
/** File transfers, newest first (running ones and the latest finished). */
val transfers: List<Transfer> = emptyList(),
) {
@@ -145,6 +148,7 @@ data class CoreState(
devices = devices.filterNot { it.id == event.id },
ringingFrom = if (ringingFrom == nameOf(event.id)) null else ringingFrom,
storageRequestedFrom = if (storageRequestedFrom == event.id) null else storageRequestedFrom,
+ webcamRequest = if (webcamRequest?.pcId == event.id) null else webcamRequest,
)
is Event.LinkChanged -> update(event.id) {
it.copy(
@@ -183,7 +187,7 @@ data class CoreState(
// Shown in Android's media controls (see media/PcMedia).
is Event.MediaChanged -> this
is Event.StorageRequested -> copy(storageRequestedFrom = event.id)
- // PCs only: phones announce their own photos, calls, contacts, texts, toggles, storage and screen.
+ // PCs only: phones announce their own photos, calls, contacts, texts, toggles, storage, screen and webcam.
is Event.PhotoAdded,
is Event.PhotosChanged,
is Event.CallChanged,
@@ -194,6 +198,7 @@ data class CoreState(
is Event.Mirroring,
is Event.RemoteInputRequested,
is Event.StorageChanged,
+ is Event.Webcam,
-> this
}
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.kt
index b52a857..c9ccbb4 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
@@ -23,6 +23,9 @@ import app.nectarlink.android.mirror.MirrorService
import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.android.storage.PhoneStorage
import app.nectarlink.android.toggles.PhoneToggles
+import app.nectarlink.android.webcam.WebcamRequest
+import app.nectarlink.android.webcam.WebcamRequests
+import app.nectarlink.android.webcam.WebcamService
import app.nectarlink.core.CallCommand
import app.nectarlink.core.CallLogEntry
import app.nectarlink.core.Contact
@@ -43,6 +46,7 @@ import app.nectarlink.core.Platform
import app.nectarlink.core.StorageEntry
import app.nectarlink.core.StorageReadFile
import app.nectarlink.core.StorageWriteDone
+import app.nectarlink.core.WebcamOptions
/**
* What the core asks of the phone: ring it, and act on its notifications
@@ -66,6 +70,8 @@ internal class PhonePlatform(
private val storage: () -> PhoneStorage,
/** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */
private val onMirror: (String, MirrorRequest) -> Boolean,
+ /** Asks the user to stream the camera as a webcam to a PC: (PC's ID, request) → asked. */
+ private val onWebcam: (String, WebcamRequest) -> Boolean,
/** Apps in windows of their own on PCs (Elevated). */
private val appWindows: AppWindows,
) : Platform {
@@ -131,6 +137,26 @@ internal class PhonePlatform(
if (!Elevated.handle(input)) InputService.handle(input)
}
+ override fun webcamRequested(pcId: String, options: WebcamOptions): Boolean {
+ val request = WebcamRequest(
+ pcId = pcId,
+ width = options.width.toInt(),
+ height = options.height.toInt(),
+ fps = options.fps.toInt(),
+ bitrate = options.bitrate.toInt(),
+ camera = options.camera,
+ )
+ return onWebcam(pcId, request)
+ }
+
+ override fun webcamStopRequested(pcId: String) {
+ WebcamRequests.dismiss(context, pcId)
+ WebcamService.stopForPc(context, pcId)
+ }
+
+ override fun webcamKeyframeRequested(pcId: String) =
+ WebcamService.keyframe(pcId)
+
override fun phoneApps(): List<PhoneApp> = AppWindows.list(context)
override fun smsThreads(limit: UInt): List<SmsThread> = sms().threads(limit.toInt())
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index ab06244..0c4e703 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -39,6 +39,8 @@ class ConnectionService : LifecycleService() {
app.nectarlink.android.files.TransferNotifications.createChannels(this)
app.nectarlink.android.media.PcMedia.createChannel(this)
app.nectarlink.android.links.LinkNotifications.createChannel(this)
+ app.nectarlink.android.webcam.WebcamService.createChannel(this)
+ app.nectarlink.android.webcam.WebcamRequests.createChannel(this)
val core = (application as NectarlinkApplication).core
if (!startInForeground(core.state.value)) {
stopSelf()
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 5375962..0230847 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -56,6 +56,7 @@ import app.nectarlink.android.ui.remote.RemoteMode
import app.nectarlink.android.ui.remote.RemoteScreen
import app.nectarlink.android.ui.settings.SettingsScreen
import app.nectarlink.android.ui.theme.NectarlinkTheme
+import app.nectarlink.android.ui.webcam.WebcamScreen
class MainActivity : ComponentActivity() {
@Volatile
@@ -64,6 +65,10 @@ class MainActivity : ComponentActivity() {
private var requestedRemoteMode by mutableStateOf(RemoteMode.Touchpad)
private var requestedDeckPc by mutableStateOf<String?>(null)
private var requestedRecordPc by mutableStateOf<String?>(null)
+ private var requestedWebcamPc by mutableStateOf<String?>(null)
+ private var requestedWebcamAutoStart by mutableStateOf(false)
+ private var requestedWebcamHeight by mutableStateOf<Int?>(null)
+ private var requestedWebcamCamera by mutableStateOf<String?>(null)
private val permissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
@@ -89,6 +94,7 @@ class MainActivity : ComponentActivity() {
handleRemoteIntent(intent)
handleDeckIntent(intent)
handleRecordIntent(intent)
+ handleWebcamIntent(intent)
}
setContent {
@@ -117,6 +123,16 @@ class MainActivity : ComponentActivity() {
onDeckConsumed = { requestedDeckPc = null },
requestedRecordPc = requestedRecordPc,
onRecordConsumed = { requestedRecordPc = null },
+ requestedWebcamPc = requestedWebcamPc,
+ requestedWebcamAutoStart = requestedWebcamAutoStart,
+ requestedWebcamHeight = requestedWebcamHeight,
+ requestedWebcamCamera = requestedWebcamCamera,
+ onWebcamConsumed = {
+ requestedWebcamPc = null
+ requestedWebcamAutoStart = false
+ requestedWebcamHeight = null
+ requestedWebcamCamera = null
+ },
onActiveRemoteChanged = { activeRemotePcId = it },
)
}
@@ -138,6 +154,7 @@ class MainActivity : ComponentActivity() {
handleRemoteIntent(intent)
handleDeckIntent(intent)
handleRecordIntent(intent)
+ handleWebcamIntent(intent)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
@@ -193,6 +210,14 @@ class MainActivity : ComponentActivity() {
requestedRecordPc = pc
}
+ private fun handleWebcamIntent(intent: Intent?) {
+ val pc = intent?.getStringExtra("webcam_pc") ?: return
+ requestedWebcamAutoStart = intent.getBooleanExtra("webcam_auto_start", false)
+ requestedWebcamHeight = intent.getIntExtra("webcam_height", 0).takeIf { it > 0 }
+ requestedWebcamCamera = intent.getStringExtra("webcam_camera")
+ requestedWebcamPc = pc
+ }
+
/**
* A PC's pairing QR code opened from another app (e.g. the camera).
* Each link holds a one-time secret, so a link is used once: Android
@@ -222,6 +247,11 @@ private fun App(
onDeckConsumed: () -> Unit,
requestedRecordPc: String?,
onRecordConsumed: () -> Unit,
+ requestedWebcamPc: String?,
+ requestedWebcamAutoStart: Boolean,
+ requestedWebcamHeight: Int?,
+ requestedWebcamCamera: String?,
+ onWebcamConsumed: () -> Unit,
onActiveRemoteChanged: (String?) -> Unit,
) {
var tab by rememberSaveable { mutableStateOf(Tab.Home) }
@@ -230,6 +260,10 @@ private fun App(
var remoteInitialMode by rememberSaveable { mutableStateOf(RemoteMode.Touchpad) }
var deckPcId by rememberSaveable { mutableStateOf<String?>(null) }
var recordPcId by rememberSaveable { mutableStateOf<String?>(null) }
+ var webcamPcId by rememberSaveable { mutableStateOf<String?>(null) }
+ var webcamAutoStart by rememberSaveable { mutableStateOf(false) }
+ var webcamInitialHeight by rememberSaveable { mutableStateOf<Int?>(null) }
+ var webcamInitialCamera by rememberSaveable { mutableStateOf<String?>(null) }
val snackbar = remember { SnackbarHostState() }
LaunchedEffect(Unit) { core.messages.collect { snackbar.showSnackbar(it) } }
@@ -239,6 +273,7 @@ private fun App(
if (target != null) {
recordPcId = null
deckPcId = null
+ webcamPcId = null
remoteInitialMode = requestedRemoteMode
remotePcId = target
onRemoteConsumed()
@@ -251,6 +286,7 @@ private fun App(
if (target != null) {
remotePcId = null
recordPcId = null
+ webcamPcId = null
deckPcId = target
onDeckConsumed()
}
@@ -262,14 +298,31 @@ private fun App(
if (target != null) {
remotePcId = null
deckPcId = null
+ webcamPcId = null
recordPcId = target
onRecordConsumed()
}
}
+ LaunchedEffect(requestedWebcamPc, state.devices) {
+ val req = requestedWebcamPc ?: return@LaunchedEffect
+ val target = if (req == "first") state.devices.firstOrNull()?.id else state.device(req)?.id
+ if (target != null) {
+ remotePcId = null
+ deckPcId = null
+ recordPcId = null
+ webcamAutoStart = requestedWebcamAutoStart
+ webcamInitialHeight = requestedWebcamHeight
+ webcamInitialCamera = requestedWebcamCamera
+ webcamPcId = target
+ onWebcamConsumed()
+ }
+ }
+
val remoteDevice = remotePcId?.let { state.device(it) }
val deckDevice = deckPcId?.let { state.device(it) }
val recordDevice = recordPcId?.let { state.device(it) }
+ val webcamDevice = webcamPcId?.let { state.device(it) }
LaunchedEffect(remoteDevice?.id) {
onActiveRemoteChanged(remoteDevice?.id)
}
@@ -295,6 +348,27 @@ private fun App(
BackHandler(enabled = pairing && state.devices.isNotEmpty()) { core.resetPairing(); pairing = false }
PairingScreen(state, actions, cancellable = state.devices.isNotEmpty()) { pairing = false }
}
+ webcamDevice != null -> {
+ BackHandler { webcamPcId = null }
+ Scaffold(
+ snackbarHost = { SnackbarHost(snackbar) },
+ ) { padding ->
+ WebcamScreen(
+ device = webcamDevice,
+ autoStart = webcamAutoStart,
+ initialHeight = webcamInitialHeight,
+ initialCamera = webcamInitialCamera,
+ onAutoStartConsumed = {
+ webcamAutoStart = false
+ webcamInitialHeight = null
+ webcamInitialCamera = null
+ },
+ onAccessChanged = core::refreshNotificationAccess,
+ onBack = { webcamPcId = null },
+ modifier = Modifier.fillMaxSize().padding(padding),
+ )
+ }
+ }
recordDevice != null -> {
BackHandler { recordPcId = null }
Scaffold(
@@ -377,6 +451,10 @@ private fun App(
onRecord = { id ->
recordPcId = id
},
+ onWebcam = { id ->
+ webcamAutoStart = false
+ webcamPcId = id
+ },
updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,
onSendFiles = core::sendFiles,
onSendFolder = core::sendFolder,
@@ -384,6 +462,14 @@ private fun App(
onCancelTransfer = core::cancelTransfer,
onAllowStorage = { pcId -> core.setStorageEnabled(pcId, true) },
onDismissStorageRequest = core::dismissStorageRequest,
+ onAcceptWebcamRequest = { req ->
+ core.clearWebcamRequest(req.pcId)
+ webcamInitialHeight = req.height
+ webcamInitialCamera = req.camera
+ webcamAutoStart = true
+ webcamPcId = req.pcId
+ },
+ onDismissWebcamRequest = { core.clearWebcamRequest() },
modifier = modifier,
)
Tab.Settings -> SettingsScreen(
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index bca9d8c..ae85153 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -86,6 +86,7 @@ fun HomeScreen(
onRemote: (pcId: String) -> Unit,
onDeck: (pcId: String) -> Unit,
onRecord: (pcId: String) -> Unit,
+ onWebcam: (pcId: String) -> Unit = {},
updater: AppUpdater,
onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,
onSendFolder: (pcId: String, tree: Uri) -> Unit,
@@ -93,6 +94,8 @@ fun HomeScreen(
onCancelTransfer: (id: String) -> Unit,
onAllowStorage: (pcId: String) -> Unit = {},
onDismissStorageRequest: () -> Unit = {},
+ onAcceptWebcamRequest: (app.nectarlink.android.webcam.WebcamRequest) -> Unit = {},
+ onDismissWebcamRequest: () -> Unit = {},
modifier: Modifier = Modifier,
) {
LazyColumn(
@@ -131,6 +134,35 @@ fun HomeScreen(
state.ringingFrom?.let { from ->
item { RingingBanner(from, onStopRinging) }
}
+ state.webcamRequest?.let { req ->
+ item {
+ val pcName = state.nameOf(req.pcId) ?: stringResource(R.string.your_pc)
+ Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.secondaryContainer) {
+ Column(Modifier.fillMaxWidth().padding(20.dp)) {
+ Text(
+ stringResource(R.string.webcam_request_title, pcName),
+ style = MaterialTheme.typography.titleMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ stringResource(R.string.webcam_request_text),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(Modifier.height(12.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(onClick = { onAcceptWebcamRequest(req) }) {
+ Text(stringResource(R.string.webcam_start))
+ }
+ OutlinedButton(onClick = onDismissWebcamRequest) {
+ Text(stringResource(R.string.action_not_now))
+ }
+ }
+ }
+ }
+ }
+ }
state.storageRequestedFrom?.let { pcId ->
item {
val pcName = state.nameOf(pcId) ?: stringResource(R.string.your_pc)
@@ -239,7 +271,7 @@ fun HomeScreen(
}
}
items(state.devices, key = { it.id }) { device ->
- PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onWake, onRemote, onDeck, onRecord)
+ PcCard(device, onRing, onSendFiles, onSendFolder, onPower, onWake, onRemote, onDeck, onRecord, onWebcam)
}
if (state.transfers.isNotEmpty()) {
item { TransfersCard(state, onCancelTransfer) }
@@ -287,6 +319,7 @@ private fun PcCard(
onRemote: (String) -> Unit,
onDeck: (String) -> Unit,
onRecord: (String) -> Unit,
+ onWebcam: (String) -> Unit,
) {
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isNotEmpty()) onSendFiles(device.id, uris)
@@ -391,6 +424,12 @@ private fun PcCard(
) {
Text(stringResource(R.string.action_record_pc))
}
+ FilledTonalButton(
+ colors = tonal,
+ onClick = { onWebcam(device.id) },
+ ) {
+ Text(stringResource(R.string.action_webcam_pc))
+ }
FilledTonalButton(
enabled = device.online,
colors = tonal,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt
new file mode 100644
index 0000000..0071735
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/webcam/WebcamScreen.kt
@@ -0,0 +1,422 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.ui.webcam
+
+import android.Manifest
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.camera.view.PreviewView
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.FilterChip
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Slider
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import app.nectarlink.android.R
+import app.nectarlink.android.core.Device
+import app.nectarlink.android.webcam.WebcamService
+import java.util.Locale
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+fun WebcamScreen(
+ device: Device,
+ autoStart: Boolean = false,
+ initialHeight: Int? = null,
+ initialCamera: String? = null,
+ onAutoStartConsumed: () -> Unit = {},
+ onAccessChanged: () -> Unit = {},
+ onBack: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val context = LocalContext.current
+ val view = LocalView.current
+ val session by WebcamService.session.collectAsStateWithLifecycle()
+
+ // Keep the phone's screen on while the webcam viewfinder/controls are open.
+ DisposableEffect(view) {
+ val prev = view.keepScreenOn
+ view.keepScreenOn = true
+ onDispose { view.keepScreenOn = prev }
+ }
+
+ var hasCameraPermission by remember { mutableStateOf(WebcamService.hasPermission(context)) }
+ var startAfterGrant by remember { mutableStateOf(false) }
+ val askCamera = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ hasCameraPermission = WebcamService.hasPermission(context)
+ onAccessChanged()
+ if (granted && startAfterGrant) {
+ startAfterGrant = false
+ WebcamService.start(
+ context = context,
+ pcId = device.id,
+ height = initialHeight ?: session.height,
+ camera = initialCamera ?: session.camera,
+ )
+ } else {
+ startAfterGrant = false
+ }
+ }
+
+ LaunchedEffect(initialHeight, initialCamera) {
+ if (initialHeight != null) WebcamService.setResolutionHeight(initialHeight)
+ if (initialCamera != null) WebcamService.setCamera(initialCamera)
+ }
+
+ LaunchedEffect(autoStart, hasCameraPermission, device.online) {
+ if (autoStart) {
+ onAutoStartConsumed()
+ if (hasCameraPermission && device.online) {
+ WebcamService.start(
+ context = context,
+ pcId = device.id,
+ height = initialHeight ?: session.height,
+ camera = initialCamera ?: session.camera,
+ )
+ } else if (!hasCameraPermission) {
+ startAfterGrant = true
+ askCamera.launch(Manifest.permission.CAMERA)
+ }
+ }
+ }
+
+ val previewView = remember {
+ PreviewView(context).apply {
+ scaleType = PreviewView.ScaleType.FIT_CENTER
+ implementationMode = PreviewView.ImplementationMode.COMPATIBLE
+ }
+ }
+
+ DisposableEffect(previewView) {
+ WebcamService.attachUiPreview(previewView.surfaceProvider)
+ onDispose {
+ WebcamService.attachUiPreview(null)
+ }
+ }
+
+ val isStreamingHere = session.active && session.pcId == device.id
+
+ LazyColumn(
+ modifier = modifier.fillMaxSize(),
+ contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ // Header: Back, PC name, online dot
+ item {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ TextButton(
+ onClick = onBack,
+ contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
+ ) {
+ Text("← " + stringResource(R.string.action_back), style = MaterialTheme.typography.labelLarge)
+ }
+ Spacer(Modifier.width(4.dp))
+ Text(
+ device.name,
+ style = MaterialTheme.typography.titleLarge,
+ modifier = Modifier.weight(1f),
+ )
+ Surface(
+ shape = CircleShape,
+ color = if (device.online) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
+ modifier = Modifier.size(10.dp),
+ ) {}
+ }
+ }
+
+ // Camera permission prompt card when CAMERA permission is not granted yet
+ if (!hasCameraPermission) {
+ item {
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = MaterialTheme.colorScheme.secondaryContainer,
+ ) {
+ Column(Modifier.fillMaxWidth().padding(20.dp)) {
+ Text(
+ stringResource(R.string.webcam_permission_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ stringResource(R.string.webcam_permission_text, device.name),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(Modifier.height(12.dp))
+ Button(
+ onClick = {
+ startAfterGrant = device.online
+ askCamera.launch(Manifest.permission.CAMERA)
+ },
+ ) {
+ Text(stringResource(R.string.webcam_allow_camera))
+ }
+ }
+ }
+ }
+ }
+
+ // Offline notice
+ if (!device.online) {
+ item {
+ Surface(
+ shape = MaterialTheme.shapes.large,
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ ) {
+ Column(Modifier.fillMaxWidth().padding(16.dp)) {
+ Text(
+ stringResource(R.string.not_connected),
+ style = MaterialTheme.typography.titleSmall,
+ )
+ Spacer(Modifier.height(2.dp))
+ Text(
+ stringResource(R.string.webcam_offline_hint, device.name),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ }
+ }
+
+ // Live 16:9 camera preview box
+ item {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(16f / 9f)
+ .clip(MaterialTheme.shapes.extraLarge)
+ .background(Color(0xFF101216)),
+ contentAlignment = Alignment.Center,
+ ) {
+ if (isStreamingHere && hasCameraPermission) {
+ AndroidView(
+ factory = { previewView },
+ modifier = Modifier.fillMaxSize(),
+ )
+ } else {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier.padding(24.dp),
+ ) {
+ Text(
+ text = if (isStreamingHere && session.connecting) {
+ stringResource(R.string.webcam_status_connecting, device.name)
+ } else {
+ stringResource(R.string.webcam_status_ready, device.name)
+ },
+ style = MaterialTheme.typography.titleMedium,
+ color = Color.White,
+ )
+ Spacer(Modifier.height(6.dp))
+ Text(
+ text = "${session.width} × ${session.height} · ${session.fps} fps",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.72f),
+ )
+ }
+ }
+
+ // Overlay badge in top-left corner
+ Surface(
+ shape = MaterialTheme.shapes.medium,
+ color = Color.Black.copy(alpha = 0.58f),
+ contentColor = Color.White,
+ modifier = Modifier
+ .align(Alignment.TopStart)
+ .padding(12.dp),
+ ) {
+ val camLabel = stringResource(
+ if (session.camera == "front") R.string.webcam_camera_front else R.string.webcam_camera_back,
+ )
+ Text(
+ text = if (isStreamingHere && !session.connecting) {
+ stringResource(R.string.webcam_status_streaming, session.width, session.height, device.name) +
+ " · $camLabel"
+ } else {
+ "${session.width} × ${session.height} · $camLabel"
+ },
+ style = MaterialTheme.typography.labelMedium,
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
+ )
+ }
+ }
+ }
+
+ // Controls Card: Start/Stop, Front/Back switch, Torch, Resolution, Zoom
+ item {
+ Surface(
+ shape = MaterialTheme.shapes.extraLarge,
+ color = MaterialTheme.colorScheme.primaryContainer,
+ contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ // Primary Start/Stop + Flip camera + Torch
+ FlowRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ if (isStreamingHere) {
+ Button(
+ onClick = { WebcamService.stop(context) },
+ colors = ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.error,
+ contentColor = MaterialTheme.colorScheme.onError,
+ ),
+ ) {
+ Text(stringResource(R.string.webcam_stop))
+ }
+ } else {
+ Button(
+ enabled = device.online,
+ onClick = {
+ if (!hasCameraPermission) {
+ startAfterGrant = true
+ askCamera.launch(Manifest.permission.CAMERA)
+ } else {
+ WebcamService.start(
+ context = context,
+ pcId = device.id,
+ height = session.height,
+ camera = session.camera,
+ )
+ }
+ },
+ ) {
+ Text(stringResource(R.string.webcam_start))
+ }
+ }
+
+ FilledTonalButton(
+ onClick = {
+ val next = if (session.camera == "front") "back" else "front"
+ WebcamService.setCamera(next)
+ },
+ ) {
+ val currentLabel = stringResource(
+ if (session.camera == "front") R.string.webcam_camera_front else R.string.webcam_camera_back,
+ )
+ Text(stringResource(R.string.webcam_switch_camera) + " ($currentLabel)")
+ }
+
+ if (session.camera == "back" && (!isStreamingHere || session.hasFlash)) {
+ OutlinedButton(
+ enabled = isStreamingHere && session.hasFlash,
+ onClick = { WebcamService.setTorch(!session.torchOn) },
+ ) {
+ Text(
+ stringResource(
+ if (session.torchOn) R.string.webcam_torch_on else R.string.webcam_torch_off,
+ ),
+ )
+ }
+ }
+ }
+
+ // Resolution picker: 720p, 1080p, and 4K (when supported)
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ stringResource(R.string.webcam_resolution_label),
+ style = MaterialTheme.typography.labelLarge,
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ val resolutions = buildList {
+ add(720 to "720p")
+ add(1080 to "1080p")
+ if (session.supports4k) add(2160 to "4K")
+ }
+ for ((h, label) in resolutions) {
+ FilterChip(
+ selected = session.height == h,
+ onClick = { WebcamService.setResolutionHeight(h) },
+ label = { Text(label) },
+ )
+ }
+ }
+ }
+
+ // Zoom controls: 1x / 2x presets + smooth slider
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ stringResource(
+ R.string.webcam_zoom_label,
+ String.format(Locale.US, "%.1f", session.zoomRatio).toFloat(),
+ ),
+ style = MaterialTheme.typography.labelLarge,
+ modifier = Modifier.weight(1f),
+ )
+ FilterChip(
+ selected = kotlin.math.abs(session.zoomRatio - 1f) < 0.08f,
+ onClick = { WebcamService.setZoomRatio(1f) },
+ label = { Text("1×") },
+ )
+ Spacer(Modifier.width(8.dp))
+ FilterChip(
+ selected = kotlin.math.abs(session.zoomRatio - 2f) < 0.08f,
+ onClick = { WebcamService.setZoomRatio(2f.coerceAtMost(session.maxZoomRatio)) },
+ label = { Text("2×") },
+ )
+ }
+ val minZ = session.minZoomRatio
+ val maxZ = session.maxZoomRatio.coerceAtLeast(minZ + 0.1f)
+ Slider(
+ value = session.zoomRatio.coerceIn(minZ, maxZ),
+ onValueChange = { WebcamService.setZoomRatio(it) },
+ valueRange = minZ..maxZ,
+ enabled = isStreamingHere,
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt
new file mode 100644
index 0000000..bc4810c
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/CameraEncoder.kt
@@ -0,0 +1,479 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.webcam
+
+import android.content.Context
+import android.media.MediaCodec
+import android.media.MediaCodecInfo
+import android.media.MediaCodecList
+import android.media.MediaFormat
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import android.util.Size
+import android.view.Surface
+import androidx.camera.core.Camera
+import androidx.camera.core.CameraSelector
+import androidx.camera.core.Preview
+import androidx.camera.core.resolutionselector.AspectRatioStrategy
+import androidx.camera.core.resolutionselector.ResolutionSelector
+import androidx.camera.core.resolutionselector.ResolutionStrategy
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.LifecycleOwner
+import app.nectarlink.core.MirrorSendResult
+import app.nectarlink.core.MirrorStream
+import app.nectarlink.core.VideoPacketKind
+import app.nectarlink.core.webcamConfig
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+
+data class CameraLiveState(
+ val width: Int = 1280,
+ val height: Int = 720,
+ val fps: Int = 30,
+ val camera: String = "back",
+ val zoomRatio: Float = 1f,
+ val minZoomRatio: Float = 1f,
+ val maxZoomRatio: Float = 4f,
+ val hasFlash: Boolean = false,
+ val torchOn: Boolean = false,
+ val supports4k: Boolean = false,
+)
+
+/**
+ * Captures frames from the phone's front or back camera with CameraX and
+ * encodes them into low-latency Annex B H.264 access units with hardware
+ * [MediaCodec] (`COLOR_FormatSurface`) for `docs/protocol/webcam.md`.
+ *
+ * Switching cameras (`front` / `back`) or resolution (`720p` / `1080p` /
+ * `4K`) rebinds CameraX and starts a fresh [MediaCodec] on the same
+ * [MirrorStream], emitting a new `WebcamConfig` packet followed by an IDR
+ * keyframe without dropping the QUIC stream.
+ */
+internal class CameraEncoder(
+ context: Context,
+ private val lifecycleOwner: LifecycleOwner,
+ private val stream: MirrorStream,
+ initialHeight: Int,
+ private val fps: Int,
+ initialCamera: String,
+ private val onStateChanged: (CameraLiveState) -> Unit,
+ private val onEnded: () -> Unit,
+) {
+ private val context = context.applicationContext
+ private val main = Handler(Looper.getMainLooper())
+ private val mainExecutor = ContextCompat.getMainExecutor(this.context)
+ private val surfaceExecutor = Executors.newSingleThreadExecutor()
+
+ val supports4k: Boolean = supports4kEncoder()
+
+ @Volatile private var running = true
+ @Volatile private var keyframeWanted = false
+ @Volatile private var targetHeight: Int = normalizeHeight(initialHeight, supports4k)
+ @Volatile private var cameraFacing: String = if (initialCamera == "front") "front" else "back"
+ @Volatile private var activeCodec: ActiveCodec? = null
+
+ private var cameraProvider: ProcessCameraProvider? = null
+ private var boundCamera: Camera? = null
+ private var uiPreview: Preview? = null
+ private var pendingUiSurfaceProvider: Preview.SurfaceProvider? = null
+ private var liveState = CameraLiveState(
+ width = widthForHeight(targetHeight),
+ height = targetHeight,
+ fps = fps,
+ camera = cameraFacing,
+ supports4k = supports4k,
+ )
+
+ fun start() {
+ main.post {
+ if (!running) return@post
+ val future = ProcessCameraProvider.getInstance(context)
+ future.addListener({
+ if (!running) return@addListener
+ val provider = runCatching { future.get() }.getOrElse { e ->
+ Log.w(TAG, "can't get ProcessCameraProvider", e)
+ stop()
+ return@addListener
+ }
+ cameraProvider = provider
+ bindCamera()
+ }, mainExecutor)
+ }
+ }
+
+ fun stop() {
+ if (!running) return
+ running = false
+ main.post {
+ runCatching { cameraProvider?.unbindAll() }
+ boundCamera = null
+ uiPreview = null
+ }
+ surfaceExecutor.execute {
+ activeCodec?.stop()
+ activeCodec = null
+ runCatching { stream.end() }
+ main.post { onEnded() }
+ }
+ surfaceExecutor.shutdown()
+ }
+
+ fun requestKeyframe() {
+ keyframeWanted = true
+ }
+
+ fun setCamera(camera: String) {
+ val normalized = if (camera == "front") "front" else "back"
+ main.post {
+ if (!running || cameraFacing == normalized) return@post
+ cameraFacing = normalized
+ bindCamera()
+ }
+ }
+
+ fun setResolutionHeight(height: Int) {
+ val normalized = normalizeHeight(height, supports4k)
+ main.post {
+ if (!running || targetHeight == normalized) return@post
+ targetHeight = normalized
+ bindCamera()
+ }
+ }
+
+ fun setZoomRatio(ratio: Float) {
+ main.post {
+ val cam = boundCamera ?: return@post
+ val minZ = liveState.minZoomRatio
+ val maxZ = liveState.maxZoomRatio
+ val clamped = ratio.coerceIn(minZ, maxZ)
+ cam.cameraControl.setZoomRatio(clamped)
+ updateState { it.copy(zoomRatio = clamped) }
+ }
+ }
+
+ fun setTorch(on: Boolean) {
+ main.post {
+ val cam = boundCamera ?: return@post
+ if (!cam.cameraInfo.hasFlashUnit()) return@post
+ cam.cameraControl.enableTorch(on)
+ updateState { it.copy(torchOn = on) }
+ }
+ }
+
+ fun setUiSurfaceProvider(provider: Preview.SurfaceProvider?) {
+ main.post {
+ pendingUiSurfaceProvider = provider
+ uiPreview?.setSurfaceProvider(provider)
+ }
+ }
+
+ private fun updateState(transform: (CameraLiveState) -> CameraLiveState) {
+ liveState = transform(liveState)
+ onStateChanged(liveState)
+ }
+
+ private fun bindCamera() {
+ val provider = cameraProvider ?: return
+ if (!running) return
+
+ val desiredSize = Size(widthForHeight(targetHeight), targetHeight)
+ val resSelector = ResolutionSelector.Builder()
+ .setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY)
+ .setResolutionStrategy(
+ ResolutionStrategy(
+ desiredSize,
+ ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,
+ ),
+ )
+ .build()
+
+ val encoderPreview = Preview.Builder()
+ .setResolutionSelector(resSelector)
+ .build()
+
+ val facingForRequest = cameraFacing
+ encoderPreview.setSurfaceProvider(surfaceExecutor) { request ->
+ if (!running) {
+ request.willNotProvideSurface()
+ return@setSurfaceProvider
+ }
+ activeCodec?.stop()
+ activeCodec = null
+
+ val w = request.resolution.width
+ val h = request.resolution.height
+ val started = startCodecForResolution(w, h, facingForRequest)
+ if (started == null) {
+ request.willNotProvideSurface()
+ if (targetHeight > 1080) {
+ // Fall back from 4K to 1080p if the codec rejected 4K.
+ main.post { setResolutionHeight(1080) }
+ } else {
+ stop()
+ }
+ return@setSurfaceProvider
+ }
+ activeCodec = started
+ main.post {
+ updateState { it.copy(width = started.width, height = started.height, camera = facingForRequest) }
+ }
+ request.provideSurface(started.surface, surfaceExecutor) {
+ if (activeCodec === started) {
+ activeCodec = null
+ }
+ started.stop()
+ }
+ }
+
+ val previewForUi = Preview.Builder()
+ .setResolutionSelector(
+ ResolutionSelector.Builder()
+ .setAspectRatioStrategy(AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY)
+ .build(),
+ )
+ .build()
+ .also { it.setSurfaceProvider(pendingUiSurfaceProvider) }
+ uiPreview = previewForUi
+
+ val requestedSelector = if (cameraFacing == "front") {
+ CameraSelector.DEFAULT_FRONT_CAMERA
+ } else {
+ CameraSelector.DEFAULT_BACK_CAMERA
+ }
+ val selector = if (runCatching { provider.hasCamera(requestedSelector) }.getOrDefault(false)) {
+ requestedSelector
+ } else if (runCatching { provider.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA) }.getOrDefault(false)) {
+ cameraFacing = "back"
+ CameraSelector.DEFAULT_BACK_CAMERA
+ } else {
+ cameraFacing = "front"
+ CameraSelector.DEFAULT_FRONT_CAMERA
+ }
+
+ provider.unbindAll()
+ val camera = runCatching {
+ provider.bindToLifecycle(lifecycleOwner, selector, encoderPreview, previewForUi)
+ }.getOrElse {
+ // Fallback for single-stream legacy cameras: bind encoderPreview alone.
+ runCatching {
+ provider.bindToLifecycle(lifecycleOwner, selector, encoderPreview)
+ }.getOrNull()
+ }
+
+ if (camera == null) {
+ Log.w(TAG, "failed to bind camera")
+ stop()
+ return
+ }
+ boundCamera = camera
+ val zoomState = camera.cameraInfo.zoomState.value
+ val hasFlash = camera.cameraInfo.hasFlashUnit()
+ updateState {
+ it.copy(
+ camera = cameraFacing,
+ zoomRatio = zoomState?.zoomRatio ?: 1f,
+ minZoomRatio = zoomState?.minZoomRatio ?: 1f,
+ maxZoomRatio = (zoomState?.maxZoomRatio ?: 4f).coerceAtLeast(2f),
+ hasFlash = hasFlash,
+ torchOn = false,
+ )
+ }
+ }
+
+ private fun startCodecForResolution(width: Int, height: Int, camera: String): ActiveCodec? {
+ val bitrate = bitrateForHeight(height)
+ return runCatching {
+ val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height).apply {
+ setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
+ setInteger(MediaFormat.KEY_BIT_RATE, bitrate)
+ setInteger(MediaFormat.KEY_FRAME_RATE, fps)
+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, I_FRAME_INTERVAL_SEC)
+ setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 100_000L)
+ setInteger(MediaFormat.KEY_PRIORITY, 0)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ setInteger(MediaFormat.KEY_MAX_B_FRAMES, 0)
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ setInteger(MediaFormat.KEY_LOW_LATENCY, 1)
+ setInteger(MediaFormat.KEY_LATENCY, 1)
+ }
+ setInteger(MediaFormat.KEY_COLOR_STANDARD, MediaFormat.COLOR_STANDARD_BT709)
+ setInteger(MediaFormat.KEY_COLOR_RANGE, MediaFormat.COLOR_RANGE_LIMITED)
+ setInteger(MediaFormat.KEY_COLOR_TRANSFER, MediaFormat.COLOR_TRANSFER_SDR_VIDEO)
+ }
+ val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ val surface = codec.createInputSurface()
+ codec.start()
+ ActiveCodec(codec, surface, width, height, camera).also { it.startDrain() }
+ }.onFailure { e ->
+ Log.w(TAG, "can't start H.264 encoder for ${width}x${height}", e)
+ }.getOrNull()
+ }
+
+ private inner class ActiveCodec(
+ val codec: MediaCodec,
+ val surface: Surface,
+ val width: Int,
+ val height: Int,
+ val camera: String,
+ ) {
+ private val active = AtomicBoolean(true)
+ private var drainThread: Thread? = null
+
+ fun startDrain() {
+ drainThread = Thread(::drainLoop, "webcam-encoder-${width}x${height}").also { it.start() }
+ }
+
+ fun stop() {
+ if (!active.compareAndSet(true, false)) return
+ drainThread?.let { runCatching { it.join(500) } }
+ runCatching { codec.stop() }
+ runCatching { codec.release() }
+ runCatching { surface.release() }
+ }
+
+ private fun drainLoop() {
+ val cfgBytes = webcamConfig(width.toUInt(), height.toUInt(), camera, fps.toUInt())
+ if (stream.send(VideoPacketKind.CONFIG, 0u, cfgBytes) == MirrorSendResult.CLOSED) {
+ return
+ }
+ val info = MediaCodec.BufferInfo()
+ var parameters = ByteArray(0)
+ try {
+ while (active.get() && running) {
+ if (keyframeWanted) {
+ keyframeWanted = false
+ runCatching {
+ codec.setParameters(
+ Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) },
+ )
+ }
+ }
+ val index = codec.dequeueOutputBuffer(info, WAIT_US)
+ if (index < 0) continue
+ val bytes = ByteArray(info.size)
+ codec.getOutputBuffer(index)?.let { buf ->
+ buf.position(info.offset)
+ buf.get(bytes)
+ }
+ codec.releaseOutputBuffer(index, false)
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {
+ parameters = bytes
+ continue
+ }
+ if (bytes.isEmpty()) continue
+ val key = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
+ val payload = ensureAudAndParameters(bytes, parameters, key)
+ val result = stream.send(
+ if (key) VideoPacketKind.KEYFRAME else VideoPacketKind.FRAME,
+ info.presentationTimeUs.toULong(),
+ payload,
+ )
+ when (result) {
+ MirrorSendResult.NEED_KEYFRAME, MirrorSendResult.DROPPED -> keyframeWanted = true
+ MirrorSendResult.CLOSED -> {
+ return
+ }
+ MirrorSendResult.QUEUED -> {}
+ }
+ }
+ } catch (e: Exception) {
+ if (active.get() && running) {
+ Log.w(TAG, "webcam encoder drain interrupted", e)
+ }
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "CameraEncoder"
+ private const val WAIT_US = 40_000L
+ private const val I_FRAME_INTERVAL_SEC = 2
+
+ /** Annex B Access Unit Delimiter NAL (`00 00 00 01 09 F0`). */
+ internal val AUD_NAL = byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x09, 0xF0.toByte())
+
+ fun widthForHeight(height: Int): Int = when (height) {
+ 2160 -> 3840
+ 1080 -> 1920
+ else -> 1280
+ }
+
+ fun bitrateForHeight(height: Int): Int = when {
+ height >= 2160 -> 20_000_000
+ height >= 1080 -> 8_000_000
+ else -> 4_000_000
+ }
+
+ fun normalizeHeight(height: Int, supports4k: Boolean): Int = when {
+ height >= 2160 && supports4k -> 2160
+ height >= 1080 -> 1080
+ else -> 720
+ }
+
+ /** Checks whether any hardware AVC encoder on this device supports 3840×2160. */
+ fun supports4kEncoder(): Boolean = runCatching {
+ val list = MediaCodecList(MediaCodecList.REGULAR_CODECS)
+ list.codecInfos.any { info ->
+ info.isEncoder &&
+ info.supportedTypes.any { it.equals(MediaFormat.MIMETYPE_VIDEO_AVC, ignoreCase = true) } &&
+ runCatching {
+ info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC)
+ .videoCapabilities?.isSizeSupported(3840, 2160) == true
+ }.getOrDefault(false)
+ }
+ }.getOrDefault(false)
+
+ /**
+ * Guarantees each H.264 access unit starts with an Annex B Access
+ * Unit Delimiter (`00 00 00 01 09 F0`) and that keyframes include
+ * the cached SPS/PPS (`parameters`) right after the AUD so the PC's
+ * Media Foundation decoder flushes every frame immediately.
+ */
+ internal fun ensureAudAndParameters(
+ bytes: ByteArray,
+ parameters: ByteArray,
+ isKeyframe: Boolean,
+ ): ByteArray {
+ val stripped = stripLeadingAud(bytes)
+ return if (isKeyframe && parameters.isNotEmpty()) {
+ val cleanParams = stripLeadingAud(parameters)
+ ByteArray(AUD_NAL.size + cleanParams.size + stripped.size).also { out ->
+ System.arraycopy(AUD_NAL, 0, out, 0, AUD_NAL.size)
+ System.arraycopy(cleanParams, 0, out, AUD_NAL.size, cleanParams.size)
+ System.arraycopy(stripped, 0, out, AUD_NAL.size + cleanParams.size, stripped.size)
+ }
+ } else {
+ ByteArray(AUD_NAL.size + stripped.size).also { out ->
+ System.arraycopy(AUD_NAL, 0, out, 0, AUD_NAL.size)
+ System.arraycopy(stripped, 0, out, AUD_NAL.size, stripped.size)
+ }
+ }
+ }
+
+ private fun stripLeadingAud(data: ByteArray): ByteArray {
+ if (data.size >= 6 &&
+ data[0] == 0.toByte() && data[1] == 0.toByte() &&
+ data[2] == 0.toByte() && data[3] == 1.toByte() &&
+ (data[4].toInt() and 0x1F) == 9
+ ) {
+ return data.copyOfRange(6, data.size)
+ }
+ if (data.size >= 5 &&
+ data[0] == 0.toByte() && data[1] == 0.toByte() &&
+ data[2] == 1.toByte() &&
+ (data[3].toInt() and 0x1F) == 9
+ ) {
+ return data.copyOfRange(5, data.size)
+ }
+ return data
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamRequest.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamRequest.kt
new file mode 100644
index 0000000..b67edac
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamRequest.kt
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.webcam
+
+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 androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import app.nectarlink.android.R
+import app.nectarlink.android.ui.MainActivity
+
+/** A PC asking for this phone's camera as a webcam (`webcam.start`). */
+data class WebcamRequest(
+ val pcId: String,
+ val width: Int = 1280,
+ val height: Int = 720,
+ val fps: Int = 30,
+ val bitrate: Int = 4_000_000,
+ val camera: String = "back",
+)
+
+/**
+ * Posts a high-priority notification when a paired PC asks to use this
+ * phone's camera (`webcam.start`). Tapping the notification opens
+ * [MainActivity] on the Webcam screen for that PC so the camera only turns
+ * on with the user's explicit action.
+ */
+object WebcamRequests {
+ private const val CHANNEL = "webcam_requests"
+ private const val TAG = "webcam_req"
+ private const val REQUEST_TIMEOUT_MS = 2 * 60 * 1000L
+
+ fun createChannel(context: Context) {
+ context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL,
+ context.getString(R.string.channel_webcam_requests),
+ NotificationManager.IMPORTANCE_HIGH,
+ ),
+ )
+ }
+
+ /** Shows the request notification; returns true if shown. */
+ fun show(context: Context, request: WebcamRequest, pcName: String): Boolean {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
+ PackageManager.PERMISSION_GRANTED
+ ) {
+ return false
+ }
+ createChannel(context)
+ val openIntent = Intent(context, MainActivity::class.java).apply {
+ putExtra("webcam_pc", request.pcId)
+ putExtra("webcam_height", request.height)
+ putExtra("webcam_camera", request.camera)
+ putExtra("webcam_auto_start", true)
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ val open = PendingIntent.getActivity(
+ context,
+ request.pcId.hashCode(),
+ openIntent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val title = context.getString(
+ R.string.webcam_request_title,
+ pcName.ifEmpty { context.getString(R.string.your_pc) },
+ )
+ val notification = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(title)
+ .setContentText(context.getString(R.string.webcam_request_text))
+ .setContentIntent(open)
+ .setAutoCancel(true)
+ .setTimeoutAfter(REQUEST_TIMEOUT_MS)
+ .setCategory(NotificationCompat.CATEGORY_CALL)
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
+ .build()
+ return runCatching {
+ NotificationManagerCompat.from(context).notify(TAG, request.pcId.hashCode(), notification)
+ }.isSuccess
+ }
+
+ fun dismiss(context: Context, pcId: String) {
+ NotificationManagerCompat.from(context).cancel(TAG, pcId.hashCode())
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt
new file mode 100644
index 0000000..7c2d909
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/webcam/WebcamService.kt
@@ -0,0 +1,351 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.webcam
+
+import android.Manifest
+import android.app.Notification
+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.content.pm.ServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import androidx.camera.core.Preview
+import androidx.core.app.NotificationCompat
+import androidx.core.app.ServiceCompat
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.LifecycleService
+import androidx.lifecycle.lifecycleScope
+import app.nectarlink.android.NectarlinkApplication
+import app.nectarlink.android.R
+import app.nectarlink.android.ui.MainActivity
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+data class WebcamSession(
+ val active: Boolean = false,
+ val connecting: Boolean = false,
+ val pcId: String? = null,
+ val width: Int = 1280,
+ val height: Int = 720,
+ val fps: Int = 30,
+ val camera: String = "back",
+ val zoomRatio: Float = 1f,
+ val minZoomRatio: Float = 1f,
+ val maxZoomRatio: Float = 4f,
+ val hasFlash: Boolean = false,
+ val torchOn: Boolean = false,
+ val supports4k: Boolean = CameraEncoder.supports4kEncoder(),
+)
+
+/**
+ * Streams the phone's camera as H.264 to a paired PC (`docs/protocol/webcam.md`).
+ * Runs as a `camera` foreground service with an ongoing notification and a
+ * Stop action so streaming continues if the user switches apps or locks the
+ * screen.
+ */
+class WebcamService : LifecycleService() {
+ private val main = Handler(Looper.getMainLooper())
+ private var encoder: CameraEncoder? = null
+ private var pcId: String? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ super.onStartCommand(intent, flags, startId)
+ when (intent?.action) {
+ ACTION_STOP -> {
+ stopStreaming()
+ return START_NOT_STICKY
+ }
+ ACTION_START -> {
+ val targetPc = intent.getStringExtra(EXTRA_PC)
+ if (targetPc == null || !hasPermission(this)) {
+ stopStreaming()
+ return START_NOT_STICKY
+ }
+ val height = intent.getIntExtra(EXTRA_HEIGHT, _session.value.height)
+ val fps = intent.getIntExtra(EXTRA_FPS, 30).coerceIn(15, 60)
+ val camera = intent.getStringExtra(EXTRA_CAMERA) ?: _session.value.camera
+ if (encoder != null && pcId == targetPc) {
+ encoder?.setCamera(camera)
+ encoder?.setResolutionHeight(height)
+ return START_NOT_STICKY
+ }
+ startStreamingSession(targetPc, height, fps, camera)
+ }
+ }
+ return START_NOT_STICKY
+ }
+
+ private fun startStreamingSession(targetPc: String, height: Int, fps: Int, camera: String) {
+ encoder?.stop()
+ encoder = null
+ pcId = targetPc
+ current = this
+ WebcamRequests.dismiss(this, targetPc)
+
+ val supports4k = CameraEncoder.supports4kEncoder()
+ val normHeight = CameraEncoder.normalizeHeight(height, supports4k)
+ val normWidth = CameraEncoder.widthForHeight(normHeight)
+ val normCamera = if (camera == "front") "front" else "back"
+
+ _session.value = WebcamSession(
+ active = true,
+ connecting = true,
+ pcId = targetPc,
+ width = normWidth,
+ height = normHeight,
+ fps = fps,
+ camera = normCamera,
+ supports4k = supports4k,
+ )
+
+ createChannel(this)
+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
+ } else {
+ 0
+ }
+ val startedFg = runCatching {
+ ServiceCompat.startForeground(
+ this,
+ NOTIFICATION_ID,
+ buildNotification(targetPc, normWidth, normHeight, normCamera),
+ type,
+ )
+ }.onFailure { e ->
+ Log.w(TAG, "can't enter camera foreground service", e)
+ }.isSuccess
+ if (!startedFg) {
+ stopStreaming()
+ return
+ }
+
+ val core = (application as NectarlinkApplication).core
+ core.clearWebcamRequest(targetPc)
+
+ lifecycleScope.launch(Dispatchers.IO) {
+ val stream = core.webcamOpenOrMessage(targetPc)
+ if (stream == null) {
+ main.post { stopStreaming() }
+ return@launch
+ }
+ main.post {
+ if (pcId != targetPc || current !== this@WebcamService) {
+ runCatching { stream.end() }
+ return@post
+ }
+ val camEncoder = CameraEncoder(
+ context = this@WebcamService,
+ lifecycleOwner = this@WebcamService,
+ stream = stream,
+ initialHeight = normHeight,
+ fps = fps,
+ initialCamera = normCamera,
+ onStateChanged = { live ->
+ _session.update { s ->
+ s.copy(
+ active = true,
+ connecting = false,
+ width = live.width,
+ height = live.height,
+ fps = live.fps,
+ camera = live.camera,
+ zoomRatio = live.zoomRatio,
+ minZoomRatio = live.minZoomRatio,
+ maxZoomRatio = live.maxZoomRatio,
+ hasFlash = live.hasFlash,
+ torchOn = live.torchOn,
+ supports4k = live.supports4k,
+ )
+ }
+ updateNotification()
+ },
+ onEnded = {
+ if (current === this@WebcamService) {
+ stopStreaming()
+ }
+ },
+ )
+ camEncoder.setUiSurfaceProvider(uiSurfaceProvider)
+ encoder = camEncoder
+ camEncoder.start()
+ }
+ }
+ }
+
+ private fun updateNotification() {
+ val s = _session.value
+ val targetPc = s.pcId ?: return
+ val nm = getSystemService(NotificationManager::class.java) ?: return
+ nm.notify(NOTIFICATION_ID, buildNotification(targetPc, s.width, s.height, s.camera))
+ }
+
+ private fun buildNotification(targetPc: String, width: Int, height: Int, camera: String): Notification {
+ val core = (application as NectarlinkApplication).core
+ val pcName = core.state.value.nameOf(targetPc).orEmpty().ifEmpty { getString(R.string.your_pc) }
+
+ val openIntent = Intent(this, MainActivity::class.java).apply {
+ putExtra("webcam_pc", targetPc)
+ flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ val openPending = PendingIntent.getActivity(
+ this,
+ 10,
+ openIntent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val stopPending = PendingIntent.getService(
+ this,
+ 11,
+ Intent(this, WebcamService::class.java).setAction(ACTION_STOP),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val camLabel = getString(
+ if (camera == "front") R.string.webcam_camera_front else R.string.webcam_camera_back,
+ ).lowercase()
+
+ return NotificationCompat.Builder(this, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(getString(R.string.webcam_notification_streaming, pcName))
+ .setContentText(getString(R.string.webcam_notification_detail, width, height, camLabel))
+ .setContentIntent(openPending)
+ .setOngoing(true)
+ .setSilent(true)
+ .setOnlyAlertOnce(true)
+ .setCategory(NotificationCompat.CATEGORY_SERVICE)
+ .addAction(0, getString(R.string.action_stop), stopPending)
+ .build()
+ }
+
+ private fun stopStreaming() {
+ val runningEncoder = encoder
+ encoder = null
+ pcId = null
+ if (current === this) current = null
+ runningEncoder?.stop()
+ _session.update {
+ it.copy(
+ active = false,
+ connecting = false,
+ pcId = null,
+ torchOn = false,
+ )
+ }
+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
+ stopSelf()
+ }
+
+ override fun onDestroy() {
+ stopStreaming()
+ super.onDestroy()
+ }
+
+ companion object {
+ private const val TAG = "WebcamService"
+ private const val CHANNEL = "webcam"
+ private const val NOTIFICATION_ID = 8
+
+ private const val ACTION_START = "app.nectarlink.android.webcam.START"
+ private const val ACTION_STOP = "app.nectarlink.android.webcam.STOP"
+ private const val EXTRA_PC = "pc"
+ private const val EXTRA_HEIGHT = "height"
+ private const val EXTRA_FPS = "fps"
+ private const val EXTRA_CAMERA = "camera"
+
+ @Volatile private var current: WebcamService? = null
+ @Volatile private var uiSurfaceProvider: Preview.SurfaceProvider? = null
+
+ private val _session = MutableStateFlow(WebcamSession())
+ val session: StateFlow<WebcamSession> = _session.asStateFlow()
+
+ fun hasPermission(context: Context): Boolean =
+ ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
+ PackageManager.PERMISSION_GRANTED &&
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
+
+ fun start(
+ context: Context,
+ pcId: String,
+ height: Int = _session.value.height,
+ fps: Int = 30,
+ camera: String = _session.value.camera,
+ ) {
+ val intent = Intent(context, WebcamService::class.java)
+ .setAction(ACTION_START)
+ .putExtra(EXTRA_PC, pcId)
+ .putExtra(EXTRA_HEIGHT, height)
+ .putExtra(EXTRA_FPS, fps)
+ .putExtra(EXTRA_CAMERA, camera)
+ ContextCompat.startForegroundService(context, intent)
+ }
+
+ fun stop(context: Context) {
+ val srv = current
+ if (srv != null) {
+ srv.main.post { srv.stopStreaming() }
+ } else {
+ runCatching { context.stopService(Intent(context, WebcamService::class.java)) }
+ }
+ }
+
+ fun stopForPc(context: Context, pcId: String) {
+ val srv = current ?: return
+ srv.main.post {
+ if (srv.pcId == pcId) srv.stopStreaming()
+ }
+ }
+
+ fun keyframe(pcId: String) {
+ current?.takeIf { it.pcId == pcId }?.encoder?.requestKeyframe()
+ }
+
+ fun setCamera(camera: String) {
+ val norm = if (camera == "front") "front" else "back"
+ _session.update { it.copy(camera = norm, torchOn = false) }
+ current?.encoder?.setCamera(norm)
+ }
+
+ fun setResolutionHeight(height: Int) {
+ val norm = CameraEncoder.normalizeHeight(height, _session.value.supports4k)
+ _session.update {
+ it.copy(width = CameraEncoder.widthForHeight(norm), height = norm)
+ }
+ current?.encoder?.setResolutionHeight(norm)
+ }
+
+ fun setZoomRatio(ratio: Float) {
+ _session.update { it.copy(zoomRatio = ratio) }
+ current?.encoder?.setZoomRatio(ratio)
+ }
+
+ fun setTorch(on: Boolean) {
+ _session.update { it.copy(torchOn = on) }
+ current?.encoder?.setTorch(on)
+ }
+
+ fun attachUiPreview(provider: Preview.SurfaceProvider?) {
+ uiSurfaceProvider = provider
+ current?.encoder?.setUiSurfaceProvider(provider)
+ }
+
+ fun createChannel(context: Context) {
+ val nm = context.getSystemService(NotificationManager::class.java) ?: return
+ val channel = NotificationChannel(
+ CHANNEL,
+ context.getString(R.string.channel_webcam),
+ NotificationManager.IMPORTANCE_LOW,
+ ).apply {
+ setShowBadge(false)
+ }
+ nm.createNotificationChannel(channel)
+ }
+ }
+}
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index ed89cbb..a4f0ba4 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -330,4 +330,30 @@
<string name="storage_request_title">%1$s wants to browse this phone’s storage</string>
<string name="storage_request_text">Allow %1$s to browse your shared storage (or selected folders) in File Explorer?</string>
<string name="action_not_now">Not now</string>
+
+ <!-- Phone as webcam -> PC -->
+ <string name="action_webcam_pc">Webcam</string>
+ <string name="channel_webcam">Webcam</string>
+ <string name="channel_webcam_requests">Webcam requests</string>
+ <string name="webcam_notification_streaming">Streaming camera to %1$s</string>
+ <string name="webcam_notification_detail">%1$d × %2$d · %3$s camera</string>
+ <string name="webcam_request_title">%1$s wants to use your camera</string>
+ <string name="webcam_request_text">Tap to open the webcam controls and start streaming.</string>
+ <string name="webcam_permission_title">Allow camera access</string>
+ <string name="webcam_permission_text">Nectarlink uses the camera only while you stream video to %1$s as a webcam.</string>
+ <string name="webcam_allow_camera">Allow camera</string>
+ <string name="webcam_status_streaming">Streaming %1$d × %2$d to %3$s</string>
+ <string name="webcam_status_connecting">Connecting camera to %1$s…</string>
+ <string name="webcam_status_ready">Ready to stream to %1$s</string>
+ <string name="webcam_start">Start webcam</string>
+ <string name="webcam_stop">Stop webcam</string>
+ <string name="webcam_camera_back">Back</string>
+ <string name="webcam_camera_front">Front</string>
+ <string name="webcam_switch_camera">Flip camera</string>
+ <string name="webcam_torch_on">Torch on</string>
+ <string name="webcam_torch_off">Torch off</string>
+ <string name="webcam_zoom_label">Zoom %1$.1f×</string>
+ <string name="webcam_resolution_label">Resolution</string>
+ <string name="webcam_denied_text">Webcam is turned off for this phone on %1$s.</string>
+ <string name="webcam_offline_hint">Connect %1$s on the same network to start streaming your camera.</string>
</resources>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/webcam/CameraEncoderTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/webcam/CameraEncoderTest.kt
new file mode 100644
index 0000000..f8d49f6
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/webcam/CameraEncoderTest.kt
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.webcam
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class CameraEncoderTest {
+ @Test
+ fun `prepends AUD and SPS PPS to keyframes and avoids duplicate AUD`() {
+ val spsPps = byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x00, 0x00, 0x01, 0x68, 0x11)
+ val idrSlice = byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x65, 0xAA.toByte())
+
+ val keyOut = CameraEncoder.ensureAudAndParameters(idrSlice, spsPps, isKeyframe = true)
+ assertArrayEquals(CameraEncoder.AUD_NAL + spsPps + idrSlice, keyOut)
+
+ // When the encoder already emitted an AUD at the front of the slice, it is not duplicated.
+ val idrWithAud = CameraEncoder.AUD_NAL + idrSlice
+ val keyDedup = CameraEncoder.ensureAudAndParameters(idrWithAud, spsPps, isKeyframe = true)
+ assertArrayEquals(CameraEncoder.AUD_NAL + spsPps + idrSlice, keyDedup)
+
+ // Non-keyframe gets AUD prepended without SPS/PPS.
+ val pSlice = byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x41, 0x55)
+ val pOut = CameraEncoder.ensureAudAndParameters(pSlice, spsPps, isKeyframe = false)
+ assertArrayEquals(CameraEncoder.AUD_NAL + pSlice, pOut)
+ }
+
+ @Test
+ fun `normalizes resolution height and selects matching width and bitrate`() {
+ assertEquals(720, CameraEncoder.normalizeHeight(720, supports4k = false))
+ assertEquals(1080, CameraEncoder.normalizeHeight(1080, supports4k = false))
+ assertEquals(1080, CameraEncoder.normalizeHeight(2160, supports4k = false))
+ assertEquals(2160, CameraEncoder.normalizeHeight(2160, supports4k = true))
+
+ assertEquals(1280, CameraEncoder.widthForHeight(720))
+ assertEquals(1920, CameraEncoder.widthForHeight(1080))
+ assertEquals(3840, CameraEncoder.widthForHeight(2160))
+
+ assertEquals(4_000_000, CameraEncoder.bitrateForHeight(720))
+ assertEquals(8_000_000, CameraEncoder.bitrateForHeight(1080))
+ assertEquals(20_000_000, CameraEncoder.bitrateForHeight(2160))
+ }
+}
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index ee6bc83..084dcf3 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -283,6 +283,24 @@ enum Command {
#[arg(long)]
apps: bool,
},
+ /// Act as a phone streaming its camera as a webcam (use with --as-phone):
+ /// streams an H.264 file (Annex B, with access unit delimiters) in a loop
+ /// at `fps` when a PC asks (or right away with `--to <device>`). Stays online.
+ Webcam {
+ video: PathBuf,
+ #[arg(long, default_value_t = 1280)]
+ width: u32,
+ #[arg(long, default_value_t = 720)]
+ height: u32,
+ #[arg(long, default_value_t = 30)]
+ fps: u32,
+ #[arg(long, default_value = "back")]
+ camera: String,
+ /// Start streaming to this paired PC immediately (without waiting for
+ /// the PC to request it).
+ #[arg(long)]
+ to: Option<String>,
+ },
/// Act as a phone with a few sample conversations (use with --as-phone),
/// so a PC can read them and text through this client; stays online.
Texts,
@@ -788,6 +806,10 @@ type ScreenSession = (
std::sync::Arc<nectarlink_core::MirrorStream>,
);
static SCREEN_SESSIONS: std::sync::Mutex<Vec<ScreenSession>> = std::sync::Mutex::new(Vec::new());
+static WEBCAM_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(DeviceId, String)>> =
+ std::sync::OnceLock::new();
+static WEBCAM_SESSIONS: std::sync::Mutex<Vec<(DeviceId, std::sync::Arc<nectarlink_core::MirrorStream>)>> =
+ std::sync::Mutex::new(Vec::new());
/// The apps `screen --apps` offers.
const SAMPLE_APPS: &[(&str, &str)] = &[
("com.example.calendar", "Calendar"),
@@ -1485,6 +1507,33 @@ impl Platform for TerminalPlatform {
fn mirror_keyframe_requested(&self, _peer: &DeviceId, _session: u32) {
println!("The PC asked for a keyframe.");
}
+ fn webcam_requested(
+ &self,
+ peer: &DeviceId,
+ options: &nectarlink_core::WebcamStart,
+ ) -> std::result::Result<(), String> {
+ let asks = WEBCAM_ASKS.get().ok_or("not sharing a webcam (run `webcam`)")?;
+ println!(
+ "A PC asked for the {} camera ({}x{} @ {} fps); sharing it.",
+ options.camera, options.width, options.height, options.fps
+ );
+ asks.send((*peer, options.camera.clone())).map_err(|e| e.to_string())
+ }
+ fn webcam_stop_requested(&self, peer: &DeviceId) {
+ println!("The PC stopped the webcam.");
+ let mut sessions = WEBCAM_SESSIONS.lock().unwrap();
+ sessions.retain(|(p, stream)| {
+ if p == peer {
+ stream.close();
+ false
+ } else {
+ true
+ }
+ });
+ }
+ fn webcam_keyframe_requested(&self, _peer: &DeviceId) {
+ println!("The PC asked for a webcam keyframe.");
+ }
fn sms_threads(&self, limit: u32) -> std::result::Result<Vec<nectarlink_core::SmsThread>, String> {
let texts = TEXTS.lock().unwrap();
let mut threads: Vec<nectarlink_core::SmsThread> = Vec::new();
@@ -1891,6 +1940,44 @@ impl Platform for TerminalPlatform {
println!("Deleted {path} from phone storage.");
Ok(())
}
+ fn webcam_sink(&self, peer: &DeviceId) -> Option<Arc<dyn nectarlink_core::WebcamSink>> {
+ Some(Arc::new(CliWebcamSink { peer: *peer, frames: std::sync::atomic::AtomicU64::new(0) }))
+ }
+}
+
+struct CliWebcamSink {
+ peer: DeviceId,
+ frames: std::sync::atomic::AtomicU64,
+}
+
+impl nectarlink_core::WebcamSink for CliWebcamSink {
+ fn config(&self, config: nectarlink_core::WebcamConfig) {
+ println!(
+ "Webcam stream from {}: {}x{} @ {} fps ({}, {})",
+ self.peer.short(),
+ config.width,
+ config.height,
+ config.fps,
+ config.camera,
+ config.codec
+ );
+ }
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
+ let n = self.frames.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
+ if keyframe || n <= 5 || n.is_multiple_of(30) {
+ println!(
+ "Webcam frame #{n} from {}: {} ({} B, pts {} us)",
+ self.peer.short(),
+ if keyframe { "keyframe" } else { "frame" },
+ data.len(),
+ time_us
+ );
+ }
+ }
+ fn ended(&self) {
+ let total = self.frames.load(std::sync::atomic::Ordering::Relaxed);
+ println!("Webcam stream from {} ended ({total} frames received).", self.peer.short());
+ }
}
fn main() -> Result<()> {
@@ -1953,6 +2040,8 @@ async fn start_node(cli: &Cli) -> Result<Node> {
config.capabilities.push(nectarlink_core::PC_WAKE.into());
config.capabilities.push(nectarlink_core::DECK_ACTIONS.into());
config.capabilities.push(nectarlink_core::STORAGE_MOUNT.into());
+ config.capabilities.push(nectarlink_core::WEBCAM_VIRTUAL.into());
+ config.capabilities.push(nectarlink_core::WEBCAM_ADDON_VCAM.into());
}
let extra_caps = config.capabilities.clone();
let node = Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")?;
@@ -2663,6 +2752,55 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
});
watch(node, false).await?;
}
+ Command::Webcam { video, width, height, fps, camera, to } => {
+ if !cli.as_phone {
+ bail!("webcams are shared by phones: add --as-phone");
+ }
+ let stream = std::fs::read(video).context("can't read the video")?;
+ let units = std::sync::Arc::new(access_units(&stream));
+ if units.is_empty() {
+ bail!("no access unit delimiters in the video");
+ }
+ let (asks, mut asked) = tokio::sync::mpsc::unbounded_channel();
+ let _ = WEBCAM_ASKS.set(asks.clone());
+ let mut offers = cli.offers.clone();
+ offers.push(nectarlink_core::WEBCAM_STREAM.into());
+ node.update_power(node_power(cli), offers).await;
+ println!("Sharing a {width}x{height} webcam ({} frames) with PCs.", units.len());
+ if let Some(target) = to {
+ let pc = resolve(node, target)?;
+ wait_until_online(node, pc).await?;
+ let _ = asks.send((pc, camera.clone()));
+ }
+ let streamer = node.clone();
+ let (width, height, fps) = (*width, *height, *fps);
+ tokio::spawn(async move {
+ while let Some((pc, cam)) = asked.recv().await {
+ let webcam = match streamer.webcam_open(pc).await {
+ Ok(s) => std::sync::Arc::new(s),
+ Err(e) => {
+ println!("Couldn't open the webcam stream: {e}");
+ continue;
+ }
+ };
+ {
+ let mut sessions = WEBCAM_SESSIONS.lock().unwrap();
+ sessions.retain(|(p, old)| {
+ if *p == pc {
+ old.close();
+ false
+ } else {
+ true
+ }
+ });
+ sessions.push((pc, webcam.clone()));
+ }
+ let units = units.clone();
+ std::thread::spawn(move || stream_webcam(&webcam, &units, width, height, fps, &cam));
+ }
+ });
+ watch(node, false).await?;
+ }
Command::Texts => {
if !cli.as_phone {
bail!("texts are on phones: add --as-phone");
@@ -4096,3 +4234,42 @@ fn stream_screen(
}
println!("Stopped sharing the screen ({dropped} frames dropped to keep up).");
}
+
+fn stream_webcam(
+ webcam: &nectarlink_core::MirrorStream,
+ units: &[Vec<u8>],
+ width: u32,
+ height: u32,
+ fps: u32,
+ camera: &str,
+) {
+ use nectarlink_core::{MirrorSend, PacketKind};
+ let config = nectarlink_core::WebcamConfig {
+ codec: nectarlink_core::WEBCAM_H264.into(),
+ width,
+ height,
+ camera: camera.into(),
+ fps,
+ }
+ .to_cbor();
+ if webcam.send(PacketKind::Config, 0, config) == MirrorSend::Closed {
+ return;
+ }
+ let frame = std::time::Duration::from_secs_f64(1.0 / f64::from(fps.max(1)));
+ let started = std::time::Instant::now();
+ let mut dropped = 0u32;
+ for (n, unit) in units.iter().cycle().enumerate() {
+ let due = started + frame * n as u32;
+ if let Some(wait) = due.checked_duration_since(std::time::Instant::now()) {
+ std::thread::sleep(wait);
+ }
+ let time = started.elapsed().as_micros() as u64;
+ let kind = if is_keyframe(unit) { PacketKind::Keyframe } else { PacketKind::Frame };
+ match webcam.send(kind, time, unit.clone()) {
+ MirrorSend::Queued => {}
+ MirrorSend::NeedKeyframe | MirrorSend::Dropped => dropped += 1,
+ MirrorSend::Closed => break,
+ }
+ }
+ println!("Stopped sharing the webcam ({dropped} frames dropped to keep up).");
+}
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index 5327b28..eabfab1 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -332,6 +332,32 @@ pub trait Platform: Send + Sync + 'static {
fn storage_delete(&self, _path: &str, _confirmed: bool) -> Result<(), crate::StorageError> {
Err(crate::StorageError::Unsupported)
}
+
+ /// Where a phone's webcam video stream goes on this PC when it starts
+ /// streaming (`docs/protocol/webcam.md`). `None` refuses the stream.
+ fn webcam_sink(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ ) -> Option<std::sync::Arc<dyn crate::WebcamSink>> {
+ None
+ }
+
+ /// A PC asked this phone to start streaming its camera (or updated camera /
+ /// resolution while already streaming): prompt the user for consent (or
+ /// update the running stream) and stream with [`Node::webcam_open`](crate::Node::webcam_open).
+ fn webcam_requested(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ _options: &crate::WebcamStart,
+ ) -> Result<(), String> {
+ Err("this device doesn't stream a camera".into())
+ }
+
+ /// The PC stopped using this phone's webcam: stop streaming.
+ fn webcam_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}
+
+ /// The PC's webcam decoder needs a fresh keyframe (`webcam.keyframe`).
+ fn webcam_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}
}
/// A platform that does nothing; useful for tests and headless tools.
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 437e115..2730bff 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -202,4 +202,9 @@ pub enum NodeEvent {
device: DeviceId,
path: String,
},
+ /// A paired phone's webcam stream started or stopped arriving on this PC.
+ Webcam {
+ device: DeviceId,
+ on: bool,
+ },
}
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index 978843b..b81deba 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -343,6 +343,7 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[
("toggles", true),
("pc_actions", true),
("mirroring", true),
+ ("webcam", true),
// Browsing the phone's storage on a PC is opt-in.
("storage", false),
// Controlling this PC's mouse and keyboard is opt-in.
@@ -849,8 +850,10 @@ pub const FEATURES: &[FeatureDef] = &[
group: FeatureGroup::Camera,
requires: &[
phone("camera.stream", Unlock::Permission(Permission::Camera)),
+ desktop("camera.virtual", UPDATE),
desktop("addon.vcam", Unlock::Addon("vcam")),
WindowsBuildAtLeast(22000),
+ DeviceToggle("webcam"),
],
partial: None,
},
@@ -934,6 +937,7 @@ mod tests {
"deck.actions",
"mirror.view",
"mirror.listen",
+ "camera.virtual",
];
fn pc() -> DeviceFacts {
@@ -1123,8 +1127,13 @@ mod tests {
fn old_systems_are_unsupported() {
let phone =
facts(DeviceKind::Phone, "android", "10", PowerLevel::Elevated, &["mirror.virtual_display"]);
- let win10 =
- facts(DeviceKind::Desktop, "windows", "10.0.19045", PowerLevel::NotApplicable, &["addon.vcam"]);
+ let win10 = facts(
+ DeviceKind::Desktop,
+ "windows",
+ "10.0.19045",
+ PowerLevel::NotApplicable,
+ &["camera.virtual", "addon.vcam"],
+ );
let m = matrix_with(&phone, &win10, &HashMap::new());
assert_eq!(
m.state("mirroring.app_windows"),
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index ab272d3..28bd743 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -29,6 +29,7 @@ pub mod storage;
mod store;
pub mod toggles;
mod transfer;
+pub mod webcam;
pub use actions::{PC_WAKE, PowerAction};
pub use calls::CallCommand;
@@ -60,7 +61,7 @@ pub use nectarlink_protocol::{
PhoneToggles, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, SmsMessage, SmsPart,
SmsThread, StorageChanged, StorageDelete, StorageEntries, StorageEntry, StorageList, StorageMkdir,
StorageRead, StorageReadMeta, StorageRename, StorageWriteAccept, StorageWriteDone, StorageWriteOffer,
- TouchAction,
+ TouchAction, WebcamConfig, WebcamStart,
calls::{
CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,
SHOW as CALLS_SHOW, STATE as CALLS_STATE,
@@ -89,6 +90,11 @@ pub use nectarlink_protocol::{
FLASHLIGHT as TOGGLES_FLASHLIGHT, READ as TOGGLES_READ, RINGER as TOGGLES_RINGER,
SHOW as TOGGLES_SHOW, VOLUME as TOGGLES_VOLUME, WIFI as TOGGLES_WIFI,
},
+ webcam::{
+ ADDON_VCAM as WEBCAM_ADDON_VCAM, CAMERA_BACK as WEBCAM_CAMERA_BACK,
+ CAMERA_FRONT as WEBCAM_CAMERA_FRONT, H264 as WEBCAM_H264, STREAM as WEBCAM_STREAM,
+ VIRTUAL as WEBCAM_VIRTUAL,
+ },
},
pairing::PairingUri,
};
@@ -100,6 +106,7 @@ pub use transfer::{
Direction, FileSource, OutgoingFile, RECORDER, RecordingMarker, Transfer, TransferFailure, TransferState,
outgoing_paths, safe_file_name,
};
+pub use webcam::{TOGGLE as WEBCAM_TOGGLE, WebcamSink};
pub(crate) fn device_id(key: &iroh::PublicKey) -> DeviceId {
DeviceId(*key.as_bytes())
diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rs
index 93ea674..35a4da9 100644
--- a/core/nectarlink-core/src/mirror.rs
+++ b/core/nectarlink-core/src/mirror.rs
@@ -429,47 +429,53 @@ pub(crate) async fn open(shared: &Arc<Shared>, session: &Session, audio: bool) -
if !shared.toggle_on(&session.peer, TOGGLE) {
return Err(Error::Denied);
}
- let (mut send, mut recv) = session.conn.open_bi().await.map_err(crate::error::net)?;
+ let (mut send, recv) = session.conn.open_bi().await.map_err(crate::error::net)?;
let op = if audio { mirror::OP_AUDIO } else { mirror::OP_VIDEO };
let header = StreamHeader { svc: mirror::SERVICE.into(), op: op.into(), v: mirror::VERSION };
write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;
- // Sound and video go out as soon as they're written; sound first, as a
- // gap in it is the more noticeable.
- let _ = send.set_priority(if audio { 2 } else { 1 });
- let (queue, mut packets) =
- mpsc::channel::<(PacketKind, u64, Vec<u8>)>(if audio { AUDIO_QUEUE } else { QUEUE });
- let closed = Arc::new(AtomicBool::new(false));
- let done = closed.clone();
- let stop = Arc::new(tokio::sync::Notify::new());
- let stopped = stop.clone();
- tokio::spawn(async move {
- let mut ended = Box::pin(async move {
- // The PC stops reading (STOP_SENDING) when it's done watching.
- let _ = recv.read_to_end(64).await;
- });
- loop {
- let next = tokio::select! {
- _ = &mut ended => break,
- _ = stopped.notified() => break,
- next = packets.recv() => next,
- };
- let Some((kind, time, data)) = next else { break };
- if done.load(Ordering::Acquire) {
- break;
- }
- let Ok(header) = video_packet_header(kind, time, data.len()) else { continue };
- let written = async {
- send.write_all(&header).await?;
- send.write_all(&data).await
- };
- if written.await.is_err() {
- break;
+ Ok(MirrorStream::spawn_stream(send, recv, audio))
+}
+
+impl MirrorStream {
+ pub(crate) fn spawn_stream(mut send: SendStream, mut recv: RecvStream, audio: bool) -> MirrorStream {
+ // Sound and video go out as soon as they're written; sound first, as a
+ // gap in it is the more noticeable.
+ let _ = send.set_priority(if audio { 2 } else { 1 });
+ let (queue, mut packets) =
+ mpsc::channel::<(PacketKind, u64, Vec<u8>)>(if audio { AUDIO_QUEUE } else { QUEUE });
+ let closed = Arc::new(AtomicBool::new(false));
+ let done = closed.clone();
+ let stop = Arc::new(tokio::sync::Notify::new());
+ let stopped = stop.clone();
+ tokio::spawn(async move {
+ let mut ended = Box::pin(async move {
+ // The PC stops reading (STOP_SENDING) when it's done watching.
+ let _ = recv.read_to_end(64).await;
+ });
+ loop {
+ let next = tokio::select! {
+ _ = &mut ended => break,
+ _ = stopped.notified() => break,
+ next = packets.recv() => next,
+ };
+ let Some((kind, time, data)) = next else { break };
+ if done.load(Ordering::Acquire) {
+ break;
+ }
+ let Ok(header) = video_packet_header(kind, time, data.len()) else { continue };
+ let written = async {
+ send.write_all(&header).await?;
+ send.write_all(&data).await
+ };
+ if written.await.is_err() {
+ break;
+ }
}
- }
- done.store(true, Ordering::Release);
- let _ = send.finish();
- });
- Ok(MirrorStream { queue, closed, stop, resyncing: Mutex::new(false), audio })
+ done.store(true, Ordering::Release);
+ let _ = send.finish();
+ });
+ MirrorStream { queue, closed, stop, resyncing: Mutex::new(false), audio }
+ }
}
impl Shared {
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 0ec58b8..d308bc6 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -128,6 +128,8 @@ pub(crate) struct Shared {
pub(crate) deck: crate::deck::Current,
/// Stop signals for phone screens shown here, by phone.
pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,
+ /// Stop signals for phone webcam streams arriving here, by phone.
+ pub(crate) webcam_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.
@@ -320,6 +322,7 @@ impl Shared {
lock(&self.storage).remove_peer(peer);
self.toggles.remove_peer(peer);
self.deck.remove_peer(peer);
+ self.stop_webcam(peer);
if existed {
self.emit(NodeEvent::DeviceRemoved(*peer));
}
@@ -654,6 +657,7 @@ impl Node {
wake_info: Default::default(),
deck: Default::default(),
mirror_stops: Mutex::new(HashMap::new()),
+ webcam_stops: Mutex::new(HashMap::new()),
remote: Mutex::new(Default::default()),
storage: Mutex::new(Default::default()),
data_dir: config.data_dir.clone(),
@@ -902,6 +906,16 @@ impl Node {
st.remove_peer(&peer);
}
}
+ if toggle == crate::webcam::TOGGLE && !enabled {
+ self.shared.stop_webcam(&peer);
+ let platform = self.shared.platform.clone();
+ drop(self.shared.runtime.spawn_blocking(move || platform.webcam_stop_requested(&peer)));
+ if let Some(session) = self.shared.session(&peer) {
+ self.shared.runtime.spawn(async move {
+ let _ = crate::webcam::stop(&session).await;
+ });
+ }
+ }
Ok(())
}
@@ -1105,6 +1119,36 @@ impl Node {
crate::mirror::open(&self.shared, &session, true).await
}
+ // ---- Webcam (docs/protocol/webcam.md) ----
+
+ /// Asks a paired phone to start streaming its camera as a webcam.
+ /// Video then arrives through [`Platform::webcam_sink`](crate::Platform::webcam_sink).
+ pub async fn webcam_start(&self, peer: DeviceId, options: crate::WebcamStart) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::webcam::start(&self.shared, &session, options).await
+ }
+
+ /// Stops a webcam stream with `peer` (either direction) and tells `peer`.
+ pub async fn webcam_stop(&self, peer: DeviceId) {
+ self.shared.stop_webcam(&peer);
+ if let Ok(session) = self.connected(&peer) {
+ let _ = crate::webcam::stop(&session).await;
+ }
+ }
+
+ /// Asks a phone for a fresh H.264 keyframe on the webcam stream.
+ pub async fn webcam_keyframe(&self, peer: DeviceId) {
+ if let Ok(session) = self.connected(&peer) {
+ crate::webcam::request_keyframe(&session).await;
+ }
+ }
+
+ /// Opens this phone's camera stream to a paired PC.
+ pub async fn webcam_open(&self, peer: DeviceId) -> Result<crate::MirrorStream> {
+ let session = self.connected(&peer)?;
+ crate::webcam::open(&self.shared, &session).await
+ }
+
// ---- Messages (docs/protocol/sms.md) ----
/// This phone's messages changed (in `thread`, or anywhere): connected
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 7630c9f..4320f89 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -335,6 +335,7 @@ fn is_background_rpc(t: &str) -> bool {
| types::PHOTOS_GET
| types::MIRROR_START
| types::MIRROR_APPS
+ | types::WEBCAM_START
| types::STORAGE_LIST
| types::STORAGE_MKDIR
| types::STORAGE_RENAME
@@ -408,6 +409,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
t if t.starts_with("contacts.") && crate::contacts::handle(shared, session, &env).await? => {}
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("remote.") && crate::remote::handle(shared, session, &env).await? => {}
t if t.starts_with("phone.toggle") && crate::toggles::handle(shared, session, &env).await? => {}
t if t.starts_with("deck.") && crate::deck::handle(shared, session, &env).await? => {}
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index da5e08a..059765f 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -626,6 +626,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::webcam::SERVICE
+ && h.op == nectarlink_protocol::messages::webcam::OP_VIDEO
+ && h.v == nectarlink_protocol::messages::webcam::VERSION =>
+ {
+ crate::webcam::receive(shared, session.peer, send, recv).await;
+ }
Some(h)
if h.svc == nectarlink_protocol::messages::remote::SERVICE
&& h.op == nectarlink_protocol::messages::remote::OP_MOTION
diff --git a/core/nectarlink-core/src/webcam.rs b/core/nectarlink-core/src/webcam.rs
new file mode 100644
index 0000000..2f1fd44
--- /dev/null
+++ b/core/nectarlink-core/src/webcam.rs
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Phone as webcam (`docs/protocol/webcam.md`): a phone streams encoded H.264
+//! video from its camera on a dedicated QUIC stream (`webcam/video`), either
+//! started directly from the phone's Webcam screen or after the phone's user
+//! accepts a PC's `webcam.start` request.
+
+use std::sync::Arc;
+
+use iroh::endpoint::{RecvStream, SendStream, VarInt};
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode, PacketKind,
+ messages::{StreamHeader, WebcamConfig, WebcamStart, types, webcam},
+ read_video_packet, write_frame,
+};
+
+use crate::{Error, MirrorStream, Result, events::NodeEvent, node::Shared, session::Session};
+
+/// The device toggle that allows webcam streaming for a device.
+pub const TOGGLE: &str = "webcam";
+
+/// What the PC's app gets of a phone's webcam stream. Called from the core's
+/// threads; must return quickly (hand decoding off to a dedicated thread).
+pub trait WebcamSink: Send + Sync {
+ /// The stream's format: first, and again whenever camera or resolution changes.
+ fn config(&self, config: WebcamConfig);
+ /// Encoded video (Annex B H.264), `keyframe` when it starts fresh (SPS+PPS+IDR).
+ fn packet(&self, keyframe: bool, 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 WebcamSink {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("WebcamSink")
+ }
+}
+
+// ---- The PC ----
+
+pub(crate) async fn start(shared: &Shared, session: &Session, options: WebcamStart) -> Result<()> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Err(Error::Denied);
+ }
+ if !options.is_valid() {
+ return Err(Error::Protocol("invalid webcam options".into()));
+ }
+ let env = Envelope::new(types::WEBCAM_START, &options)?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::WEBCAM_OK)?;
+ Ok(())
+}
+
+pub(crate) async fn stop(session: &Session) -> Result<()> {
+ session.send(Envelope::empty(types::WEBCAM_STOP)).await
+}
+
+pub(crate) async fn request_keyframe(session: &Session) {
+ let _ = session.send(Envelope::empty(types::WEBCAM_KEYFRAME)).await;
+}
+
+/// A phone opened a `webcam/video` 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(webcam::STOPPED));
+ let _ = recv.stop(VarInt::from_u32(webcam::STOPPED));
+ };
+ let supports = shared.local_capabilities().iter().any(|c| c == webcam::VIRTUAL);
+ if !supports || !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 => {
+ WebcamConfig::from_cbor(&p.data).ok().filter(WebcamConfig::is_valid)
+ }
+ _ => None,
+ };
+ let Some(config) = first else {
+ tracing::warn!("a phone sent a webcam format this PC can't decode");
+ return refuse(send, recv);
+ };
+ let Some(sink) = shared.platform.webcam_sink(&peer) else {
+ return refuse(send, recv);
+ };
+ let stopped = shared.new_webcam_stop(&peer);
+ shared.emit(NodeEvent::Webcam { 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 WebcamConfig::from_cbor(&p.data) {
+ Ok(config) if config.is_valid() => sink.config(config),
+ _ => {
+ tracing::warn!("a phone sent a webcam format this PC can't decode");
+ break;
+ }
+ },
+ Ok(Some(p)) => sink.packet(p.kind == PacketKind::Keyframe, p.time_us, p.data),
+ Ok(None) => break,
+ Err(e) => {
+ tracing::debug!(error = %e, "webcam stream ended");
+ break;
+ }
+ }
+ }
+ let _ = recv.stop(VarInt::from_u32(webcam::STOPPED));
+ let _ = send.finish();
+ sink.ended();
+ if shared.clear_webcam_stop(&peer, &stopped) {
+ shared.emit(NodeEvent::Webcam { 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::WEBCAM_START => {
+ let options: WebcamStart = env.body()?;
+ let reply = if !shared.toggle_on(&peer, TOGGLE) {
+ Envelope::error(ErrorCode::Denied, "webcam is off for this device")
+ } else if !options.is_valid() {
+ Envelope::error(ErrorCode::BadMessage, "invalid webcam options")
+ } else if !shared.local_capabilities().iter().any(|c| c == webcam::STREAM) {
+ Envelope::error(ErrorCode::Unsupported, "this device doesn't stream a camera")
+ } else {
+ match tokio::task::spawn_blocking(move || platform.webcam_requested(&peer, &options))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ Ok(()) => Envelope::empty(types::WEBCAM_OK),
+ Err(reason) => {
+ tracing::warn!(reason, "can't ask to start the webcam");
+ Envelope::error(ErrorCode::Internal, "the phone couldn't start the webcam")
+ }
+ }
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ }
+ types::WEBCAM_STOP => {
+ shared.stop_webcam(&peer);
+ tokio::task::spawn_blocking(move || platform.webcam_stop_requested(&peer));
+ if env.id.is_some() {
+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;
+ }
+ }
+ types::WEBCAM_KEYFRAME => {
+ tokio::task::spawn_blocking(move || platform.webcam_keyframe_requested(&peer));
+ }
+ _ => return Ok(false),
+ }
+ Ok(true)
+}
+
+/// Opens a webcam video stream from this phone to a connected PC.
+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: webcam::SERVICE.into(), op: webcam::OP_VIDEO.into(), v: webcam::VERSION };
+ write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;
+ Ok(MirrorStream::spawn_stream(send, recv, false))
+}
+
+impl Shared {
+ fn new_webcam_stop(&self, peer: &DeviceId) -> Arc<tokio::sync::Notify> {
+ let signal = Arc::new(tokio::sync::Notify::new());
+ if let Some(prev) =
+ self.webcam_stops.lock().unwrap_or_else(|e| e.into_inner()).insert(*peer, signal.clone())
+ {
+ prev.notify_one();
+ }
+ signal
+ }
+
+ fn clear_webcam_stop(&self, peer: &DeviceId, signal: &Arc<tokio::sync::Notify>) -> bool {
+ let mut stops = self.webcam_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_webcam(&self, peer: &DeviceId) {
+ if let Some(signal) = self.webcam_stops.lock().unwrap_or_else(|e| e.into_inner()).remove(peer) {
+ signal.notify_one();
+ self.emit(NodeEvent::Webcam { device: *peer, on: false });
+ }
+ }
+}
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index cc4b717..d106d82 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -36,6 +36,8 @@ struct RecordingPlatform {
mirror_asks: Mutex<Vec<String>>,
/// What a PC got of a phone's screen.
screen: Arc<ScreenSink>,
+ webcam_asks: Mutex<Vec<String>>,
+ webcam: Arc<TestWebcamSink>,
/// Photos `open_photo` finds, by ID.
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
/// Optional barrier `open_photo` waits on to simulate a slow platform call.
@@ -126,6 +128,27 @@ impl Platform for RecordingPlatform {
) {
self.mirror_asks.lock().unwrap().push(format!("{input:?} on {session}"));
}
+ 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())
+ }
+ fn webcam_requested(
+ &self,
+ _peer: &nectarlink_core::DeviceId,
+ options: &nectarlink_core::WebcamStart,
+ ) -> Result<(), String> {
+ self.webcam_asks
+ .lock()
+ .unwrap()
+ .push(format!("start {} {}x{} @ {}", options.camera, options.width, options.height, options.fps));
+ Ok(())
+ }
+ fn webcam_stop_requested(&self, _peer: &nectarlink_core::DeviceId) {
+ self.webcam_asks.lock().unwrap().push("stop".into());
+ }
+ fn webcam_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId) {
+ self.webcam_asks.lock().unwrap().push("keyframe".into());
+ }
fn phone_apps(&self) -> Result<Vec<nectarlink_core::PhoneApp>, String> {
let app = |pkg: &str, label: &str, icon: usize| nectarlink_core::PhoneApp {
pkg: pkg.into(),
@@ -474,6 +497,30 @@ impl nectarlink_core::MirrorSink for ScreenSink {
}
}
+#[derive(Debug, Default)]
+struct TestWebcamSink {
+ got: Mutex<Vec<String>>,
+}
+
+impl nectarlink_core::WebcamSink for TestWebcamSink {
+ fn config(&self, config: nectarlink_core::WebcamConfig) {
+ self.got
+ .lock()
+ .unwrap()
+ .push(format!("config {} {}x{} @ {}", config.camera, config.width, config.height, config.fps));
+ }
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
+ self.got.lock().unwrap().push(format!(
+ "{} {time_us} {}",
+ if keyframe { "key" } else { "frame" },
+ data.len()
+ ));
+ }
+ fn ended(&self) {
+ self.got.lock().unwrap().push("ended".into());
+ }
+}
+
struct TestDevice {
node: Node,
events: Receiver<NodeEvent>,
@@ -2881,3 +2928,76 @@ async fn phone_storage_lists_reads_ranges_writes_resumes_mutates_and_enforces_se
));
}
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn the_phone_camera_streams_to_the_pc_as_a_webcam() {
+ use nectarlink_core::{MirrorSend, PacketKind};
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::WEBCAM_VIRTUAL]).await;
+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::WEBCAM_STREAM]).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ let options = nectarlink_core::WebcamStart {
+ camera: nectarlink_core::WEBCAM_CAMERA_BACK.into(),
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ bitrate: 6_000_000,
+ };
+ with_timeout("webcam_start", pc.node.webcam_start(phone_id, options.clone())).await.unwrap();
+ assert_eq!(*phone.platform.webcam_asks.lock().unwrap(), ["start back 1920x1080 @ 30"]);
+
+ let stream = Arc::new(with_timeout("webcam_open", phone.node.webcam_open(pc_id)).await.unwrap());
+ let config = nectarlink_core::WebcamConfig {
+ codec: nectarlink_core::WEBCAM_H264.into(),
+ width: 1920,
+ height: 1080,
+ camera: nectarlink_core::WEBCAM_CAMERA_BACK.into(),
+ fps: 30,
+ };
+ let sender = stream.clone();
+ let sent = tokio::task::spawn_blocking(move || {
+ [
+ sender.send(PacketKind::Config, 0, config.to_cbor()),
+ sender.send(PacketKind::Keyframe, 1, vec![0; 48_000]),
+ sender.send(PacketKind::Frame, 33_333, vec![0; 3_200]),
+ ]
+ })
+ .await
+ .unwrap();
+ assert!(sent.iter().all(|s| *s == MirrorSend::Queued), "{sent:?}");
+ wait_for(&mut pc, "webcam on", |e| matches!(e, NodeEvent::Webcam { on: true, .. }).then_some(())).await;
+
+ let sink = pc.platform.webcam.clone();
+ let deadline = tokio::time::Instant::now() + WAIT;
+ while sink.got.lock().unwrap().len() < 3 && tokio::time::Instant::now() < deadline {
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert_eq!(*sink.got.lock().unwrap(), ["config back 1920x1080 @ 30", "key 1 48000", "frame 33333 3200"]);
+
+ pc.node.webcam_keyframe(phone_id).await;
+ pc.node.webcam_stop(phone_id).await;
+ wait_for(&mut pc, "webcam off", |e| matches!(e, NodeEvent::Webcam { on: false, .. }).then_some(())).await;
+
+ let deadline = tokio::time::Instant::now() + WAIT;
+ while !stream.is_closed() && tokio::time::Instant::now() < deadline {
+ let s = stream.clone();
+ tokio::task::spawn_blocking(move || s.send(PacketKind::Frame, 0, vec![0])).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert!(stream.is_closed(), "the phone's webcam stream closes");
+
+ for wanted in ["keyframe", "stop"] {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while !phone.platform.webcam_asks.lock().unwrap().iter().any(|a| a == wanted) {
+ let asks = phone.platform.webcam_asks.lock().unwrap().clone();
+ assert!(std::time::Instant::now() < deadline, "{wanted}: {asks:?}");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+
+ // Turning off the webcam device toggle refuses new requests.
+ phone.node.set_device_toggle(pc_id, "webcam", false).unwrap();
+ let refused = pc.node.webcam_start(phone_id, options).await;
+ assert!(matches!(refused, Err(Error::Denied)), "{refused:?}");
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 2727fd9..308cb8b 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -496,6 +496,12 @@ pub enum Event {
id: String,
state: DeckState,
},
+ /// A paired phone's camera started or stopped streaming as a webcam
+ /// (PCs only).
+ Webcam {
+ id: String,
+ on: bool,
+ },
/// A paired PC asked to browse this phone's storage while `storage` is off
/// (phones only).
StorageRequested {
@@ -794,6 +800,23 @@ pub fn mirror_audio_config(rate: u32, channels: u8) -> Vec<u8> {
core::MirrorAudioConfig { codec: core::MIRROR_PCM.into(), rate, channels }.to_cbor()
}
+/// The bytes of a config packet for an H.264 webcam stream (`docs/protocol/webcam.md`).
+#[uniffi::export]
+pub fn webcam_config(width: u32, height: u32, camera: String, fps: u32) -> Vec<u8> {
+ core::WebcamConfig { codec: core::WEBCAM_H264.into(), width, height, camera, fps }.to_cbor()
+}
+
+/// What a PC asked the phone's camera to stream (`docs/protocol/webcam.md`).
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct WebcamOptions {
+ /// `"back"` or `"front"`.
+ pub camera: String,
+ pub width: u32,
+ pub height: u32,
+ pub fps: u32,
+ pub bitrate: u32,
+}
+
/// A conversation (docs/protocol/sms.md).
#[derive(Clone, PartialEq, Eq, uniffi::Record)]
pub struct SmsThread {
@@ -1439,6 +1462,7 @@ impl From<NodeEvent> for Event {
NodeEvent::Mirroring { device, session, on } => {
Event::Mirroring { id: device.to_string(), session, on }
}
+ NodeEvent::Webcam { device, on } => Event::Webcam { id: device.to_string(), on },
NodeEvent::RemoteInputRequested { device } => {
Event::RemoteInputRequested { id: device.to_string() }
}
@@ -1645,6 +1669,14 @@ pub trait Platform: Send + Sync {
/// The PC's mouse or keyboard on the mirrored screen (only while this
/// phone offers `mirror.input`) or an app window. Return quickly.
fn mirror_input(&self, pc_id: String, session: u32, input: MirrorInputEvent);
+ /// A PC asked for this phone's camera as a webcam: start streaming (or
+ /// ask the user) and call `webcam_open`. False if it can't or the user
+ /// declined.
+ 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);
+ /// The PC needs a fresh H.264 keyframe on the webcam stream.
+ fn webcam_keyframe_requested(&self, pc_id: String);
/// A PC asked for the apps it may open in windows (launchable ones).
fn phone_apps(&self) -> Vec<PhoneApp>;
/// A PC asked for the latest conversations, newest first.
@@ -1769,6 +1801,26 @@ impl core::Platform for PlatformAdapter {
fn mirror_input(&self, peer: &DeviceId, session: u32, input: core::MirrorInput) {
self.0.mirror_input(peer.to_string(), session, input.into());
}
+ fn webcam_requested(&self, peer: &DeviceId, options: &core::WebcamStart) -> Result<(), String> {
+ let options = WebcamOptions {
+ camera: options.camera.clone(),
+ width: options.width,
+ height: options.height,
+ fps: options.fps,
+ bitrate: options.bitrate,
+ };
+ if self.0.webcam_requested(peer.to_string(), options) {
+ Ok(())
+ } else {
+ Err("the phone couldn't".into())
+ }
+ }
+ fn webcam_stop_requested(&self, peer: &DeviceId) {
+ self.0.webcam_stop_requested(peer.to_string());
+ }
+ fn webcam_keyframe_requested(&self, peer: &DeviceId) {
+ self.0.webcam_keyframe_requested(peer.to_string());
+ }
fn phone_apps(&self) -> Result<Vec<core::PhoneApp>, String> {
Ok(self
.0
@@ -2431,6 +2483,24 @@ impl NectarlinkNode {
self.run(async move { Ok(Arc::new(MirrorStream(node.mirror_open_audio(id).await?))) }).await
}
+ /// Opens this phone's camera stream to a paired PC (`docs/protocol/webcam.md`).
+ pub async fn webcam_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.webcam_open(id).await?))) }).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)?;
+ let node = self.node.clone();
+ self.run(async move {
+ node.webcam_stop(id).await;
+ Ok(())
+ })
+ .await
+ }
+
/// This phone's messages changed (in `thread`, or anywhere when null):
/// PCs that show them catch up.
pub async fn sms_changed(&self, thread: Option<String>) {
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 90e8288..94fb4ae 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -87,6 +87,10 @@ 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 WEBCAM_START: &str = "webcam.start";
+ pub const WEBCAM_STOP: &str = "webcam.stop";
+ pub const WEBCAM_KEYFRAME: &str = "webcam.keyframe";
+ pub const WEBCAM_OK: &str = "webcam.ok";
}
/// What kind of device this is.
@@ -950,6 +954,113 @@ impl MirrorAudioConfig {
}
}
+// ---- Phone as webcam (docs/protocol/webcam.md) ----
+
+pub mod webcam {
+ /// Offered by phones that stream their camera as a webcam.
+ pub const STREAM: &str = "camera.stream";
+ /// Offered by PCs that receive and decode a phone's webcam stream.
+ pub const VIRTUAL: &str = "camera.virtual";
+ /// Offered by PCs where the Windows virtual camera COM add-on is registered.
+ pub const ADDON_VCAM: &str = "addon.vcam";
+ pub const SERVICE: &str = "webcam";
+ pub const OP_VIDEO: &str = "video";
+ pub const VERSION: u32 = 1;
+ /// Stream reset code: webcam stopped.
+ pub const STOPPED: u32 = 12;
+ pub const H264: &str = "h264";
+ pub const CAMERA_BACK: &str = "back";
+ pub const CAMERA_FRONT: &str = "front";
+}
+
+fn default_webcam_camera() -> String {
+ webcam::CAMERA_BACK.to_owned()
+}
+
+fn default_webcam_fps() -> u32 {
+ 30
+}
+
+fn default_webcam_bitrate() -> u32 {
+ 6_000_000
+}
+
+/// Body of `webcam.start`: ask a paired phone to stream its camera (or update
+/// camera/resolution while already streaming).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct WebcamStart {
+ /// `"back"` or `"front"`.
+ #[serde(default = "default_webcam_camera")]
+ pub camera: String,
+ /// Requested frame width in pixels (e.g. 1280, 1920, 3840).
+ pub width: u32,
+ /// Requested frame height in pixels (e.g. 720, 1080, 2160).
+ pub height: u32,
+ /// Target frames per second (`1..=60`).
+ #[serde(default = "default_webcam_fps")]
+ pub fps: u32,
+ /// Target bitrate in bits per second (`100_000..=50_000_000`).
+ #[serde(default = "default_webcam_bitrate")]
+ pub bitrate: u32,
+}
+
+impl Default for WebcamStart {
+ fn default() -> Self {
+ Self {
+ camera: default_webcam_camera(),
+ width: 1280,
+ height: 720,
+ fps: default_webcam_fps(),
+ bitrate: default_webcam_bitrate(),
+ }
+ }
+}
+
+impl WebcamStart {
+ pub fn is_valid(&self) -> bool {
+ (self.camera == webcam::CAMERA_BACK || self.camera == webcam::CAMERA_FRONT)
+ && (320..=3840).contains(&self.width)
+ && (240..=2160).contains(&self.height)
+ && (1..=60).contains(&self.fps)
+ && (100_000..=50_000_000).contains(&self.bitrate)
+ }
+}
+
+/// The format of a webcam stream (a `PacketKind::Config` packet's payload, in CBOR).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct WebcamConfig {
+ /// `"h264"`.
+ pub codec: String,
+ pub width: u32,
+ pub height: u32,
+ /// `"back"` or `"front"`.
+ #[serde(default = "default_webcam_camera")]
+ pub camera: String,
+ /// Frames per second.
+ #[serde(default = "default_webcam_fps")]
+ pub fps: u32,
+}
+
+impl WebcamConfig {
+ pub fn to_cbor(&self) -> Vec<u8> {
+ let mut out = Vec::new();
+ ciborium::into_writer(self, &mut out).expect("writing to a Vec cannot fail");
+ out
+ }
+
+ pub fn from_cbor(bytes: &[u8]) -> Result<WebcamConfig, crate::ProtocolError> {
+ ciborium::from_reader(bytes).map_err(|e| crate::ProtocolError::BadMessage(e.to_string()))
+ }
+
+ pub fn is_valid(&self) -> bool {
+ self.codec == webcam::H264
+ && (1..=8192).contains(&self.width)
+ && (1..=8192).contains(&self.height)
+ && (self.camera == webcam::CAMERA_BACK || self.camera == webcam::CAMERA_FRONT)
+ && (1..=120).contains(&self.fps)
+ }
+}
+
// ---- Messages (docs/protocol/sms.md) ----
pub mod sms {
@@ -3646,4 +3757,37 @@ mod tests {
assert!(rename.is_valid());
assert!(!StorageRename { from: "a.txt".into(), to: "a.txt".into() }.is_valid());
}
+
+ #[test]
+ fn webcam_messages_validate_and_round_trip() {
+ let start = WebcamStart::default();
+ assert!(start.is_valid());
+ let env = Envelope::new(types::WEBCAM_START, &start).unwrap();
+ let back: WebcamStart = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();
+ assert_eq!(back, start);
+
+ let front_1080 = WebcamStart {
+ camera: webcam::CAMERA_FRONT.into(),
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ bitrate: 8_000_000,
+ };
+ assert!(front_1080.is_valid());
+ assert!(!WebcamStart { camera: "telephoto".into(), ..start.clone() }.is_valid());
+ assert!(!WebcamStart { width: 100, ..start.clone() }.is_valid());
+ assert!(!WebcamStart { fps: 0, ..start }.is_valid());
+
+ let cfg = WebcamConfig {
+ codec: webcam::H264.into(),
+ width: 1280,
+ height: 720,
+ camera: webcam::CAMERA_BACK.into(),
+ fps: 30,
+ };
+ assert!(cfg.is_valid());
+ assert_eq!(WebcamConfig::from_cbor(&cfg.to_cbor()).unwrap(), cfg);
+ assert!(!WebcamConfig { codec: "vp8".into(), ..cfg.clone() }.is_valid());
+ assert!(!WebcamConfig { width: 0, ..cfg }.is_valid());
+ }
}
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index f70e8a4..18be331 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -23,6 +23,7 @@ dirs.workspace = true
hostname.workspace = true
material-colors.workspace = true
nectarlink-core.workspace = true
+nectarlink-vcam.workspace = true
qrcode.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -77,6 +78,7 @@ windows = { workspace = true, features = [
"Win32_Networking_WinSock",
"Win32_Media_Audio",
"Win32_Media_Audio_Endpoints",
+ "Win32_Media_KernelStreaming",
"Win32_Media_MediaFoundation",
] }
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index 4b0b8ea..d340799 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -183,6 +183,9 @@ END
fn main() {
println!("cargo:rerun-if-changed=src/mark.rs");
+ for qml in QML.iter().chain(QML_SINGLETONS.iter()) {
+ println!("cargo:rerun-if-changed={qml}");
+ }
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
windows_resources();
}
@@ -214,6 +217,7 @@ fn main() {
"src/bridge/photos.rs",
"src/bridge/prefs.rs",
"src/bridge/transfers.rs",
+ "src/bridge/webcam.rs",
])
.build();
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index b6a0658..9205543 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -773,6 +773,63 @@ Item {
}
}
+ // Phone as a webcam on this PC.
+ Card {
+ id: webcamHomeCard
+ width: parent.width
+ visible: home.online || webcamFeature.state === "locked"
+ readonly property var webcamFeature: home.feature("camera.webcam")
+ readonly property bool isThisPhone: (Webcam.phase === "streaming" || Webcam.phase === "asking")
+ && Webcam.activeDevice === home.deviceId
+ Column {
+ width: parent.width
+ spacing: 10
+ Row {
+ spacing: 8
+ Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ path: Icons.video
+ color: webcamHomeCard.isThisPhone ? Theme.primary : Theme.surfaceContentVariant
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Webcam")
+ role: "label"
+ muted: !webcamHomeCard.isThisPhone
+ }
+ }
+ Txt {
+ width: parent.width
+ role: "bodySmall"
+ muted: true
+ wrapMode: Text.WordWrap
+ text: webcamHomeCard.isThisPhone && Webcam.statusText.length > 0
+ ? Webcam.statusText
+ : qsTr("Use %1's camera in video calls on this PC.").arg(home.name)
+ }
+ LockChip {
+ visible: webcamHomeCard.webcamFeature.state === "locked" && label.length > 0
+ feature: webcamHomeCard.webcamFeature
+ maxWidth: parent.width
+ }
+ Button {
+ visible: webcamHomeCard.isThisPhone
+ || (home.online && (webcamHomeCard.webcamFeature.state === "available"
+ || webcamHomeCard.webcamFeature.action === "enableAddon"))
+ variant: webcamHomeCard.isThisPhone ? "tonal" : "fill"
+ size: "sm"
+ iconPath: webcamHomeCard.isThisPhone ? Icons.close : Icons.video
+ text: webcamHomeCard.isThisPhone ? qsTr("Stop webcam") : qsTr("Start webcam")
+ onClicked: {
+ if (webcamHomeCard.isThisPhone)
+ Webcam.stop()
+ else
+ Webcam.start(home.deviceId)
+ }
+ }
+ }
+ }
+
Card {
width: parent.width
Column {
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index fb094a9..1f2aa8b 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -31,6 +31,7 @@ Item {
toggles: qsTr("Phone controls"),
pc_actions: qsTr("Lock, sleep and wake this PC"),
mirroring: qsTr("Screen mirroring"),
+ webcam: qsTr("Webcam"),
storage: qsTr("Phone storage in File Explorer"),
remote_input: qsTr("Control this PC's mouse, keyboard and Deck"),
commands: qsTr("Allow running Deck commands"),
@@ -38,6 +39,7 @@ Item {
})
readonly property var toggleDescriptions: ({
+ webcam: qsTr("Use this phone's camera as a webcam on this PC."),
storage: qsTr("Show this phone's storage in File Explorer so you can browse, open and drop in files."),
commands: qsTr("Lets this phone trigger Deck tiles that run shell commands configured on this PC. Off by default — only enable for a phone you control.")
})
@@ -270,6 +272,149 @@ Item {
}
}
+ // ---- Webcam ----
+ Txt { text: qsTr("Webcam"); role: "label"; muted: true }
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ ListRow {
+ width: parent.width
+ iconPath: Icons.video
+ title: qsTr("Virtual camera add-on")
+ description: Webcam.addonRegistered
+ ? qsTr("\"Nectarlink Webcam\" is registered for Zoom, Teams, Meet and other apps.")
+ : qsTr("Set up once (needs administrator approval) so Zoom, Teams, Meet and other apps see \"Nectarlink Webcam\".")
+ Row {
+ spacing: 8
+ Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Webcam.addonBusy
+ }
+ Chip {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: Webcam.addonRegistered
+ selected: true
+ text: qsTr("Ready")
+ }
+ Button {
+ anchors.verticalCenter: parent.verticalCenter
+ variant: Webcam.addonRegistered ? "outline" : "tonal"
+ size: "sm"
+ enabled: !Webcam.addonBusy
+ text: Webcam.addonRegistered ? qsTr("Remove") : qsTr("Set up")
+ onClicked: Webcam.addonRegistered ? Webcam.removeAddon() : Webcam.setupAddon()
+ }
+ }
+ }
+ Divider { width: parent.width; visible: DeviceList.count > 1 }
+ ListRow {
+ width: parent.width
+ visible: DeviceList.count > 1
+ iconPath: Icons.phone
+ title: qsTr("Phone")
+ description: qsTr("Which phone's camera to use on this PC.")
+ Row {
+ spacing: 8
+ Repeater {
+ model: DeviceList
+ delegate: Chip {
+ required property string deviceId
+ required property string name
+ text: name
+ selected: Webcam.selectedPhone === deviceId
+ TapHandler { onTapped: Webcam.selectPhone(deviceId) }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ }
+ }
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.camera
+ title: qsTr("Resolution")
+ description: qsTr("720p uses less battery; 1080p is sharper.")
+ Segmented {
+ options: [
+ { value: "720", label: "720p" },
+ { value: "1080", label: "1080p" }
+ ]
+ value: String(Webcam.height)
+ onPicked: (value) => Webcam.setResolution(Number(value))
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.mirror
+ title: qsTr("Mirror image")
+ description: qsTr("Flip the camera picture horizontally.")
+ Toggle {
+ label: qsTr("Mirror image")
+ checked: Webcam.mirror
+ onToggled: (on) => Webcam.setMirrorImage(on)
+ }
+ }
+ Divider { width: parent.width }
+ Column {
+ width: parent.width
+ spacing: 10
+ topPadding: 8
+ Item {
+ width: parent.width
+ height: Math.max(webcamStatusLabel.height, webcamStartBtn.height)
+ Txt {
+ id: webcamStatusLabel
+ anchors.left: parent.left
+ anchors.right: webcamStartBtn.left
+ anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ role: "bodySmall"
+ muted: Webcam.phase !== "streaming"
+ elide: Text.ElideRight
+ text: Webcam.statusText.length > 0
+ ? Webcam.statusText
+ : (Webcam.selectedPhoneName.length > 0
+ ? qsTr("Preview · %1").arg(Webcam.selectedPhoneName)
+ : qsTr("Pair a phone to use its camera as a webcam"))
+ }
+ Button {
+ id: webcamStartBtn
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ enabled: DeviceList.count > 0
+ variant: Webcam.phase === "streaming" || Webcam.phase === "asking" ? "outline" : "tonal"
+ size: "sm"
+ iconPath: Webcam.phase === "streaming" || Webcam.phase === "asking" ? Icons.close : Icons.video
+ text: Webcam.phase === "streaming" || Webcam.phase === "asking"
+ ? qsTr("Stop webcam")
+ : qsTr("Start webcam")
+ onClicked: {
+ if (Webcam.phase === "streaming" || Webcam.phase === "asking")
+ Webcam.stop()
+ else
+ Webcam.start("")
+ }
+ }
+ }
+ Rectangle {
+ width: parent.width
+ height: Math.round(width * 9 / 16)
+ radius: Theme.radiusMd
+ color: "#121318"
+ border.width: 1
+ border.color: Theme.outlineVariant
+ clip: true
+ VideoView {
+ anchors.fill: parent
+ stream: "webcam"
+ }
+ }
+ }
+ }
+ }
+
// ---- Connection ----
Txt { text: qsTr("Connection"); role: "label"; muted: true }
Card {
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index b3fbef3..ee4a05f 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -33,6 +33,8 @@ pub mod photos;
pub mod prefs;
#[allow(unsafe_code)]
pub mod transfers;
+#[allow(unsafe_code)]
+pub mod webcam;
use std::{
pin::Pin,
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 1c2be15..240a055 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -270,6 +270,9 @@ impl qobject::Preferences {
start_with_windows: p.start_choice,
recordings_folder: p.custom_recordings_folder.clone(),
recordings_format: RecordingFormat::from_str_lossy(&String::from(&p.recordings_format)),
+ webcam_phone: crate::webcam::selected_phone().map(|d| d.to_string()),
+ webcam_height: crate::webcam::height(),
+ webcam_mirror: crate::webcam::mirror(),
};
save_in_background(settings);
}
diff --git a/desktop/app/src/bridge/webcam.rs b/desktop/app/src/bridge/webcam.rs
new file mode 100644
index 0000000..af28818
--- /dev/null
+++ b/desktop/app/src/bridge/webcam.rs
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `Webcam`: QML singleton exposing the Windows virtual camera add-on status,
+//! webcam preferences (phone, 720p/1080p, mirror), and live stream state.
+
+use std::pin::Pin;
+
+use cxx_qt::Threading;
+use cxx_qt_lib::QString;
+
+use crate::{
+ state::Changes,
+ webcam::{self, Phase},
+};
+
+#[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]
+ #[qproperty(bool, addon_registered, cxx_name = "addonRegistered")]
+ #[qproperty(bool, addon_busy, cxx_name = "addonBusy")]
+ #[qproperty(QString, selected_phone, cxx_name = "selectedPhone")]
+ #[qproperty(QString, selected_phone_name, cxx_name = "selectedPhoneName")]
+ #[qproperty(i32, height)]
+ #[qproperty(bool, mirror)]
+ #[qproperty(QString, phase)]
+ #[qproperty(QString, active_device, cxx_name = "activeDevice")]
+ #[qproperty(QString, status_text, cxx_name = "statusText")]
+ type Webcam = super::WebcamRust;
+ }
+
+ impl cxx_qt::Threading for Webcam {}
+ impl cxx_qt::Initialize for Webcam {}
+
+ unsafe extern "RustQt" {
+ #[qinvokable]
+ #[cxx_name = "setupAddon"]
+ fn setup_addon(self: &Webcam);
+ #[qinvokable]
+ #[cxx_name = "removeAddon"]
+ fn remove_addon(self: &Webcam);
+ #[qinvokable]
+ #[cxx_name = "selectPhone"]
+ fn select_phone(self: &Webcam, device: &QString);
+ #[qinvokable]
+ #[cxx_name = "setResolution"]
+ fn set_resolution(self: &Webcam, height: i32);
+ #[qinvokable]
+ #[cxx_name = "setMirrorImage"]
+ fn set_mirror_image(self: &Webcam, on: bool);
+ #[qinvokable]
+ fn start(self: &Webcam, device: &QString);
+ #[qinvokable]
+ fn stop(self: &Webcam);
+ }
+}
+
+#[derive(Default)]
+pub struct WebcamRust {
+ addon_registered: bool,
+ addon_busy: bool,
+ selected_phone: QString,
+ selected_phone_name: QString,
+ height: i32,
+ mirror: bool,
+ phase: QString,
+ active_device: QString,
+ status_text: QString,
+}
+
+impl cxx_qt::Initialize for qobject::Webcam {
+ fn initialize(self: Pin<&mut Self>) {
+ super::subscribe(
+ self.qt_thread(),
+ Changes::WEBCAM | Changes::DEVICES | Changes::CAPABILITIES,
+ Self::refresh,
+ );
+ }
+}
+
+impl qobject::Webcam {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let hub = &crate::core_host::host().hub;
+ self.as_mut().set_addon_registered(webcam::addon_registered());
+ self.as_mut().set_addon_busy(webcam::addon_busy());
+ self.as_mut().set_height(webcam::height() as i32);
+ self.as_mut().set_mirror(webcam::mirror());
+
+ let selected = webcam::selected_phone();
+ let selected_id = selected.map(|id| id.to_string()).unwrap_or_default();
+ let selected_name = selected.and_then(|id| hub.read(|s| s.name_of(&id))).unwrap_or_default();
+ self.as_mut().set_selected_phone(QString::from(&selected_id));
+ self.as_mut().set_selected_phone_name(QString::from(&selected_name));
+
+ let (phase_str, active_dev, status) = match webcam::phase() {
+ Phase::Idle => ("idle", String::new(), String::new()),
+ Phase::Asking { device } => {
+ let name = hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "phone".into());
+ ("asking", device.to_string(), format!("Starting camera on {name}…"))
+ }
+ Phase::Streaming { device, width, height, fps } => {
+ let name = hub.read(|s| s.name_of(&device)).unwrap_or_else(|| "phone".into());
+ (
+ "streaming",
+ device.to_string(),
+ format!("Streaming {width} × {height} · {fps} fps from {name}"),
+ )
+ }
+ Phase::Ended { reason } => ("ended", String::new(), reason),
+ };
+ self.as_mut().set_phase(QString::from(phase_str));
+ self.as_mut().set_active_device(QString::from(&active_dev));
+ self.as_mut().set_status_text(QString::from(&status));
+ }
+
+ pub fn setup_addon(&self) {
+ webcam::setup_addon();
+ }
+
+ pub fn remove_addon(&self) {
+ webcam::remove_addon();
+ }
+
+ pub fn select_phone(&self, device: &QString) {
+ if let Some(id) = super::parse_device(device) {
+ webcam::set_selected_phone(id);
+ }
+ }
+
+ pub fn set_resolution(&self, height: i32) {
+ webcam::set_height(height.max(0) as u32);
+ }
+
+ pub fn set_mirror_image(&self, on: bool) {
+ webcam::set_mirror(on);
+ }
+
+ pub fn start(&self, device: &QString) {
+ webcam::start(super::parse_device(device));
+ }
+
+ pub fn stop(&self) {
+ webcam::stop();
+ }
+}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 4d3077e..7acd9a3 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -111,7 +111,11 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
nectarlink_core::RECORDER.into(),
nectarlink_core::TOGGLES_SHOW.into(),
nectarlink_core::STORAGE_MOUNT.into(),
+ nectarlink_core::WEBCAM_VIRTUAL.into(),
];
+ if crate::win::vcam::is_registered() {
+ config.capabilities.push(nectarlink_core::WEBCAM_ADDON_VCAM.into());
+ }
let node = match Node::start(config, platform).await {
Ok(node) => node,
Err(e) => {
@@ -173,6 +177,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::send_to::on_event(&event);
crate::battery::on_event(&event);
crate::storage::on_event(&event);
+ crate::webcam::on_event(&event);
}
Err(RecvError::Lagged(missed)) => {
// Resynchronize what can be re-read; transient events are lost.
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 45ffd69..4f98262 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -37,6 +37,7 @@ mod state;
mod storage;
mod transfers;
mod updater;
+mod webcam;
mod win;
use std::{
@@ -98,6 +99,12 @@ impl Platform for DesktopPlatform {
) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {
mirror::sink(peer, session)
}
+ fn webcam_sink(
+ &self,
+ peer: &nectarlink_core::DeviceId,
+ ) -> Option<std::sync::Arc<dyn nectarlink_core::WebcamSink>> {
+ webcam::sink(peer)
+ }
fn remote_input(
&self,
peer: &nectarlink_core::DeviceId,
@@ -125,6 +132,10 @@ struct Options {
/// Quit the running app and undo what it set up in Windows (the
/// uninstaller). Data is kept.
uninstall: bool,
+ /// Elevated helper: register `nectarlink_vcam.dll` in `HKLM` and exit.
+ register_vcam: bool,
+ /// Elevated helper: unregister `nectarlink_vcam.dll` from `HKLM` and exit.
+ unregister_vcam: bool,
}
fn parse_options() -> Options {
@@ -137,6 +148,8 @@ fn parse_options() -> Options {
Some("--minimized") => options.minimized = true,
Some("--quit") => options.quit = true,
Some("--uninstall") => options.uninstall = true,
+ Some(win::vcam::REGISTER_ARG) => options.register_vcam = true,
+ Some(win::vcam::UNREGISTER_ARG) => options.unregister_vcam = true,
Some(send_to::ARG) => {
let device = args.next().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();
options.send_to = Some((device, Vec::new()));
@@ -193,6 +206,7 @@ fn uninstall() {
tracing::warn!(error = %e, "can't remove the Send to entries");
}
storage::unregister_all();
+ let _ = win::vcam::unregister_hklm();
win::toast::unregister();
startup::remove();
}
@@ -207,6 +221,24 @@ fn install_panic_logging() {
fn main() -> ExitCode {
let options = parse_options();
+ if options.register_vcam {
+ return match win::vcam::register_hklm() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(e) => {
+ eprintln!("nectarlink: register-vcam failed: {e}");
+ ExitCode::FAILURE
+ }
+ };
+ }
+ if options.unregister_vcam {
+ return match win::vcam::unregister_hklm() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(e) => {
+ eprintln!("nectarlink: unregister-vcam failed: {e}");
+ ExitCode::FAILURE
+ }
+ };
+ }
let data_dir = options.data_dir.clone().unwrap_or_else(default_data_dir);
if let Err(e) = std::fs::create_dir_all(&data_dir) {
eprintln!("nectarlink: can't create {}: {e}", data_dir.display());
@@ -266,6 +298,7 @@ fn main() -> ExitCode {
send_to::set_enabled(settings.send_to_menu);
battery::set_enabled(settings.battery_alerts);
storage::start();
+ webcam::init(&settings);
// A test instance (own data folder) leaves the user's menu and sign-in
// alone.
if options.data_dir.is_none() {
@@ -321,6 +354,7 @@ fn main() -> ExitCode {
tracing::info!(code, "shutting down");
// QML first (it holds references into Qt), then the core.
drop(engine);
+ webcam::shutdown();
storage::shutdown();
win::net::stop();
core_host::shutdown();
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index b107425..5b0be3c 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -89,6 +89,13 @@ pub struct Settings {
pub recordings_folder: Option<PathBuf>,
/// Output format for saved voice recordings (`m4a`, `mp3`, `wav`, or `flac`).
pub recordings_format: RecordingFormat,
+ /// Preferred phone for the webcam feature (`None` = first paired phone).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub webcam_phone: Option<String>,
+ /// Webcam output resolution height (`720` or `1080`).
+ pub webcam_height: u32,
+ /// Horizontally mirror the webcam video.
+ pub webcam_mirror: bool,
}
impl Default for Settings {
@@ -106,6 +113,9 @@ impl Default for Settings {
start_with_windows: None,
recordings_folder: None,
recordings_format: RecordingFormat::default(),
+ webcam_phone: None,
+ webcam_height: 720,
+ webcam_mirror: false,
}
}
}
@@ -172,6 +182,9 @@ mod tests {
start_with_windows: Some(true),
recordings_folder: Some(PathBuf::from(r"C:\Recordings")),
recordings_format: RecordingFormat::Flac,
+ webcam_phone: Some("0101".repeat(16)),
+ webcam_height: 1080,
+ webcam_mirror: true,
};
settings.save(dir.path()).unwrap();
assert_eq!(Settings::load(dir.path()), settings);
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 94f467d..e8fdfaf 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -51,6 +51,8 @@ impl Changes {
pub const TOGGLES: Changes = Changes(1 << 17);
/// This PC's Deck layout or live state (kept by crate::deck).
pub const DECK: Changes = Changes(1 << 18);
+ /// Phone as a webcam state or preferences (kept by crate::webcam).
+ pub const WEBCAM: Changes = Changes(1 << 19);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -441,7 +443,8 @@ impl AppState {
| NodeEvent::DeckLayout { .. }
| NodeEvent::DeckState { .. }
| NodeEvent::StorageRequested { .. }
- | NodeEvent::StorageChanged { .. } => Changes::NONE,
+ | NodeEvent::StorageChanged { .. }
+ | NodeEvent::Webcam { .. } => Changes::NONE,
// The gallery's own downloads (for its viewer, or the clipboard)
// aren't files the user keeps.
NodeEvent::Transfer(transfer) if crate::photos::is_private(&transfer.id) => {
diff --git a/desktop/app/src/webcam.rs b/desktop/app/src/webcam.rs
new file mode 100644
index 0000000..cbe81da
--- /dev/null
+++ b/desktop/app/src/webcam.rs
@@ -0,0 +1,532 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Phone as a webcam (`docs/protocol/webcam.md`): decodes a phone's H.264
+//! camera stream on a dedicated thread, publishes BGRX frames into the
+//! shared-memory mapping read by `nectarlink_vcam.dll` (the global one the
+//! camera creates inside Windows' Frame Server, or this session's while it
+//! isn't there), and feeds the live preview `VideoView` (`stream:
+//! "webcam"`) in Settings.
+
+use std::sync::{
+ Arc, Mutex, OnceLock,
+ atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
+ mpsc::{Receiver, SyncSender, TrySendError, sync_channel},
+};
+
+use nectarlink_core::{DeviceId, Error, NodeEvent, WebcamConfig, WebcamSink, WebcamStart};
+use nectarlink_vcam::{
+ DEFAULT_MAPPING_NAME, LOCAL_MAPPING_NAME, SharedFrameMapping, render_placeholder_bgrx,
+};
+
+use crate::{
+ bridge::{app::describe, native::ffi},
+ core_host,
+ settings::Settings,
+ state::Changes,
+ win::{
+ h264::{Decoder, to_bgrx},
+ vcam::{self, VirtualCameraHandle},
+ },
+};
+
+/// Stream key used by `VideoView` in `SettingsPage.qml`.
+pub const PREVIEW_STREAM: &str = "webcam";
+
+/// Packets waiting for the decoder, at most (~2 seconds at 30 fps).
+const BACKLOG: usize = 60;
+
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub enum Phase {
+ #[default]
+ Idle,
+ Asking {
+ device: DeviceId,
+ },
+ Streaming {
+ device: DeviceId,
+ width: u32,
+ height: u32,
+ fps: u32,
+ },
+ Ended {
+ reason: String,
+ },
+}
+
+#[derive(Debug, Default)]
+struct State {
+ phase: Phase,
+ preferred_phone: Option<DeviceId>,
+ addon_registered: bool,
+ addon_busy: bool,
+ vcam_handle: Option<VirtualCameraHandle>,
+ mapping: Option<Arc<SharedFrameMapping>>,
+ /// Whether `mapping` is the camera's global one (else this session's).
+ mapping_global: bool,
+ /// When joining the global one was last tried.
+ global_tried: Option<std::time::Instant>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static MIRROR: AtomicBool = AtomicBool::new(false);
+static HEIGHT: AtomicU32 = AtomicU32::new(720);
+
+fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {
+ f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+/// Initializes shared memory, placeholder preview, and (if registered) the
+/// Windows virtual camera session.
+pub fn init(settings: &Settings) {
+ MIRROR.store(settings.webcam_mirror, Ordering::Relaxed);
+ let h = if settings.webcam_height == 1080 { 1080 } else { 720 };
+ HEIGHT.store(h, Ordering::Relaxed);
+ let preferred = settings.webcam_phone.as_deref().and_then(|s| s.parse().ok());
+ let registered = vcam::is_registered();
+ let vcam_handle = if registered {
+ match VirtualCameraHandle::start() {
+ Ok(handle) => Some(handle),
+ Err(e) => {
+ tracing::warn!(error = %e, "can't start IMFVirtualCamera session");
+ None
+ }
+ }
+ } else {
+ None
+ };
+ state(|s| {
+ s.preferred_phone = preferred;
+ s.addon_registered = registered;
+ s.vcam_handle = vcam_handle;
+ });
+ refresh_idle_frame();
+}
+
+/// Stops the virtual camera session on app exit.
+pub fn shutdown() {
+ state(|s| {
+ if let Some(mapping) = &s.mapping {
+ mapping.set_idle("");
+ }
+ s.vcam_handle = None;
+ });
+}
+
+fn save_settings(update: impl FnOnce(&mut Settings)) {
+ let dir = &core_host::host().data_dir;
+ let mut s = Settings::load(dir);
+ update(&mut s);
+ if let Err(e) = s.save(dir) {
+ tracing::warn!(error = %e, "can't save webcam settings");
+ }
+}
+
+/// Currently selected phone (`preferred_phone` if still paired, otherwise the
+/// first paired phone).
+pub fn selected_phone() -> Option<DeviceId> {
+ let preferred = state(|s| s.preferred_phone);
+ core_host::host().hub.read(|app| {
+ if let Some(id) = preferred
+ && app.devices.iter().any(|d| d.id == id)
+ {
+ return Some(id);
+ }
+ app.devices.first().map(|d| d.id)
+ })
+}
+
+pub fn set_selected_phone(device: DeviceId) {
+ state(|s| s.preferred_phone = Some(device));
+ save_settings(|s| s.webcam_phone = Some(device.to_string()));
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+}
+
+pub fn height() -> u32 {
+ HEIGHT.load(Ordering::Relaxed)
+}
+
+pub fn set_height(h: u32) {
+ let h = if h == 1080 { 1080 } else { 720 };
+ HEIGHT.store(h, Ordering::Relaxed);
+ save_settings(|s| s.webcam_height = h);
+ core_host::host().hub.changed(Changes::WEBCAM);
+}
+
+pub fn mirror() -> bool {
+ MIRROR.load(Ordering::Relaxed)
+}
+
+pub fn set_mirror(on: bool) {
+ MIRROR.store(on, Ordering::Relaxed);
+ save_settings(|s| s.webcam_mirror = on);
+ core_host::host().hub.changed(Changes::WEBCAM);
+}
+
+pub fn phase() -> Phase {
+ state(|s| s.phase.clone())
+}
+
+pub fn addon_registered() -> bool {
+ state(|s| s.addon_registered)
+}
+
+pub fn addon_busy() -> bool {
+ state(|s| s.addon_busy)
+}
+
+/// Launches the elevated helper (`--register-vcam`) when the user clicks "Set up".
+pub fn setup_addon() {
+ let already_busy = state(|s| {
+ if s.addon_busy {
+ return true;
+ }
+ s.addon_busy = true;
+ false
+ });
+ if already_busy {
+ return;
+ }
+ core_host::host().hub.changed(Changes::WEBCAM);
+ vcam::run_elevated(vcam::REGISTER_ARG, |_ok| {
+ let registered = vcam::is_registered();
+ let handle = if registered { VirtualCameraHandle::start().ok() } else { None };
+ state(|s| {
+ s.addon_busy = false;
+ s.addon_registered = registered;
+ if handle.is_some() {
+ s.vcam_handle = handle;
+ }
+ });
+ core_host::host().hub.changed(Changes::WEBCAM);
+ });
+}
+
+/// Launches the elevated helper (`--unregister-vcam`) when the user clicks "Remove".
+pub fn remove_addon() {
+ let already_busy = state(|s| {
+ if s.addon_busy {
+ return true;
+ }
+ s.addon_busy = true;
+ s.vcam_handle = None;
+ false
+ });
+ if already_busy {
+ return;
+ }
+ core_host::host().hub.changed(Changes::WEBCAM);
+ vcam::run_elevated(vcam::UNREGISTER_ARG, |_ok| {
+ let registered = vcam::is_registered();
+ state(|s| {
+ s.addon_busy = false;
+ s.addon_registered = registered;
+ });
+ core_host::host().hub.changed(Changes::WEBCAM);
+ });
+}
+
+fn phone_name_for(device: Option<DeviceId>) -> String {
+ let Some(id) = device else { return String::new() };
+ core_host::host().hub.read(|s| s.name_of(&id).unwrap_or_default())
+}
+
+/// The shared mapping to publish frames into: the camera's global one as soon
+/// as it exists (the camera creates it when an app first opens it, so look
+/// again every second until then), else this session's.
+fn mapping() -> Option<Arc<SharedFrameMapping>> {
+ state(|s| {
+ let due = s.global_tried.is_none_or(|at| at.elapsed() >= std::time::Duration::from_secs(1));
+ if !s.mapping_global && due {
+ s.global_tried = Some(std::time::Instant::now());
+ if let Ok(global) = SharedFrameMapping::open_existing(DEFAULT_MAPPING_NAME) {
+ tracing::debug!("joined the virtual camera's frame mapping");
+ s.mapping = Some(Arc::new(global));
+ s.mapping_global = true;
+ }
+ }
+ if s.mapping.is_none() {
+ s.mapping = SharedFrameMapping::open_or_create(LOCAL_MAPPING_NAME).ok().map(Arc::new);
+ }
+ s.mapping.clone()
+ })
+}
+
+/// Updates the shared-memory header and the QML preview `VideoView` with the
+/// idle placeholder frame when no stream is active.
+fn refresh_idle_frame() {
+ let is_streaming = state(|s| matches!(s.phase, Phase::Streaming { .. }));
+ if is_streaming {
+ return;
+ }
+ let phone = selected_phone();
+ let name = phone_name_for(phone);
+ if let Some(mapping) = mapping() {
+ mapping.set_idle(&name);
+ }
+ let (w, h) = (640u32, 360u32);
+ let mut bgrx = vec![0u8; (w * h * 4) as usize];
+ render_placeholder_bgrx(&mut bgrx, w, h, &name);
+ ffi::video_frame(PREVIEW_STREAM, w, h, &bgrx);
+}
+
+/// Requests a webcam stream from `device` (or the selected phone).
+pub fn start(device: Option<DeviceId>) {
+ let Some(device) = device.or_else(selected_phone) else { return };
+ set_selected_phone(device);
+ let h = height();
+ let w = if h == 1080 { 1920 } else { 1280 };
+ state(|s| s.phase = Phase::Asking { device });
+ core_host::host().hub.changed(Changes::WEBCAM);
+
+ let Some(node) = core_host::node() else { return };
+ let bitrate = if h == 1080 { 8_000_000 } else { 4_000_000 };
+ let options = WebcamStart { width: w, height: h, fps: 30, bitrate, camera: "back".into() };
+ core_host::spawn(async move {
+ if let Err(e) = node.webcam_start(device, options).await {
+ let reason = match e {
+ Error::Denied => "Webcam is turned off for this phone.".to_owned(),
+ Error::Unsupported => {
+ "This phone's app doesn't support Webcam yet. Update Nectarlink on the phone.".into()
+ }
+ Error::Offline | Error::NotPaired => "The phone isn't connected.".into(),
+ e => describe(&e),
+ };
+ state(|s| {
+ if matches!(s.phase, Phase::Asking { device: d } if d == device) {
+ s.phase = Phase::Ended { reason };
+ }
+ });
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+ }
+ });
+}
+
+/// Stops the active or pending webcam stream.
+pub fn stop() {
+ let device = state(|s| {
+ let dev = match s.phase {
+ Phase::Asking { device } | Phase::Streaming { device, .. } => Some(device),
+ Phase::Idle | Phase::Ended { .. } => None,
+ };
+ s.phase = Phase::Idle;
+ dev
+ });
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+ if let (Some(device), Some(node)) = (device, core_host::node()) {
+ core_host::spawn(async move {
+ node.webcam_stop(device).await;
+ });
+ }
+}
+
+pub fn on_event(event: &NodeEvent) {
+ match event {
+ NodeEvent::Webcam { device, on: true } => {
+ state(|s| {
+ s.preferred_phone = Some(*device);
+ if !matches!(s.phase, Phase::Streaming { device: d, .. } if d == *device) {
+ s.phase = Phase::Streaming { device: *device, width: 1280, height: 720, fps: 30 };
+ }
+ });
+ core_host::host().hub.changed(Changes::WEBCAM);
+ }
+ NodeEvent::Webcam { device, on: false }
+ | NodeEvent::LinkChanged { device, link: nectarlink_core::LinkState::Offline { .. } } => {
+ let changed = state(|s| {
+ if matches!(s.phase, Phase::Asking { device: d } | Phase::Streaming { device: d, .. } if d == *device)
+ {
+ s.phase = Phase::Idle;
+ true
+ } else {
+ false
+ }
+ });
+ if changed {
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+ }
+ }
+ NodeEvent::DeviceAdded(_) | NodeEvent::DeviceRemoved(_) | NodeEvent::PeerInfoChanged { .. } => {
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+ }
+ _ => {}
+ }
+}
+
+/// Returns a [`WebcamSink`] for an incoming `"webcam"` stream from `device`.
+pub fn sink(device: &DeviceId) -> Option<Arc<dyn WebcamSink>> {
+ Some(Arc::new(Sink::new(*device)))
+}
+
+enum Item {
+ Config(WebcamConfig),
+ Packet { keyframe: bool, time_us: u64, data: Vec<u8> },
+ Ended,
+}
+
+struct Video {
+ queue: SyncSender<Item>,
+ waiting: Arc<AtomicUsize>,
+}
+
+struct Sink {
+ device: DeviceId,
+ video: OnceLock<Video>,
+}
+
+impl Sink {
+ fn new(device: DeviceId) -> Self {
+ Self { device, video: OnceLock::new() }
+ }
+
+ fn keyframe_please(&self) {
+ let device = self.device;
+ if let Some(node) = core_host::node() {
+ core_host::spawn(async move { node.webcam_keyframe(device).await });
+ }
+ }
+}
+
+impl Video {
+ fn start(device: DeviceId) -> Self {
+ let (queue, items) = sync_channel(BACKLOG);
+ let waiting = Arc::new(AtomicUsize::new(0));
+ let counter = waiting.clone();
+ let started = std::thread::Builder::new()
+ .name("webcam-decoder".into())
+ .spawn(move || decode(device, &items, &counter));
+ if let Err(e) = started {
+ tracing::error!(error = %e, "can't start the webcam decoder");
+ }
+ Self { queue, waiting }
+ }
+}
+
+impl WebcamSink for Sink {
+ fn config(&self, config: WebcamConfig) {
+ state(|s| {
+ s.preferred_phone = Some(self.device);
+ s.phase = Phase::Streaming {
+ device: self.device,
+ width: config.width,
+ height: config.height,
+ fps: config.fps,
+ };
+ });
+ core_host::host().hub.changed(Changes::WEBCAM);
+ let video = self.video.get_or_init(|| Video::start(self.device));
+ let _ = video.queue.send(Item::Config(config));
+ }
+
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
+ let Some(video) = self.video.get() else { return };
+ match video.queue.try_send(Item::Packet { keyframe, time_us, data }) {
+ Ok(()) => {
+ video.waiting.fetch_add(1, Ordering::AcqRel);
+ }
+ Err(TrySendError::Disconnected(_)) => {}
+ Err(TrySendError::Full(_)) => self.keyframe_please(),
+ }
+ }
+
+ fn ended(&self) {
+ if let Some(video) = self.video.get() {
+ let _ = video.queue.send(Item::Ended);
+ }
+ }
+}
+
+fn mirror_bgrx_in_place(bgrx: &mut [u8], width: u32, height: u32) {
+ let row_bytes = (width as usize) * 4;
+ for y in 0..height as usize {
+ let row = &mut bgrx[y * row_bytes..(y + 1) * row_bytes];
+ for x in 0..(width as usize) / 2 {
+ let l = x * 4;
+ let r = (width as usize - 1 - x) * 4;
+ for c in 0..4 {
+ row.swap(l + c, r + c);
+ }
+ }
+ }
+}
+
+fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
+ let mut decoder = match Decoder::new() {
+ Ok(decoder) => decoder,
+ Err(e) => {
+ tracing::error!(error = %e, "no H.264 decoder for webcam");
+ state(|s| {
+ s.phase = Phase::Ended { reason: "This PC can't decode the phone's camera video.".into() };
+ });
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+ return;
+ }
+ };
+ let keyframe_please = || {
+ if let Some(node) = core_host::node() {
+ core_host::spawn(async move { node.webcam_keyframe(device).await });
+ }
+ };
+ let phone_name = phone_name_for(Some(device));
+ let mut size = (0u32, 0u32);
+ let mut need_keyframe = true;
+
+ while let Ok(item) = items.recv() {
+ match item {
+ Item::Config(config) => {
+ if size != (0, 0) && size != (config.width, config.height) {
+ decoder.flush();
+ }
+ size = (config.width, config.height);
+ need_keyframe = true;
+ }
+ Item::Packet { keyframe, time_us, data } => {
+ let behind = waiting.fetch_sub(1, Ordering::AcqRel) > 1;
+ if need_keyframe && !keyframe {
+ continue;
+ }
+ need_keyframe = false;
+ let pictures = match decoder.decode(&data, time_us) {
+ Ok(pictures) => pictures,
+ Err(e) => {
+ tracing::debug!(error = %e, "webcam packet didn't decode");
+ decoder.flush();
+ need_keyframe = true;
+ keyframe_please();
+ continue;
+ }
+ };
+ if let (Some(picture), false) = (pictures.last(), behind) {
+ let (w, h) = if size.0 > 0 { size } else { (picture.width, picture.height) };
+ let (src_w, src_h) = (w.min(picture.width), h.min(picture.height));
+ if src_w == 0 || src_h == 0 {
+ continue;
+ }
+ let mut bgrx = to_bgrx(picture, w, h);
+ let flip = mirror();
+ if flip {
+ mirror_bgrx_in_place(&mut bgrx, src_w, src_h);
+ }
+ if let Some(mapping) = mapping() {
+ // Already flipped in place if `flip` is true, so pass `false` here.
+ mapping.write_frame(&phone_name, src_w, src_h, time_us, &bgrx, false);
+ }
+ ffi::video_frame(PREVIEW_STREAM, src_w, src_h, &bgrx);
+ }
+ }
+ Item::Ended => break,
+ }
+ }
+
+ state(|s| {
+ if matches!(s.phase, Phase::Streaming { device: d, .. } if d == device) {
+ s.phase = Phase::Idle;
+ }
+ });
+ refresh_idle_frame();
+ core_host::host().hub.changed(Changes::WEBCAM);
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 590ff3e..64804ee 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -24,6 +24,7 @@ pub mod smtc;
pub mod sound;
pub mod toast;
pub mod tray;
+pub mod vcam;
pub mod wallpaper;
pub mod wol;
diff --git a/desktop/app/src/win/vcam.rs b/desktop/app/src/win/vcam.rs
new file mode 100644
index 0000000..830b64c
--- /dev/null
+++ b/desktop/app/src/win/vcam.rs
@@ -0,0 +1,275 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Windows 11 Virtual Camera (`MFCreateVirtualCamera`) registration and
+//! session management for `"Nectarlink Webcam"`.
+
+use std::path::{Path, PathBuf};
+
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, ERROR_SUCCESS},
+ Media::{
+ KernelStreaming::KSCATEGORY_VIDEO_CAMERA,
+ MediaFoundation::{
+ IMFVirtualCamera, MF_VERSION, MFCreateVirtualCamera, MFSTARTUP_NOSOCKET, MFStartup,
+ MFVirtualCameraAccess_CurrentUser, MFVirtualCameraLifetime_Session,
+ MFVirtualCameraType_SoftwareCameraSource,
+ },
+ },
+ System::{
+ Registry::{
+ HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WRITE, REG_OPTION_NON_VOLATILE, REG_SZ,
+ RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteTreeW, RegGetValueW, RegSetValueExW,
+ },
+ Threading::{GetExitCodeProcess, WaitForSingleObject},
+ },
+ UI::{
+ Shell::{SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, ShellExecuteExW},
+ WindowsAndMessaging::SW_HIDE,
+ },
+ },
+ core::{HSTRING, PCWSTR, w},
+};
+
+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 HKLM_CLSID_PREFIX: &str = r"SOFTWARE\Classes\CLSID";
+const HKLM_FRAMESERVER_PREFIX: &str =
+ r"SOFTWARE\Microsoft\Windows Media Foundation\Platform\FrameServer\Sources";
+
+/// Resolves `nectarlink_vcam.dll` alongside `nectarlink-desktop.exe`.
+pub fn dll_path() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ let dir = exe.parent()?;
+ Some(dir.join("nectarlink_vcam.dll"))
+}
+
+/// Checks whether the virtual camera COM media source is registered under `root\classes_prefix`
+/// and its `InprocServer32` DLL exists on disk.
+pub fn is_registered_under(root: HKEY, classes_prefix: &str) -> bool {
+ let subkey = format!(r"{classes_prefix}\{CLSID_STR}\InprocServer32");
+ let mut buf = [0u16; 512];
+ let mut size = std::mem::size_of_val(&buf) as u32;
+ let status = unsafe {
+ RegGetValueW(
+ root,
+ &HSTRING::from(subkey.as_str()),
+ PCWSTR::null(),
+ RRF_RT_REG_SZ,
+ None,
+ Some(buf.as_mut_ptr().cast()),
+ Some(&mut size),
+ )
+ };
+ if status != ERROR_SUCCESS {
+ return false;
+ }
+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
+ if len == 0 {
+ return false;
+ }
+ let path = PathBuf::from(String::from_utf16_lossy(&buf[..len]));
+ path.is_file()
+}
+
+/// Returns `true` if `nectarlink_vcam.dll` is registered in `HKLM` and exists on disk.
+pub fn is_registered() -> bool {
+ is_registered_under(HKEY_LOCAL_MACHINE, HKLM_CLSID_PREFIX)
+}
+
+fn set_reg_sz(key: HKEY, name: Option<&str>, value: &str) -> Result<(), String> {
+ let mut wide: Vec<u16> = value.encode_utf16().collect();
+ wide.push(0);
+ let bytes: &[u8] = unsafe { std::slice::from_raw_parts(wide.as_ptr().cast::<u8>(), wide.len() * 2) };
+ let name_h = name.map(HSTRING::from);
+ let name_pcwstr = name_h.as_ref().map_or(PCWSTR::null(), |h| PCWSTR(h.as_ptr()));
+ let status = unsafe { RegSetValueExW(key, name_pcwstr, Some(0), REG_SZ, Some(bytes)) };
+ if status != ERROR_SUCCESS {
+ return Err(format!("RegSetValueExW failed: {}", status.0));
+ }
+ Ok(())
+}
+
+fn create_and_set(root: HKEY, subkey: &str, values: &[(Option<&str>, &str)]) -> Result<(), String> {
+ let mut hkey = HKEY::default();
+ let status = unsafe {
+ RegCreateKeyExW(
+ root,
+ &HSTRING::from(subkey),
+ Some(0),
+ PCWSTR::null(),
+ REG_OPTION_NON_VOLATILE,
+ KEY_WRITE | KEY_READ,
+ None,
+ &mut hkey,
+ None,
+ )
+ };
+ if status != ERROR_SUCCESS {
+ return Err(format!("RegCreateKeyExW({subkey}) failed: {}", status.0));
+ }
+ let res = (|| {
+ for &(name, val) in values {
+ set_reg_sz(hkey, name, val)?;
+ }
+ Ok(())
+ })();
+ unsafe {
+ let _ = RegCloseKey(hkey);
+ }
+ res
+}
+
+/// Writes the COM `InprocServer32` and FrameServer source registration keys under `root`.
+pub fn register_under(
+ root: HKEY,
+ classes_prefix: &str,
+ frameserver_prefix: &str,
+ dll: &Path,
+) -> Result<(), String> {
+ if !dll.is_file() {
+ return Err(format!("missing {}", dll.display()));
+ }
+ let dll_str = dll.to_string_lossy();
+ let clsid_key = format!(r"{classes_prefix}\{CLSID_STR}");
+ let inproc_key = format!(r"{clsid_key}\InprocServer32");
+ let fs_key = format!(r"{frameserver_prefix}\{CLSID_STR}");
+
+ create_and_set(root, &clsid_key, &[(None, "Nectarlink Virtual Camera Media Source")])?;
+ create_and_set(root, &inproc_key, &[(None, dll_str.as_ref()), (Some("ThreadingModel"), "Both")])?;
+ create_and_set(root, &fs_key, &[(Some("FriendlyName"), FRIENDLY_NAME)])?;
+ Ok(())
+}
+
+/// Removes the COM `CLSID` and FrameServer source registration keys under `root`.
+pub fn unregister_under(root: HKEY, classes_prefix: &str, frameserver_prefix: &str) -> Result<(), String> {
+ for subkey in [format!(r"{classes_prefix}\{CLSID_STR}"), format!(r"{frameserver_prefix}\{CLSID_STR}")] {
+ let status = unsafe { RegDeleteTreeW(root, &HSTRING::from(subkey.as_str())) };
+ if status != ERROR_SUCCESS && status != ERROR_FILE_NOT_FOUND && status != ERROR_PATH_NOT_FOUND {
+ return Err(format!("RegDeleteTreeW({subkey}) failed: {}", status.0));
+ }
+ }
+ Ok(())
+}
+
+/// Registers `nectarlink_vcam.dll` in `HKLM` (requires administrator privileges).
+pub fn register_hklm() -> Result<(), String> {
+ let dll = dll_path().ok_or_else(|| "cannot resolve nectarlink_vcam.dll path".to_owned())?;
+ register_under(HKEY_LOCAL_MACHINE, HKLM_CLSID_PREFIX, HKLM_FRAMESERVER_PREFIX, &dll)
+}
+
+/// Unregisters `nectarlink_vcam.dll` from `HKLM` (requires administrator privileges).
+pub fn unregister_hklm() -> Result<(), String> {
+ unregister_under(HKEY_LOCAL_MACHINE, HKLM_CLSID_PREFIX, HKLM_FRAMESERVER_PREFIX)
+}
+
+/// Launches `nectarlink-desktop.exe <arg>` elevated via `ShellExecuteExW` (`"runas"`)
+/// and invokes `on_done` once the helper process exits.
+pub fn run_elevated(arg: &'static str, on_done: impl FnOnce(bool) + Send + 'static) {
+ std::thread::spawn(move || {
+ let Ok(exe) = std::env::current_exe() else {
+ on_done(false);
+ return;
+ };
+ let exe_h = HSTRING::from(exe.as_os_str());
+ let params_h = HSTRING::from(arg);
+ let mut info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ fMask: SEE_MASK_NOCLOSEPROCESS,
+ lpVerb: w!("runas"),
+ lpFile: PCWSTR(exe_h.as_ptr()),
+ lpParameters: PCWSTR(params_h.as_ptr()),
+ nShow: SW_HIDE.0,
+ ..Default::default()
+ };
+ let ok = unsafe { ShellExecuteExW(&mut info) }.is_ok();
+ if !ok || info.hProcess.is_invalid() {
+ on_done(false);
+ return;
+ }
+ unsafe {
+ let _ = WaitForSingleObject(info.hProcess, 60_000);
+ let mut code = 1u32;
+ let _ = GetExitCodeProcess(info.hProcess, &mut code);
+ let _ = CloseHandle(info.hProcess);
+ on_done(code == 0);
+ }
+ });
+}
+
+/// Active `IMFVirtualCamera` session handle.
+pub struct VirtualCameraHandle {
+ vcam: IMFVirtualCamera,
+}
+
+// SAFETY: `IMFVirtualCamera` is a thread-safe COM interface.
+unsafe impl Send for VirtualCameraHandle {}
+unsafe impl Sync for VirtualCameraHandle {}
+
+impl std::fmt::Debug for VirtualCameraHandle {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VirtualCameraHandle").finish()
+ }
+}
+
+impl VirtualCameraHandle {
+ /// Creates and starts the `"Nectarlink Webcam"` session-lifetime virtual camera.
+ /// Succeeds when `nectarlink_vcam.dll` is registered in `HKLM`.
+ pub fn start() -> Result<Self, String> {
+ unsafe {
+ MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET).map_err(|e| e.to_string())?;
+ let categories = [KSCATEGORY_VIDEO_CAMERA];
+ let vcam = MFCreateVirtualCamera(
+ MFVirtualCameraType_SoftwareCameraSource,
+ MFVirtualCameraLifetime_Session,
+ MFVirtualCameraAccess_CurrentUser,
+ &HSTRING::from(FRIENDLY_NAME),
+ &HSTRING::from(CLSID_STR),
+ Some(&categories),
+ )
+ .map_err(|e| e.to_string())?;
+ vcam.Start(None).map_err(|e| e.to_string())?;
+ Ok(Self { vcam })
+ }
+ }
+}
+
+impl Drop for VirtualCameraHandle {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = self.vcam.Stop();
+ let _ = self.vcam.Remove();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use windows::Win32::System::Registry::HKEY_CURRENT_USER;
+
+ #[test]
+ fn registers_checks_and_unregisters_under_test_key() {
+ let pid = std::process::id();
+ let base = format!(r"Software\NectarlinkTest_Vcam_{pid}");
+ let classes = format!(r"{base}\Classes\CLSID");
+ let fs = format!(r"{base}\FrameServer\Sources");
+
+ // Create a temporary dummy DLL file so `is_registered_under` sees an existing file.
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ assert!(!is_registered_under(HKEY_CURRENT_USER, &classes));
+
+ register_under(HKEY_CURRENT_USER, &classes, &fs, tmp.path()).unwrap();
+ assert!(is_registered_under(HKEY_CURRENT_USER, &classes));
+
+ unregister_under(HKEY_CURRENT_USER, &classes, &fs).unwrap();
+ assert!(!is_registered_under(HKEY_CURRENT_USER, &classes));
+
+ // Clean up the test root key completely.
+ unsafe {
+ let _ = RegDeleteTreeW(HKEY_CURRENT_USER, &HSTRING::from(base.as_str()));
+ }
+ }
+}
diff --git a/desktop/installer/nectarlink.nsi b/desktop/installer/nectarlink.nsi
index 4a8ae0e..171b2f5 100644
--- a/desktop/installer/nectarlink.nsi
+++ b/desktop/installer/nectarlink.nsi
@@ -163,6 +163,7 @@ Section "Uninstall"
RMDir /r "$INSTDIR"
${Else}
Delete "$INSTDIR\${EXE}"
+ Delete "$INSTDIR\nectarlink_vcam.dll"
Delete "$INSTDIR\uninstall.exe"
${EndIf}
diff --git a/desktop/vcam/Cargo.toml b/desktop/vcam/Cargo.toml
new file mode 100644
index 0000000..77c0427
--- /dev/null
+++ b/desktop/vcam/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "nectarlink-vcam"
+description = "Nectarlink virtual camera Media Foundation media source (Windows 11)"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+repository.workspace = true
+license = "GPL-3.0-or-later"
+publish = false
+
+[lib]
+name = "nectarlink_vcam"
+crate-type = ["cdylib", "rlib"]
+
+[target.'cfg(windows)'.dependencies]
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_Media_KernelStreaming",
+ "Win32_Media_MediaFoundation",
+ "Win32_Security",
+ "Win32_Security_Authorization",
+ "Win32_System_Com",
+ "Win32_System_Com_StructuredStorage",
+ "Win32_System_LibraryLoader",
+ "Win32_System_Memory",
+ "Win32_System_SystemServices",
+ "Win32_System_Variant",
+] }
+windows-core = "0.62"
+
+[lints]
+workspace = true
diff --git a/desktop/vcam/src/lib.rs b/desktop/vcam/src/lib.rs
new file mode 100644
index 0000000..323daa7
--- /dev/null
+++ b/desktop/vcam/src/lib.rs
@@ -0,0 +1,302 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `nectarlink_vcam`: Windows 11 Media Foundation virtual camera media source
+//! COM DLL and shared-memory frame transport (`docs/protocol/webcam.md`).
+
+#![allow(linker_messages)]
+
+use std::sync::atomic::Ordering;
+
+use windows::{
+ Win32::{
+ Foundation::{CLASS_E_CLASSNOTAVAILABLE, E_INVALIDARG, E_POINTER, S_FALSE, S_OK},
+ Media::MediaFoundation::{MF_VERSION, MFSTARTUP_NOSOCKET, MFStartup},
+ System::Com::IClassFactory,
+ },
+ core::{GUID, HRESULT, IUnknown, Interface},
+};
+
+pub mod shm;
+pub mod source;
+
+pub use shm::{
+ DEFAULT_MAPPING_NAME, LOCAL_MAPPING_NAME, MAX_FRAME_BYTES, MAX_HEIGHT, MAX_WIDTH, SharedFrameMapping,
+ bgrx_to_nv12, fit_bgrx_aspect, render_placeholder_bgrx,
+};
+pub use source::{SAMPLE_DURATION_100NS, VcamClassFactory, VcamMediaSource, VcamMediaStream};
+
+/// CLSID of the Nectarlink Virtual Camera Media Foundation media source:
+/// `{8E6C3B74-5D4A-4B9E-9A12-7C8F1E2D3A40}`.
+pub const CLSID_NECTARLINK_VCAM: GUID = GUID::from_u128(0x8e6c3b74_5d4a_4b9e_9a12_7c8f1e2d3a40);
+
+/// Standard COM DLL entry point returning an `IClassFactory` for
+/// [`CLSID_NECTARLINK_VCAM`].
+///
+/// # Safety
+/// `rclsid`, `riid`, and `ppv` must be valid pointers as specified by COM.
+#[unsafe(no_mangle)]
+#[allow(unsafe_code)]
+pub unsafe extern "system" fn DllGetClassObject(
+ rclsid: *const GUID,
+ riid: *const GUID,
+ ppv: *mut *mut std::ffi::c_void,
+) -> HRESULT {
+ if ppv.is_null() {
+ return E_POINTER;
+ }
+ unsafe { *ppv = std::ptr::null_mut() };
+ if rclsid.is_null() || riid.is_null() {
+ return E_INVALIDARG;
+ }
+ let clsid = unsafe { *rclsid };
+ if clsid != CLSID_NECTARLINK_VCAM {
+ return CLASS_E_CLASSNOTAVAILABLE;
+ }
+ let _ = unsafe { MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET) };
+ let factory: IClassFactory = VcamClassFactory::new().into();
+ let unk: IUnknown = match factory.cast() {
+ Ok(u) => u,
+ Err(e) => return e.code(),
+ };
+ unsafe { unk.query(riid, ppv) }
+}
+
+/// Standard COM DLL unload check.
+#[unsafe(no_mangle)]
+#[allow(unsafe_code)]
+pub extern "system" fn DllCanUnloadNow() -> HRESULT {
+ if source::ACTIVE_OBJECTS.load(Ordering::Relaxed) == 0 { S_OK } else { S_FALSE }
+}
+
+#[cfg(test)]
+#[allow(unsafe_code)]
+mod tests {
+ use super::*;
+ use windows::Win32::{
+ Media::{
+ KernelStreaming::PINNAME_VIDEO_CAPTURE,
+ MediaFoundation::{
+ IMFMediaBuffer, IMFMediaSource, IMFMediaStream, IMFMediaStream2, IMFSample, MEMediaSample,
+ MENewStream, MESourcePaused, MESourceStarted, MESourceStopped, MEStreamPaused,
+ MEStreamStarted, MEStreamStopped, MEUpdatedStream,
+ MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MF_DEVICESTREAM_FRAMESERVER_SHARED,
+ MF_DEVICESTREAM_STREAM_CATEGORY, MF_DEVICESTREAM_STREAM_ID, MF_EVENT_FLAG_NO_WAIT,
+ MF_MT_FRAME_SIZE, MF_MT_SUBTYPE, MF_STREAM_STATE_PAUSED, MF_STREAM_STATE_RUNNING,
+ MF_STREAM_STATE_STOPPED, MFFrameSourceTypes_Color, MFVideoFormat_NV12, MFVideoFormat_RGB32,
+ },
+ },
+ System::Com::StructuredStorage::PROPVARIANT,
+ };
+
+ #[test]
+ fn dll_get_class_object_activates_media_source_in_process() {
+ unsafe {
+ let mut raw = std::ptr::null_mut();
+ let hr = DllGetClassObject(&CLSID_NECTARLINK_VCAM, &IClassFactory::IID, &mut raw);
+ assert_eq!(hr, S_OK);
+ assert!(!raw.is_null());
+ let factory: IClassFactory = IClassFactory::from_raw(raw);
+ let source: windows::Win32::Media::MediaFoundation::IMFMediaSourceEx =
+ factory.CreateInstance(None).unwrap();
+ let attrs = source.GetSourceAttributes().unwrap();
+ assert_eq!(
+ attrs.GetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES).unwrap(),
+ MFFrameSourceTypes_Color.0 as u32
+ );
+ source.Shutdown().unwrap();
+ }
+ }
+
+ #[test]
+ fn media_source_delivers_placeholder_and_live_shared_memory_samples() {
+ unsafe {
+ let _ = MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET);
+ let map_name = format!("Local\\NectarlinkVcamSrcTest_{}", std::process::id());
+ let writer = SharedFrameMapping::open_or_create(&map_name).unwrap();
+ writer.set_idle("Pixel 8");
+
+ let source_ex = VcamMediaSource::new_with_mapping(&map_name).unwrap();
+ let source: IMFMediaSource = source_ex.cast().unwrap();
+
+ // Verify source & stream attributes required by Windows Camera Frame Server.
+ let src_attrs = source_ex.GetSourceAttributes().unwrap();
+ assert_eq!(
+ src_attrs.GetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES).unwrap(),
+ MFFrameSourceTypes_Color.0 as u32
+ );
+ let stm_attrs = source_ex.GetStreamAttributes(0).unwrap();
+ assert_eq!(stm_attrs.GetGUID(&MF_DEVICESTREAM_STREAM_CATEGORY).unwrap(), PINNAME_VIDEO_CAPTURE);
+ assert_eq!(stm_attrs.GetUINT32(&MF_DEVICESTREAM_STREAM_ID).unwrap(), 0);
+ assert_eq!(stm_attrs.GetUINT32(&MF_DEVICESTREAM_FRAMESERVER_SHARED).unwrap(), 1);
+
+ // Presentation descriptor & media types (RGB32/NV12 @ 720p & 1080p).
+ let pd = source.CreatePresentationDescriptor().unwrap();
+ assert_eq!(pd.GetStreamDescriptorCount().unwrap(), 1);
+ let mut selected = windows::core::BOOL(0);
+ let mut sd_opt = None;
+ pd.GetStreamDescriptorByIndex(0, &mut selected, &mut sd_opt).unwrap();
+ assert!(selected.as_bool());
+ let sd = sd_opt.unwrap();
+ let handler = sd.GetMediaTypeHandler().unwrap();
+ assert_eq!(handler.GetMediaTypeCount().unwrap(), 4);
+
+ // Start the media source.
+ let start_pos = PROPVARIANT::default();
+ source.Start(&pd, &GUID::zeroed(), &start_pos).unwrap();
+
+ // Pop MENewStream and MESourceStarted from the source event queue.
+ let ev_new_stream = source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ assert_eq!(ev_new_stream.GetType().unwrap(), MENewStream.0 as u32);
+ let val = ev_new_stream.GetValue().unwrap();
+ let stream_unk: IUnknown = val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().clone();
+ let stream: IMFMediaStream = stream_unk.cast().unwrap();
+ let stream2: IMFMediaStream2 = stream.cast().unwrap();
+ assert_eq!(stream2.GetStreamState().unwrap(), MF_STREAM_STATE_RUNNING);
+
+ let ev_src_started = source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ assert_eq!(ev_src_started.GetType().unwrap(), MESourceStarted.0 as u32);
+
+ let ev_stm_started = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ assert_eq!(ev_stm_started.GetType().unwrap(), MEStreamStarted.0 as u32);
+
+ // 1. RequestSample while inactive -> placeholder 1280x720 RGB32 sample.
+ stream.RequestSample(None).unwrap();
+ let ev_sample0 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ assert_eq!(ev_sample0.GetType().unwrap(), MEMediaSample.0 as u32);
+ let s0_val = ev_sample0.GetValue().unwrap();
+ let sample0: IMFSample =
+ s0_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
+ assert_eq!(sample0.GetSampleTime().unwrap(), 0);
+ assert_eq!(sample0.GetSampleDuration().unwrap(), SAMPLE_DURATION_100NS);
+ let buf0: IMFMediaBuffer = sample0.ConvertToContiguousBuffer().unwrap();
+ assert_eq!(buf0.GetCurrentLength().unwrap(), 1280 * 720 * 4);
+ let mut ptr0 = std::ptr::null_mut();
+ let mut cur_len0 = 0;
+ buf0.Lock(&mut ptr0, None, Some(&mut cur_len0)).unwrap();
+ let bytes0 = std::slice::from_raw_parts(ptr0, cur_len0 as usize);
+ // Placeholder contains amber/white text pixels over the dark background.
+ assert!(bytes0.as_chunks::<4>().0.iter().any(|px| px[2] > 200));
+ buf0.Unlock().unwrap();
+
+ // 2. Write a live 1280x720 BGRX frame to shared memory and request a sample.
+ let mut live_frame = vec![0u8; 1280 * 720 * 4];
+ for px in live_frame.as_chunks_mut::<4>().0 {
+ px[0] = 0x22;
+ px[1] = 0x88;
+ px[2] = 0xEE;
+ px[3] = 0xFF;
+ }
+ writer.write_frame("Pixel 8", 1280, 720, 12_345, &live_frame, false);
+
+ stream.RequestSample(None).unwrap();
+ let ev_sample1 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ assert_eq!(ev_sample1.GetType().unwrap(), MEMediaSample.0 as u32);
+ let s1_val = ev_sample1.GetValue().unwrap();
+ let sample1: IMFSample =
+ s1_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
+ assert_eq!(sample1.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS);
+ let buf1: IMFMediaBuffer = sample1.ConvertToContiguousBuffer().unwrap();
+ assert_eq!(buf1.GetCurrentLength().unwrap(), 1280 * 720 * 4);
+ let mut ptr1 = std::ptr::null_mut();
+ let mut cur_len1 = 0;
+ buf1.Lock(&mut ptr1, None, Some(&mut cur_len1)).unwrap();
+ let bytes1 = std::slice::from_raw_parts(ptr1, cur_len1 as usize);
+ assert_eq!(&bytes1[..4], &[0x22, 0x88, 0xEE, 0xFF]);
+ assert_eq!(&bytes1[bytes1.len() - 4..], &[0x22, 0x88, 0xEE, 0xFF]);
+ buf1.Unlock().unwrap();
+
+ // 3. Switch stream media type to NV12 @ 1280x720 and request a sample.
+ let mt_nv12 = handler.GetMediaTypeByIndex(1).unwrap();
+ assert_eq!(mt_nv12.GetGUID(&MF_MT_SUBTYPE).unwrap(), MFVideoFormat_NV12);
+ handler.SetCurrentMediaType(&mt_nv12).unwrap();
+ stream.RequestSample(None).unwrap();
+ let ev_sample2 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ let s2_val = ev_sample2.GetValue().unwrap();
+ let sample2: IMFSample =
+ s2_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
+ assert_eq!(sample2.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS * 2);
+ let buf2: IMFMediaBuffer = sample2.ConvertToContiguousBuffer().unwrap();
+ assert_eq!(buf2.GetCurrentLength().unwrap(), 1280 * 720 * 3 / 2);
+
+ // 4. Switch stream media type to RGB32 @ 1920x1080 and request a sample.
+ let mt_1080 = handler.GetMediaTypeByIndex(2).unwrap();
+ assert_eq!(mt_1080.GetGUID(&MF_MT_SUBTYPE).unwrap(), MFVideoFormat_RGB32);
+ assert_eq!(mt_1080.GetUINT64(&MF_MT_FRAME_SIZE).unwrap(), (1920u64 << 32) | 1080u64);
+ handler.SetCurrentMediaType(&mt_1080).unwrap();
+ stream.RequestSample(None).unwrap();
+ let ev_sample3 = stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap();
+ let s3_val = ev_sample3.GetValue().unwrap();
+ let sample3: IMFSample =
+ s3_val.Anonymous.Anonymous.Anonymous.punkVal.as_ref().unwrap().cast().unwrap();
+ assert_eq!(sample3.GetSampleTime().unwrap(), SAMPLE_DURATION_100NS * 3);
+ let buf3: IMFMediaBuffer = sample3.ConvertToContiguousBuffer().unwrap();
+ assert_eq!(buf3.GetCurrentLength().unwrap(), 1920 * 1080 * 4);
+
+ // Pause, restart (MEUpdatedStream), stop, and shutdown.
+ source.Pause().unwrap();
+ assert_eq!(stream2.GetStreamState().unwrap(), MF_STREAM_STATE_PAUSED);
+ assert_eq!(
+ source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MESourcePaused.0 as u32
+ );
+ assert_eq!(
+ stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MEStreamPaused.0 as u32
+ );
+
+ source.Start(&pd, &GUID::zeroed(), &start_pos).unwrap();
+ assert_eq!(
+ source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MEUpdatedStream.0 as u32
+ );
+ assert_eq!(
+ source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MESourceStarted.0 as u32
+ );
+ assert_eq!(
+ stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MEStreamStarted.0 as u32
+ );
+
+ source.Stop().unwrap();
+ assert_eq!(stream2.GetStreamState().unwrap(), MF_STREAM_STATE_STOPPED);
+ assert_eq!(
+ source.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MESourceStopped.0 as u32
+ );
+ assert_eq!(
+ stream.GetEvent(MF_EVENT_FLAG_NO_WAIT).unwrap().GetType().unwrap(),
+ MEStreamStopped.0 as u32
+ );
+
+ source.Shutdown().unwrap();
+ }
+ }
+
+ #[test]
+ fn shared_memory_mirror_and_aspect_fit_round_trip() {
+ let map_name = format!("Local\\NectarlinkVcamShmTest_{}", std::process::id());
+ let writer = SharedFrameMapping::open_or_create(&map_name).unwrap();
+ let reader = SharedFrameMapping::open_or_create(&map_name).unwrap();
+
+ // 4x2 frame where left half is blue and right half is red.
+ let mut src = vec![0u8; 4 * 2 * 4];
+ for y in 0..2 {
+ for x in 0..4 {
+ let off = (y * 4 + x) * 4;
+ if x < 2 {
+ src[off..off + 4].copy_from_slice(&[255, 0, 0, 255]);
+ } else {
+ src[off..off + 4].copy_from_slice(&[0, 0, 255, 255]);
+ }
+ }
+ }
+ writer.write_frame("Pixel 8", 4, 2, 999, &src, true);
+
+ let mut dst = vec![0u8; 4 * 2 * 4];
+ let ts = reader.read_bgrx(4, 2, &mut dst);
+ assert_eq!(ts, (true, 999));
+ // Because mirror=true, left half is now red and right half is blue.
+ assert_eq!(&dst[0..4], &[0, 0, 255, 255]);
+ assert_eq!(&dst[8..12], &[255, 0, 0, 255]);
+ }
+}
diff --git a/desktop/vcam/src/shm.rs b/desktop/vcam/src/shm.rs
new file mode 100644
index 0000000..c3c3c98
--- /dev/null
+++ b/desktop/vcam/src/shm.rs
@@ -0,0 +1,589 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Shared-memory frame transport between `nectarlink-desktop.exe` and
+//! `nectarlink_vcam.dll`, plus placeholder frame rendering and RGB32/NV12
+//! conversion.
+
+use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};
+
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, HANDLE, HLOCAL, INVALID_HANDLE_VALUE, LocalFree},
+ Security::{
+ Authorization::{ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1},
+ PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
+ },
+ System::Memory::{
+ CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
+ OpenFileMappingW, PAGE_READWRITE, UnmapViewOfFile,
+ },
+ },
+ core::{PCWSTR, w},
+};
+
+/// The mapping the camera and the app share. The camera's media source runs
+/// inside Windows' Frame Server service, in another session than the app, so
+/// it has to be in the global namespace: the service creates it (only
+/// services may create global objects) and the signed-in user's app opens it.
+pub const DEFAULT_MAPPING_NAME: &str = "Global\\NectarlinkVcamFrame_v1";
+/// The same mapping in the caller's own session, when the global one can't be
+/// created (the media source running in-process, as in tests).
+pub const LOCAL_MAPPING_NAME: &str = "Local\\NectarlinkVcamFrame_v1";
+
+/// Who may use the global mapping: the system, the Frame Server's
+/// LocalService account and administrators fully, signed-in (interactive)
+/// users read and write (the app), nobody else.
+const GLOBAL_SDDL: PCWSTR = w!("D:P(A;;GA;;;SY)(A;;GA;;;LS)(A;;GA;;;BA)(A;;GRGW;;;IU)");
+
+pub const MAX_WIDTH: u32 = 1920;
+pub const MAX_HEIGHT: u32 = 1080;
+pub const MAX_FRAME_BYTES: usize = (MAX_WIDTH as usize) * (MAX_HEIGHT as usize) * 4;
+pub const HEADER_BYTES: usize = std::mem::size_of::<SharedHeader>();
+pub const TOTAL_MAPPING_BYTES: usize = HEADER_BYTES + MAX_FRAME_BYTES;
+
+const MAGIC: u32 = 0x4E4C_5643; // "NLVC"
+const VERSION: u32 = 1;
+
+#[repr(C, align(64))]
+#[derive(Debug)]
+pub struct SharedHeader {
+ pub magic: AtomicU32,
+ pub version: AtomicU32,
+ /// Even when consistent, odd while a writer is updating the buffer.
+ pub seq: AtomicU64,
+ /// `1` while a live camera stream is active, `0` when idle.
+ pub active: AtomicU32,
+ pub width: AtomicU32,
+ pub height: AtomicU32,
+ pub stride: AtomicU32,
+ pub _pad: AtomicU32,
+ pub timestamp_us: AtomicU64,
+ pub phone_name: [AtomicU8; 24],
+}
+
+/// Shared-memory mapping handle and view. Safe to share across threads.
+pub struct SharedFrameMapping {
+ handle: HANDLE,
+ view: MEMORY_MAPPED_VIEW_ADDRESS,
+}
+
+#[allow(unsafe_code)]
+// SAFETY: the underlying OS file mapping handle and mapped view address are
+// process-wide and synchronized via atomic operations in `SharedHeader`.
+unsafe impl Send for SharedFrameMapping {}
+#[allow(unsafe_code)]
+unsafe impl Sync for SharedFrameMapping {}
+
+impl std::fmt::Debug for SharedFrameMapping {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SharedFrameMapping").field("view", &self.view.Value).finish()
+ }
+}
+
+impl SharedFrameMapping {
+ /// Opens or creates the shared-memory frame mapping with `name` (a
+ /// `Global\` name gets [`GLOBAL_SDDL`]'s permissions).
+ #[allow(unsafe_code)]
+ pub fn open_or_create(name: &str) -> windows::core::Result<Self> {
+ let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
+ let mut sd = PSECURITY_DESCRIPTOR::default();
+ if name.starts_with("Global\\") {
+ // SAFETY: a constant SDDL string; the descriptor is freed below.
+ unsafe {
+ ConvertStringSecurityDescriptorToSecurityDescriptorW(
+ GLOBAL_SDDL,
+ SDDL_REVISION_1,
+ &mut sd,
+ None,
+ )?;
+ }
+ }
+ let attrs = SECURITY_ATTRIBUTES {
+ nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
+ lpSecurityDescriptor: sd.0,
+ bInheritHandle: false.into(),
+ };
+ // SAFETY: `CreateFileMappingW` with `INVALID_HANDLE_VALUE` creates or opens
+ // a pagefile-backed named mapping of `TOTAL_MAPPING_BYTES` bytes; `attrs`
+ // and the descriptor it points to outlive the call.
+ let handle = unsafe {
+ let handle = CreateFileMappingW(
+ INVALID_HANDLE_VALUE,
+ (!sd.0.is_null()).then_some(&raw const attrs),
+ PAGE_READWRITE,
+ 0,
+ TOTAL_MAPPING_BYTES as u32,
+ PCWSTR(wide.as_ptr()),
+ );
+ if !sd.0.is_null() {
+ let _ = LocalFree(Some(HLOCAL(sd.0)));
+ }
+ handle?
+ };
+ Self::map(handle)
+ }
+
+ /// For the camera's media source: the global mapping, or the caller's
+ /// session's when it may not create global objects (in-process tests).
+ pub fn for_camera(name: &str) -> windows::core::Result<Self> {
+ if name == DEFAULT_MAPPING_NAME {
+ Self::open_or_create(DEFAULT_MAPPING_NAME).or_else(|_| Self::open_or_create(LOCAL_MAPPING_NAME))
+ } else {
+ Self::open_or_create(name)
+ }
+ }
+
+ /// Opens an existing mapping (the app joining the camera's global one).
+ #[allow(unsafe_code)]
+ pub fn open_existing(name: &str) -> windows::core::Result<Self> {
+ let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
+ // SAFETY: opens a named mapping by a NUL-terminated name.
+ let handle =
+ unsafe { OpenFileMappingW((FILE_MAP_READ | FILE_MAP_WRITE).0, false, PCWSTR(wide.as_ptr()))? };
+ Self::map(handle)
+ }
+
+ #[allow(unsafe_code)]
+ fn map(handle: HANDLE) -> windows::core::Result<Self> {
+ // SAFETY: maps the whole section, which is `TOTAL_MAPPING_BYTES` long
+ // whichever side created it (both use the same size).
+ unsafe {
+ // Read and write only: that's all the app is granted on the global one.
+ let view = MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, TOTAL_MAPPING_BYTES);
+ if view.Value.is_null() {
+ let err = windows::core::Error::from_thread();
+ let _ = CloseHandle(handle);
+ return Err(err);
+ }
+ let mapping = Self { handle, view };
+ mapping.ensure_initialized();
+ Ok(mapping)
+ }
+ }
+
+ #[allow(unsafe_code)]
+ fn header(&self) -> &SharedHeader {
+ // SAFETY: `self.view.Value` points to a valid mapping of `TOTAL_MAPPING_BYTES`
+ // aligned to page boundaries (>= 64 bytes).
+ unsafe { &*(self.view.Value as *const SharedHeader) }
+ }
+
+ #[allow(unsafe_code)]
+ fn payload_ptr(&self) -> *mut u8 {
+ // SAFETY: `HEADER_BYTES` is within `TOTAL_MAPPING_BYTES`.
+ unsafe { (self.view.Value as *mut u8).add(HEADER_BYTES) }
+ }
+
+ fn ensure_initialized(&self) {
+ let h = self.header();
+ if h.magic.load(Ordering::Acquire) != MAGIC {
+ h.version.store(VERSION, Ordering::Relaxed);
+ h.magic.store(MAGIC, Ordering::Release);
+ }
+ }
+
+ fn store_phone_name(&self, name: &str) {
+ let h = self.header();
+ let bytes = name.as_bytes();
+ let mut len = bytes.len().min(h.phone_name.len());
+ while len > 0 && !name.is_char_boundary(len) {
+ len -= 1;
+ }
+ for (i, slot) in h.phone_name.iter().enumerate() {
+ let b = if i < len { bytes[i] } else { 0 };
+ slot.store(b, Ordering::Relaxed);
+ }
+ }
+
+ pub fn load_phone_name(&self) -> String {
+ let h = self.header();
+ let mut bytes = Vec::with_capacity(h.phone_name.len());
+ for slot in &h.phone_name {
+ let b = slot.load(Ordering::Relaxed);
+ if b == 0 {
+ break;
+ }
+ bytes.push(b);
+ }
+ String::from_utf8_lossy(&bytes).into_owned()
+ }
+
+ /// Marks the webcam stream as idle (placeholder shown) and updates the
+ /// phone name displayed on the placeholder card.
+ pub fn set_idle(&self, phone_name: &str) {
+ let h = self.header();
+ let seq = h.seq.load(Ordering::Relaxed);
+ let odd = if seq & 1 == 0 { seq.wrapping_add(1) } else { seq };
+ h.seq.store(odd, Ordering::Release);
+ self.store_phone_name(phone_name);
+ h.active.store(0, Ordering::Release);
+ h.seq.store(odd.wrapping_add(1), Ordering::Release);
+ }
+
+ /// Writes a decoded top-down BGRX frame into the shared mapping.
+ /// If `width > MAX_WIDTH` or `height > MAX_HEIGHT`, scales down to fit
+ /// `1920x1080`. Optionally mirrors horizontally when `mirror` is true.
+ #[allow(unsafe_code)]
+ pub fn write_frame(
+ &self,
+ phone_name: &str,
+ width: u32,
+ height: u32,
+ timestamp_us: u64,
+ bgrx: &[u8],
+ mirror: bool,
+ ) {
+ if width == 0 || height == 0 || bgrx.len() < (width as usize) * (height as usize) * 4 {
+ return;
+ }
+ let dst_w = width.min(MAX_WIDTH);
+ let dst_h = height.min(MAX_HEIGHT);
+ let dst_stride = dst_w * 4;
+ let dst_len = (dst_stride as usize) * (dst_h as usize);
+
+ let h = self.header();
+ let seq = h.seq.load(Ordering::Relaxed);
+ let odd = if seq & 1 == 0 { seq.wrapping_add(1) } else { seq };
+ h.seq.store(odd, Ordering::Release);
+ std::sync::atomic::fence(Ordering::AcqRel);
+
+ self.store_phone_name(phone_name);
+ h.width.store(dst_w, Ordering::Relaxed);
+ h.height.store(dst_h, Ordering::Relaxed);
+ h.stride.store(dst_stride, Ordering::Relaxed);
+ h.timestamp_us.store(timestamp_us, Ordering::Relaxed);
+
+ // SAFETY: writer holds the seqlock (`seq` is odd) and writes at most
+ // `MAX_FRAME_BYTES` into the payload region.
+ let dst = unsafe { std::slice::from_raw_parts_mut(self.payload_ptr(), dst_len) };
+ if dst_w == width && dst_h == height && !mirror {
+ dst.copy_from_slice(&bgrx[..dst_len]);
+ } else {
+ scale_or_mirror_bgrx(bgrx, width, height, dst, dst_w, dst_h, mirror);
+ }
+
+ h.active.store(1, Ordering::Release);
+ h.seq.store(odd.wrapping_add(1), Ordering::Release);
+ }
+
+ /// Reads the latest frame into `out_bgrx` (`out_width * out_height * 4` bytes).
+ /// Returns `(true, timestamp_us)` when a live frame was read, or
+ /// `(false, 0)` when idle (in which case `out_bgrx` is filled with the
+ /// placeholder frame).
+ #[allow(unsafe_code)]
+ pub fn read_bgrx(&self, out_width: u32, out_height: u32, out_bgrx: &mut [u8]) -> (bool, u64) {
+ let needed = (out_width as usize) * (out_height as usize) * 4;
+ if out_bgrx.len() < needed || out_width == 0 || out_height == 0 {
+ return (false, 0);
+ }
+ let h = self.header();
+ if h.magic.load(Ordering::Acquire) == MAGIC && h.active.load(Ordering::Acquire) == 1 {
+ for _ in 0..3 {
+ let seq1 = h.seq.load(Ordering::Acquire);
+ if seq1 == 0 || (seq1 & 1) != 0 {
+ std::hint::spin_loop();
+ continue;
+ }
+ let src_w = h.width.load(Ordering::Relaxed);
+ let src_h = h.height.load(Ordering::Relaxed);
+ let ts = h.timestamp_us.load(Ordering::Relaxed);
+ let src_len = (src_w as usize).saturating_mul(src_h as usize).saturating_mul(4);
+ if src_w > 0 && src_h > 0 && src_len <= MAX_FRAME_BYTES {
+ // SAFETY: `src_len <= MAX_FRAME_BYTES`; seqlock verifies consistency.
+ let src = unsafe { std::slice::from_raw_parts(self.payload_ptr(), src_len) };
+ if src_w == out_width && src_h == out_height {
+ out_bgrx[..needed].copy_from_slice(src);
+ } else {
+ fit_bgrx_aspect(src, src_w, src_h, &mut out_bgrx[..needed], out_width, out_height);
+ }
+ std::sync::atomic::fence(Ordering::Acquire);
+ let seq2 = h.seq.load(Ordering::Acquire);
+ if seq1 == seq2 {
+ return (true, ts);
+ }
+ }
+ }
+ }
+ let phone = self.load_phone_name();
+ render_placeholder_bgrx(&mut out_bgrx[..needed], out_width, out_height, &phone);
+ (false, 0)
+ }
+}
+
+impl Drop for SharedFrameMapping {
+ #[allow(unsafe_code)]
+ fn drop(&mut self) {
+ // SAFETY: paired with `MapViewOfFile` and `CreateFileMappingW`.
+ unsafe {
+ let _ = UnmapViewOfFile(self.view);
+ let _ = CloseHandle(self.handle);
+ }
+ }
+}
+
+fn scale_or_mirror_bgrx(
+ src: &[u8],
+ src_w: u32,
+ src_h: u32,
+ dst: &mut [u8],
+ dst_w: u32,
+ dst_h: u32,
+ mirror: bool,
+) {
+ let sw = src_w as usize;
+ let sh = src_h as usize;
+ let dw = dst_w as usize;
+ let dh = dst_h as usize;
+ for y in 0..dh {
+ let sy = (y * sh / dh).min(sh - 1);
+ let src_row = &src[sy * sw * 4..(sy + 1) * sw * 4];
+ let dst_row = &mut dst[y * dw * 4..(y + 1) * dw * 4];
+ for x in 0..dw {
+ let sx = (x * sw / dw).min(sw - 1);
+ let sx = if mirror { sw - 1 - sx } else { sx };
+ dst_row[x * 4..x * 4 + 4].copy_from_slice(&src_row[sx * 4..sx * 4 + 4]);
+ }
+ }
+}
+
+/// Scales `src` (`src_w x src_h`) into `dst` (`dst_w x dst_h`) preserving aspect
+/// ratio with dark pillarbox/letterbox bars when aspect ratios differ (e.g.
+/// portrait phone camera in a 16:9 webcam frame).
+pub fn fit_bgrx_aspect(src: &[u8], src_w: u32, src_h: u32, dst: &mut [u8], dst_w: u32, dst_h: u32) {
+ let sw = src_w as usize;
+ let sh = src_h as usize;
+ let dw = dst_w as usize;
+ let dh = dst_h as usize;
+ if sw == 0 || sh == 0 || dw == 0 || dh == 0 {
+ return;
+ }
+ // Fill background with dark neutral (#101216) when letterboxing/pillarboxing.
+ let (fit_w, fit_h) = if sw * dh >= sh * dw {
+ (dw, (dw * sh / sw).max(1).min(dh))
+ } else {
+ ((dh * sw / sh).max(1).min(dw), dh)
+ };
+ let off_x = (dw - fit_w) / 2;
+ let off_y = (dh - fit_h) / 2;
+ if off_x > 0 || off_y > 0 {
+ for px in dst.as_chunks_mut::<4>().0 {
+ px.copy_from_slice(&[0x16, 0x12, 0x10, 0xFF]);
+ }
+ }
+ for y in 0..fit_h {
+ let sy = (y * sh / fit_h).min(sh - 1);
+ let src_row = &src[sy * sw * 4..(sy + 1) * sw * 4];
+ let dst_row = &mut dst[(off_y + y) * dw * 4..(off_y + y + 1) * dw * 4];
+ for x in 0..fit_w {
+ let sx = (x * sw / fit_w).min(sw - 1);
+ let dx = (off_x + x) * 4;
+ dst_row[dx..dx + 4].copy_from_slice(&src_row[sx * 4..sx * 4 + 4]);
+ }
+ }
+}
+
+/// Converts top-down BGRX (`width * height * 4`) to NV12 (`width * height * 3 / 2`,
+/// BT.709 limited range).
+pub fn bgrx_to_nv12(bgrx: &[u8], width: u32, height: u32, nv12: &mut [u8]) {
+ let w = width as usize;
+ let h = height as usize;
+ let y_size = w * h;
+ let total = y_size + (w * (h / 2));
+ if bgrx.len() < w * h * 4 || nv12.len() < total {
+ return;
+ }
+ let (y_plane, uv_plane) = nv12[..total].split_at_mut(y_size);
+ for y in 0..h {
+ let row = &bgrx[y * w * 4..(y + 1) * w * 4];
+ let y_row = &mut y_plane[y * w..(y + 1) * w];
+ for x in 0..w {
+ let b = i32::from(row[x * 4]);
+ let g = i32::from(row[x * 4 + 1]);
+ let r = i32::from(row[x * 4 + 2]);
+ let luma = ((47 * r + 157 * g + 16 * b + 128) >> 8) + 16;
+ y_row[x] = luma.clamp(16, 235) as u8;
+ }
+ if y % 2 == 0 && (y / 2) * w < uv_plane.len() {
+ let uv_row = &mut uv_plane[(y / 2) * w..((y / 2) + 1) * w];
+ for x in (0..w).step_by(2) {
+ let b = i32::from(row[x * 4]);
+ let g = i32::from(row[x * 4 + 1]);
+ let r = i32::from(row[x * 4 + 2]);
+ let u = ((-26 * r - 87 * g + 112 * b + 128) >> 8) + 128;
+ let v = ((112 * r - 102 * g - 10 * b + 128) >> 8) + 128;
+ uv_row[x] = u.clamp(16, 240) as u8;
+ if x + 1 < w {
+ uv_row[x + 1] = v.clamp(16, 240) as u8;
+ }
+ }
+ }
+ }
+}
+
+/// Renders a clean placeholder frame ("NECTARLINK WEBCAM" / "START THE WEBCAM ON <PHONE>")
+/// into `bgrx` (`width * height * 4`).
+pub fn render_placeholder_bgrx(bgrx: &mut [u8], width: u32, height: u32, phone_name: &str) {
+ let w = width as usize;
+ let h = height as usize;
+ if bgrx.len() < w * h * 4 || w == 0 || h == 0 {
+ return;
+ }
+ // Dark slate background (#14171F)
+ for px in bgrx[..w * h * 4].as_chunks_mut::<4>().0 {
+ px.copy_from_slice(&[0x1F, 0x17, 0x14, 0xFF]);
+ }
+
+ // Center card (#1D222E) with subtle amber top accent bar (#F59E0B -> BGR 0x0B, 0x9E, 0xF5)
+ let card_w = (w * 3 / 5).clamp(320.min(w), w);
+ let card_h = (h * 2 / 5).clamp(180.min(h), h);
+ let cx0 = (w - card_w) / 2;
+ let cy0 = (h - card_h) / 2;
+ fill_rect(bgrx, w, h, cx0, cy0, card_w, card_h, [0x2E, 0x22, 0x1D, 0xFF]);
+ fill_rect(bgrx, w, h, cx0, cy0, card_w, 4.min(card_h), [0x0B, 0x9E, 0xF5, 0xFF]);
+
+ // Camera icon in the middle-top of the card
+ let scale = (h / 360).clamp(2, 4);
+ let icon_w = 18 * scale;
+ let icon_h = 12 * scale;
+ let ix = w / 2 - icon_w / 2;
+ let iy = cy0 + card_h / 4;
+ fill_rect(bgrx, w, h, ix, iy, icon_w * 3 / 4, icon_h, [0x0B, 0x9E, 0xF5, 0xFF]);
+ fill_rect(
+ bgrx,
+ w,
+ h,
+ ix + icon_w * 3 / 4 + scale,
+ iy + icon_h / 4,
+ icon_w / 4,
+ icon_h / 2,
+ [0x0B, 0x9E, 0xF5, 0xFF],
+ );
+
+ let title = "NECTARLINK WEBCAM";
+ let subtitle = if phone_name.trim().is_empty() {
+ "START THE WEBCAM ON YOUR PHONE".to_owned()
+ } else {
+ format!("START THE WEBCAM ON {}", phone_name.trim().to_ascii_uppercase())
+ };
+ draw_text_centered(bgrx, w, h, iy + icon_h + 8 * scale, scale, title, [0xF4, 0xF0, 0xEC, 0xFF]);
+ draw_text_centered(
+ bgrx,
+ w,
+ h,
+ iy + icon_h + 20 * scale,
+ (scale - 1).max(1),
+ &subtitle,
+ [0xB8, 0xA8, 0x9C, 0xFF],
+ );
+}
+
+#[allow(clippy::too_many_arguments)]
+fn fill_rect(
+ bgrx: &mut [u8],
+ w: usize,
+ h: usize,
+ x0: usize,
+ y0: usize,
+ rw: usize,
+ rh: usize,
+ color: [u8; 4],
+) {
+ let x1 = (x0 + rw).min(w);
+ let y1 = (y0 + rh).min(h);
+ for y in y0.min(h)..y1 {
+ let row = &mut bgrx[y * w * 4..(y + 1) * w * 4];
+ for x in x0.min(w)..x1 {
+ row[x * 4..x * 4 + 4].copy_from_slice(&color);
+ }
+ }
+}
+
+fn draw_text_centered(
+ bgrx: &mut [u8],
+ w: usize,
+ h: usize,
+ y: usize,
+ scale: usize,
+ text: &str,
+ color: [u8; 4],
+) {
+ let char_adv = 6 * scale;
+ let total_w = text.chars().count().saturating_mul(char_adv);
+ let start_x = w.saturating_sub(total_w) / 2;
+ for (i, ch) in text.chars().enumerate() {
+ let glyph = glyph_5x7(ch);
+ let gx = start_x + i * char_adv;
+ for (row_idx, &bits) in glyph.iter().enumerate() {
+ for col_idx in 0..5 {
+ if (bits >> (4 - col_idx)) & 1 != 0 {
+ fill_rect(bgrx, w, h, gx + col_idx * scale, y + row_idx * scale, scale, scale, color);
+ }
+ }
+ }
+ }
+}
+
+fn glyph_5x7(ch: char) -> [u8; 7] {
+ match ch.to_ascii_uppercase() {
+ 'A' => [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
+ 'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
+ 'C' => [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
+ 'D' => [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
+ 'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
+ 'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
+ 'G' => [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110],
+ 'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
+ 'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
+ 'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b10010, 0b10010, 0b01100],
+ 'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
+ 'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
+ 'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
+ 'N' => [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
+ 'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
+ 'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
+ 'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
+ 'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
+ 'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
+ 'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
+ 'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
+ 'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
+ 'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
+ 'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
+ 'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
+ 'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
+ '0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
+ '1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
+ '2' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
+ '3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
+ '4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
+ '5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
+ '6' => [0b01110, 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
+ '7' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
+ '8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
+ '9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00001, 0b01110],
+ '-' => [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
+ _ => [0; 7],
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_camera_always_gets_a_mapping_and_the_app_finds_it() {
+ // Outside a service the global name usually can't be created; the
+ // camera then falls back to this session's mapping.
+ let camera = SharedFrameMapping::for_camera(DEFAULT_MAPPING_NAME).unwrap();
+ camera.set_idle("Pixel 9");
+ let app = SharedFrameMapping::open_existing(DEFAULT_MAPPING_NAME)
+ .or_else(|_| SharedFrameMapping::open_existing(LOCAL_MAPPING_NAME))
+ .unwrap();
+ assert_eq!(app.load_phone_name(), "Pixel 9");
+ }
+
+ #[test]
+ fn opening_a_missing_mapping_fails() {
+ let name = format!(r"Local\NectarlinkVcamMissing_{}", std::process::id());
+ assert!(SharedFrameMapping::open_existing(&name).is_err());
+ }
+}
diff --git a/desktop/vcam/src/source.rs b/desktop/vcam/src/source.rs
new file mode 100644
index 0000000..459593f
--- /dev/null
+++ b/desktop/vcam/src/source.rs
@@ -0,0 +1,715 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Media Foundation custom media source (`IMFMediaSourceEx`, `IMFMediaStream2`,
+//! `IMFMediaEventGenerator`, `IMFGetService`, `IClassFactory`) for the Nectarlink
+//! virtual camera.
+
+#![allow(unsafe_code, clippy::not_unsafe_ptr_arg_deref)]
+
+use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicU32, Ordering},
+};
+
+use windows::{
+ Win32::{
+ Foundation::{E_INVALIDARG, E_POINTER, S_OK},
+ Media::{
+ KernelStreaming::PINNAME_VIDEO_CAPTURE,
+ MediaFoundation::{
+ IMFAttributes, IMFGetService, IMFGetService_Impl, IMFMediaEvent, IMFMediaEventGenerator,
+ IMFMediaEventGenerator_Impl, IMFMediaEventQueue, IMFMediaSource, IMFMediaSource_Impl,
+ IMFMediaSourceEx, IMFMediaSourceEx_Impl, IMFMediaStream, IMFMediaStream_Impl,
+ IMFMediaStream2, IMFMediaStream2_Impl, IMFMediaType, IMFPresentationDescriptor,
+ IMFStreamDescriptor, MEDIA_EVENT_GENERATOR_GET_EVENT_FLAGS, MEMediaSample, MENewStream,
+ MESourcePaused, MESourceStarted, MESourceStopped, MEStreamPaused, MEStreamStarted,
+ MEStreamStopped, MEUpdatedStream, MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES,
+ MF_DEVICESTREAM_FRAMESERVER_SHARED, MF_DEVICESTREAM_STREAM_CATEGORY,
+ MF_DEVICESTREAM_STREAM_ID, MF_E_NO_MORE_TYPES, MF_E_SHUTDOWN, MF_MT_ALL_SAMPLES_INDEPENDENT,
+ MF_MT_AVG_BITRATE, MF_MT_DEFAULT_STRIDE, MF_MT_FIXED_SIZE_SAMPLES, MF_MT_FRAME_RATE,
+ MF_MT_FRAME_RATE_RANGE_MAX, MF_MT_FRAME_RATE_RANGE_MIN, MF_MT_FRAME_SIZE,
+ MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SAMPLE_SIZE,
+ MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MF_STREAM_STATE,
+ MF_STREAM_STATE_PAUSED, MF_STREAM_STATE_RUNNING, MF_STREAM_STATE_STOPPED, MFCreateAttributes,
+ MFCreateEventQueue, MFCreateMediaType, MFCreateMemoryBuffer, MFCreatePresentationDescriptor,
+ MFCreateSample, MFCreateStreamDescriptor, MFFrameSourceTypes_Color, MFMediaType_Video,
+ MFNominalRange_0_255, MFNominalRange_16_235, MFSampleExtension_CleanPoint,
+ MFSampleExtension_Token, MFVideoFormat_NV12, MFVideoFormat_RGB32,
+ MFVideoInterlace_Progressive, MFVideoTransferMatrix_BT709,
+ },
+ },
+ System::Com::{IClassFactory, IClassFactory_Impl, StructuredStorage::PROPVARIANT},
+ },
+ core::{AsImpl, BOOL, GUID, HRESULT, IUnknown, Interface, Ref, implement},
+};
+
+use crate::shm::{DEFAULT_MAPPING_NAME, SharedFrameMapping, bgrx_to_nv12, render_placeholder_bgrx};
+
+/// Active DLL object/lock counter for `DllCanUnloadNow`.
+pub static ACTIVE_OBJECTS: AtomicU32 = AtomicU32::new(0);
+
+/// Sample duration for 30 fps in 100-ns units (`10_000_000 / 30 = 333_333`).
+pub const SAMPLE_DURATION_100NS: i64 = 333_333;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SourceState {
+ Stopped,
+ Paused,
+ Started,
+ Shutdown,
+}
+
+#[derive(Debug)]
+struct ObjectGuard;
+
+impl ObjectGuard {
+ fn new() -> Self {
+ ACTIVE_OBJECTS.fetch_add(1, Ordering::Relaxed);
+ Self
+ }
+}
+
+impl Drop for ObjectGuard {
+ fn drop(&mut self) {
+ ACTIVE_OBJECTS.fetch_sub(1, Ordering::Relaxed);
+ }
+}
+
+/// Builds an `IMFMediaType` for uncompressed `RGB32` or `NV12` video at `width × height` @ `fps`.
+#[allow(unsafe_code)]
+pub fn create_video_media_type(
+ subtype: &GUID,
+ width: u32,
+ height: u32,
+ fps: u32,
+) -> windows::core::Result<IMFMediaType> {
+ // SAFETY: standard Media Foundation attribute calls on a newly created `IMFMediaType`.
+ unsafe {
+ let mt = MFCreateMediaType()?;
+ mt.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
+ mt.SetGUID(&MF_MT_SUBTYPE, subtype)?;
+ mt.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)?;
+ mt.SetUINT32(&MF_MT_ALL_SAMPLES_INDEPENDENT, 1)?;
+ mt.SetUINT32(&MF_MT_FIXED_SIZE_SAMPLES, 1)?;
+ let frame_size = (u64::from(width) << 32) | u64::from(height);
+ mt.SetUINT64(&MF_MT_FRAME_SIZE, frame_size)?;
+ let frame_rate = (u64::from(fps) << 32) | 1u64;
+ mt.SetUINT64(&MF_MT_FRAME_RATE, frame_rate)?;
+ mt.SetUINT64(&MF_MT_FRAME_RATE_RANGE_MAX, frame_rate)?;
+ mt.SetUINT64(&MF_MT_FRAME_RATE_RANGE_MIN, frame_rate)?;
+ let par = (1u64 << 32) | 1u64;
+ mt.SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, par)?;
+
+ let (sample_size, stride, nominal_range) = if *subtype == MFVideoFormat_NV12 {
+ (width * height * 3 / 2, width, MFNominalRange_16_235.0 as u32)
+ } else {
+ (width * height * 4, width * 4, MFNominalRange_0_255.0 as u32)
+ };
+ mt.SetUINT32(&MF_MT_SAMPLE_SIZE, sample_size)?;
+ mt.SetUINT32(&MF_MT_DEFAULT_STRIDE, stride)?;
+ mt.SetUINT32(&MF_MT_AVG_BITRATE, sample_size.saturating_mul(fps).saturating_mul(8))?;
+ mt.SetUINT32(&MF_MT_VIDEO_NOMINAL_RANGE, nominal_range)?;
+ mt.SetUINT32(&MF_MT_YUV_MATRIX, MFVideoTransferMatrix_BT709.0 as u32)?;
+ Ok(mt)
+ }
+}
+
+struct SourceInner {
+ state: SourceState,
+ ever_started: bool,
+ events: IMFMediaEventQueue,
+ attrs: IMFAttributes,
+ pd: IMFPresentationDescriptor,
+ stream: Option<IMFMediaStream>,
+}
+
+#[implement(IMFMediaSourceEx, IMFMediaSource, IMFMediaEventGenerator, IMFGetService)]
+pub struct VcamMediaSource {
+ _guard: ObjectGuard,
+ mapping_name: String,
+ inner: Mutex<SourceInner>,
+}
+
+impl std::fmt::Debug for VcamMediaSource {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VcamMediaSource").field("mapping_name", &self.mapping_name).finish()
+ }
+}
+
+impl VcamMediaSource {
+ /// Creates a new `IMFMediaSourceEx` reading frames from `mapping_name`.
+ #[allow(unsafe_code)]
+ pub fn new_with_mapping(mapping_name: impl Into<String>) -> windows::core::Result<IMFMediaSourceEx> {
+ let mapping_name = mapping_name.into();
+ // SAFETY: Media Foundation helper calls creating attributes, media types,
+ // stream descriptor, presentation descriptor, and event queues.
+ unsafe {
+ let events = MFCreateEventQueue()?;
+ let mut attrs_opt = None;
+ MFCreateAttributes(&mut attrs_opt, 8)?;
+ let attrs = attrs_opt.ok_or_else(|| windows::core::Error::from(E_POINTER))?;
+ attrs
+ .SetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MFFrameSourceTypes_Color.0 as u32)?;
+
+ let media_types = [
+ Some(create_video_media_type(&MFVideoFormat_RGB32, 1280, 720, 30)?),
+ Some(create_video_media_type(&MFVideoFormat_NV12, 1280, 720, 30)?),
+ Some(create_video_media_type(&MFVideoFormat_RGB32, 1920, 1080, 30)?),
+ Some(create_video_media_type(&MFVideoFormat_NV12, 1920, 1080, 30)?),
+ ];
+ let sd = MFCreateStreamDescriptor(0, &media_types)?;
+ sd.SetGUID(&MF_DEVICESTREAM_STREAM_CATEGORY, &PINNAME_VIDEO_CAPTURE)?;
+ sd.SetUINT32(&MF_DEVICESTREAM_STREAM_ID, 0)?;
+ sd.SetUINT32(&MF_DEVICESTREAM_FRAMESERVER_SHARED, 1)?;
+ sd.SetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MFFrameSourceTypes_Color.0 as u32)?;
+
+ let handler = sd.GetMediaTypeHandler()?;
+ if let Some(first) = &media_types[0] {
+ handler.SetCurrentMediaType(first)?;
+ }
+
+ let sds = [Some(sd.clone())];
+ let pd = MFCreatePresentationDescriptor(Some(&sds))?;
+ pd.SelectStream(0)?;
+
+ let source: IMFMediaSourceEx = Self {
+ _guard: ObjectGuard::new(),
+ mapping_name: mapping_name.clone(),
+ inner: Mutex::new(SourceInner {
+ state: SourceState::Stopped,
+ ever_started: false,
+ events,
+ attrs,
+ pd,
+ stream: None,
+ }),
+ }
+ .into();
+
+ let mf_source: IMFMediaSource = source.cast()?;
+ let stream = VcamMediaStream::create(&mf_source, &sd, mapping_name)?;
+ let src_impl: &VcamMediaSource = source.as_impl();
+ if let Ok(mut guard) = src_impl.inner.lock() {
+ guard.stream = Some(stream);
+ }
+ Ok(source)
+ }
+ }
+}
+
+impl IMFMediaEventGenerator_Impl for VcamMediaSource_Impl {
+ fn GetEvent(
+ &self,
+ dwflags: MEDIA_EVENT_GENERATOR_GET_EVENT_FLAGS,
+ ) -> windows::core::Result<IMFMediaEvent> {
+ let events = {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.events.clone()
+ };
+ unsafe { events.GetEvent(dwflags.0) }
+ }
+
+ fn BeginGetEvent(
+ &self,
+ pcallback: Ref<'_, windows::Win32::Media::MediaFoundation::IMFAsyncCallback>,
+ punkstate: Ref<'_, IUnknown>,
+ ) -> windows::core::Result<()> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.BeginGetEvent(pcallback.as_ref(), punkstate.as_ref()) }
+ }
+
+ fn EndGetEvent(
+ &self,
+ presult: Ref<'_, windows::Win32::Media::MediaFoundation::IMFAsyncResult>,
+ ) -> windows::core::Result<IMFMediaEvent> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.EndGetEvent(presult.as_ref()) }
+ }
+
+ fn QueueEvent(
+ &self,
+ met: u32,
+ guidextendedtype: *const GUID,
+ hrstatus: HRESULT,
+ pvvalue: *const PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.QueueEventParamVar(met, guidextendedtype, hrstatus, pvvalue) }
+ }
+}
+
+impl IMFMediaSource_Impl for VcamMediaSource_Impl {
+ fn GetCharacteristics(&self) -> windows::core::Result<u32> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ // MFMEDIASOURCE_IS_LIVE = 0x1
+ Ok(0x1)
+ }
+
+ fn CreatePresentationDescriptor(&self) -> windows::core::Result<IMFPresentationDescriptor> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.pd.Clone() }
+ }
+
+ fn Start(
+ &self,
+ ppresentationdescriptor: Ref<'_, IMFPresentationDescriptor>,
+ pguidtimeformat: *const GUID,
+ pvarstartposition: *const PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ if ppresentationdescriptor.is_null() {
+ return Err(E_POINTER.into());
+ }
+ if !pguidtimeformat.is_null() {
+ let guid = unsafe { *pguidtimeformat };
+ if guid != GUID::zeroed() {
+ return Err(E_INVALIDARG.into());
+ }
+ }
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ let Some(stream) = guard.stream.clone() else {
+ return Err(MF_E_SHUTDOWN.into());
+ };
+ let event_type = if guard.ever_started { MEUpdatedStream } else { MENewStream };
+ guard.ever_started = true;
+ guard.state = SourceState::Started;
+
+ unsafe {
+ let unk: IUnknown = stream.cast()?;
+ guard.events.QueueEventParamUnk(event_type.0 as u32, &GUID::zeroed(), S_OK, &unk)?;
+ let empty = PROPVARIANT::default();
+ let pos = if pvarstartposition.is_null() { &empty } else { &*pvarstartposition };
+ guard.events.QueueEventParamVar(MESourceStarted.0 as u32, &GUID::zeroed(), S_OK, pos)?;
+ let stream_impl: &VcamMediaStream = stream.as_impl();
+ stream_impl.on_start(pos)?;
+ }
+ Ok(())
+ }
+
+ fn Stop(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.state = SourceState::Stopped;
+ if let Some(stream) = guard.stream.clone() {
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ stream_impl.on_stop()?;
+ }
+ let empty = PROPVARIANT::default();
+ unsafe { guard.events.QueueEventParamVar(MESourceStopped.0 as u32, &GUID::zeroed(), S_OK, &empty) }
+ }
+
+ fn Pause(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.state = SourceState::Paused;
+ if let Some(stream) = guard.stream.clone() {
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ stream_impl.on_pause()?;
+ }
+ let empty = PROPVARIANT::default();
+ unsafe { guard.events.QueueEventParamVar(MESourcePaused.0 as u32, &GUID::zeroed(), S_OK, &empty) }
+ }
+
+ fn Shutdown(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Ok(());
+ }
+ guard.state = SourceState::Shutdown;
+ if let Some(stream) = guard.stream.take() {
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ let _ = stream_impl.on_shutdown();
+ }
+ unsafe { guard.events.Shutdown() }
+ }
+}
+
+impl IMFMediaSourceEx_Impl for VcamMediaSource_Impl {
+ fn GetSourceAttributes(&self) -> windows::core::Result<IMFAttributes> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ Ok(guard.attrs.clone())
+ }
+
+ fn GetStreamAttributes(&self, dwstreamidentifier: u32) -> windows::core::Result<IMFAttributes> {
+ if dwstreamidentifier != 0 {
+ return Err(E_INVALIDARG.into());
+ }
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.state == SourceState::Shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ let Some(stream) = guard.stream.as_ref() else {
+ return Err(MF_E_SHUTDOWN.into());
+ };
+ let stream_impl: &VcamMediaStream = unsafe { stream.as_impl() };
+ Ok(stream_impl.attributes())
+ }
+
+ fn SetD3DManager(&self, _punkmanager: Ref<'_, IUnknown>) -> windows::core::Result<()> {
+ // Software camera frames are delivered in system-memory buffers.
+ Ok(())
+ }
+}
+
+impl IMFGetService_Impl for VcamMediaSource_Impl {
+ fn GetService(
+ &self,
+ _guidservice: *const GUID,
+ _riid: *const GUID,
+ ppvobject: *mut *mut std::ffi::c_void,
+ ) -> windows::core::Result<()> {
+ if !ppvobject.is_null() {
+ unsafe { *ppvobject = std::ptr::null_mut() };
+ }
+ Err(MF_E_NO_MORE_TYPES.into())
+ }
+}
+
+struct StreamInner {
+ state: MF_STREAM_STATE,
+ shutdown: bool,
+ events: IMFMediaEventQueue,
+ attrs: IMFAttributes,
+ sd: IMFStreamDescriptor,
+ source: IMFMediaSource,
+ mapping: Option<Arc<SharedFrameMapping>>,
+ sample_index: u64,
+ bgrx_scratch: Vec<u8>,
+}
+
+#[implement(IMFMediaStream2, IMFMediaStream, IMFMediaEventGenerator)]
+pub struct VcamMediaStream {
+ _guard: ObjectGuard,
+ mapping_name: String,
+ inner: Mutex<StreamInner>,
+}
+
+impl std::fmt::Debug for VcamMediaStream {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VcamMediaStream").field("mapping_name", &self.mapping_name).finish()
+ }
+}
+
+impl VcamMediaStream {
+ fn create(
+ source: &IMFMediaSource,
+ sd: &IMFStreamDescriptor,
+ mapping_name: String,
+ ) -> windows::core::Result<IMFMediaStream> {
+ unsafe {
+ let events = MFCreateEventQueue()?;
+ let mut attrs_opt = None;
+ MFCreateAttributes(&mut attrs_opt, 8)?;
+ let attrs = attrs_opt.ok_or_else(|| windows::core::Error::from(E_POINTER))?;
+ attrs.SetGUID(&MF_DEVICESTREAM_STREAM_CATEGORY, &PINNAME_VIDEO_CAPTURE)?;
+ attrs.SetUINT32(&MF_DEVICESTREAM_STREAM_ID, 0)?;
+ attrs.SetUINT32(&MF_DEVICESTREAM_FRAMESERVER_SHARED, 1)?;
+ attrs
+ .SetUINT32(&MF_DEVICESTREAM_ATTRIBUTE_FRAMESOURCE_TYPES, MFFrameSourceTypes_Color.0 as u32)?;
+ let mapping = SharedFrameMapping::for_camera(&mapping_name).ok().map(Arc::new);
+ let stream: IMFMediaStream = Self {
+ _guard: ObjectGuard::new(),
+ mapping_name,
+ inner: Mutex::new(StreamInner {
+ state: MF_STREAM_STATE_STOPPED,
+ shutdown: false,
+ events,
+ attrs,
+ sd: sd.clone(),
+ source: source.clone(),
+ mapping,
+ sample_index: 0,
+ bgrx_scratch: Vec::new(),
+ }),
+ }
+ .into();
+ Ok(stream)
+ }
+ }
+
+ fn attributes(&self) -> IMFAttributes {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ guard.attrs.clone()
+ }
+
+ fn on_start(&self, pos: &PROPVARIANT) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ if guard.mapping.is_none() {
+ guard.mapping = SharedFrameMapping::for_camera(&self.mapping_name).ok().map(Arc::new);
+ }
+ guard.state = MF_STREAM_STATE_RUNNING;
+ guard.sample_index = 0;
+ unsafe { guard.events.QueueEventParamVar(MEStreamStarted.0 as u32, &GUID::zeroed(), S_OK, pos) }
+ }
+
+ fn on_stop(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.state = MF_STREAM_STATE_STOPPED;
+ let empty = PROPVARIANT::default();
+ unsafe { guard.events.QueueEventParamVar(MEStreamStopped.0 as u32, &GUID::zeroed(), S_OK, &empty) }
+ }
+
+ fn on_pause(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.state = MF_STREAM_STATE_PAUSED;
+ let empty = PROPVARIANT::default();
+ unsafe { guard.events.QueueEventParamVar(MEStreamPaused.0 as u32, &GUID::zeroed(), S_OK, &empty) }
+ }
+
+ fn on_shutdown(&self) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ guard.shutdown = true;
+ guard.mapping = None;
+ unsafe { guard.events.Shutdown() }
+ }
+}
+
+impl IMFMediaEventGenerator_Impl for VcamMediaStream_Impl {
+ fn GetEvent(
+ &self,
+ dwflags: MEDIA_EVENT_GENERATOR_GET_EVENT_FLAGS,
+ ) -> windows::core::Result<IMFMediaEvent> {
+ let events = {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ guard.events.clone()
+ };
+ unsafe { events.GetEvent(dwflags.0) }
+ }
+
+ fn BeginGetEvent(
+ &self,
+ pcallback: Ref<'_, windows::Win32::Media::MediaFoundation::IMFAsyncCallback>,
+ punkstate: Ref<'_, IUnknown>,
+ ) -> windows::core::Result<()> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.BeginGetEvent(pcallback.as_ref(), punkstate.as_ref()) }
+ }
+
+ fn EndGetEvent(
+ &self,
+ presult: Ref<'_, windows::Win32::Media::MediaFoundation::IMFAsyncResult>,
+ ) -> windows::core::Result<IMFMediaEvent> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.EndGetEvent(presult.as_ref()) }
+ }
+
+ fn QueueEvent(
+ &self,
+ met: u32,
+ guidextendedtype: *const GUID,
+ hrstatus: HRESULT,
+ pvvalue: *const PROPVARIANT,
+ ) -> windows::core::Result<()> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ unsafe { guard.events.QueueEventParamVar(met, guidextendedtype, hrstatus, pvvalue) }
+ }
+}
+
+impl IMFMediaStream_Impl for VcamMediaStream_Impl {
+ fn GetMediaSource(&self) -> windows::core::Result<IMFMediaSource> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ Ok(guard.source.clone())
+ }
+
+ fn GetStreamDescriptor(&self) -> windows::core::Result<IMFStreamDescriptor> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ Ok(guard.sd.clone())
+ }
+
+ fn RequestSample(&self, punktoken: Ref<'_, IUnknown>) -> windows::core::Result<()> {
+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ if guard.state != MF_STREAM_STATE_RUNNING {
+ return Err(E_INVALIDARG.into());
+ }
+ if guard.mapping.is_none() {
+ guard.mapping = SharedFrameMapping::for_camera(&self.mapping_name).ok().map(Arc::new);
+ }
+
+ unsafe {
+ let handler = guard.sd.GetMediaTypeHandler()?;
+ let mt = handler.GetCurrentMediaType()?;
+ let subtype = mt.GetGUID(&MF_MT_SUBTYPE)?;
+ let frame_size = mt.GetUINT64(&MF_MT_FRAME_SIZE)?;
+ let width = ((frame_size >> 32) as u32).max(1);
+ let height = (frame_size as u32).max(1);
+
+ let bgrx_len = (width as usize) * (height as usize) * 4;
+ if guard.bgrx_scratch.len() < bgrx_len {
+ guard.bgrx_scratch.resize(bgrx_len, 0);
+ }
+ if let Some(mapping) = guard.mapping.clone() {
+ mapping.read_bgrx(width, height, &mut guard.bgrx_scratch[..bgrx_len]);
+ } else {
+ render_placeholder_bgrx(&mut guard.bgrx_scratch[..bgrx_len], width, height, "");
+ }
+
+ let out_bytes = if subtype == MFVideoFormat_NV12 {
+ (width as usize) * (height as usize) * 3 / 2
+ } else {
+ bgrx_len
+ };
+
+ let buffer = MFCreateMemoryBuffer(out_bytes as u32)?;
+ let mut ptr = std::ptr::null_mut();
+ buffer.Lock(&mut ptr, None, None)?;
+ let dst = std::slice::from_raw_parts_mut(ptr, out_bytes);
+ if subtype == MFVideoFormat_NV12 {
+ bgrx_to_nv12(&guard.bgrx_scratch[..bgrx_len], width, height, dst);
+ } else {
+ dst.copy_from_slice(&guard.bgrx_scratch[..bgrx_len]);
+ }
+ buffer.Unlock()?;
+ buffer.SetCurrentLength(out_bytes as u32)?;
+
+ let sample = MFCreateSample()?;
+ sample.AddBuffer(&buffer)?;
+ let sample_time = (guard.sample_index as i64).saturating_mul(SAMPLE_DURATION_100NS);
+ guard.sample_index = guard.sample_index.wrapping_add(1);
+ sample.SetSampleTime(sample_time)?;
+ sample.SetSampleDuration(SAMPLE_DURATION_100NS)?;
+ sample.SetUINT32(&MFSampleExtension_CleanPoint, 1)?;
+ if let Some(token) = punktoken.as_ref() {
+ sample.SetUnknown(&MFSampleExtension_Token, token)?;
+ }
+
+ let sample_unk: IUnknown = sample.cast()?;
+ guard.events.QueueEventParamUnk(MEMediaSample.0 as u32, &GUID::zeroed(), S_OK, &sample_unk)?;
+ }
+ Ok(())
+ }
+}
+
+impl IMFMediaStream2_Impl for VcamMediaStream_Impl {
+ fn SetStreamState(&self, value: MF_STREAM_STATE) -> windows::core::Result<()> {
+ match value {
+ MF_STREAM_STATE_RUNNING => {
+ let empty = PROPVARIANT::default();
+ self.on_start(&empty)
+ }
+ MF_STREAM_STATE_PAUSED => self.on_pause(),
+ MF_STREAM_STATE_STOPPED => self.on_stop(),
+ _ => Err(E_INVALIDARG.into()),
+ }
+ }
+
+ fn GetStreamState(&self) -> windows::core::Result<MF_STREAM_STATE> {
+ let guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.shutdown {
+ return Err(MF_E_SHUTDOWN.into());
+ }
+ Ok(guard.state)
+ }
+}
+
+/// COM `IClassFactory` creating [`VcamMediaSource`] instances.
+#[implement(IClassFactory)]
+pub struct VcamClassFactory {
+ _guard: ObjectGuard,
+}
+
+impl std::fmt::Debug for VcamClassFactory {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VcamClassFactory").finish()
+ }
+}
+
+impl Default for VcamClassFactory {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl VcamClassFactory {
+ pub fn new() -> Self {
+ Self { _guard: ObjectGuard::new() }
+ }
+}
+
+#[allow(unsafe_code)]
+impl IClassFactory_Impl for VcamClassFactory_Impl {
+ fn CreateInstance(
+ &self,
+ punkouter: Ref<'_, IUnknown>,
+ riid: *const GUID,
+ ppvobject: *mut *mut std::ffi::c_void,
+ ) -> windows::core::Result<()> {
+ if ppvobject.is_null() {
+ return Err(E_POINTER.into());
+ }
+ unsafe { *ppvobject = std::ptr::null_mut() };
+ if !punkouter.is_null() {
+ return Err(windows::Win32::Foundation::CLASS_E_NOAGGREGATION.into());
+ }
+ if riid.is_null() {
+ return Err(E_INVALIDARG.into());
+ }
+ let source = VcamMediaSource::new_with_mapping(DEFAULT_MAPPING_NAME)?;
+ let unk: IUnknown = source.cast()?;
+ unsafe { unk.query(riid, ppvobject).ok() }
+ }
+
+ fn LockServer(&self, flock: BOOL) -> windows::core::Result<()> {
+ if flock.as_bool() {
+ ACTIVE_OBJECTS.fetch_add(1, Ordering::Relaxed);
+ } else {
+ ACTIVE_OBJECTS.fetch_sub(1, Ordering::Relaxed);
+ }
+ Ok(())
+ }
+}
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 1edec27..05310f0 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -193,7 +193,7 @@ current Android. Talking through the PC comes with the HFP item above.
### 3.9 Camera
| Feature | Tier |
|---|---|
-| **Phone as webcam** (Windows 11 virtual camera, shows up in Teams/Zoom/OBS/Camera app). Front/back, zoom, torch, HDR, 1080p/4K | P1 🟢 (CameraX) |
+| **Phone as webcam** (Windows 11 virtual camera, shows up in Teams/Zoom/OBS/Camera app). Front/back, zoom, torch, HDR, 1080p/4K ✅ | P1 🟢 (Camera2) |
| **Continuity Camera**: right-click in any PC app → "Take photo / Scan document with phone" → the phone opens the camera (with document edge detection) → the result is pasted at the cursor | P1 🟢 |
### 3.10 Remote input & control
diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.md
index 8848c30..dff870b 100644
--- a/docs/architecture/capabilities.md
+++ b/docs/architecture/capabilities.md
@@ -121,8 +121,8 @@ the OS (`android` → phone, `windows`/`macos` → desktop).
## Per-device toggles
`notifications`, `messages`, `calls`, `contacts`, `clipboard`, `files`,
-`media`, `photos`, `recordings`, `toggles`, `pc_actions`, `mirroring` (on by
-default) and `storage`, `remote_input`, `commands`, `remote_files` (off by default). Toggles are this
+`media`, `photos`, `recordings`, `toggles`, `pc_actions`, `mirroring`,
+`webcam` (on by default) and `storage`, `remote_input`, `commands`, `remote_files` (off by default). Toggles are this
device's policy for that peer and are stored locally, so a feature the PC
user switched off is Locked on the PC while the phone may still show it as
Available. Everything else in the matrix is identical on both devices.
@@ -136,7 +136,7 @@ Available. Everything else in the matrix is identical on both devices.
| `notifications.sensitive` | phone `notify.sensitive` (Elevated), toggle | – | Locked → Elevated · ~2 min |
| `mirroring.control` | phone `mirror.capture`, `mirror.input` (Assist) | – | Locked → Assist · ~1 min |
| `mirroring.app_windows` | phone `mirror.virtual_display` (Elevated), Elevated, Android ≥ 11 | – | Locked → Elevated |
-| `camera.webcam` | phone `camera.stream` (camera permission), desktop `addon.vcam`, Windows build ≥ 22000 | – | Locked → install virtual camera · ~1 min |
+| `camera.webcam` | phone `camera.stream` (camera permission), desktop `camera.virtual`, desktop `addon.vcam`, Windows build ≥ 22000, toggle `webcam` | – | Locked → install virtual camera · ~1 min |
The full registry is `FEATURES` in `core/nectarlink-core/src/features.rs`.
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 17df672..0eef242 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -61,7 +61,7 @@ capability is missing.
| `toggles.bluetooth` | Turns Bluetooth on or off ([toggles](toggles.md)) | Elevated |
| `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 | camera permission |
+| `camera.stream` | Streams a camera for webcam use ([webcam](webcam.md)) | camera permission |
## Desktop
@@ -81,4 +81,5 @@ capability is missing.
| `input.inject` | Accepts pointer, keyboard and presentation input ([remote input](remote.md)) | app update |
| `recorder` | Saves and converts voice recordings from a phone ([recorder](recorder.md)) | app update |
| `deck.actions` | Shares its Deck layout and live tile state and runs Deck actions ([deck](deck.md)) | app update |
-| `addon.vcam` | The virtual camera add-on is installed | installing the add-on |
+| `camera.virtual` | Receives and decodes a phone's camera stream ([webcam](webcam.md)) | app update |
+| `addon.vcam` | The virtual camera add-on is installed ([webcam](webcam.md)) | installing the add-on |
diff --git a/docs/protocol/webcam.md b/docs/protocol/webcam.md
new file mode 100644
index 0000000..4d9842c
--- /dev/null
+++ b/docs/protocol/webcam.md
@@ -0,0 +1,95 @@
+# Phone as webcam (v1)
+
+Uses a paired phone's camera as a webcam on a PC. Control messages travel on
+the session's control stream ([protocol v0](v0.md) §4); encoded video frames
+travel on a dedicated bidirectional QUIC stream (`{ svc: "webcam", op: "video", v: 1 }`).
+
+## 1. Capabilities and toggle
+
+| Capability | Offered by | Meaning |
+|---|---|---|
+| `camera.stream` | Phone | Streams a camera for webcam use (when `CAMERA` permission is granted) |
+| `camera.virtual` | PC | Receives and decodes a phone's webcam stream |
+| `addon.vcam` | PC | The Windows virtual camera COM add-on is registered in `HKLM`, so apps (Teams, Meet, Zoom, Windows Camera) see `"Nectarlink - <Phone name>"` |
+
+Both devices have a `webcam` per-device toggle (on by default). When turned off
+for a peer, `webcam.start` is refused with `denied` (`4`), incoming `webcam`
+streams are reset with code `12`, and any active webcam stream with that peer
+is stopped immediately.
+
+A phone **never** starts streaming its camera silently: streaming starts only
+when the user starts it on the phone's Webcam screen or explicitly accepts a
+PC's request, and an ongoing `camera` foreground service notification with a
+**Stop** button is shown the entire time.
+
+## 2. Starting and stopping
+
+### `webcam.start` → `webcam.ok` (PC → phone, request)
+
+Asks the phone to stream its camera (or updates camera/resolution while
+already streaming):
+
+```
+{
+ t: "webcam.start",
+ id: uint,
+ camera: "back" | "front", // default: "back"
+ width: uint, // 320..=3840 (e.g. 1280, 1920, 3840)
+ height: uint, // 240..=2160 (e.g. 720, 1080, 2160)
+ fps: uint, // 1..=60 (default: 30)
+ bitrate: uint // 100_000..=50_000_000 bits/s (default: 6_000_000)
+}
+```
+
+The phone answers `{ t: "webcam.ok", re: id }` once it has shown the user the
+request (or applied the updated options to an already-active stream), or an
+`error` (`denied` when the `webcam` toggle is off on either side, `unsupported`
+when `camera.stream` is not offered, `bad_message` when fields are out of
+bounds).
+
+The user may also start the webcam directly from the phone's Webcam screen
+without a prior `webcam.start` from the PC; in that case the phone opens the
+`webcam/video` stream directly to the selected PC.
+
+### `webcam.stop` (either direction, notification)
+
+```
+{ t: "webcam.stop" }
+```
+
+Stops the webcam stream. Either side may also stop by closing or resetting the
+`webcam/video` stream with application error code `12` (`webcam::STOPPED`).
+
+### `webcam.keyframe` (PC → phone, notification)
+
+```
+{ t: "webcam.keyframe" }
+```
+
+Asks the phone's hardware H.264 encoder for an immediate IDR keyframe
+(`PARAMETER_KEY_REQUEST_SYNC_FRAME`), sent when the PC decoder starts mid-stream
+or after a dropped packet.
+
+## 3. Video stream
+
+The phone opens a bidirectional stream to the PC and writes the stream header:
+
+```
+{ t: "stream", svc: "webcam", op: "video", v: 1 }
+```
+
+Followed by a sequence of framed video packets (`core/nectarlink-protocol/src/video.rs`):
+
+```
+[kind: u8][timestamp_us: u64 big-endian][length: u32 big-endian][payload: length bytes]
+```
+
+| `kind` | Name | Payload |
+|---|---|---|
+| `0` | `Config` | CBOR `WebcamConfig` (`{ codec: "h264", width: uint, height: uint, camera: "back" \| "front", fps: uint }`), sent at the start of the stream and whenever resolution or camera changes |
+| `1` | `Frame` | Annex B H.264 non-IDR access unit |
+| `2` | `Keyframe` | Annex B H.264 IDR access unit (preceded by SPS and PPS NAL units) |
+
+The phone's sender bounds its outgoing queue to a few frames (`QUEUE_FRAMES = 4`):
+if the network falls behind, queued frames are dropped and the encoder is asked
+for a fresh keyframe rather than building up latency.
diff --git a/scripts/package.ps1 b/scripts/package.ps1
index d3de20a..7552b8e 100644
--- a/scripts/package.ps1
+++ b/scripts/package.ps1
@@ -59,10 +59,12 @@ if (-not (Test-Path $windeployqt)) { throw "windeployqt not found under $QtRoot;
if (-not $SkipBuild) {
Step "Build"
$env:PATH = "$(Join-Path $QtRoot 'bin');$env:PATH"
- Invoke-Native "the build" { cargo build --locked --release -p nectarlink-desktop }
+ Invoke-Native "the build" { cargo build --locked --release -p nectarlink-desktop -p nectarlink-vcam }
}
$exe = Join-Path $root 'target\release\nectarlink-desktop.exe'
if (-not (Test-Path $exe)) { throw "no release build at $exe" }
+$vcamDll = Join-Path $root 'target\release\nectarlink_vcam.dll'
+if (-not (Test-Path $vcamDll)) { throw "no release build at $vcamDll" }
# ---- Stage ----
Step "Stage"
@@ -71,6 +73,7 @@ $stage = Join-Path $package 'Nectarlink'
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
New-Item -ItemType Directory -Force $stage | Out-Null
Copy-Item $exe $stage
+Copy-Item $vcamDll $stage
Invoke-Native "windeployqt" {
& $windeployqt --verbose 0 --release --qmldir (Join-Path $root 'desktop\app\qml') --no-translations `