Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Screen mirroring, phone side; Android reconnects after a network comes up
Bee846ecf5b340e
diff --git a/README.md b/README.mdindex 731b86d..fd97c53 100644--- a/README.md+++ b/README.md@@ -89,6 +89,9 @@ place and tested; the user-facing features of Phase 1 come next.on the phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and`Download/Nectarlink` on the phone, with progress, cancelling, and transfersthat pick up where they left off after a dropped connection.+- **Screen mirroring** (view): see the phone's screen on the PC, in a+ window of its own, at up to 1920 pixels and 60 frames a second, hardware+ encoded on the phone. Android asks each time; stop it from either side.- **Texts** on the PC: a Messages page with the phone's conversations(pictures included), to reply or start a new one; texts go out throughthe phone.diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 7552239..05dc955 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -11,6 +11,8 @@<!-- Staying reachable in the background. --><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />+ <!-- Sharing the screen with a PC (each time, after Android's prompt). -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" /><uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><!-- Scanning the pairing QR code. --><uses-permission android:name="android.permission.CAMERA" />@@ -151,6 +153,20 @@</intent-filter></service>+ <!-- Shows Android's screen capture prompt for a PC's request. -->+ <activity+ android:name=".mirror.MirrorConsentActivity"+ android:exported="false"+ android:excludeFromRecents="true"+ android:noHistory="false"+ android:taskAffinity=""+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />++ <service+ android:name=".mirror.MirrorService"+ android:exported="false"+ android:foregroundServiceType="mediaProjection" />+<serviceandroid: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.ktindex c34e641..a4b4892 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@@ -17,11 +17,13 @@ import app.nectarlink.android.files.TransferNotificationsimport app.nectarlink.android.Rimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.calls.PhoneCalls+import app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.core.Eventimport app.nectarlink.core.EventListenerimport app.nectarlink.core.FileToSend+import app.nectarlink.core.MirrorStreamimport app.nectarlink.core.Linkimport app.nectarlink.core.NectarlinkExceptionimport app.nectarlink.core.NectarlinkNode@@ -67,6 +69,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListeneronLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },onCall = { id, command -> calls.command(id, command) },sms = { sms },+ onMirror = { pc, request ->+ MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())+ },)private val sms = PhoneSms(this.context) {notificationOps.trySend { it.smsChanged(null) }@@ -258,6 +263,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener* The files are opened right away: Android's permission to read a* shared item ends with the activity that received it.*/+ /** Opens this phone's screen stream to a PC (after the user agreed). */+ suspend fun mirrorOpen(pcId: String): MirrorStream {+ startJob?.join()+ val node = checkNotNull(node) { "the core isn't running" }+ return node.mirrorOpen(pcId)+ }+fun sendFiles(pcId: String, uris: List<Uri>) = send(pcId, OutgoingFiles.open(context, uris))/** Sends a folder the user picked, with everything in it. */@@ -490,7 +502,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener/** Sharing this phone's players, which also needs notification access. */val MEDIA_CAPABILITIES = listOf("media.control")/** Accepting the PC's clipboard, and sending this one when asked. */- val CLIPBOARD_CAPABILITIES = listOf("clip.write", "clip.share")+ val CLIPBOARD_CAPABILITIES = listOf("clip.write", "clip.share", "mirror.capture")/** With access to the phone's photos. */val PHOTO_CAPABILITIES = listOf("photos.read")}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.ktindex d4874b5..dd7a2de 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@@ -114,8 +114,8 @@ data class CoreState(is Event.Transfer -> copy(transfers = withTransfer(event.transfer))// Shown in Android's media controls (see media/PcMedia).is Event.MediaChanged -> this- // PCs only: phones announce their own photos and calls.- is Event.PhotoAdded, is Event.CallChanged, is Event.SmsChanged -> this+ // PCs only: phones announce their own photos, calls, texts and screen.+ is Event.PhotoAdded, is Event.CallChanged, is Event.SmsChanged, is Event.Mirroring -> this}private fun withTransfer(transfer: Transfer): List<Transfer> {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 6e88dd7..35912b5 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@@ -12,6 +12,9 @@ import app.nectarlink.android.clipboard.PhoneClipboardimport app.nectarlink.android.notifications.NotificationListenerimport app.nectarlink.android.media.PhoneMediaimport app.nectarlink.android.photos.RecentPhotos+import app.nectarlink.android.mirror.MirrorRequest+import app.nectarlink.android.mirror.MirrorRequests+import app.nectarlink.android.mirror.MirrorServiceimport app.nectarlink.android.sms.PhoneSmsimport app.nectarlink.core.CallCommandimport app.nectarlink.core.SmsMessage@@ -36,6 +39,8 @@ internal class PhonePlatform(private val onCall: (String, CallCommand) -> Boolean,/** The phone's texts (created after this). */private val sms: () -> PhoneSms,+ /** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */+ private val onMirror: (String, MirrorRequest) -> Boolean,) : Platform {private val context = context.applicationContext@@ -57,6 +62,16 @@ internal class PhonePlatform(override fun callCommand(id: String, command: CallCommand): Boolean = onCall(id, command)+ override fun mirrorRequested(pcId: String, maxSize: UInt, fps: UInt, bitrate: UInt): Boolean =+ onMirror(pcId, MirrorRequest(pcId, maxSize.toInt(), fps.toInt(), bitrate.toInt()))++ override fun mirrorStopRequested(pcId: String) {+ MirrorRequests.dismiss(context, pcId)+ MirrorService.stop(pcId)+ }++ override fun mirrorKeyframeRequested(pcId: String) = MirrorService.keyframe(pcId)+override fun smsThreads(limit: UInt): List<SmsThread> = sms().threads(limit.toInt())override fun smsMessages(thread: String, before: Long?, limit: UInt): List<SmsMessage> =diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.ktindex 44e940c..60d90e3 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt@@ -6,6 +6,7 @@ import android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.net.ConnectivityManager+import android.net.LinkPropertiesimport android.net.Networkimport android.net.NetworkCapabilitiesimport android.os.BatteryManager@@ -76,9 +77,26 @@ class BatteryMonitor(private val context: Context, private val onChange: (Batterclass NetworkMonitor(context: Context, private val onChange: () -> Unit) {private val connectivity = context.getSystemService(ConnectivityManager::class.java)private val callback = object : ConnectivityManager.NetworkCallback() {+ /** Whether the default network was confirmed working, last we heard. */+ private var validated = false+override fun onAvailable(network: Network) = onChange()- override fun onLost(network: Network) = onChange()- override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = Unit+ override fun onLost(network: Network) {+ validated = false+ onChange()+ }++ // Right after boot a network is "available" before it has its+ // addresses and routes, and before it's known to work: both come+ // later, and the core has to hear of them too.+ override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) = onChange()+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {+ val now = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)+ if (now != validated) {+ validated = now+ onChange()+ }+ }}fun start() {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.ktnew file mode 100644index 0000000..af5356b--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorRequest.kt@@ -0,0 +1,106 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mirror++import android.Manifest+import android.app.Activity+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.media.projection.MediaProjectionManager+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import app.nectarlink.android.R++/** A PC asking for the screen, with what it wants. */+data class MirrorRequest(val pcId: String, val maxSize: Int, val fps: Int, val bitrate: Int) {+ fun toIntent(intent: Intent): Intent = intent+ .putExtra("pc", pcId)+ .putExtra("maxSize", maxSize)+ .putExtra("fps", fps)+ .putExtra("bitrate", bitrate)++ companion object {+ fun of(intent: Intent): MirrorRequest? = intent.getStringExtra("pc")?.let {+ MirrorRequest(it, intent.getIntExtra("maxSize", 1920), intent.getIntExtra("fps", 60), intent.getIntExtra("bitrate", 8_000_000))+ }+ }+}++/**+ * Asking the user: Android shows its screen capture prompt only from a+ * screen the user is on, so a PC's request waits in a notification; tapping+ * it opens [MirrorConsentActivity], which shows the prompt.+ */+object MirrorRequests {+ private const val CHANNEL = "mirror_requests"+ private const val TAG = "mirror"++ fun createChannel(context: Context) {+ context.getSystemService(NotificationManager::class.java).createNotificationChannel(+ NotificationChannel(CHANNEL, context.getString(R.string.channel_mirror_requests), NotificationManager.IMPORTANCE_HIGH),+ )+ }++ /** Shows the request; false if notifications are off for the app. */+ fun show(context: Context, request: MirrorRequest, pcName: String): Boolean {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {+ return false+ }+ createChannel(context)+ val open = PendingIntent.getActivity(+ context,+ request.pcId.hashCode(),+ request.toIntent(Intent(context, MirrorConsentActivity::class.java)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val notification = NotificationCompat.Builder(context, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(context.getString(R.string.mirror_request_title, pcName.ifEmpty { context.getString(R.string.your_pc) }))+ .setContentText(context.getString(R.string.mirror_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())+ }++ /** A request nobody answered goes away after a while. */+ private const val REQUEST_TIMEOUT_MS = 2 * 60 * 1000L+}++/** Shows Android's screen capture prompt for a PC's request, then starts sharing. */+class MirrorConsentActivity : ComponentActivity() {+ private var request: MirrorRequest? = null++ private val prompt = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->+ val data = result.data+ val asked = request+ if (result.resultCode == Activity.RESULT_OK && data != null && asked != null) {+ MirrorService.start(this, asked, result.resultCode, data)+ }+ finish()+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ request = MirrorRequest.of(intent)+ val asked = request ?: return finish()+ MirrorRequests.dismiss(this, asked.pcId)+ if (savedInstanceState == null) {+ prompt.launch(getSystemService(MediaProjectionManager::class.java).createScreenCaptureIntent())+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.ktnew file mode 100644index 0000000..d9188ea--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt@@ -0,0 +1,177 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mirror++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.media.projection.MediaProjection+import android.media.projection.MediaProjectionManager+import android.os.Build+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.ServiceCompat+import androidx.core.content.ContextCompat+import androidx.core.content.IntentCompat+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * Shares the screen with one PC while the user agreed: holds the screen+ * capture (Android wants a foreground service for it, with its own+ * notification and a Stop button) and runs the encoder.+ */+class MirrorService : Service() {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val main = Handler(Looper.getMainLooper())+ private var projection: MediaProjection? = null+ private var encoder: ScreenEncoder? = null+ private var pcId: String? = null++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ if (intent?.action == ACTION_STOP) {+ stopSharing()+ return START_NOT_STICKY+ }+ val pc = intent?.getStringExtra(EXTRA_PC)+ val consent = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_CONSENT, Intent::class.java) }+ if (pc == null || consent == null || projection != null) {+ if (projection == null) stopSelf()+ return START_NOT_STICKY+ }+ val core = (application as NectarlinkApplication).core+ val name = core.state.value.nameOf(pc).orEmpty()+ createChannel(this)+ // The screen capture needs the service in the foreground first.+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION else 0+ ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(name), type)+ val manager = getSystemService(MediaProjectionManager::class.java)+ val granted = runCatching {+ manager.getMediaProjection(intent.getIntExtra(EXTRA_RESULT, 0), consent)+ }.getOrNull()+ if (granted == null) {+ Log.w(TAG, "no screen capture")+ stopSharing()+ return START_NOT_STICKY+ }+ projection = granted+ pcId = pc+ current = this+ granted.registerCallback(object : MediaProjection.Callback() {+ // The user stopped it (from the status bar, or by locking).+ override fun onStop() = main.post { stopSharing() }.let {}+ }, main)+ val maxSize = intent.getIntExtra(EXTRA_MAX_SIZE, 1920)+ val fps = intent.getIntExtra(EXTRA_FPS, 60)+ val bitrate = intent.getIntExtra(EXTRA_BITRATE, 8_000_000)+ scope.launch {+ val stream = runCatching { core.mirrorOpen(pc) }.getOrElse {+ Log.w(TAG, "can't stream to the PC", it)+ main.post { stopSharing() }+ return@launch+ }+ main.post {+ val running = projection+ if (running == null) {+ stream.end()+ return@post+ }+ encoder = ScreenEncoder(this@MirrorService, running, stream, maxSize, fps, bitrate) {+ main.post { stopSharing() }+ }.also { it.start() }+ }+ }+ return START_NOT_STICKY+ }++ private fun notification(pcName: String): Notification {+ val stop = PendingIntent.getService(+ this, 0, Intent(this, MirrorService::class.java).setAction(ACTION_STOP),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ return NotificationCompat.Builder(this, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(getString(R.string.mirror_sharing, pcName.ifEmpty { getString(R.string.your_pc) }))+ .setOngoing(true)+ .setSilent(true)+ .setCategory(NotificationCompat.CATEGORY_SERVICE)+ .addAction(0, getString(R.string.action_stop), stop)+ .build()+ }++ private fun stopSharing() {+ encoder?.stop()+ encoder = null+ projection?.let { runCatching { it.stop() } }+ projection = null+ pcId = null+ if (current === this) current = null+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)+ stopSelf()+ }++ override fun onDestroy() {+ stopSharing()+ scope.cancel()+ super.onDestroy()+ }++ companion object {+ private const val TAG = "MirrorService"+ private const val CHANNEL = "mirroring"+ private const val NOTIFICATION_ID = 4+ private const val ACTION_STOP = "app.nectarlink.android.mirror.STOP"+ private const val EXTRA_PC = "pc"+ private const val EXTRA_CONSENT = "consent"+ private const val EXTRA_RESULT = "result"+ private const val EXTRA_MAX_SIZE = "maxSize"+ private const val EXTRA_FPS = "fps"+ private const val EXTRA_BITRATE = "bitrate"++ /** The service sharing the screen now, if any. */+ @Volatile private var current: MirrorService? = null++ fun createChannel(context: Context) {+ context.getSystemService(NotificationManager::class.java).createNotificationChannel(+ NotificationChannel(CHANNEL, context.getString(R.string.channel_mirroring), NotificationManager.IMPORTANCE_LOW),+ )+ }++ /** Starts sharing with `request`'s PC, with the user's consent (from the capture prompt). */+ fun start(context: Context, request: MirrorRequest, result: Int, consent: Intent) {+ val intent = Intent(context, MirrorService::class.java)+ .putExtra(EXTRA_PC, request.pcId)+ .putExtra(EXTRA_CONSENT, consent)+ .putExtra(EXTRA_RESULT, result)+ .putExtra(EXTRA_MAX_SIZE, request.maxSize)+ .putExtra(EXTRA_FPS, request.fps)+ .putExtra(EXTRA_BITRATE, request.bitrate)+ ContextCompat.startForegroundService(context, intent)+ }++ /** The PC stopped watching. */+ fun stop(pcId: String) {+ val service = current ?: return+ service.main.post { if (service.pcId == pcId) service.stopSharing() }+ }++ /** The PC needs a keyframe. */+ fun keyframe(pcId: String) {+ current?.takeIf { it.pcId == pcId }?.encoder?.requestKeyframe()+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.ktnew file mode 100644index 0000000..825d873--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt@@ -0,0 +1,197 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.mirror++import android.content.Context+import android.hardware.display.DisplayManager+import android.hardware.display.VirtualDisplay+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.media.projection.MediaProjection+import android.os.Build+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.util.Log+import android.view.Display+import android.view.WindowManager+import app.nectarlink.core.MirrorSendResult+import app.nectarlink.core.MirrorStream+import app.nectarlink.core.VideoPacketKind+import app.nectarlink.core.mirrorConfig+import kotlin.math.max+import kotlin.math.min++/**+ * The screen as H.264 for a PC (docs/protocol/mirror.md): the projection+ * draws into the hardware encoder's input surface, and each encoded+ * picture goes straight to the stream. When the network is behind, the+ * stream drops pictures and this asks the encoder for a keyframe. Turning+ * the phone restarts the encoder at the new size.+ */+internal class ScreenEncoder(+ context: Context,+ private val projection: MediaProjection,+ private val stream: MirrorStream,+ private val maxSize: Int,+ private val fps: Int,+ private val bitrate: Int,+ private val onEnded: () -> Unit,+) {+ private val context = context.applicationContext+ private val displays = context.getSystemService(DisplayManager::class.java)+ private val main = Handler(Looper.getMainLooper())++ @Volatile private var running = true+ @Volatile private var keyframeWanted = false+ @Volatile private var resizeWanted = false+ @Volatile private var size: Size = screenSize()++ private data class Size(val width: Int, val height: Int, val dpi: Int)++ private val rotation = object : DisplayManager.DisplayListener {+ override fun onDisplayChanged(displayId: Int) {+ if (displayId != Display.DEFAULT_DISPLAY) return+ val now = screenSize()+ if (now.width != size.width || now.height != size.height) resizeWanted = true+ }+ override fun onDisplayAdded(displayId: Int) {}+ override fun onDisplayRemoved(displayId: Int) {}+ }++ fun start() {+ displays.registerDisplayListener(rotation, main)+ Thread(::run, "screen-encoder").start()+ }++ /** Stops (the encoder thread ends and calls `onEnded`). */+ fun stop() {+ running = false+ }++ /** The PC needs a fresh start. */+ fun requestKeyframe() {+ keyframeWanted = true+ }++ private fun run() {+ var display: VirtualDisplay? = null+ try {+ while (running) {+ size = screenSize()+ resizeWanted = false+ val codec = encoder(size)+ val surface = codec.createInputSurface()+ codec.start()+ val current = display+ if (current == null) {+ display = projection.createVirtualDisplay(+ "Nectarlink", size.width, size.height, size.dpi,+ DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null,+ )+ } else {+ current.resize(size.width, size.height, size.dpi)+ current.surface = surface+ }+ val closed = stream.send(VideoPacketKind.CONFIG, 0u, mirrorConfig(size.width.toUInt(), size.height.toUInt())) ==+ MirrorSendResult.CLOSED || drain(codec)+ runCatching { codec.stop() }+ codec.release()+ surface.release()+ if (closed) break+ }+ } catch (e: Exception) {+ Log.w(TAG, "screen sharing failed", e)+ } finally {+ running = false+ main.post { displays.unregisterDisplayListener(rotation) }+ display?.release()+ stream.end()+ onEnded()+ }+ }++ /** Sends what the encoder makes until the size changes (false) or it's over (true). */+ private fun drain(codec: MediaCodec): Boolean {+ val info = MediaCodec.BufferInfo()+ // The parameter sets, sent again with each keyframe so the PC can+ // start from any of them.+ var parameters = ByteArray(0)+ while (running && !resizeWanted) {+ if (keyframeWanted) {+ keyframeWanted = false+ 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 { buffer ->+ buffer.position(info.offset)+ buffer.get(bytes)+ }+ codec.releaseOutputBuffer(index, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return true+ 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 result = stream.send(+ if (key) VideoPacketKind.KEYFRAME else VideoPacketKind.FRAME,+ info.presentationTimeUs.toULong(),+ if (key) parameters + bytes else bytes,+ )+ when (result) {+ MirrorSendResult.NEED_KEYFRAME -> keyframeWanted = true+ MirrorSendResult.CLOSED -> return true+ MirrorSendResult.QUEUED -> {}+ }+ }+ return !running+ }++ private fun encoder(size: Size): MediaCodec {+ val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, size.width, size.height).apply {+ setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)+ setInteger(MediaFormat.KEY_BIT_RATE, bitrate)+ setInteger(MediaFormat.KEY_FRAME_RATE, fps)+ // Keyframes when the PC asks; a periodic one heals the rest.+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10)+ // A still screen still sends now and then, so the PC isn't stale.+ setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 100_000)+ // Real time, no reordering.+ 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_LATENCY, 1)+ // What the PC assumes when it turns the picture into RGB.+ 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)+ return codec+ }++ /** The screen's size scaled to fit `maxSize`, in multiples of 16 (what encoders like). */+ private fun screenSize(): Size {+ val windows = context.getSystemService(WindowManager::class.java)+ val (w, h) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ windows.maximumWindowMetrics.bounds.let { it.width() to it.height() }+ } else {+ val metrics = android.util.DisplayMetrics()+ @Suppress("DEPRECATION")+ windows.defaultDisplay.getRealMetrics(metrics)+ metrics.widthPixels to metrics.heightPixels+ }+ val scale = min(1.0, maxSize.toDouble() / max(w, h))+ fun fit(v: Int) = max(16, ((v * scale) / 16).toInt() * 16)+ return Size(fit(w), fit(h), context.resources.displayMetrics.densityDpi)+ }++ companion object {+ private const val TAG = "ScreenEncoder"+ private const val WAIT_US = 50_000L+ }+}diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex b1edb10..cbb78fd 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -67,6 +67,12 @@<string name="media_previous">Previous</string><string name="action_send_files">Send files</string><string name="action_send_folder">Send a folder</string>+ <string name="channel_mirroring">Screen sharing</string>+ <string name="channel_mirror_requests">Screen sharing requests</string>+ <string name="mirror_request_title">%1$s wants to see your screen</string>+ <string name="mirror_request_text">Tap to share it. You can stop anytime.</string>+ <string name="mirror_sharing">Sharing your screen with %1$s</string>+ <string name="action_stop">Stop</string><string name="sms_title">Text from your PC</string><string name="sms_off">Read your conversations and send texts from your PC. Nectarlink needs access to your messages and contacts for that.</string><string name="calls_title">Show calls on your PC</string>diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 258e85a..0c2c643 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -164,6 +164,18 @@ enum Command {/// Show new photos from paired phones as this PC would, and fetch each/// one; stays online until Ctrl+C.Photos,+ /// Ask a paired phone for its screen and save the video (H.264, Annex B)+ /// for `seconds`; prints what arrived.+ Mirror {+ device: String,+ out: PathBuf,+ #[arg(long, default_value_t = 10)]+ seconds: u64,+ /// Where to reach the phone, when discovery can't (e.g. an emulator+ /// with a forwarded port).+ #[arg(long)]+ at: Vec<std::net::SocketAddr>,+ },/// Act as a phone sharing its screen (use with --as-phone): when a PC/// asks, streams an H.264 file (Annex B, with access unit delimiters) in/// a loop at `fps`. Stays online.@@ -301,6 +313,43 @@ enum OnOff {Off,}+/// Where `mirror` saves the video, and what arrived.+static RECORDING: std::sync::OnceLock<std::sync::Arc<Recording>> = std::sync::OnceLock::new();++#[derive(Debug, Default)]+struct Recording {+ file: std::sync::Mutex<Option<std::fs::File>>,+ stats: std::sync::Mutex<RecordingStats>,+}++#[derive(Debug, Default, Clone, Copy)]+struct RecordingStats {+ frames: u32,+ keyframes: u32,+ bytes: u64,+ size: Option<(u32, u32)>,+}++impl nectarlink_core::MirrorSink for Recording {+ fn config(&self, config: nectarlink_core::MirrorConfig) {+ println!("The phone streams {}x{} {}.", config.width, config.height, config.codec);+ self.stats.lock().unwrap().size = Some((config.width, config.height));+ }+ fn packet(&self, keyframe: bool, _time_us: u64, data: Vec<u8>) {+ use std::io::Write;+ let mut stats = self.stats.lock().unwrap();+ stats.frames += 1;+ stats.keyframes += u32::from(keyframe);+ stats.bytes += data.len() as u64;+ if let Some(file) = self.file.lock().unwrap().as_mut() {+ let _ = file.write_all(&data);+ }+ }+ fn ended(&self) {+ println!("The stream ended.");+ }+}+/// PCs that asked for the screen, for `screen`.static SCREEN_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<DeviceId>> =std::sync::OnceLock::new();@@ -346,6 +395,9 @@ const PHOTO_ID: &str = "cli-photo";struct TerminalPlatform;impl Platform for TerminalPlatform {+ fn mirror_sink(&self, _peer: &DeviceId) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {+ RECORDING.get().map(|r| r.clone() as std::sync::Arc<dyn nectarlink_core::MirrorSink>)+ }fn mirror_requested(&self,peer: &DeviceId,@@ -681,6 +733,42 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {node.update_power(node_power(cli), offers).await;watch(node, true).await?;}+ Command::Mirror { device, out, seconds, at } => {+ let recording = std::sync::Arc::new(Recording::default());+ *recording.file.lock().unwrap() =+ Some(std::fs::File::create(out).context("can't create the file")?);+ let _ = RECORDING.set(recording.clone());+ let mut offers = cli.offers.clone();+ offers.push(nectarlink_core::MIRROR_VIEW.into());+ node.update_power(node_power(cli), offers).await;+ let id = resolve(node, device)?;+ if !at.is_empty() {+ node.add_known_addrs(id, at);+ }+ wait_until_online(node, id).await?;+ let options = nectarlink_core::MirrorStart { max_size: 1920, fps: 60, bitrate: 8_000_000 };+ node.mirror_start(id, options).await.context("the phone didn't ask its user")?;+ println!(+ "Asked the phone; accept on the phone. Recording for {seconds} s after the first frame."+ );+ let mut events = node.events();+ loop {+ if let Ok(NodeEvent::Mirroring { on: true, .. }) = events.recv().await {+ break;+ }+ }+ let started = std::time::Instant::now();+ tokio::time::sleep(std::time::Duration::from_secs(*seconds)).await;+ node.mirror_stop(id).await;+ let RecordingStats { frames, keyframes, bytes, size } = *recording.stats.lock().unwrap();+ let secs = started.elapsed().as_secs_f64();+ println!(+ "{frames} frames ({keyframes} keyframes) in {secs:.1} s: {:.1} fps, {:.1} Mbit/s{}",+ f64::from(frames) / secs,+ bytes as f64 * 8.0 / secs / 1e6,+ size.map(|(w, h)| format!(", {w}x{h}")).unwrap_or_default()+ );+ }Command::Screen { video, width, height, fps } => {if !cli.as_phone {bail!("screens are shared by phones: add --as-phone");diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 41e5a6f..84b01bb 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -486,8 +486,8 @@ impl MirrorStream {}}- /// Ends the stream.- pub fn close(&self) {+ /// Ends the stream (`close` frees the object, as for every object).+ pub fn end(&self) {self.0.close();}}diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 8d350ab..5132670 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -42,7 +42,7 @@ capability is missing.| `clip.share` | Sends the clipboard when the user taps "Send" | app update || `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated || `photos.read` | Announces new photos and screenshots and sends them on request ([photos](photos.md)) | photos permission |-| `mirror.capture` | Streams its screen (with the system's capture prompt at Basic) | app update |+| `mirror.capture` | Streams its screen (with the system's capture prompt at Basic; [mirroring](mirror.md)) | app update || `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist || `mirror.virtual_display` | Runs apps on a separate virtual display (app windows) | Elevated || `mirror.audio` | Streams all audio while mirrored | Elevated |@@ -57,6 +57,7 @@ capability is missing.| `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update || `call.show` | Shows a phone's calls ([calls](calls.md)) | app update || `sms.show` | Shows a phone's text messages ([messages](sms.md)) | app update |+| `mirror.view` | Shows a phone's screen ([mirroring](mirror.md)) | app update || `files.browse` | Lets a paired phone browse and fetch its files | app update || `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update || `deck.actions` | Runs Deck actions | app update |diff --git a/docs/protocol/mirror.md b/docs/protocol/mirror.mdnew file mode 100644index 0000000..3f8401e--- /dev/null+++ b/docs/protocol/mirror.md@@ -0,0 +1,78 @@+# Screen mirroring (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are+> allowed until v1. License: CC BY 4.0.++A PC shows a phone's screen. The phone's user agrees each time (Android+asks); the phone then streams its screen as H.264 on a stream of its own.+This version is view-only: controlling the phone comes later.++## 1. Capabilities++| ID | Offered by | Meaning |+|---|---|---|+| `mirror.capture` | phone | Shares its screen when its user agrees |+| `mirror.view` | PC | Shows a phone's screen |++Both devices must allow it: the `mirroring` device toggle, on by default,+on each side.++## 2. Control messages++On the control stream.++```+t = "mirror.start" id = n b = { max_size: uint, fps: uint, bitrate: uint }+t = "mirror.stop" id = n+t = "mirror.keyframe"+t = "ok" re = n+```++- `mirror.start` (PC → phone): show me your screen, its longer side at most+ `max_size` pixels, at most `fps` frames a second, aiming for `bitrate`+ bits a second. The phone answers `ok` once it has asked its user; video+ follows only if the user agrees. Errors: `DENIED` (mirroring is off for+ the PC), `UNSUPPORTED` (no `mirror.capture`).+- `mirror.stop` (either way): stop. The PC stops reading the video stream;+ the phone stops sharing and finishes it.+- `mirror.keyframe` (PC → phone): the decoder lost its place; send a+ keyframe next. Not answered.++## 3. The video stream++The phone opens a bidirectional stream with the header+`{ svc: "mirror", op: "video", v: 1 }` (v0 §4), then writes packets until+it stops. The PC writes nothing; it finishes its side, or stops reading,+to end the stream.++Each packet is:++```+u32 length (big-endian; counts everything after it)+u8 kind // 0 config, 1 frame, 2 keyframe+u64 time // capture time in microseconds, big-endian (only differences mean anything)+ data+```++- **config**: the stream's format, CBOR `{ codec: "h264", width: uint,+ height: uint }`. First, and again whenever it changes (the phone turned).+- **frame**: one H.264 access unit (Annex B) that depends on earlier ones.+- **keyframe**: an access unit that starts fresh (an IDR picture), with its+ SPS and PPS before it.++Packets are at most 8 MiB. Video is BT.709, limited range.++## 4. Latency over completeness++The stream is reliable, so a slow network would otherwise build up delay.+Instead, the phone keeps only a few packets waiting to go out: when that's+full it drops the picture and every one after it until a keyframe, and asks+its encoder for one. The PC likewise decodes everything it gets but shows+only the newest picture when it's behind, and asks for a keyframe when a+picture doesn't decode.++## 5. Privacy++The screen is never recorded or logged by either side. Android shows that+the screen is being shared (in the status bar), and the user can stop it+there, from the phone's notification, or from the PC.