cast: mirror the screen over Cast Streaming from a tile
- Commit
8f38d9ca7a20ecb2d9c26000c75c490c68043011- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 06:56 UTC (3 months ago)
- Parents
300a8f8
Diff
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex 253026f91a..595a8ce2df 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -2,7 +2,8 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Google Cast (CastV2) without Play Services or the Cast SDK: mDNS discovery of- _googlecast._tcp and a TLS socket to port 8009 for the control plane. -->+ _googlecast._tcp, a TLS socket to port 8009 for the control plane, and UDP to the+ port the receiver names in its ANSWER for the RTP stream. --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />@@ -12,17 +13,21 @@ does is on the LAN, so it is not optional. --> <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" /> - <!-- mediaPlayback rather than connectedDevice: the session this service holds open is a- playback session on the receiver, which is what Android's own docs list this type- for. Not dataSync - Android 15 caps that at 6 cumulative hours per 24h and then- calls onTimeout(), which for a long session would stop the service part-way through- (see :vpn's manifest for the same reasoning first-hand). -->+ <!-- mediaProjection is the type that must be in force before getMediaProjection() is+ called; mediaPlayback covers the window where a control channel is open but nothing+ is being captured yet. Neither is subject to Android 15's cumulative-runtime cap,+ which applies only to dataSync and mediaProcessing. --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <!-- AudioRecord needs this even for playback capture, where no microphone is involved:+ the permission gates the API, not the source. -->+ <uses-permission android:name="android.permission.RECORD_AUDIO" /> <!-- Deliberately NO storage or media permissions: nothing is read from the device's- storage. -->+ storage. Screen capture is granted per session by the system consent dialog rather+ than by a manifest permission, and the token is single-use. --> <uses-feature android:name="android.hardware.wifi" android:required="false" /> @@ -44,13 +49,42 @@ <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>+ <!-- Without this filter the system ignores the tile's ACTIVITY meta-data, so a+ long-press on the tile would go nowhere. -->+ <intent-filter>+ <action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />+ </intent-filter> </activity> - <!-- Holds the cast channel up while the app is not in front, so backgrounding the app- does not stop mirroring. -->+ <!-- The consent trampoline. Translucent and NOT android:noHistory: noHistory finishes an+ activity as soon as it stops being visible, which is exactly what launching the system+ consent dialog does, so the result callback would be dropped. -->+ <activity+ android:name=".platform.mirror.MirrorConsentActivity"+ android:excludeFromRecents="true"+ android:exported="false"+ android:launchMode="singleTop"+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />++ <!-- Holds the cast channel and the screen-capture projection up while the app is not in+ front, so backgrounding the app does not stop mirroring. --> <service android:name=".service.CastService" android:exported="false"- android:foregroundServiceType="mediaPlayback" />+ android:foregroundServiceType="mediaProjection|mediaPlayback" />++ <service+ android:name=".platform.mirror.MirrorTileService"+ android:exported="true"+ android:icon="@drawable/ic_tile_cast_mirror"+ android:label="@string/cast_tile_label"+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">+ <intent-filter>+ <action android:name="android.service.quicksettings.action.QS_TILE" />+ </intent-filter>+ <meta-data+ android:name="android.service.quicksettings.ACTIVITY"+ android:value="com.vayunmathur.cast.MainActivity" />+ </service> </application> </manifest>
cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt b/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.ktindex f74b8e69d7..1f0b99ecd2 100644--- a/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt+++ b/cast/src/main/java/com/vayunmathur/cast/domain/CastSession.kt@@ -49,6 +49,15 @@ class CastSession(private val appId: String) { var state: CastSessionState = CastSessionState() private set + /**+ * Every `webrtc` payload, verbatim.+ *+ * The seam between the control plane and the streaming session: OFFER/ANSWER is a separate+ * state machine, so this class routes those payloads out rather than growing to understand+ * them. A callback rather than a `Log` call because this class has no Android imports.+ */+ var onWebrtcPayload: ((String) -> Unit)? = null+ private var nextRequestId = 1 fun allocateRequestId(): Int = nextRequestId++@@ -91,10 +100,25 @@ class CastSession(private val appId: String) { emptyList() } CastNamespaces.RECEIVER -> onReceiverMessage(envelope, payload)+ CastNamespaces.WEBRTC -> {+ onWebrtcPayload?.invoke(payload)+ emptyList()+ } else -> emptyList() } } + /**+ * Address a payload to the running app on the `webrtc` namespace.+ *+ * Empty until the app is joined: a frame sent before the second CONNECT is dropped with no+ * error, so an OFFER sent too early would simply never be answered.+ */+ fun webrtcFrame(payload: String): List<CastFrame> {+ val transportId = state.transportId ?: return emptyList()+ return listOf(CastFrame(CastNamespaces.WEBRTC, transportId, payload))+ }+ /** * Volume is the *receiver's* volume, so it goes to [RECEIVER_ID] on the receiver namespace * rather than to the running app.
cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.ktnew file mode 100644index 0000000000..4f622b652b--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/network/CastUdpTransport.kt@@ -0,0 +1,82 @@+package com.vayunmathur.cast.network++import android.util.Log+import java.net.InetSocketAddress+import java.nio.ByteBuffer+import java.nio.channels.DatagramChannel++private const val TAG = "CastUdpTransport"++/**+ * The UDP socket carrying RTP out and RTCP back.+ *+ * Same idiom as `vpn/.../VpnTunnelService.kt:227-236` - `DatagramChannel.open()`,+ * `configureBlocking(false)`, `connect()` - **minus `protect()`**, which is a `VpnService` method+ * and does not exist here. Connecting rather than sending to an address each time is what lets the+ * kernel filter inbound datagrams to the receiver, so RTCP from anything else never arrives.+ *+ * The receiver sends RTCP from the same port it receives RTP on, so one connected socket does both+ * directions.+ */+class CastUdpTransport(private val host: String, private val port: Int) {++ private var channel: DatagramChannel? = null+ private val readBuffer = ByteBuffer.allocateDirect(MAX_DATAGRAM)++ /** Set to log every packet as hex. Off by default: it is per-packet and very loud. */+ var hexDump: Boolean = false++ fun open(): Boolean = try {+ channel = DatagramChannel.open().apply {+ configureBlocking(false)+ connect(InetSocketAddress(host, port))+ }+ Log.i(TAG, "udp connected to $host:$port")+ true+ } catch (e: Exception) {+ Log.w(TAG, "could not open a udp socket to $host:$port", e)+ close()+ false+ }++ fun send(packet: ByteArray): Boolean {+ val active = channel ?: return false+ if (hexDump) Log.i(TAG, "-> ${packet.size}B ${packet.toHexPreview()}")+ return try {+ active.write(ByteBuffer.wrap(packet))+ true+ } catch (e: Exception) {+ Log.w(TAG, "udp send failed", e)+ false+ }+ }++ /** One datagram, or null when nothing is waiting. Never blocks. */+ fun receive(): ByteArray? {+ val active = channel ?: return null+ return try {+ readBuffer.clear()+ if (active.read(readBuffer) <= 0) return null+ readBuffer.flip()+ ByteArray(readBuffer.remaining()).also { readBuffer.get(it) }+ .also { if (hexDump) Log.i(TAG, "<- ${it.size}B ${it.toHexPreview()}") }+ } catch (e: Exception) {+ // A port-unreachable ICMP surfaces here on a connected socket. Not fatal: the receiver+ // may not have bound yet.+ null+ }+ }++ fun close() {+ runCatching { channel?.close() }+ channel = null+ }++ /** Enough to identify a header without filling logcat with a whole video frame. */+ private fun ByteArray.toHexPreview(): String =+ take(32).joinToString("") { "%02x".format(it) } + if (size > 32) "..." else ""++ private companion object {+ const val MAX_DATAGRAM = 2048+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex d8d4e9e014..1f0ef9da76 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -1,6 +1,8 @@ package com.vayunmathur.cast.platform import android.content.Context+import android.content.Intent+import android.media.projection.MediaProjection import android.util.Log import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastDevice@@ -9,8 +11,17 @@ import com.vayunmathur.cast.domain.CastPhase import com.vayunmathur.cast.domain.CastSession import com.vayunmathur.cast.domain.CastSessionState import com.vayunmathur.cast.domain.MirroringAppIds+import com.vayunmathur.cast.domain.streaming.NegotiationFailure+import com.vayunmathur.cast.domain.streaming.StreamSelection+import com.vayunmathur.cast.domain.streaming.StreamingSession+import com.vayunmathur.cast.domain.streaming.encode+import com.vayunmathur.cast.domain.streaming.parseAnswer import com.vayunmathur.cast.network.CastChannel import com.vayunmathur.cast.platform.discovery.CastDiscoveryManager+import com.vayunmathur.cast.platform.mirror.MirrorDegradation+import com.vayunmathur.cast.platform.mirror.MirrorEngine+import com.vayunmathur.cast.platform.mirror.MirrorPreferences+import com.vayunmathur.cast.platform.mirror.MirrorStopReason import com.vayunmathur.cast.service.CastService import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.CancellationException@@ -56,6 +67,25 @@ object CastController { private var pumpJob: Job? = null private var heartbeatJob: Job? = null + /** The OFFER/ANSWER half, alive only while a mirror is being negotiated or run. */+ private var streaming: StreamingSession? = null+ private var engine: MirrorEngine? = null++ private val _mirrorPhase = MutableStateFlow(MirrorPhase.Idle)+ val mirrorPhase: StateFlow<MirrorPhase> = _mirrorPhase.asStateFlow()++ private val _degradation = MutableStateFlow(MirrorDegradation())+ val degradation: StateFlow<MirrorDegradation> = _degradation.asStateFlow()++ /**+ * Why mirroring failed, already a user-facing sentence.+ *+ * Separate from `CastSessionState.failure`, which is a raw `LAUNCH_ERROR` reason: these come+ * from our own pipeline and there is no wire constant to translate.+ */+ private val _failure = MutableStateFlow<String?>(null)+ val mirrorFailure: StateFlow<String?> = _failure.asStateFlow()+ private var discoveryManager: CastDiscoveryManager? = null private val _device = MutableStateFlow<CastDevice?>(null)@@ -107,6 +137,8 @@ object CastController { } channel = newChannel session = newSession+ // Whatever the user last tapped is the tile's target from now on.+ MirrorPreferences.setTarget(appContext, device) startPump(appContext, newChannel, newSession) send(newChannel, newSession) { it.open() } heartbeatJob = scope.launch {@@ -137,6 +169,110 @@ object CastController { fun setVolume(level: Double) = act { it.setVolume(level) } + /**+ * Begin mirroring with an already-granted projection.+ *+ * Called from [CastService] rather than from the UI, because the projection may only be+ * obtained after the service is in the foreground - see `MirrorConsentActivity` for the full+ * ordering constraint.+ *+ * The OFFER goes out only once the receiver app is joined; before that the `webrtc` namespace+ * is not addressable and the frame would be dropped without an error.+ */+ fun startMirroring(context: Context, projection: MediaProjection) {+ val appContext = context.applicationContext+ scope.launch {+ val activeChannel = channel+ val activeSession = session+ val device = _device.value+ if (activeChannel == null || activeSession == null || device == null) {+ Log.w(TAG, "asked to mirror with no session")+ projection.stop()+ return@launch+ }+ stopEngine()+ _mirrorPhase.value = MirrorPhase.Negotiating+ _degradation.value = MirrorDegradation()+ _failure.value = null+ val plan = StreamSelection.offer(device.kind)+ val streamingSession = StreamingSession(plan)+ streaming = streamingSession+ // Fed by CastSession's webrtc route rather than parsed there: OFFER/ANSWER is its own+ // state machine and the control plane has no business understanding it.+ activeSession.onWebrtcPayload = { payload ->+ onWebrtcPayload(appContext, payload, projection, device.host)+ }+ send(activeChannel, activeSession) {+ it.webrtcFrame(plan.message(it.allocateRequestId()).encode())+ }+ }+ }++ fun stopMirroring(context: Context) {+ val appContext = context.applicationContext+ scope.launch {+ stopEngine()+ _mirrorPhase.value = MirrorPhase.Idle+ CastService.stopMirroring(appContext)+ }+ }++ private fun onWebrtcPayload(+ context: Context,+ payload: String,+ projection: MediaProjection,+ host: String,+ ) {+ val answer = parseAnswer(payload) ?: return+ val streamingSession = streaming ?: return+ scope.launch {+ val failure = streamingSession.onAnswer(answer)+ if (failure != null) {+ Log.w(TAG, "the receiver would not agree a stream: $failure")+ _mirrorPhase.value = MirrorPhase.Failed+ _failure.value = context.getString(+ when (failure) {+ is NegotiationFailure.NoStreams -> R.string.cast_mirror_no_streams+ else -> R.string.cast_mirror_negotiation_failed+ },+ )+ projection.stop()+ CastService.stopMirroring(context)+ return@launch+ }+ val negotiation = streamingSession.negotiation ?: return@launch+ val started = MirrorEngine(+ context = context,+ projection = projection,+ receiverHost = host,+ negotiation = negotiation,+ session = streamingSession,+ onDegraded = { _degradation.value = it },+ onStopped = { reason -> onEngineStopped(context, reason) },+ ).also { engine = it }.start()+ _mirrorPhase.value = if (started) MirrorPhase.Mirroring else MirrorPhase.Failed+ }+ }++ private fun onEngineStopped(context: Context, reason: MirrorStopReason) {+ _failure.value = context.getString(+ when (reason) {+ MirrorStopReason.Udp -> R.string.cast_mirror_udp_failed+ MirrorStopReason.NoEncoders -> R.string.cast_mirror_no_encoder+ MirrorStopReason.NoAudioForSpeaker -> R.string.cast_mirror_no_audio+ },+ )+ _mirrorPhase.value = MirrorPhase.Failed+ CastService.stopMirroring(context)+ }++ private fun stopEngine() {+ engine?.stop()+ engine = null+ streaming = null+ session?.onWebrtcPayload = null+ }+ fun setMuted(muted: Boolean) = act { it.setMuted(muted) } /** Run [block] against the live session, if there is one, and send what it produces. */@@ -216,6 +352,7 @@ object CastController { private suspend fun teardown() { pumpJob?.cancel() heartbeatJob?.cancel()+ stopEngine() channel?.close() mutex.withLock { pumpJob = null@@ -225,6 +362,9 @@ object CastController { _device.value = null _isConnecting.value = false _sessionState.value = CastSessionState()+ _mirrorPhase.value = MirrorPhase.Idle+ _degradation.value = MirrorDegradation()+ _failure.value = null } } }
cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.ktindex 3b486d3ff4..d4b2bdd872 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastUiContract.kt@@ -10,6 +10,26 @@ import com.vayunmathur.cast.domain.CastDevice */ enum class CastConnection { Disconnected, Connecting, Connected, Failed } +/**+ * How far mirroring itself has got, which is a separate axis from [CastConnection].+ *+ * A joined receiver is not a running mirror: OFFER/ANSWER has to succeed and the encoders have to+ * start, and either can fail while the control channel stays perfectly healthy.+ */+enum class MirrorPhase {+ /** Nothing is being sent. The receiver may still be joined. */+ Idle,++ /** OFFER is on the wire, or the encoders are starting. */+ Negotiating,++ /** Frames are going out. */+ Mirroring,++ /** Mirroring stopped or never started, and [CastUiState.failure] says why. */+ Failed,+}+ /** * Everything the Cast screen draws. *@@ -28,6 +48,7 @@ data class CastUiState( val localNetworkBlocked: Boolean = false, val connectedDevice: CastDevice? = null, val connection: CastConnection = CastConnection.Disconnected,+ val mirrorPhase: MirrorPhase = MirrorPhase.Idle, /** * True when the target has no screen, so only audio can be sent to it. *@@ -35,17 +56,28 @@ data class CastUiState( * that is what lets the UI say "audio only" while the receiver is still being joined. */ val audioOnly: Boolean = false,+ /** Video could not be encoded, so only audio is going out on a target that could take both. */+ val videoDegraded: Boolean = false,+ /** Audio could not be captured or encoded. */+ val audioDegraded: Boolean = false, val volumeLevel: Double = 1.0, val muted: Boolean = false,- /** Why the receiver refused, already turned into something worth showing a user. */+ /** Why the receiver refused, or why mirroring stopped, ready to show a user. */ val failure: String? = null,-)+) {+ val isMirroring: Boolean get() = mirrorPhase == MirrorPhase.Mirroring++ /** Mirroring can be offered only once there is somewhere to send it. */+ val canMirror: Boolean get() = connection == CastConnection.Connected+} interface CastActions { fun startScan() {} fun stopScan() {} fun connect(device: CastDevice) {} fun disconnect() {}+ fun startMirroring() {}+ fun stopMirroring() {} fun setVolume(level: Double) {} fun setMuted(muted: Boolean) {} fun openLocalNetworkSettings() {}
cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.ktindex 4777e623fa..6fb1c2784b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastViewModel.kt@@ -14,6 +14,7 @@ import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastDevice import com.vayunmathur.cast.domain.CastDeviceKind import com.vayunmathur.cast.domain.CastPhase+import com.vayunmathur.cast.platform.mirror.MirrorConsentActivity import com.vayunmathur.library.ui.ExternalIntents import kotlinx.coroutines.Job import kotlinx.coroutines.delay@@ -60,12 +61,21 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C Triple(devices.sortedBy { it.friendlyName.lowercase() }, scanning, blocked) } + /** Combined here because `combine` takes at most five flows. */+ private val mirrorState = combine(+ CastController.mirrorPhase,+ CastController.degradation,+ CastController.mirrorFailure,+ ) { phase, degradation, failure -> Triple(phase, degradation, failure) }+ val uiState: StateFlow<CastUiState> = combine( discoveryState, CastController.device, CastController.isConnecting, CastController.sessionState,- ) { (devices, scanning, blocked), device, connecting, session ->+ mirrorState,+ ) { (devices, scanning, blocked), device, connecting, session, mirror ->+ val (phase, degradation, mirrorFailure) = mirror CastUiState( devices = devices, isScanning = scanning,@@ -77,13 +87,17 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C device != null && session.phase == CastPhase.Ready -> CastConnection.Connected else -> CastConnection.Disconnected },+ mirrorPhase = phase, // A speaker or a group has no screen, so only audio can go to it. Known from the // mDNS capability bitmask before anything is negotiated, which is what lets the UI // say "audio only" while the receiver is still being joined. audioOnly = device != null && device.kind != CastDeviceKind.Tv,+ videoDegraded = degradation.videoUnavailable,+ audioDegraded = degradation.audioUnavailable, volumeLevel = session.volumeLevel, muted = session.muted,- failure = failureMessage(session.failure),+ // The pipeline's own message wins: it is more specific than a LAUNCH_ERROR reason.+ failure = mirrorFailure ?: failureMessage(session.failure), ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), CastUiState()) @@ -121,6 +135,17 @@ class CastViewModel(application: Application) : AndroidViewModel(application), C override fun disconnect() = CastController.disconnect(appContext) + /**+ * Mirroring cannot be started from here directly: the screen-capture consent dialog needs an+ * Activity to host it, and the token it returns is single-use, so the trampoline runs afresh+ * every session.+ */+ override fun startMirroring() {+ ExternalIntents.launch(appContext, MirrorConsentActivity.intent(appContext))+ }++ override fun stopMirroring() = CastController.stopMirroring(appContext)+ override fun setVolume(level: Double) = CastController.setVolume(level) override fun setMuted(muted: Boolean) = CastController.setMuted(muted)
cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.ktnew file mode 100644index 0000000000..db1fab1d61--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.kt@@ -0,0 +1,167 @@+package com.vayunmathur.cast.platform.mirror++import android.annotation.SuppressLint+import android.media.AudioAttributes+import android.media.AudioFormat+import android.media.AudioPlaybackCaptureConfiguration+import android.media.AudioRecord+import android.media.MediaCodec+import android.media.MediaFormat+import android.media.projection.MediaProjection+import android.util.Log++private const val TAG = "AudioEncoder"++private const val TIMEOUT_US = 10_000L++/**+ * Captures playing audio and encodes it as Opus.+ *+ * **Two honest limitations, neither of which this class can fix:**+ *+ * 1. `AudioPlaybackCapture` silently excludes any app that sets `ALLOW_CAPTURE_BY_NONE` - which is+ * most DRM and music apps. Those are simply not in the stream, so the captured audio can be+ * digital silence through no fault of ours and with no error anywhere.+ * 2. `audio/opus` encoders are not universally present.+ *+ * [EncoderSupport] answers the second before anything starts, and the UI says which one degraded.+ * Nothing here can detect the first, so the copy has to warn about it in general terms.+ *+ * `RECORD_AUDIO` is required even though no microphone is involved - the permission gates+ * `AudioRecord` itself, not the source.+ */+class AudioEncoder(private val projection: MediaProjection) {++ private var record: AudioRecord? = null+ private var codec: MediaCodec? = null+ private val bufferInfo = MediaCodec.BufferInfo()++ @SuppressLint("MissingPermission")+ fun start(): Boolean {+ val name = EncoderSupport.audioEncoderName()+ if (name == null) {+ Log.w(TAG, "no ${EncoderSupport.AUDIO_MIME} encoder on this device")+ return false+ }+ return try {+ val config = AudioPlaybackCaptureConfiguration.Builder(projection)+ .addMatchingUsage(AudioAttributes.USAGE_MEDIA)+ .addMatchingUsage(AudioAttributes.USAGE_GAME)+ .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)+ .build()+ val format = AudioFormat.Builder()+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT)+ .setSampleRate(SAMPLE_RATE)+ .setChannelMask(AudioFormat.CHANNEL_IN_STEREO)+ .build()+ val minBuffer = AudioRecord.getMinBufferSize(+ SAMPLE_RATE,+ AudioFormat.CHANNEL_IN_STEREO,+ AudioFormat.ENCODING_PCM_16BIT,+ ).coerceAtLeast(FRAME_BYTES * 4)+ val created = AudioRecord.Builder()+ .setAudioFormat(format)+ .setBufferSizeInBytes(minBuffer)+ .setAudioPlaybackCaptureConfig(config)+ .build()+ if (created.state != AudioRecord.STATE_INITIALIZED) {+ Log.w(TAG, "AudioRecord did not initialise")+ created.release()+ return false+ }+ val mediaFormat = MediaFormat.createAudioFormat(+ EncoderSupport.AUDIO_MIME,+ SAMPLE_RATE,+ CHANNELS,+ ).apply {+ setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)+ }+ val encoder = MediaCodec.createByCodecName(name)+ encoder.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ encoder.start()+ created.startRecording()+ record = created+ codec = encoder+ true+ } catch (e: Exception) {+ Log.w(TAG, "could not start audio capture", e)+ release()+ false+ }+ }++ /**+ * Read one buffer of PCM, feed it in, and return whatever came out.+ *+ * Opus wants 20 ms frames; [FRAME_BYTES] is exactly that at [SAMPLE_RATE] in stereo 16-bit.+ */+ fun pump(): List<EncodedChunk> {+ val activeRecord = record ?: return emptyList()+ val activeCodec = codec ?: return emptyList()+ val pcm = ByteArray(FRAME_BYTES)+ val read = try {+ activeRecord.read(pcm, 0, pcm.size)+ } catch (e: Exception) {+ Log.w(TAG, "audio read failed", e)+ return emptyList()+ }+ if (read > 0) {+ val index = activeCodec.dequeueInputBuffer(TIMEOUT_US)+ if (index >= 0) {+ val input = activeCodec.getInputBuffer(index)+ input?.clear()+ input?.put(pcm, 0, read)+ activeCodec.queueInputBuffer(index, 0, read, presentationTimeUs, 0)+ // Derived from the sample count rather than the clock: a timestamp that drifts+ // against the sample rate is what makes audio slowly desynchronise from video.+ samplesWritten += read / (2 * CHANNELS)+ }+ }+ val out = mutableListOf<EncodedChunk>()+ while (true) {+ val index = try {+ activeCodec.dequeueOutputBuffer(bufferInfo, 0)+ } catch (e: IllegalStateException) {+ Log.w(TAG, "audio encoder went away mid-drain", e)+ return out+ }+ if (index < 0) return out+ val buffer = activeCodec.getOutputBuffer(index)+ if (buffer != null &&+ bufferInfo.size > 0 &&+ bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG == 0+ ) {+ buffer.position(bufferInfo.offset)+ buffer.limit(bufferInfo.offset + bufferInfo.size)+ val bytes = ByteArray(bufferInfo.size).also { buffer.get(it) }+ // Every audio frame is independently decodable, so all of them are "key frames".+ out += EncodedChunk(bytes, bufferInfo.presentationTimeUs, isKeyFrame = true)+ }+ activeCodec.releaseOutputBuffer(index, false)+ }+ }++ fun release() {+ runCatching { record?.stop() }+ runCatching { record?.release() }+ runCatching { codec?.stop() }+ runCatching { codec?.release() }+ record = null+ codec = null+ }++ private var samplesWritten = 0L++ private val presentationTimeUs: Long+ get() = samplesWritten * 1_000_000L / SAMPLE_RATE++ companion object {+ /** Matches the OFFER's `1/48000` timebase. */+ const val SAMPLE_RATE = 48_000+ const val CHANNELS = 2+ const val BIT_RATE = 128_000++ /** 20 ms of stereo 16-bit PCM. */+ const val FRAME_BYTES = SAMPLE_RATE / 50 * 2 * CHANNELS+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.ktnew file mode 100644index 0000000000..b1c8a02fd9--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/EncoderSupport.kt@@ -0,0 +1,50 @@+package com.vayunmathur.cast.platform.mirror++import android.media.MediaCodecInfo+import android.media.MediaCodecList+import android.media.MediaFormat++/**+ * What this device can actually encode.+ *+ * Deliberately **not** built on `camera/.../CodecSupport.kt`: that asks CameraX what the camera+ * pipeline supports, which says nothing about a `MediaCodec` fed by a `VirtualDisplay`. The two+ * questions only look alike.+ *+ * Both answers gate real behaviour rather than being informational: without an H.264 surface+ * encoder there is nothing to mirror, and `audio/opus` encoders are genuinely absent on some+ * devices, which the UI has to be able to explain.+ */+object EncoderSupport {++ const val VIDEO_MIME = MediaFormat.MIMETYPE_VIDEO_AVC+ const val AUDIO_MIME = MediaFormat.MIMETYPE_AUDIO_OPUS++ /**+ * An H.264 encoder that can take frames from a `Surface`.+ *+ * `COLOR_FormatSurface` is the requirement that matters. An encoder that only accepts byte+ * buffers would mean reading pixels back from the display and pushing them in by hand, which is+ * both slow and pointless when `createInputSurface()` exists.+ */+ fun videoEncoderName(): String? = findEncoder(VIDEO_MIME) { caps ->+ caps.colorFormats.contains(MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)+ }++ fun audioEncoderName(): String? = findEncoder(AUDIO_MIME) { true }++ /** REGULAR_CODECS, so the list matches what an ordinary app is allowed to instantiate. */+ private inline fun findEncoder(+ mime: String,+ predicate: (MediaCodecInfo.CodecCapabilities) -> Boolean,+ ): String? {+ val codecs = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos+ for (info in codecs) {+ if (!info.isEncoder) continue+ if (info.supportedTypes.none { it.equals(mime, ignoreCase = true) }) continue+ val caps = runCatching { info.getCapabilitiesForType(mime) }.getOrNull() ?: continue+ if (predicate(caps)) return info.name+ }+ return null+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.ktnew file mode 100644index 0000000000..3536cee1a1--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorConsentActivity.kt@@ -0,0 +1,78 @@+package com.vayunmathur.cast.platform.mirror++import android.content.Context+import android.content.Intent+import android.media.projection.MediaProjectionManager+import android.os.Bundle+import android.util.Log+import androidx.activity.ComponentActivity+import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.content.getSystemService+import com.vayunmathur.cast.R+import com.vayunmathur.cast.service.CastService+import com.vayunmathur.library.util.AppMessages++private const val TAG = "MirrorConsent"++/**+ * Transparent trampoline that asks for screen-capture consent and hands the result to+ * [CastService].+ *+ * It exists because of a hard platform ordering constraint, not for style. On Android 14+:+ *+ * 1. `createScreenCaptureIntent()` needs an Activity to launch it and receive the result, so a+ * Quick Settings tile can never obtain consent by itself.+ * 2. A `mediaProjection`-typed foreground service must already be in the foreground *before*+ * `getMediaProjection()` is called, which is why the token is forwarded to the service rather+ * than turned into a projection here.+ * 3. The consent token is **single-use**. It cannot be cached, so this runs afresh for every+ * session - which is also why there is no boot receiver anywhere in this feature.+ *+ * **Not `android:noHistory`**, unlike a first guess would suggest for a trampoline. `noHistory`+ * finishes an activity as soon as it stops being visible, and launching the system consent dialog+ * does exactly that - the result callback would never arrive.+ */+class MirrorConsentActivity : ComponentActivity() {++ private val consent = registerForActivityResult(+ ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ val data = result.data+ if (result.resultCode != RESULT_OK || data == null) {+ // Declining is a choice, not an error, so it is not worth a message.+ Log.i(TAG, "screen capture consent declined")+ finish()+ return@registerForActivityResult+ }+ CastService.startMirroring(this, result.resultCode, data)+ finish()+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ val manager = getSystemService<MediaProjectionManager>()+ if (manager == null) {+ Log.w(TAG, "no MediaProjectionManager on this device")+ AppMessages.show(getString(R.string.cast_mirror_unavailable))+ finish()+ return+ }+ // Only on a fresh launch: registerForActivityResult restores a pending request across a+ // configuration change on its own, and asking again would stack a second consent dialog.+ if (savedInstanceState == null) {+ consent.launch(manager.createScreenCaptureIntent())+ }+ }++ companion object {+ /**+ * An intent that starts the consent flow.+ *+ * `NEW_TASK` because the callers are a tile and a notification, neither of which has a task+ * of its own to launch into.+ */+ fun intent(context: Context): Intent =+ Intent(context, MirrorConsentActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.ktnew file mode 100644index 0000000000..9c9451e936--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -0,0 +1,250 @@+package com.vayunmathur.cast.platform.mirror++import android.content.Context+import android.media.projection.MediaProjection+import android.util.Log+import com.vayunmathur.cast.domain.streaming.CastRtcp+import com.vayunmathur.cast.domain.streaming.NegotiatedStream+import com.vayunmathur.cast.domain.streaming.Negotiation+import com.vayunmathur.cast.domain.streaming.StreamKind+import com.vayunmathur.cast.domain.streaming.StreamSelection+import com.vayunmathur.cast.domain.streaming.StreamingSession+import com.vayunmathur.cast.network.CastUdpTransport+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch++private const val TAG = "MirrorEngine"++/** How often a sender report goes out; roughly openscreen's cadence. */+private const val SENDER_REPORT_INTERVAL_MS = 500L++/** Seconds between the NTP epoch (1900) and the Unix epoch (1970). */+private const val NTP_UNIX_OFFSET_SECONDS = 2_208_988_800L++private const val FRAME_POLL_MS = 4L+private const val RTCP_POLL_MS = 20L++/** What could not be started, so the UI can say so rather than looking broken. */+data class MirrorDegradation(+ val videoUnavailable: Boolean = false,+ val audioUnavailable: Boolean = false,+)++/** Why mirroring could not start, or stopped. */+enum class MirrorStopReason { Udp, NoEncoders, NoAudioForSpeaker }++/**+ * The running mirror: capture and encode in, RTP out, RTCP back.+ *+ * Holds no protocol knowledge - [StreamingSession] decides what to retransmit, [CastRtpPacketizer]+ * decides byte layout, [StreamSender] does the per-stream work. This class is the part that cannot+ * be unit-tested, so it is kept to the wiring and two loops.+ *+ * [receiverHost] is passed in because the ANSWER carries only a port; the address is the one the+ * control channel is already talking to.+ *+ * The context is reduced to the application context on the way in: this is reachable from+ * `CastController`, which is an object, so holding the Service that started mirroring would outlive+ * it. Only `WindowManager` metrics are read from it, which the application context serves fine.+ */+class MirrorEngine(+ context: Context,+ private val projection: MediaProjection,+ private val receiverHost: String,+ private val negotiation: Negotiation,+ private val session: StreamingSession,+ private val onDegraded: (MirrorDegradation) -> Unit,+ private val onStopped: (MirrorStopReason) -> Unit,+) {++ private val appContext: Context = context.applicationContext++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ private val senders = mutableMapOf<StreamKind, StreamSender>()++ private var videoJob: Job? = null+ private var audioJob: Job? = null+ private var rtcpJob: Job? = null++ private var transport: CastUdpTransport? = null+ private var capture: ScreenCapture? = null+ private var videoEncoder: VideoEncoder? = null+ private var audioEncoder: AudioEncoder? = null++ /** Hex-dump every packet. Off by default: per-packet and very loud. */+ var hexDump: Boolean = false++ fun start(): Boolean {+ val udp = CastUdpTransport(receiverHost, negotiation.udpPort)+ udp.hexDump = hexDump+ if (!udp.open()) {+ onStopped(MirrorStopReason.Udp)+ return false+ }+ transport = udp++ val videoStream = negotiation.video+ val audioStream = negotiation.audio+ val videoUnavailable = videoStream != null && !startVideo(videoStream, udp)+ val audioUnavailable = audioStream != null && !startAudio(audioStream, udp)++ // Stated degradation policy: a TV that lost audio still mirrors, with a notice; a speaker+ // that lost audio has nothing left to send at all, so it refuses.+ if (audioUnavailable && !negotiation.hasVideo) {+ Log.w(TAG, "audio-only target but no audio pipeline")+ stop()+ onStopped(MirrorStopReason.NoAudioForSpeaker)+ return false+ }+ if (senders.isEmpty()) {+ stop()+ onStopped(MirrorStopReason.NoEncoders)+ return false+ }+ if (videoUnavailable || audioUnavailable) {+ onDegraded(MirrorDegradation(videoUnavailable, audioUnavailable))+ }+ startRtcp(udp)+ return true+ }++ private fun startVideo(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {+ val screen = ScreenCapture(appContext, projection)+ val geometry = screen.geometry()+ val encoder = VideoEncoder(+ width = geometry.width,+ height = geometry.height,+ frameRate = StreamSelection.VIDEO_MAX_FRAME_RATE,+ bitRate = StreamSelection.VIDEO_MAX_BITRATE,+ )+ if (!encoder.start()) return false+ val surface = encoder.inputSurface+ if (surface == null || !screen.start(surface, geometry)) {+ encoder.release()+ screen.release()+ return false+ }+ Log.i(TAG, "mirroring at ${geometry.width}x${geometry.height}")+ videoEncoder = encoder+ capture = screen+ val sender = StreamSender(stream, udp, session)+ senders[StreamKind.Video] = sender+ videoJob = scope.launch {+ while (isActive) {+ val chunks = encoder.drain()+ if (chunks.isEmpty()) {+ delay(FRAME_POLL_MS)+ continue+ }+ for (chunk in chunks) sender.send(chunk)+ }+ }+ return true+ }++ private fun startAudio(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {+ val encoder = AudioEncoder(projection)+ if (!encoder.start()) return false+ audioEncoder = encoder+ val sender = StreamSender(stream, udp, session)+ senders[StreamKind.Audio] = sender+ audioJob = scope.launch {+ while (isActive) {+ val chunks = encoder.pump()+ for (chunk in chunks) sender.send(chunk)+ if (chunks.isEmpty()) delay(FRAME_POLL_MS)+ }+ }+ return true+ }++ /**+ * Sender reports out, feedback in.+ *+ * One loop for both directions because they share one socket, and because a report is cheap+ * enough that polling for feedback at report cadence needs no second coroutine.+ */+ private fun startRtcp(udp: CastUdpTransport) {+ rtcpJob = scope.launch {+ var lastReport = 0L+ while (isActive) {+ val now = System.currentTimeMillis()+ if (now - lastReport >= SENDER_REPORT_INTERVAL_MS) {+ lastReport = now+ for ((kind, sender) in senders) {+ val stream = negotiation.streams.firstOrNull { it.kind == kind } ?: continue+ udp.send(+ CastRtcp.senderReport(+ senderSsrc = stream.senderSsrc,+ ntpTimestamp = ntpTimestamp(now),+ rtpTimestamp = sender.stats.lastRtpTimestamp,+ packetCount = sender.stats.packets,+ octetCount = sender.stats.octets,+ ),+ )+ }+ }+ var packet = udp.receive()+ while (packet != null) {+ handleFeedback(packet)+ packet = udp.receive()+ }+ delay(RTCP_POLL_MS)+ }+ }+ }++ /**+ * Route one datagram to whichever stream it is feedback for.+ *+ * The SSRC pair identifies the stream, so a packet that matches neither is not ours and is+ * dropped without comment - a receiver also sends receiver reports and event logs we ignore.+ */+ private fun handleFeedback(packet: ByteArray) {+ for (stream in negotiation.streams) {+ val sender = senders[stream.kind] ?: continue+ val feedback = CastRtcp.parseFeedback(+ packet = packet,+ receiverSsrc = stream.receiverSsrc,+ senderSsrc = stream.senderSsrc,+ maxFrameId = sender.lastFrameId,+ ) ?: continue+ val recovery = session.onFeedback(feedback)+ sender.retransmit(recovery.retransmissions)+ if (recovery.needsKeyFrame && stream.kind == StreamKind.Video) {+ Log.i(TAG, "receiver fell behind the retransmit buffer; forcing a key frame")+ videoEncoder?.requestKeyFrame()+ }+ return+ }+ }++ fun stop() {+ videoJob?.cancel()+ audioJob?.cancel()+ rtcpJob?.cancel()+ // The display goes first: it is what is writing into the encoder's surface, and releasing+ // the encoder underneath a live VirtualDisplay is what makes the codec throw on the way out.+ capture?.release()+ videoEncoder?.release()+ audioEncoder?.release()+ transport?.close()+ capture = null+ videoEncoder = null+ audioEncoder = null+ transport = null+ senders.clear()+ }++ /** 32 bits of seconds since 1900, then 32 bits of fraction. */+ private fun ntpTimestamp(millis: Long): Long {+ val seconds = millis / 1000 + NTP_UNIX_OFFSET_SECONDS+ val fraction = (millis % 1000) * (1L shl 32) / 1000+ return (seconds shl 32) or fraction+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.ktnew file mode 100644index 0000000000..34d794a283--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorPreferences.kt@@ -0,0 +1,57 @@+package com.vayunmathur.cast.platform.mirror++import android.content.Context+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.library.util.DataStoreUtils++/**+ * The chosen mirroring target, persisted so the Quick Settings tile can reconnect without waiting+ * for a full mDNS round trip.+ *+ * **Only the target is persisted, and deliberately not whether mirroring was on.** `:share` stores+ * an enabled flag and reconciles it after a reboot, but screen-capture consent is single-use and+ * unreplayable, so a flag saying "was mirroring" could never be acted on headlessly - it would only+ * let the tile lie about its state. Liveness therefore comes from the in-process session instead.+ *+ * Keys are namespaced `cast_*` because `DataStoreUtils` is one store shared across the app.+ */+object MirrorPreferences {++ private const val KEY_DEVICE_ID = "cast_target_id"+ private const val KEY_DEVICE_NAME = "cast_target_name"+ private const val KEY_DEVICE_HOST = "cast_target_host"+ private const val KEY_DEVICE_PORT = "cast_target_port"+ private const val KEY_DEVICE_CAPABILITIES = "cast_target_capabilities"++ /**+ * The suspend getters, not the synchronous ones: the tile and the service both read this on a+ * cold start, where the eagerly-mirrored snapshot has not hydrated yet and the synchronous+ * variants would answer null for a target that is in fact stored.+ */+ suspend fun target(context: Context): CastDevice? {+ val store = DataStoreUtils.getInstance(context)+ val id = store.getStringAwait(KEY_DEVICE_ID) ?: return null+ val host = store.getStringAwait(KEY_DEVICE_HOST) ?: return null+ val name = store.getStringAwait(KEY_DEVICE_NAME) ?: host+ return CastDevice(+ id = id,+ friendlyName = name,+ host = host,+ port = store.getLongAwait(KEY_DEVICE_PORT)?.toInt() ?: CAST_DEFAULT_PORT,+ capabilities = store.getLongAwait(KEY_DEVICE_CAPABILITIES)?.toInt() ?: 0,+ )+ }++ suspend fun setTarget(context: Context, device: CastDevice) {+ val store = DataStoreUtils.getInstance(context)+ store.setString(KEY_DEVICE_ID, device.id)+ store.setString(KEY_DEVICE_NAME, device.friendlyName)+ store.setString(KEY_DEVICE_HOST, device.host)+ store.setLong(KEY_DEVICE_PORT, device.port.toLong())+ // Kept because it is what decides audio-only, and the tile must know that before it can+ // pick an app id - without it a speaker would be offered video and refused at LAUNCH.+ store.setLong(KEY_DEVICE_CAPABILITIES, device.capabilities.toLong())+ }+}++private const val CAST_DEFAULT_PORT = 8009
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.ktnew file mode 100644index 0000000000..3ffeb275dc--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorTileService.kt@@ -0,0 +1,129 @@+package com.vayunmathur.cast.platform.mirror++import android.app.PendingIntent+import android.content.Intent+import android.os.Build+import android.service.quicksettings.Tile+import android.service.quicksettings.TileService+import com.vayunmathur.cast.MainActivity+import com.vayunmathur.cast.R+import com.vayunmathur.cast.platform.CastController+import com.vayunmathur.cast.platform.MirrorPhase+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * Start and stop mirroring from the shade.+ *+ * A close transcription of `ShareReceiveTileService` with **one deliberate divergence**: `:share`+ * treats its persisted flag as authoritative and reconciles it headlessly after a reboot. Mirroring+ * cannot do that, because screen-capture consent is single-use and unreplayable. So tile state is+ * read from the in-process [CastController] instead: the foreground service keeps the process alive+ * for as long as mirroring is on, which means that if the process died, mirroring is dead and+ * `STATE_INACTIVE` is the truth. Only the *target* is persisted.+ *+ * A tile can also never start mirroring by itself - consent needs an Activity - so turning it on+ * hands off to [MirrorConsentActivity] via `startActivityAndCollapse`. Turning it off needs no+ * Activity and goes straight to the controller.+ *+ * No `requestListeningState()`: nothing in this repo uses it and the house idiom is to reconcile on+ * the next listen.+ */+class MirrorTileService : TileService() {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ override fun onStartListening() {+ super.onStartListening()+ refreshTile()+ }++ override fun onTileAdded() {+ super.onTileAdded()+ refreshTile()+ }++ override fun onClick() {+ super.onClick()+ if (CastController.mirrorPhase.value != MirrorPhase.Idle) {+ CastController.stopMirroring(this)+ refreshTile()+ return+ }+ scope.launch {+ // Nothing to mirror to until a target has been chosen once in the app, and there is no+ // device list in the shade to choose one from.+ val target = MirrorPreferences.target(this@MirrorTileService)+ if (target == null) {+ openApp()+ return@launch+ }+ // Consent must be collected by an Activity, and it must be collected afresh every time.+ startConsent()+ }+ }++ private fun startConsent() {+ collapseTo(MirrorConsentActivity.intent(this))+ }++ /**+ * Sets only `state` and `subtitle`; the label and icon come from the manifest, as they do in+ * `:share`.+ */+ private fun refreshTile() {+ scope.launch {+ val tile = qsTile ?: return@launch+ val phase = CastController.mirrorPhase.value+ val device = CastController.device.value+ val target = MirrorPreferences.target(this@MirrorTileService)+ tile.state = when (phase) {+ MirrorPhase.Mirroring, MirrorPhase.Negotiating -> Tile.STATE_ACTIVE+ else -> Tile.STATE_INACTIVE+ }+ tile.subtitle = when {+ phase == MirrorPhase.Mirroring -> device?.friendlyName+ ?: getString(R.string.cast_tile_mirroring)+ phase == MirrorPhase.Negotiating -> getString(R.string.cast_tile_starting)+ target == null -> getString(R.string.cast_tile_no_target)+ else -> target.friendlyName+ }+ tile.updateTile()+ }+ }++ private fun openApp() {+ collapseTo(Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ }++ /**+ * Launch [intent] and close the shade.+ *+ * One call site for the version split, because the `PendingIntent` overload only exists from+ * API 34 and `minSdk` is 31 - so the deprecated one is genuinely the only option below that,+ * and suppressing it twice would be twice as easy to lose track of.+ */+ @Suppress("DEPRECATION", "StartActivityAndCollapseDeprecated")+ private fun collapseTo(intent: Intent) {+ if (Build.VERSION.SDK_INT >= 34) {+ startActivityAndCollapse(+ PendingIntent.getActivity(+ this,+ 0,+ intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ ),+ )+ } else {+ startActivityAndCollapse(intent)+ }+ }++ override fun onDestroy() {+ super.onDestroy()+ scope.cancel()+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.ktnew file mode 100644index 0000000000..f4476de399--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/ScreenCapture.kt@@ -0,0 +1,80 @@+package com.vayunmathur.cast.platform.mirror++import android.content.Context+import android.hardware.display.DisplayManager+import android.hardware.display.VirtualDisplay+import android.media.projection.MediaProjection+import android.util.DisplayMetrics+import android.util.Log+import android.view.Surface+import android.view.WindowManager+import androidx.core.content.getSystemService++private const val TAG = "ScreenCapture"++/** The capture size and the frame rate to encode at. */+data class CaptureGeometry(val width: Int, val height: Int, val densityDpi: Int)++/**+ * A `VirtualDisplay` mirroring the real screen into an encoder's input surface.+ *+ * The receiver answers `scaling: "sender"` with its own (often 4K) dimensions, so choosing the+ * capture size is ours to do. It is scaled down to at most [MAX_DIMENSION] on the long edge, keeping+ * the real aspect ratio, because that is what the OFFER promised and what keeps the bitrate sane.+ *+ * Both dimensions are rounded to even numbers: H.264's 4:2:0 chroma subsampling cannot represent an+ * odd width or height, and some encoders fail outright rather than rounding for you.+ */+class ScreenCapture(+ private val context: Context,+ private val projection: MediaProjection,+) {++ private var display: VirtualDisplay? = null++ fun geometry(): CaptureGeometry {+ val metrics = DisplayMetrics()+ val windowManager = context.getSystemService<WindowManager>()+ @Suppress("DEPRECATION")+ windowManager?.defaultDisplay?.getRealMetrics(metrics)+ val realWidth = metrics.widthPixels.takeIf { it > 0 } ?: 1080+ val realHeight = metrics.heightPixels.takeIf { it > 0 } ?: 1920+ val scale = minOf(+ 1.0,+ MAX_DIMENSION.toDouble() / maxOf(realWidth, realHeight),+ )+ return CaptureGeometry(+ width = ((realWidth * scale).toInt() / 2) * 2,+ height = ((realHeight * scale).toInt() / 2) * 2,+ densityDpi = metrics.densityDpi.takeIf { it > 0 } ?: DisplayMetrics.DENSITY_DEFAULT,+ )+ }++ /** Returns false if the platform refused the display, which leaves nothing to encode. */+ fun start(surface: Surface, geometry: CaptureGeometry): Boolean = try {+ display = projection.createVirtualDisplay(+ "cast-mirror",+ geometry.width,+ geometry.height,+ geometry.densityDpi,+ DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,+ surface,+ null,+ null,+ )+ display != null+ } catch (e: Exception) {+ Log.w(TAG, "could not create the virtual display", e)+ false+ }++ fun release() {+ runCatching { display?.release() }+ display = null+ }++ private companion object {+ /** 720p on the long edge, matching the `resolutions` the OFFER advertises. */+ const val MAX_DIMENSION = 1280+ }+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.ktnew file mode 100644index 0000000000..5743e1321d--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/StreamSender.kt@@ -0,0 +1,89 @@+package com.vayunmathur.cast.platform.mirror++import com.vayunmathur.cast.domain.streaming.CastCrypto+import com.vayunmathur.cast.domain.streaming.CastRtpPacketizer+import com.vayunmathur.cast.domain.streaming.EncryptedFrame+import com.vayunmathur.cast.domain.streaming.FrameId+import com.vayunmathur.cast.domain.streaming.NegotiatedStream+import com.vayunmathur.cast.domain.streaming.Retransmission+import com.vayunmathur.cast.domain.streaming.StreamingSession+import com.vayunmathur.cast.network.CastUdpTransport++/**+ * One stream's send path: encrypt, packetize, count.+ *+ * Audio and video are independent sequences with their own keys, frame ids and RTP timestamps, so+ * there is one of these per stream rather than one shared pipeline.+ */+class StreamSender(+ private val stream: NegotiatedStream,+ private val udp: CastUdpTransport,+ private val session: StreamingSession,+) {++ private val crypto = CastCrypto(stream.keys.key, stream.keys.ivMask)+ private val packetizer = CastRtpPacketizer(stream.payloadType, stream.senderSsrc)++ private var nextFrameId = FrameId.First+ private var lastKeyFrameId = FrameId.Leader+ private var firstPresentationTimeUs = -1L++ /** The highest frame id sent, which is what an 8-bit checkpoint is expanded against. */+ var lastFrameId: FrameId = FrameId.First+ private set++ var stats: SenderStats = SenderStats()+ private set++ fun send(chunk: EncodedChunk) {+ // Timestamps are relative to the first frame, so a receiver does not have to know when the+ // encoder happened to start.+ if (firstPresentationTimeUs < 0) firstPresentationTimeUs = chunk.presentationTimeUs+ val elapsedUs = chunk.presentationTimeUs - firstPresentationTimeUs+ val rtpTimestamp = elapsedUs * stream.timebase / 1_000_000L+ val frameId = nextFrameId+ // A key frame references the leader, having no predecessor. A delta frame references the+ // last key frame rather than the frame just before it, so one lost delta does not invalidate+ // every frame that follows.+ val referenced = if (chunk.isKeyFrame) FrameId.Leader else lastKeyFrameId+ val frame = EncryptedFrame(+ frameId = frameId,+ referencedFrameId = referenced,+ rtpTimestamp = rtpTimestamp,+ isKeyFrame = chunk.isKeyFrame,+ payload = crypto.crypt(frameId, chunk.data),+ )+ if (chunk.isKeyFrame) lastKeyFrameId = frameId+ nextFrameId += 1+ lastFrameId = frameId+ session.record(frame)+ emit(frame, packetIds = null)+ stats = stats.copy(lastRtpTimestamp = rtpTimestamp)+ }++ fun retransmit(items: List<Retransmission>) {+ for (item in items) emit(item.frame, item.packetIds)+ }++ /** [packetIds] null means every packet of the frame; otherwise only those listed. */+ private fun emit(frame: EncryptedFrame, packetIds: List<Int>?) {+ val packets = packetizer.packetize(frame)+ var sent = 0L+ var octets = 0L+ packets.forEachIndexed { index, packet ->+ if (packetIds != null && index !in packetIds) return@forEachIndexed+ if (udp.send(packet)) {+ sent+++ octets += packet.size+ }+ }+ stats = SenderStats(stats.packets + sent, stats.octets + octets, stats.lastRtpTimestamp)+ }+}++/** What a sender report reports. */+data class SenderStats(+ val packets: Long = 0,+ val octets: Long = 0,+ val lastRtpTimestamp: Long = 0,+)
cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.ktnew file mode 100644index 0000000000..696fbe8e60--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/VideoEncoder.kt@@ -0,0 +1,172 @@+package com.vayunmathur.cast.platform.mirror++import android.media.MediaCodec+import android.media.MediaFormat+import android.util.Log+import android.view.Surface+import java.nio.ByteBuffer++private const val TAG = "VideoEncoder"++private const val TIMEOUT_US = 10_000L++/** One encoded access unit, straight off the codec. */+data class EncodedChunk(+ val data: ByteArray,+ val presentationTimeUs: Long,+ val isKeyFrame: Boolean,+) {+ override fun equals(other: Any?): Boolean =+ other is EncodedChunk &&+ presentationTimeUs == other.presentationTimeUs &&+ isKeyFrame == other.isKeyFrame &&+ data.contentEquals(other.data)++ override fun hashCode(): Int {+ var result = data.contentHashCode()+ result = 31 * result + presentationTimeUs.hashCode()+ result = 31 * result + isKeyFrame.hashCode()+ return result+ }+}++/**+ * H.264 encoder fed by a `Surface`, producing raw access units.+ *+ * The drain-loop shape is borrowed from `camera/.../MotionPhotoEncoder.kt`, with two inversions+ * that matter:+ *+ * - **It never touches pixels.** [inputSurface] is handed to a `VirtualDisplay`, which writes into+ * it directly, so there is no input-buffer queueing and no `fillI420` colour conversion.+ * - **It keeps `BUFFER_FLAG_CODEC_CONFIG`.** `MotionPhotoEncoder` discards it because `MediaMuxer`+ * writes SPS/PPS into the container itself. There is no container here, so the parameter sets are+ * cached and prepended to the first IDR - a receiver handed an IDR with no SPS/PPS shows nothing+ * at all, and shows it silently.+ */+class VideoEncoder(+ private val width: Int,+ private val height: Int,+ private val frameRate: Int,+ private val bitRate: Int,+) {++ private var codec: MediaCodec? = null+ private val bufferInfo = MediaCodec.BufferInfo()++ /** SPS/PPS, cached from the codec-config buffer and prepended to the first key frame. */+ private var parameterSets: ByteArray? = null+ private var sentParameterSets = false++ var inputSurface: Surface? = null+ private set++ /** False when the device has no usable surface encoder, which is not recoverable. */+ fun start(): Boolean {+ val name = EncoderSupport.videoEncoderName()+ if (name == null) {+ Log.w(TAG, "no ${EncoderSupport.VIDEO_MIME} encoder taking COLOR_FormatSurface")+ return false+ }+ return try {+ val format = MediaFormat.createVideoFormat(EncoderSupport.VIDEO_MIME, width, height)+ .apply {+ setInteger(+ MediaFormat.KEY_COLOR_FORMAT,+ android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,+ )+ setInteger(MediaFormat.KEY_BIT_RATE, bitRate)+ setInteger(MediaFormat.KEY_FRAME_RATE, frameRate)+ // One second. A receiver that joins or loses sync recovers at the next IDR, and+ // the RTCP path can ask for one sooner when it actually needs it.+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)+ setInteger(+ MediaFormat.KEY_BITRATE_MODE,+ android.media.MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR,+ )+ }+ val created = MediaCodec.createByCodecName(name)+ created.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ inputSurface = created.createInputSurface()+ created.start()+ codec = created+ true+ } catch (e: Exception) {+ Log.w(TAG, "could not start the video encoder", e)+ release()+ false+ }+ }++ /**+ * Everything the encoder has ready right now.+ *+ * Non-blocking beyond [TIMEOUT_US], so the caller's loop stays responsive to a stop request+ * even when the encoder has produced nothing.+ */+ fun drain(): List<EncodedChunk> {+ val active = codec ?: return emptyList()+ val out = mutableListOf<EncodedChunk>()+ while (true) {+ val index = try {+ active.dequeueOutputBuffer(bufferInfo, TIMEOUT_US)+ } catch (e: IllegalStateException) {+ Log.w(TAG, "encoder went away mid-drain", e)+ return out+ }+ if (index < 0) return out+ val buffer = active.getOutputBuffer(index)+ if (buffer != null && bufferInfo.size > 0) {+ val bytes = buffer.readChunk()+ if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {+ // Not a frame: the parameter sets, which must lead the first IDR.+ parameterSets = bytes+ } else {+ val isKeyFrame =+ bufferInfo.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0+ val payload = if (isKeyFrame && !sentParameterSets) {+ sentParameterSets = true+ (parameterSets ?: ByteArray(0)) + bytes+ } else {+ bytes+ }+ out += EncodedChunk(payload, bufferInfo.presentationTimeUs, isKeyFrame)+ }+ }+ active.releaseOutputBuffer(index, false)+ }+ }++ /**+ * Ask for an IDR at the next opportunity.+ *+ * Called when RTCP feedback says a receiver has fallen further behind than the retransmit+ * buffer can repair, which is the only way it can recover.+ */+ fun requestKeyFrame() {+ val active = codec ?: return+ runCatching {+ active.setParameters(+ android.os.Bundle().apply {+ putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)+ },+ )+ }.onFailure { Log.w(TAG, "could not request a key frame", it) }+ // The new IDR needs SPS/PPS in front of it too: a receiver asking for a key frame is one+ // that may never have seen the originals.+ sentParameterSets = false+ }++ fun release() {+ runCatching { codec?.stop() }+ runCatching { codec?.release() }+ runCatching { inputSurface?.release() }+ codec = null+ inputSurface = null+ }++ private fun ByteBuffer.readChunk(): ByteArray {+ position(bufferInfo.offset)+ limit(bufferInfo.offset + bufferInfo.size)+ return ByteArray(bufferInfo.size).also { get(it) }+ }+}
cast/src/main/java/com/vayunmathur/cast/service/CastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastService.ktindex f581100020..00011564b5 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastService.kt@@ -7,15 +7,19 @@ 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.IBinder import android.util.Log import androidx.core.app.NotificationCompat+import androidx.core.content.IntentCompat import androidx.core.content.getSystemService import com.vayunmathur.cast.MainActivity import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastPhase import com.vayunmathur.cast.platform.CastController+import com.vayunmathur.cast.platform.MirrorPhase import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -35,16 +39,20 @@ private const val CHANNEL_ID = "cast_session" private const val NOTIF_ID = 4201 /**- * Keeps the cast session alive while the app is not in front.+ * Keeps the cast session alive while the app is not in front, and owns the screen-capture+ * projection. *- * A lifecycle host with no session state of its own: [CastController] owns the socket and the- * session, so this can be started and stopped freely. `START_NOT_STICKY` rather than sticky,- * because a restarted service has nothing to restore - the TLS channel died with the process and- * the receiver has already dropped it.+ * The projection lives here rather than in the controller because of the Android 14+ ordering rule:+ * a `mediaProjection`-typed foreground service must already be in the foreground *before*+ * `getMediaProjection()` is called. So [onStartCommand] calls `startForeground` first, every time,+ * and only then turns the consent token into a projection. *- * The foreground type is `mediaPlayback`, which is what Android's own documentation lists for- * casting. `dataSync` is unusable: Android 15 caps it at six cumulative hours per 24 h and then- * calls `onTimeout()`.+ * `START_NOT_STICKY` rather than sticky: a restarted service has nothing to restore. The TLS channel+ * died with the process, the receiver has already dropped it, and the consent token was single-use.+ *+ * Stop always routes through [ACTION_STOP] rather than `stopService` from outside, so the three+ * sources - the tile, the notification action and the system's own "Stop sharing" chip - all take+ * the same path. That is `ShareReceiveController`'s discipline. */ class CastService : Service() { @@ -53,6 +61,21 @@ class CastService : Service() { /** Guards against a second onStartCommand registering the status collector twice. */ private var collecting = false + private var projection: MediaProjection? = null++ /**+ * The system "Stop sharing" chip and a revoked projection both land here.+ *+ * Registered *before* `createVirtualDisplay`, which Android 14+ requires, and which also means+ * this is the only reliable notice that the user stopped sharing from outside the app.+ */+ private val projectionCallback = object : MediaProjection.Callback() {+ override fun onStop() {+ Log.i(TAG, "the projection was stopped from outside the app")+ CastController.stopMirroring(this@CastService)+ }+ }+ override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() {@@ -66,57 +89,104 @@ class CastService : Service() { } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {- // Before anything else: this is started with startForegroundService, and the platform- // kills a process that does not honour that within a few seconds.- enterForeground()- if (intent?.action == ACTION_STOP) {- CastController.disconnect(this)- return START_NOT_STICKY+ val isMirroring = intent?.action == ACTION_START_MIRRORING+ // Before anything else: this is started with startForegroundService, and the platform kills+ // a process that does not honour that within a few seconds.+ enterForeground(withProjection = isMirroring)+ when (intent?.action) {+ ACTION_STOP -> {+ CastController.disconnect(this)+ return START_NOT_STICKY+ }+ ACTION_STOP_MIRRORING -> {+ releaseProjection()+ return START_NOT_STICKY+ }+ ACTION_START_MIRRORING -> startMirroringFrom(intent) } if (!collecting) { collecting = true- // One collector for the lifetime of the service, so the notification tracks what is- // playing instead of freezing on whatever was true when it started.+ // One collector for the lifetime of the service, so the notification tracks the session+ // instead of freezing on whatever was true when it started. scope.launch { CastController.device .combine(CastController.sessionState) { device, state -> device to state }- .collect { (device, state) ->+ .combine(CastController.mirrorPhase) { pair, mirror -> Triple(pair.first, pair.second, mirror) }+ .collect { (device, state, mirror) -> if (device == null) return@collect- val text = when (state.phase) {- CastPhase.Launching ->- getString(R.string.cast_notification_text_connecting)- CastPhase.Ready -> getString(R.string.cast_notification_text_ready)- // Not the raw LAUNCH_ERROR reason: those are wire constants, and the- // screen is where the explanation belongs.- CastPhase.Failed -> getString(R.string.cast_notification_text_failed)- // The receiver app exited on its own - the channel is still up, so- // this is a real resting state rather than a transient one.- CastPhase.Idle -> getString(R.string.cast_notification_text_idle)- } getSystemService<NotificationManager>()- ?.notify(NOTIF_ID, buildNotification(device.friendlyName, text))+ ?.notify(+ NOTIF_ID,+ buildNotification(device.friendlyName, statusText(state.phase, mirror)),+ ) } } } return START_NOT_STICKY } + /**+ * Turn the consent token into a projection, in the one order the platform allows.+ *+ * `startForeground` has already happened in [onStartCommand]; the callback is registered before+ * anything is created from the projection, which Android 14+ enforces.+ */+ private fun startMirroringFrom(intent: Intent) {+ val resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, RESULT_CANCELED_FALLBACK)+ val data = IntentCompat.getParcelableExtra(intent, EXTRA_RESULT_DATA, Intent::class.java)+ if (data == null) {+ Log.w(TAG, "no consent token in the mirroring request")+ return+ }+ val manager = getSystemService<MediaProjectionManager>()+ val granted = try {+ manager?.getMediaProjection(resultCode, data)+ } catch (e: Exception) {+ // The usual cause is calling this before the service was genuinely in the foreground.+ Log.w(TAG, "getMediaProjection refused", e)+ null+ }+ if (granted == null) {+ Log.w(TAG, "no projection")+ return+ }+ releaseProjection()+ granted.registerCallback(projectionCallback, null)+ projection = granted+ CastController.startMirroring(this, granted)+ }++ private fun releaseProjection() {+ val active = projection ?: return+ runCatching { active.unregisterCallback(projectionCallback) }+ runCatching { active.stop() }+ projection = null+ }+ override fun onDestroy() { super.onDestroy()+ releaseProjection() scope.cancel() } /**- * Android 15's cumulative-runtime timeout. `mediaPlayback` is not capped, so this should- * never fire; if a future platform version caps it anyway, tearing the session down cleanly- * beats being killed with a socket open.+ * Android 15's cumulative-runtime timeout.+ *+ * Checked rather than assumed: the cap applies to `dataSync` and `mediaProcessing` only, so this+ * should never fire for either type used here. Kept because if a future platform version does+ * cap them, tearing the session down cleanly beats being killed with a socket open. */ override fun onTimeout(startId: Int, fgsType: Int) { Log.w(TAG, "foreground service timed out (type $fgsType)") CastController.disconnect(this) } - private fun enterForeground() {+ /**+ * [withProjection] switches the declared type to `mediaProjection`, which is the type that has+ * to be in force before `getMediaProjection()` is called. Until there is a projection to hold,+ * `mediaPlayback` is the honest description and does not require one.+ */+ private fun enterForeground(withProjection: Boolean) { val device = CastController.device.value val notification = buildNotification( device?.friendlyName ?: getString(R.string.app_name),@@ -124,11 +194,12 @@ class CastService : Service() { ) try { if (Build.VERSION.SDK_INT >= 34) {- startForeground(- NOTIF_ID,- notification,- ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,- )+ val type = if (withProjection) {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION+ } else {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK+ }+ startForeground(NOTIF_ID, notification, type) } else { @Suppress("DEPRECATION") startForeground(NOTIF_ID, notification)@@ -140,6 +211,17 @@ class CastService : Service() { } } + private fun statusText(phase: CastPhase, mirror: MirrorPhase): String = when {+ mirror == MirrorPhase.Mirroring -> getString(R.string.cast_notification_text_mirroring)+ mirror == MirrorPhase.Negotiating -> getString(R.string.cast_notification_text_starting)+ mirror == MirrorPhase.Failed -> getString(R.string.cast_notification_text_failed)+ phase == CastPhase.Launching -> getString(R.string.cast_notification_text_connecting)+ phase == CastPhase.Ready -> getString(R.string.cast_notification_text_ready)+ phase == CastPhase.Failed -> getString(R.string.cast_notification_text_failed)+ // The receiver app exited on its own; the channel is still up, so this is a resting state.+ else -> getString(R.string.cast_notification_text_idle)+ }+ private fun buildNotification(deviceName: String, text: String): Notification { val open = PendingIntent.getActivity( this,@@ -166,9 +248,17 @@ class CastService : Service() { } companion object {- /** Ends the session from the notification's own action. */+ /** Ends the whole session, from the notification's own action or the tile. */ const val ACTION_STOP = "com.vayunmathur.cast.action.STOP" + private const val ACTION_START_MIRRORING = "com.vayunmathur.cast.action.START_MIRRORING"+ private const val ACTION_STOP_MIRRORING = "com.vayunmathur.cast.action.STOP_MIRRORING"+ private const val EXTRA_RESULT_CODE = "resultCode"+ private const val EXTRA_RESULT_DATA = "resultData"++ /** Not `Activity.RESULT_CANCELED` only to avoid depending on the activity class here. */+ private const val RESULT_CANCELED_FALLBACK = 0+ fun start(context: Context) { launch(context, Intent(context, CastService::class.java)) }@@ -177,6 +267,24 @@ class CastService : Service() { context.stopService(Intent(context, CastService::class.java)) } + /** Called by `MirrorConsentActivity` with a freshly granted, single-use token. */+ fun startMirroring(context: Context, resultCode: Int, data: Intent) {+ launch(+ context,+ Intent(context, CastService::class.java)+ .setAction(ACTION_START_MIRRORING)+ .putExtra(EXTRA_RESULT_CODE, resultCode)+ .putExtra(EXTRA_RESULT_DATA, data),+ )+ }++ fun stopMirroring(context: Context) {+ launch(+ context,+ Intent(context, CastService::class.java).setAction(ACTION_STOP_MIRRORING),+ )+ }+ private fun launch(context: Context, intent: Intent) { try { context.startForegroundService(intent)
cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.ktindex 3fdb4d89e6..789a997496 100644--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastContent.kt@@ -18,6 +18,7 @@ import com.vayunmathur.cast.R import com.vayunmathur.cast.platform.CastActions import com.vayunmathur.cast.platform.CastConnection import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.cast.platform.MirrorPhase import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator@@ -58,6 +59,14 @@ fun CastContent( contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) {+ if (state.connection == CastConnection.Connected ||+ state.mirrorPhase != MirrorPhase.Idle+ ) {+ item { CastMirrorStatusCard(state, actions) }+ if (state.audioOnly) {+ item { ConsentNote() }+ }+ } item { SectionHeader(state, actions) } if (state.localNetworkBlocked) { item { LocalNetworkBlocked(actions) }@@ -76,6 +85,22 @@ fun CastContent( } } +/**+ * Why an audio-only cast still shows a screen-capture dialog.+ *+ * `AudioPlaybackCaptureConfiguration` requires a projection, so there is no way to capture playing+ * audio without asking to record the screen. Unexplained, it reads as a bug.+ */+@Composable+private fun ConsentNote() {+ Text(+ stringResource(R.string.cast_mirror_consent_note),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(horizontal = 4.dp),+ )+}+ @Composable private fun SectionHeader(state: CastUiState, actions: CastActions) { Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
cast/src/main/java/com/vayunmathur/cast/ui/CastMirrorStatusCard.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastMirrorStatusCard.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastMirrorStatusCard.ktnew file mode 100644index 0000000000..4d54a35f2c--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastMirrorStatusCard.kt@@ -0,0 +1,132 @@+package com.vayunmathur.cast.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.cast.R+import com.vayunmathur.cast.platform.CastActions+import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.cast.platform.MirrorPhase+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconScreenShare+import com.vayunmathur.library.ui.IconVolumeOff+import com.vayunmathur.library.ui.IconVolumeUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Text++/**+ * Mirroring status and the one control that matters: start or stop.+ *+ * Replaces the media receiver's now-playing card. Volume stays because it is the receiver's own+ * volume and works whether or not anything is being mirrored.+ */+@Composable+fun CastMirrorStatusCard(+ state: CastUiState,+ actions: CastActions,+ modifier: Modifier = Modifier,+) {+ Card(modifier = modifier.fillMaxWidth()) {+ Column(+ Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ text = stringResource(statusLabel(state)),+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.weight(1f),+ )+ if (state.mirrorPhase == MirrorPhase.Negotiating) {+ CircularProgressIndicator()+ }+ }+ // Both degradations are worth saying out loud: a silent audio stream or a+ // video-only cast otherwise just looks broken.+ if (state.audioDegraded) {+ Notice(stringResource(R.string.cast_mirror_audio_degraded))+ }+ if (state.videoDegraded) {+ Notice(stringResource(R.string.cast_mirror_video_degraded))+ }+ state.failure?.let { Notice(it, isError = true) }+ if (state.isMirroring || state.mirrorPhase == MirrorPhase.Negotiating) {+ OutlinedButton(+ onClick = actions::stopMirroring,+ modifier = Modifier.fillMaxWidth(),+ ) {+ Text(stringResource(R.string.cast_stop_mirroring))+ }+ } else {+ Button(+ onClick = actions::startMirroring,+ enabled = state.canMirror,+ modifier = Modifier.fillMaxWidth(),+ ) {+ IconScreenShare()+ Text(+ stringResource(R.string.cast_start_mirroring),+ modifier = Modifier.padding(start = 8.dp),+ )+ }+ }+ VolumeRow(state, actions)+ }+ }+}++@Composable+private fun Notice(text: String, isError: Boolean = false) {+ Text(+ text = text,+ style = MaterialTheme.typography.bodySmall,+ color = if (isError) {+ MaterialTheme.colorScheme.error+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ },+ )+}++@Composable+private fun VolumeRow(state: CastUiState, actions: CastActions) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconButton(onClick = { actions.setMuted(!state.muted) }) {+ if (state.muted) IconVolumeOff() else IconVolumeUp()+ }+ Slider(+ value = state.volumeLevel.toFloat(),+ onValueChange = { actions.setVolume(it.toDouble()) },+ modifier = Modifier.weight(1f),+ )+ }+}++private fun statusLabel(state: CastUiState): Int = when {+ state.isMirroring && state.audioOnly -> R.string.cast_status_casting_audio+ state.isMirroring -> R.string.cast_status_mirroring+ state.mirrorPhase == MirrorPhase.Negotiating -> R.string.cast_status_starting+ state.mirrorPhase == MirrorPhase.Failed -> R.string.cast_status_failed+ state.audioOnly -> R.string.cast_status_ready_audio+ else -> R.string.cast_status_ready+}
cast/src/main/res/drawable/ic_tile_cast_mirror.xml
diff --git a/cast/src/main/res/drawable/ic_tile_cast_mirror.xml b/cast/src/main/res/drawable/ic_tile_cast_mirror.xmlnew file mode 100644index 0000000000..d3df1c0e48--- /dev/null+++ b/cast/src/main/res/drawable/ic_tile_cast_mirror.xml@@ -0,0 +1,22 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24"+ android:tint="?android:attr/colorControlNormal">+ <!-- A screen with a cast glyph inside it. Monochrome and tinted by colorControlNormal so+ Quick Settings can shade it by state; the white-tinted ic_cast stays the notification+ icon, which needs a fixed colour instead. -->+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M21,3L3,3C1.9,3 1,3.9 1,5v12c0,1.1 0.9,2 2,2h5v2h8v-2h5c1.1,0 2,-0.9 2,-2L23,5c0,-1.1 -0.9,-2 -2,-2zM21,17L3,17L3,5h18v12z" />+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M5,7v1.5c3.58,0 6.5,2.92 6.5,6.5L13,15c0,-4.42 -3.58,-8 -8,-8z" />+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M5,10v1.5c1.93,0 3.5,1.57 3.5,3.5L10,15c0,-2.76 -2.24,-5 -5,-5z" />+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M5,13v2h2c0,-1.1 -0.9,-2 -2,-2z" />+</vector>
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex 86f94ed8ff..ef6a1ebab0 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -24,12 +24,41 @@ <string name="cast_launch_failed">Could not start mirroring on this device</string> <string name="cast_retry">Try again</string> + <!-- Mirroring -->+ <string name="cast_start_mirroring">Mirror my screen</string>+ <string name="cast_stop_mirroring">Stop mirroring</string>+ <string name="cast_status_ready">Ready to mirror</string>+ <string name="cast_status_ready_audio">Ready to cast audio</string>+ <string name="cast_status_starting">Starting.</string>+ <string name="cast_status_mirroring">Mirroring your screen</string>+ <string name="cast_status_casting_audio">Casting audio</string>+ <string name="cast_status_failed">Mirroring stopped</string>+ <!-- An audio cast still shows a screen-capture dialog, because that is the only way Android+ grants playback capture. Said plainly, or it looks like a bug. -->+ <string name="cast_mirror_consent_note">Android asks to record the screen even for audio, because that is how it grants permission to capture what is playing.</string>+ <string name="cast_mirror_audio_degraded">Audio is unavailable, so only the picture is being sent. Apps that block audio capture, and devices without an Opus encoder, both cause this.</string>+ <string name="cast_mirror_video_degraded">Video is unavailable on this device, so only audio is being sent.</string>+ <string name="cast_mirror_unavailable">This device cannot capture the screen</string>+ <string name="cast_mirror_no_streams">The device would not accept anything we can send</string>+ <string name="cast_mirror_negotiation_failed">The device refused to start a stream</string>+ <string name="cast_mirror_udp_failed">Could not reach the device to send video</string>+ <string name="cast_mirror_no_encoder">This device has no usable screen encoder</string>+ <string name="cast_mirror_no_audio">Audio could not be captured, and this device can only play audio</string>++ <!-- Quick Settings tile -->+ <string name="cast_tile_label">Mirror screen</string>+ <string name="cast_tile_no_target">Choose a device first</string>+ <string name="cast_tile_starting">Starting.</string>+ <string name="cast_tile_mirroring">Mirroring</string>+ <!-- Foreground service --> <string name="cast_notification_channel_name">Casting</string> <string name="cast_notification_channel_desc">Shown while a cast session is open</string> <string name="cast_notification_title">Casting to %1$s</string> <string name="cast_notification_text_connecting">Connecting</string> <string name="cast_notification_text_ready">Ready to mirror</string>+ <string name="cast_notification_text_starting">Starting</string>+ <string name="cast_notification_text_mirroring">Mirroring your screen</string> <string name="cast_notification_text_idle">Not mirroring</string> <string name="cast_notification_text_failed">Could not start mirroring</string> <string name="cast_notification_action_stop">Stop</string>
cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt
diff --git a/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt b/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.ktindex 28dcb163c1..4e361ca19f 100644--- a/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt+++ b/cast/src/screenshotTest/kotlin/com/vayunmathur/cast/ui/MetadataPreviews.kt@@ -7,6 +7,7 @@ import com.vayunmathur.cast.domain.CastDevice import com.vayunmathur.cast.platform.CastActions import com.vayunmathur.cast.platform.CastConnection import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.cast.platform.MirrorPhase import com.vayunmathur.library.ui.DynamicTheme /** Phone-shaped, roughly 1080x2340 at xxhdpi - comfortably above the F-Droid minimum. */@@ -44,12 +45,13 @@ private val Receivers = listOf( /** * Store-listing screenshots. *- * Driven through [CastContent], which is stateless by design, so no socket and no mDNS browse has- * to exist for these to render - neither of which Layoutlib could provide.+ * Driven through [CastContent], which is stateless by design, so no socket, no mDNS browse and no+ * screen-capture projection has to exist for these to render - none of which Layoutlib could+ * provide. *- * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but is- * not collected as a screenshot test. They must also be class members rather than top-level- * functions, and the listing order comes from the function names (Preview1., Preview2.).+ * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but is not+ * collected as a screenshot test. They must also be class members rather than top-level functions,+ * and the listing order comes from the function names (Preview1., Preview2.). */ class MetadataPreviews { @@ -66,15 +68,16 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "2-connecting", device = PHONE, showSystemUi = true)+ @Preview(name = "2-ready", device = PHONE, showSystemUi = true) @Composable- fun Preview2Connecting() {+ fun Preview2Ready() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers, connectedDevice = LivingRoomTv,- connection = CastConnection.Connecting,+ connection = CastConnection.Connected,+ volumeLevel = 0.55, ), actions = CastActions.Noop, )@@ -82,16 +85,17 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "3-connected-tv", device = PHONE, showSystemUi = true)+ @Preview(name = "3-mirroring", device = PHONE, showSystemUi = true) @Composable- fun Preview3ConnectedTv() {+ fun Preview3Mirroring() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers, connectedDevice = LivingRoomTv, connection = CastConnection.Connected,- volumeLevel = 0.55,+ mirrorPhase = MirrorPhase.Mirroring,+ volumeLevel = 0.7, ), actions = CastActions.Noop, )@@ -99,19 +103,20 @@ class MetadataPreviews { } @PreviewTest- @Preview(name = "4-connected-group", device = PHONE, showSystemUi = true)+ @Preview(name = "4-audio-group", device = PHONE, showSystemUi = true) @Composable- fun Preview4ConnectedGroup() {+ fun Preview4AudioGroup() { DynamicTheme(darkTheme = true) { CastContent( state = CastUiState( devices = Receivers, connectedDevice = WholeHome, connection = CastConnection.Connected,- // A group has no screen, so only audio can go to it.+ mirrorPhase = MirrorPhase.Mirroring,+ // A group has no screen, so only audio goes to it - which is also why the+ // screen-capture explanation is on this one. audioOnly = true, volumeLevel = 0.3,- muted = true, ), actions = CastActions.Noop, )
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex b3276faf2a..c27e1cab62 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -120,6 +120,7 @@ import androidx.compose.material.icons.filled.CheckBox import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Cast import androidx.compose.material.icons.filled.CastConnected+import androidx.compose.material.icons.filled.ScreenShare import androidx.compose.material.icons.filled.Speaker import androidx.compose.material.icons.filled.Tv import androidx.compose.material.icons.filled.Close@@ -372,6 +373,10 @@ fun IconSpeaker(modifier: Modifier = Modifier, tint: Color = LocalContentColor.c fun IconTv(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.Tv, "TV", modifier, tint) +@Composable+fun IconScreenShare(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.ScreenShare, "Share screen", modifier, tint)+ @Composable fun IconNavigation(navBack: () -> Unit) { IconButton({ navBack() }) {
metadata_data/cast.md
diff --git a/metadata_data/cast.md b/metadata_data/cast.mdindex 46319ca984..649a920f9b 100644--- a/metadata_data/cast.md+++ b/metadata_data/cast.md@@ -1,3 +1,3 @@ Mirror your screen to your TV-Find any Chromecast, Google TV or Nest speaker on your Wi-Fi and mirror your screen to it, with volume control from the phone.-The Cast protocol is implemented from scratch over a plain TLS socket, so there is no Google Play Services and no Cast SDK - and no storage permission either, because nothing is read from your device.+Mirror your screen to any Chromecast or Google TV on your Wi-Fi, or send just the audio to a Nest speaker or a speaker group, from the app or from a Quick Settings tile.+Cast Streaming is implemented from scratch - mDNS discovery, a TLS control channel, and encrypted RTP over UDP - so there is no Google Play Services and no Cast SDK, and no storage permission either, because nothing is read from your device.
metadata_data/photos/cast/2.png
diff --git a/metadata_data/photos/cast/2.png b/metadata_data/photos/cast/2.pngindex d90393d1c3..4ddbae2e36 100644Binary files a/metadata_data/photos/cast/2.png and b/metadata_data/photos/cast/2.png differ
metadata_data/photos/cast/3.png
diff --git a/metadata_data/photos/cast/3.png b/metadata_data/photos/cast/3.pngindex 86d04d029d..484d4bf6fd 100644Binary files a/metadata_data/photos/cast/3.png and b/metadata_data/photos/cast/3.png differ
metadata_data/photos/cast/4.png
diff --git a/metadata_data/photos/cast/4.png b/metadata_data/photos/cast/4.pngindex e6dcd68a64..11a7a7f607 100644Binary files a/metadata_data/photos/cast/4.png and b/metadata_data/photos/cast/4.png differ