cast: stream another app's content, not just the screen
- Commit
bf9593fbac307b3d4301975f2e3a5c917fe8481c- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 20:43 UTC (3 months ago)
- Parents
52a248e
Diff
cast/build.gradle.kts
diff --git a/cast/build.gradle.kts b/cast/build.gradle.ktsindex 70ee5efdd1..bef4fc3668 100644--- a/cast/build.gradle.kts+++ b/cast/build.gradle.kts@@ -16,6 +16,9 @@ android { dependencies { // The wire format, shared verbatim with the TV receiver. Nothing here re-implements it. implementation(project(":cast:protocol"))+ // The IPC contract, shared with every app that streams its content through here. Depended on+ // rather than duplicated, which is the one thing FamilyLocationProtocol gets wrong.+ implementation(project(":sdk:cast")) } // No Rust crate. The protocol module already reaches ML-KEM through :library:e2ee-p2p, and
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.ktindex 5a9c312314..0051384236 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -11,7 +11,7 @@ import kotlinx.serialization.json.Json * that disagree about the wire format are a bug to fix, not a compatibility matrix to maintain - * both halves ship from this repo at the same version. */-const val PROTOCOL_VERSION = 1+const val PROTOCOL_VERSION = 2 /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -162,6 +162,15 @@ data class StreamConfig( val video: Boolean, val audioSsrc: Long, val videoSsrc: Long,+ /**+ * The name of the app whose content this is, or empty for screen mirroring.+ *+ * The receiver shows it instead of the phone's name, so "Receiving from YouPipe" rather than+ * "Receiving from Pixel 9". Never self-reported by the streaming app: `:cast` resolves it from the+ * `callingPackage` the framework attaches to its picker Activity, so it is an identity the sender+ * could not have forged.+ */+ val appLabel: String = "", ) : ControlMessage /** Where to send it, and which SSRCs the feedback will come from. */
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.ktindex 178edd1479..e668e84939 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt@@ -90,6 +90,19 @@ class HandshakeTest { audioSsrc = 1_234, videoSsrc = 50_002, ),+ // Screen mirroring leaves the label empty; an SDK session names the app. Both have to+ // survive the round trip, and the empty case is the one `encodeDefaults` could eat.+ StreamConfig(+ width = 1920,+ height = 1080,+ frameRate = 60,+ bitRate = 12_000_000,+ audio = true,+ video = true,+ audioSsrc = 1_235,+ videoSsrc = 50_003,+ appLabel = "YouPipe",+ ), StreamReady(udpPort = 47_505, audioSsrc = 4_321, videoSsrc = 50_009), Bye(reason = "user stopped"), )
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex 449b0b07f4..17450d1b0e 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -32,6 +32,18 @@ <uses-feature android:name="android.hardware.wifi" android:required="false" /> + <!-- What another app needs to hand us a Surface and a PCM pipe. Signature-level, so only apps+ signed with the Modern Apps key can bind: that is the only enforcement available, because a+ Messenger service's Handler dispatch loses the Binder calling identity before the message is+ read. The sending app's *name* therefore never crosses that channel - CastPickerActivity+ resolves it from callingPackage, which the framework establishes. Label and description are+ declared because this is what the system shows in the caller's permission list. -->+ <permission+ android:name="com.vayunmathur.cast.permission.STREAM_CONTENT"+ android:label="@string/cast_stream_content_permission_label"+ android:description="@string/cast_stream_content_permission_desc"+ android:protectionLevel="signature" />+ <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules"@@ -67,6 +79,17 @@ android:launchMode="singleTop" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> + <!-- Where another app's user picks a TV, and the only place callingPackage is available.+ Launched for a result by CastPickerContract; permission-gated like the service. -->+ <activity+ android:name=".platform.CastPickerActivity"+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:excludeFromRecents="true"+ android:exported="true"+ android:launchMode="singleTop"+ android:permission="com.vayunmathur.cast.permission.STREAM_CONTENT"+ android:theme="@style/Theme.General" />+ <!-- 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@@ -74,6 +97,15 @@ android:exported="false" android:foregroundServiceType="mediaProjection|mediaPlayback" /> + <!-- The SDK's session channel. Exported because that is the point, and not a foreground+ service: CastService already owns that role, and an app-content session needs+ mediaPlayback only, which its enterForeground(withProjection = false) already claims.+ Unbinding is what ends a session, so the binding is the session's lifetime. -->+ <service+ android:name=".service.ContentCastService"+ android:exported="true"+ android:permission="com.vayunmathur.cast.permission.STREAM_CONTENT" />+ <service android:name=".platform.mirror.MirrorTileService" android:exported="true"
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 a102dd7ffb..eabf1887cb 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -2,7 +2,9 @@ package com.vayunmathur.cast.platform import android.content.Context import android.media.projection.MediaProjection+import android.os.ParcelFileDescriptor import android.util.Log+import android.view.Surface import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastDevice import com.vayunmathur.cast.domain.ClientFailure@@ -15,13 +17,14 @@ import com.vayunmathur.cast.platform.mirror.MirrorDegradation import com.vayunmathur.cast.platform.mirror.MirrorEngine import com.vayunmathur.cast.platform.mirror.MirrorGeometry import com.vayunmathur.cast.platform.mirror.MirrorPreferences+import com.vayunmathur.cast.platform.mirror.MirrorSource import com.vayunmathur.cast.platform.mirror.MirrorStopReason import com.vayunmathur.cast.protocol.PROTOCOL_VERSION-import com.vayunmathur.cast.protocol.StreamConstants import com.vayunmathur.cast.protocol.StreamingSession import com.vayunmathur.cast.service.CastService import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.sdk.cast.CastContract import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -33,9 +36,33 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext private const val TAG = "CastController" +/** What [CastController.startContentSession] managed. */+sealed interface ContentSessionResult {++ /**+ * Live. [surface] is the encoder's input surface and [audioWriteEnd] the PCM pipe, both of which+ * are the caller's to hand to the SDK client - and [audioWriteEnd] is the caller's to close once it+ * has been sent.+ *+ * The geometry is what the TV and this phone's encoder actually agreed, not what was asked for.+ */+ class Started(+ val surface: Surface,+ val audioWriteEnd: ParcelFileDescriptor?,+ val width: Int,+ val height: Int,+ val frameRate: Int,+ val receiverName: String,+ ) : ContentSessionResult++ /** [reason] is one of `CastContract`'s `REASON_` values, ready to send straight back. */+ class Failed(val reason: Int) : ContentSessionResult+}+ /** * The single owner of the live session. *@@ -87,6 +114,34 @@ object CastController { private val _isConnecting = MutableStateFlow(false) val isConnecting: StateFlow<Boolean> = _isConnecting.asStateFlow() + /**+ * Whether the session being opened should go on to ask for capture consent.+ *+ * Remembered from [connect] because a code pairing returns to the user and comes back through+ * [submitPairCode], which would otherwise have to assume - and assuming "yes" is what would put the+ * screen-capture dialog in front of an app that launched the picker to send its own content.+ */+ private var pendingMirror: Boolean = true++ /**+ * Notified when an SDK session ends for a reason the app did not ask for.+ *+ * Set by `ContentCastService` for the life of one session and cleared as it ends, so there is+ * exactly one at a time - which matches the one session this object holds. A callback rather than a+ * flow because there is nothing to observe when it is absent, and a reason has to reach the client+ * once rather than be a current value.+ */+ var onContentSessionEnded: ((Int) -> Unit)? = null++ /**+ * The name of the app that last completed `CastPickerActivity`, resolved from its+ * `callingPackage`.+ *+ * Kept here rather than passed through the IPC on purpose: a self-reported label would be a lie an+ * app could tell, and the TV displays this. Empty means screen mirroring.+ */+ var contentAppLabel: String = ""+ fun discovery(context: Context): CastDiscoveryManager = discoveryManager ?: CastDiscoveryManager(context.applicationContext) .also { discoveryManager = it }@@ -115,6 +170,7 @@ object CastController { val live = phase != ClientPhase.Idle && phase != ClientPhase.Failed if (_device.value?.id == device.id && live) return val appContext = context.applicationContext+ pendingMirror = thenMirror scope.launch { teardown() _device.value = device@@ -188,7 +244,7 @@ object CastController { val device = _device.value ?: return@launch when (val outcome = mutex.withLock { activeClient.enterCode(code) }) { is HandshakeOutcome.Paired ->- onPaired(appContext, device, activeClient, outcome.deviceKey, thenMirror = true)+ onPaired(appContext, device, activeClient, outcome.deviceKey, pendingMirror) is HandshakeOutcome.NeedsCode -> _sessionState.update { it.copy( phase = ClientPhase.AwaitingCode,@@ -257,6 +313,10 @@ object CastController { projection.stop() return@launch }+ // The screen and an app's content are mutually exclusive - there is one session, one+ // encoder and one socket - so whichever was running loses, with the SDK client told why+ // rather than left drawing into a dead surface.+ endContentSession(CastContract.REASON_PREEMPTED) stopEngine() _mirrorPhase.value = MirrorPhase.Negotiating _degradation.value = MirrorDegradation()@@ -265,11 +325,7 @@ object CastController { // The frame size is chosen from the TV's own reported limits, and it is the phone's real // aspect ratio: the receiver letterboxes, so none of the encoded frame is wasted on bars. val geometry = MirrorGeometry.forDisplay(appContext, activeClient.limits)- val frameRate = minOf(- StreamConstants.VIDEO_MAX_FRAME_RATE,- activeClient.limits?.maxFrameRate?.takeIf { it > 0 }- ?: StreamConstants.VIDEO_MAX_FRAME_RATE,- )+ val frameRate = MirrorGeometry.frameRateFor(activeClient.limits) val outcome = mutex.withLock { activeClient.configureStream( width = geometry.width,@@ -293,7 +349,7 @@ object CastController { val newEngine = MirrorEngine( context = appContext,- projection = projection,+ source = MirrorSource.Screen(projection), receiverHost = device.host, negotiation = ready.negotiation, geometry = geometry,@@ -307,17 +363,7 @@ object CastController { _sessionState.update { it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation) }- // Only now is the control exchange finished, so the watch loop can become the socket's- // single reader. A TV that goes away is then noticed at once rather than only when UDP- // starts failing.- watchJob = scope.launch {- activeClient.awaitEnd()- Log.i(TAG, "the control channel closed")- // Cleared first: teardown cancels watchJob, and this coroutine *is* watchJob.- watchJob = null- teardown()- CastService.stop(appContext)- }+ startWatch(appContext, activeClient) } else { // start() already called onStopped, which set the message and the phase; all that is // left is to make sure nothing keeps holding the screen.@@ -327,9 +373,120 @@ object CastController { } } + /**+ * Stream another app's content instead of the screen.+ *+ * The second entry point beside [startMirroring], and the only one `:sdk:cast` reaches. Requires a+ * TV already connected and paired - which is what `CastPickerActivity` is for - because there is+ * nothing an SDK caller could do about a pair code, and the picker is also what establishes the+ * [appLabel] the TV displays.+ *+ * Suspends until the stream is live or has failed, so the service can answer+ * `MSG_SESSION_READY` with real numbers rather than a promise. Screen mirroring and this remain+ * mutually exclusive; the single [engine] is what enforces it.+ */+ suspend fun startContentSession(+ context: Context,+ width: Int,+ height: Int,+ wantAudio: Boolean,+ appLabel: String,+ ): ContentSessionResult = withContext(Dispatchers.IO) {+ val appContext = context.applicationContext+ val activeClient = client+ val device = _device.value+ val phase = _sessionState.value.phase+ if (activeClient == null || device == null ||+ (phase != ClientPhase.Paired && phase != ClientPhase.Streaming)+ ) {+ Log.w(TAG, "asked for an app-content session with no paired TV")+ return@withContext ContentSessionResult.Failed(CastContract.REASON_NO_SESSION)+ }+ endContentSession(CastContract.REASON_PREEMPTED)+ stopEngine()+ _mirrorPhase.value = MirrorPhase.Negotiating+ _degradation.value = MirrorDegradation()+ _failure.value = null++ val geometry = MirrorGeometry.forContent(width, height, activeClient.limits)+ val frameRate = MirrorGeometry.frameRateFor(activeClient.limits)+ val outcome = mutex.withLock {+ activeClient.configureStream(+ width = geometry.width,+ height = geometry.height,+ frameRate = frameRate,+ bitRate = geometry.bitRate,+ audio = wantAudio,+ video = true,+ appLabel = appLabel,+ )+ }+ val ready = outcome as? HandshakeOutcome.Ready+ if (ready == null) {+ Log.w(TAG, "the TV would not agree an app-content stream: $outcome")+ _mirrorPhase.value = MirrorPhase.Failed+ _failure.value = appContext.getString(R.string.cast_mirror_negotiation_failed)+ return@withContext ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }++ val newEngine = MirrorEngine(+ context = appContext,+ source = MirrorSource.Content(appLabel = appLabel, wantAudio = wantAudio),+ receiverHost = device.host,+ negotiation = ready.negotiation,+ geometry = geometry,+ frameRate = frameRate,+ onDegraded = { _degradation.value = it },+ onStopped = { reason -> onEngineStopped(appContext, reason) },+ ).apply { hexDump = verboseStreamLogging }+ engine = newEngine+ // No surface means there is nowhere for the app to draw, which for an SDK session is the whole+ // point - unlike mirroring, it cannot usefully degrade to audio only.+ val surface = if (newEngine.start()) newEngine.contentSurface else null+ if (surface == null) {+ newEngine.stop()+ engine = null+ _mirrorPhase.value = MirrorPhase.Failed+ return@withContext ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }+ _mirrorPhase.value = MirrorPhase.Mirroring+ _sessionState.update {+ it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)+ }+ startWatch(appContext, activeClient)+ ContentSessionResult.Started(+ surface = surface,+ audioWriteEnd = newEngine.audioWriteEnd,+ width = geometry.width,+ height = geometry.height,+ frameRate = frameRate,+ receiverName = activeClient.receiverName ?: device.friendlyName,+ )+ }++ /**+ * Become the control socket's single reader, now the exchange is finished.+ *+ * **Not started any earlier.** [MirrorClient.awaitEnd] reads the socket, and `configureStream` has+ * a request/response to do on it - a second reader would consume the `STREAM_READY` that+ * negotiation is waiting for. Until this starts, a dead TV surfaces as a failed `configureStream`,+ * which is just as prompt.+ */+ private fun startWatch(appContext: Context, activeClient: MirrorClient) {+ watchJob = scope.launch {+ activeClient.awaitEnd()+ Log.i(TAG, "the control channel closed")+ // Cleared first: teardown cancels watchJob, and this coroutine *is* watchJob.+ watchJob = null+ teardown()+ CastService.stop(appContext)+ }+ }+ fun stopMirroring(context: Context) { val appContext = context.applicationContext scope.launch {+ endContentSession(CastContract.REASON_CLIENT_CLOSED) stopEngine() _mirrorPhase.value = MirrorPhase.Idle _sessionState.update {@@ -367,6 +524,7 @@ object CastController { }, ) _mirrorPhase.value = MirrorPhase.Failed+ endContentSession(CastContract.REASON_FAILED) CastService.stopMirroring(context) } @@ -375,6 +533,18 @@ object CastController { engine = null } + /**+ * Tell an SDK client its session is over, once.+ *+ * Cleared as it fires, so the client hears exactly one reason: a teardown runs through several of+ * these paths and a client told twice would react to the second after it had already cleaned up.+ */+ private fun endContentSession(reason: Int) {+ val notify = onContentSessionEnded ?: return+ onContentSessionEnded = null+ notify(reason)+ }+ /** * Drop everything. *@@ -388,6 +558,7 @@ object CastController { */ private suspend fun teardown(keepFailure: Boolean = false) { watchJob?.cancel()+ endContentSession(CastContract.REASON_RECEIVER_GONE) stopEngine() socket?.close() mutex.withLock {
cast/src/main/java/com/vayunmathur/cast/platform/CastPickerActivity.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastPickerActivity.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastPickerActivity.ktnew file mode 100644index 0000000000..22c7cd9f80--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastPickerActivity.kt@@ -0,0 +1,114 @@+package com.vayunmathur.cast.platform++import android.content.Context+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.ui.CastPickerContent+import com.vayunmathur.library.ui.DynamicTheme++/**+ * The TV picker another app launches, through `CastPickerContract`.+ *+ * Exported and gated by the same signature permission as `ContentCastService`, and it exists for two+ * reasons that both come back to trust and to pairing:+ *+ * - **Pairing happens once per TV for the whole device.** A self-contained SDK would make every app+ * pair separately, six digits per app per TV, and would need `ACCESS_LOCAL_NETWORK` in every+ * consumer's manifest. This screen is where that one pairing happens.+ * - **`callingPackage` is only available to an Activity started for a result.** It is the identity the+ * framework establishes rather than one the caller asserts, and resolving it through+ * `PackageManager` is what lets the TV show "Receiving from YouPipe" without taking the sending+ * app's word for it. A `Messenger` service has no equivalent, because `Message` dispatch goes+ * through a `Handler` and the Binder identity is gone by the time the handler runs.+ *+ * Finishes `RESULT_OK` the moment a TV is connected and paired, which is the caller's cue to open a+ * session - and `RESULT_CANCELED` for everything else, including simply being backed out of.+ */+class CastPickerActivity : ComponentActivity() {++ private val viewModel: CastViewModel by viewModels { CastViewModelFactory(application) }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ // Backing out has to mean "cancelled" rather than an unset result, and the only way to+ // guarantee that is to set it before anything else can happen.+ setResult(RESULT_CANCELED)+ val appName = resolveCallerLabel()+ CastController.contentAppLabel = appName+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ val state by viewModel.uiState.collectAsState()+ // The mDNS browse is tied to this screen being on screen: nothing else wants it, and+ // leaving it running afterwards is a radio kept awake for nothing.+ DisposableEffect(viewModel) {+ viewModel.startScan()+ onDispose { viewModel.stopScan() }+ }+ LaunchedEffect(state.connection) {+ if (state.connection == CastConnection.Connected) {+ setResult(RESULT_OK)+ finish()+ }+ }+ CastPickerContent(+ state = state,+ actions = PickerActions(viewModel, applicationContext),+ appName = appName,+ onCancel = { finish() },+ )+ }+ }+ }++ /**+ * The calling app's display name, or empty if it cannot be established.+ *+ * Empty is the same value screen mirroring uses, so the TV falls back to the phone's name - which+ * is the right answer for an unidentifiable caller, rather than inventing a label for it.+ */+ private fun resolveCallerLabel(): String {+ val caller = callingPackage ?: return ""+ return try {+ val manager = packageManager+ manager.getApplicationLabel(manager.getApplicationInfo(caller, 0)).toString()+ } catch (_: Exception) {+ ""+ }+ }+}++/**+ * The picker's half of [CastActions].+ *+ * The one difference from [CastViewModel]'s own behaviour, and the reason this exists: `connect` must+ * pass `thenMirror = false`. The ViewModel's version goes straight on to the screen-capture consent+ * dialog after pairing, which for an app that has its own content to send would be asking permission+ * to do the opposite of what it wanted.+ */+private class PickerActions(+ private val viewModel: CastViewModel,+ private val context: Context,+) : CastActions {++ override fun startScan() = viewModel.startScan()++ override fun stopScan() = viewModel.stopScan()++ override fun connect(device: CastDevice) =+ CastController.connect(context, device, thenMirror = false)++ override fun submitPairCode(code: String) = viewModel.submitPairCode(code)++ override fun disconnect() = viewModel.disconnect()++ override fun openLocalNetworkSettings() = viewModel.openLocalNetworkSettings()+}
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex 4d4ceef8b8..f37c88b827 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -202,6 +202,9 @@ class MirrorClient( * * [width] and [height] are the phone's own choice within the TV's reported limits: it sends its * native aspect ratio and the TV letterboxes, which is the whole reason for owning the receiver.+ *+ * [appLabel] is empty for screen mirroring and the streaming app's name for an SDK session; the TV+ * shows it instead of the phone's name. */ fun configureStream( width: Int,@@ -210,6 +213,7 @@ class MirrorClient( bitRate: Int, audio: Boolean, video: Boolean,+ appLabel: String = "", ): HandshakeOutcome { val sessionKeys = keys ?: return protocolFailure() val random = SecureRandom()@@ -222,6 +226,7 @@ class MirrorClient( video = video, audioSsrc = random.ssrc(StreamConstants.AUDIO_SSRC_MIN, StreamConstants.AUDIO_SSRC_MAX), videoSsrc = random.ssrc(StreamConstants.VIDEO_SSRC_MIN, StreamConstants.VIDEO_SSRC_MAX),+ appLabel = appLabel, ) socket.send(config) val ready = socket.receive()?.message as? StreamReady
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.ktindex db1fab1d61..85b6e789d2 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/AudioEncoder.kt@@ -5,17 +5,16 @@ 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.+ * Captures what the phone is playing and encodes it as Opus.+ *+ * The Opus half lives in [OpusEncoder], shared with [PcmAudioEncoder]; what is left here is the+ * `AudioPlaybackCapture` half, which is the part that only screen mirroring can use. * * **Two honest limitations, neither of which this class can fix:** *@@ -25,24 +24,20 @@ private const val TIMEOUT_US = 10_000L * 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.+ * Nothing here can detect the first, so the copy has to warn about it in general terms. An SDK+ * session avoids the first problem entirely, because the app hands over its own PCM. * * `RECORD_AUDIO` is required even though no microphone is involved - the permission gates * `AudioRecord` itself, not the source. */-class AudioEncoder(private val projection: MediaProjection) {+class AudioEncoder(private val projection: MediaProjection) : AudioStream { private var record: AudioRecord? = null- private var codec: MediaCodec? = null- private val bufferInfo = MediaCodec.BufferInfo()+ private val opus = OpusEncoder() @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- }+ override fun start(): Boolean {+ if (!opus.start()) return false return try { val config = AudioPlaybackCaptureConfiguration.Builder(projection) .addMatchingUsage(AudioAttributes.USAGE_MEDIA)@@ -51,14 +46,14 @@ class AudioEncoder(private val projection: MediaProjection) { .build() val format = AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_16BIT)- .setSampleRate(SAMPLE_RATE)+ .setSampleRate(OpusEncoder.SAMPLE_RATE) .setChannelMask(AudioFormat.CHANNEL_IN_STEREO) .build() val minBuffer = AudioRecord.getMinBufferSize(- SAMPLE_RATE,+ OpusEncoder.SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT,- ).coerceAtLeast(FRAME_BYTES * 4)+ ).coerceAtLeast(OpusEncoder.FRAME_BYTES * 4) val created = AudioRecord.Builder() .setAudioFormat(format) .setBufferSizeInBytes(minBuffer)@@ -67,21 +62,11 @@ class AudioEncoder(private val projection: MediaProjection) { if (created.state != AudioRecord.STATE_INITIALIZED) { Log.w(TAG, "AudioRecord did not initialise") created.release()+ 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)@@ -90,78 +75,23 @@ class AudioEncoder(private val projection: MediaProjection) { } } - /**- * 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)+ /** Read one 20 ms buffer of PCM, feed it in, and return whatever came out. */+ override fun pump(): List<EncodedChunk> {+ val active = record ?: return emptyList()+ val pcm = ByteArray(OpusEncoder.FRAME_BYTES) val read = try {- activeRecord.read(pcm, 0, pcm.size)+ active.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)- }+ return opus.encode(pcm, read.coerceAtLeast(0)) } - fun release() {+ override 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+ opus.release() } }
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.ktindex 8834972027..39546d17a4 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -1,8 +1,9 @@ package com.vayunmathur.cast.platform.mirror import android.content.Context-import android.media.projection.MediaProjection+import android.os.ParcelFileDescriptor import android.util.Log+import android.view.Surface import com.vayunmathur.cast.network.CastUdpTransport import com.vayunmathur.cast.protocol.NegotiatedStream import com.vayunmathur.cast.protocol.Negotiation@@ -48,6 +49,12 @@ enum class MirrorStopReason { Udp, NoEncoders, ReceiverGone } * 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. *+ * [source] is the only thing that differs between mirroring the screen and streaming another app's+ * content: with [MirrorSource.Screen] a `VirtualDisplay` writes into the encoder's input surface and+ * `AudioPlaybackCapture` supplies the PCM; with [MirrorSource.Content] the input surface is **handed+ * out** through [contentSurface] and the PCM arrives through [audioWriteEnd]'s pipe. Everything after+ * that point - the same [VideoEncoder], the same [StreamSender], the same RTCP loop - is shared.+ * * [receiverHost] is passed in because `STREAM_READY` carries only a port; the address is the one the * control channel is already talking to. *@@ -57,7 +64,7 @@ enum class MirrorStopReason { Udp, NoEncoders, ReceiverGone } */ class MirrorEngine( context: Context,- private val projection: MediaProjection,+ private val source: MirrorSource, private val receiverHost: String, private val negotiation: Negotiation, private val geometry: CaptureGeometry,@@ -84,7 +91,27 @@ class MirrorEngine( private var transport: CastUdpTransport? = null private var capture: ScreenCapture? = null private var videoEncoder: VideoEncoder? = null- private var audioEncoder: AudioEncoder? = null+ private var audioEncoder: AudioStream? = null++ /**+ * The encoder's input surface, for a [MirrorSource.Content] session to draw into. Null for+ * screen mirroring, where a `VirtualDisplay` already owns it.+ *+ * Valid only between a successful [start] and [stop]: [VideoEncoder.release] releases it, which is+ * correct - the client holds its own Binder-duplicated copy and must not release that one.+ */+ var contentSurface: Surface? = null+ private set++ /**+ * The write end of the PCM pipe, for a [MirrorSource.Content] session that asked for audio.+ *+ * **The caller must close it once it has been sent.** A `ParcelFileDescriptor` is duplicated by+ * the Binder transaction, so keeping this copy open would hold the pipe open from our side and the+ * read end would never see the client stop writing.+ */+ var audioWriteEnd: ParcelFileDescriptor? = null+ private set /** * Hex-dump every packet, and log throughput once a second.@@ -125,7 +152,6 @@ class MirrorEngine( } private fun startVideo(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {- val screen = ScreenCapture(projection) val encoder = VideoEncoder( width = geometry.width, height = geometry.height,@@ -134,18 +160,30 @@ class MirrorEngine( ) if (!encoder.start()) return false val surface = encoder.inputSurface- if (surface == null || !screen.start(surface, geometry)) {+ if (surface == null) { encoder.release()- screen.release() return false }+ // The one branch: mirror the screen into the surface, or hand it to whoever asked for it.+ when (source) {+ is MirrorSource.Screen -> {+ val screen = ScreenCapture(source.projection)+ if (!screen.start(surface, geometry)) {+ encoder.release()+ screen.release()+ return false+ }+ capture = screen+ }+ is MirrorSource.Content -> contentSurface = surface+ } Log.i( TAG,- "mirroring at ${geometry.width}x${geometry.height} " +- "@ ${geometry.bitRate / 1_000_000.0} Mbit/s",+ "streaming ${geometry.width}x${geometry.height} " ++ "@ ${geometry.bitRate / 1_000_000.0} Mbit/s" ++ if (source.appLabel.isEmpty()) "" else " from ${source.appLabel}", ) videoEncoder = encoder- capture = screen val sender = StreamSender(stream, udp, StreamingSession()) senders[StreamKind.Video] = sender videoJob = scope.launch {@@ -162,8 +200,26 @@ class MirrorEngine( } private fun startAudio(stream: NegotiatedStream, udp: CastUdpTransport): Boolean {- val encoder = AudioEncoder(projection)- if (!encoder.start()) return false+ val encoder = when (source) {+ is MirrorSource.Screen -> AudioEncoder(source.projection)+ is MirrorSource.Content -> {+ if (!source.wantAudio) return false+ val pipe = try {+ ParcelFileDescriptor.createPipe()+ } catch (e: Exception) {+ Log.w(TAG, "could not create the PCM pipe", e)+ return false+ }+ audioWriteEnd = pipe[1]+ PcmAudioEncoder(pipe[0])+ }+ }+ if (!encoder.start()) {+ encoder.release()+ runCatching { audioWriteEnd?.close() }+ audioWriteEnd = null+ return false+ } audioEncoder = encoder val sender = StreamSender(stream, udp, StreamingSession()) senders[StreamKind.Audio] = sender@@ -307,10 +363,14 @@ class MirrorEngine( videoEncoder?.release() audioEncoder?.release() transport?.close()+ // Only our own copy; the client's Binder-duplicated one is closed when the client goes away.+ runCatching { audioWriteEnd?.close() } capture = null videoEncoder = null audioEncoder = null transport = null+ contentSurface = null+ audioWriteEnd = null senders.clear() scope.cancel() }
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.ktindex 02c26de259..a5a1a6c8e4 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt@@ -50,6 +50,10 @@ object MirrorGeometry { /** openscreen's `kDefaultVideoMinBitRate`, as a floor. */ private const val MIN_BITRATE = 300_000 + /** What an app gets if it asks for nonsense; 720p is a size every decoder takes. */+ private const val DEFAULT_CONTENT_WIDTH = 1280+ private const val DEFAULT_CONTENT_HEIGHT = 720+ /** * The frame to send to a TV that reported [limits]. *@@ -70,14 +74,8 @@ object MirrorGeometry { // outright rather than rounding for you. val (width, height) = EncoderSupport.clampToEncoder(fittedWidth, fittedHeight) - val frameRate = minOf(- StreamConstants.VIDEO_MAX_FRAME_RATE,- limits?.maxFrameRate?.takeIf { it > 0 } ?: StreamConstants.VIDEO_MAX_FRAME_RATE,- )- var bitRate = (width.toLong() * height * frameRate * BITS_PER_PIXEL)- .toLong()- .coerceAtLeast(MIN_BITRATE.toLong())- limits?.maxBitRate?.takeIf { it > 0 }?.let { bitRate = minOf(bitRate, it.toLong()) }+ val frameRate = frameRateFor(limits)+ val bitRate = bitRateFor(width, height, frameRate, limits) Log.i( TAG,@@ -90,10 +88,57 @@ object MirrorGeometry { // The phone's own density, so text scales the way it does on the screen rather than being // rendered for a notional tablet. densityDpi = metrics.densityDpi.takeIf { it > 0 } ?: DisplayMetrics.DENSITY_DEFAULT,- bitRate = bitRate.toInt(),+ bitRate = bitRate, ) } + /**+ * The frame to send for an app that asked for [requestedWidth] x [requestedHeight].+ *+ * Same clamping as [forDisplay], different starting point: an SDK session's shape is the content's+ * own - a 16:9 video, not the phone's screen - and the app is told what it actually got, because an+ * app that laid out for the size it asked for would be stretched.+ *+ * No density: nothing renders a `VirtualDisplay` here, the client draws into the surface directly.+ */+ fun forContent(+ requestedWidth: Int,+ requestedHeight: Int,+ limits: DecoderLimits? = null,+ ): CaptureGeometry {+ val safeWidth = requestedWidth.takeIf { it > 0 } ?: DEFAULT_CONTENT_WIDTH+ val safeHeight = requestedHeight.takeIf { it > 0 } ?: DEFAULT_CONTENT_HEIGHT+ val (fittedWidth, fittedHeight) = fitWithin(safeWidth, safeHeight, limits)+ val (width, height) = EncoderSupport.clampToEncoder(fittedWidth, fittedHeight)+ val frameRate = frameRateFor(limits)+ val bitRate = bitRateFor(width, height, frameRate, limits)+ Log.i(+ TAG,+ "app content: asked for ${safeWidth}x$safeHeight, sending ${width}x$height " ++ "@ ${frameRate}fps at ${bitRate / 1_000_000.0} Mbit/s",+ )+ return CaptureGeometry(+ width = width,+ height = height,+ densityDpi = DisplayMetrics.DENSITY_DEFAULT,+ bitRate = bitRate,+ )+ }++ /** The TV's cap, or ours, whichever is lower. */+ fun frameRateFor(limits: DecoderLimits?): Int = minOf(+ StreamConstants.VIDEO_MAX_FRAME_RATE,+ limits?.maxFrameRate?.takeIf { it > 0 } ?: StreamConstants.VIDEO_MAX_FRAME_RATE,+ )++ private fun bitRateFor(width: Int, height: Int, frameRate: Int, limits: DecoderLimits?): Int {+ var bitRate = (width.toLong() * height * frameRate * BITS_PER_PIXEL)+ .toLong()+ .coerceAtLeast(MIN_BITRATE.toLong())+ limits?.maxBitRate?.takeIf { it > 0 }?.let { bitRate = minOf(bitRate, it.toLong()) }+ return bitRate.toInt()+ }+ /** * The largest frame with the same aspect ratio as [width] x [height] that fits [limits]. *
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.ktnew file mode 100644index 0000000000..a6bb073b4b--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt@@ -0,0 +1,38 @@+package com.vayunmathur.cast.platform.mirror++import android.media.projection.MediaProjection++/**+ * What [MirrorEngine] is encoding.+ *+ * The pipeline underneath - H.264 into an encoder input surface, RTP over UDP, RTCP feedback - never+ * had anything to do with screen capture; `MediaProjection` was simply the only way anything got into+ * it. Naming the two cases makes that explicit, and is the whole of what `:sdk:cast` needed from+ * `:cast`.+ */+sealed interface MirrorSource {++ /**+ * The name the TV shows as the source. Empty means the phone's own name, which is what screen+ * mirroring wants.+ */+ val appLabel: String++ /** The phone's screen, captured into the encoder's input surface by a `VirtualDisplay`. */+ class Screen(val projection: MediaProjection) : MirrorSource {+ override val appLabel: String get() = ""+ }++ /**+ * Another app's content: it is handed the encoder's input surface and draws into it itself, and+ * writes PCM into a pipe if [wantAudio].+ *+ * [appLabel] is resolved by `CastPickerActivity` from the framework's `callingPackage`, never+ * self-reported by the app - which is what makes it something the TV can display without it+ * being a claim the sender could have forged.+ */+ class Content(+ override val appLabel: String,+ val wantAudio: Boolean,+ ) : MirrorSource+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.ktnew file mode 100644index 0000000000..7177c4018f--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/OpusEncoder.kt@@ -0,0 +1,138 @@+package com.vayunmathur.cast.platform.mirror++import android.media.MediaCodec+import android.media.MediaFormat+import android.util.Log++private const val TAG = "OpusEncoder"++private const val TIMEOUT_US = 10_000L++/**+ * PCM in, Opus access units out.+ *+ * Extracted from [AudioEncoder] rather than copied into [PcmAudioEncoder], because the two differ+ * only in where the PCM comes from - playback capture or a pipe from another app - and everything+ * after that is identical: the same `MediaFormat`, the same 20 ms framing, and the same+ * sample-counted timestamps.+ *+ * `audio/opus` encoders are not universally present, which is what [start] returning false means.+ */+class OpusEncoder {++ private var codec: MediaCodec? = null+ private val bufferInfo = MediaCodec.BufferInfo()++ /**+ * 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.+ */+ private var samplesWritten = 0L++ 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 format = MediaFormat.createAudioFormat(+ EncoderSupport.AUDIO_MIME,+ SAMPLE_RATE,+ CHANNELS,+ ).apply {+ setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)+ }+ val created = MediaCodec.createByCodecName(name)+ created.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ created.start()+ codec = created+ true+ } catch (e: Exception) {+ Log.w(TAG, "could not start the Opus encoder", e)+ release()+ false+ }+ }++ /**+ * Feed [length] bytes from [pcm] and return whatever the codec has ready.+ *+ * [length] may be zero, which is how a caller with nothing to send still drains the codec.+ */+ fun encode(pcm: ByteArray, length: Int): List<EncodedChunk> {+ val active = codec ?: return emptyList()+ if (length > 0) {+ val index = try {+ active.dequeueInputBuffer(TIMEOUT_US)+ } catch (e: IllegalStateException) {+ Log.w(TAG, "audio encoder went away", e)+ return emptyList()+ }+ if (index >= 0) {+ val input = active.getInputBuffer(index)+ input?.clear()+ input?.put(pcm, 0, length)+ active.queueInputBuffer(index, 0, length, presentationTimeUs, 0)+ samplesWritten += length / (2 * CHANNELS)+ }+ }+ val out = mutableListOf<EncodedChunk>()+ while (true) {+ val index = try {+ active.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 = active.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)+ }+ active.releaseOutputBuffer(index, false)+ }+ }++ fun release() {+ runCatching { codec?.stop() }+ runCatching { codec?.release() }+ codec = null+ }++ private val presentationTimeUs: Long+ get() = samplesWritten * 1_000_000L / SAMPLE_RATE++ companion object {+ /** Matches the OFFER's `1/48000` timebase, and `CastContract.AUDIO_SAMPLE_RATE`. */+ const val SAMPLE_RATE = 48_000+ const val CHANNELS = 2+ const val BIT_RATE = 128_000++ /** 20 ms of stereo 16-bit PCM, which is the frame size Opus wants. */+ const val FRAME_BYTES = SAMPLE_RATE / 50 * 2 * CHANNELS+ }+}++/**+ * Where the Opus stream's PCM comes from.+ *+ * Two implementations, and [MirrorEngine]'s audio loop cannot tell them apart: [AudioEncoder]+ * captures what the phone is playing, [PcmAudioEncoder] reads what another app writes into a pipe.+ */+interface AudioStream {+ /** False when this source cannot be started, which degrades the session to video only. */+ fun start(): Boolean++ /** Move whatever PCM is available through the encoder. Empty means nothing yet. */+ fun pump(): List<EncodedChunk>++ fun release()+}
cast/src/main/java/com/vayunmathur/cast/platform/mirror/PcmAudioEncoder.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/PcmAudioEncoder.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/PcmAudioEncoder.ktnew file mode 100644index 0000000000..70d204823f--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/PcmAudioEncoder.kt@@ -0,0 +1,75 @@+package com.vayunmathur.cast.platform.mirror++import android.os.ParcelFileDescriptor+import android.util.Log+import java.io.FileInputStream++private const val TAG = "PcmAudioEncoder"++/**+ * Reads PCM another app wrote into a pipe and encodes it as Opus.+ *+ * The SDK's half of [AudioStream]. A pipe rather than IPC messages because 48 kHz stereo 16-bit is+ * ~192 KB/s, which as `Messenger` messages would be fifty Binder transactions a second competing+ * with everything else on the binder thread.+ *+ * **Never blocks.** `read` on a pipe with nothing in it parks the calling thread, and+ * [MirrorEngine.stop] cancels *and joins* its loops before releasing anything they touch - a thread+ * parked in a blocking read would not answer the cancellation and the join would hang. So this reads+ * only what `available()` says is there and returns empty otherwise, leaving the loop to poll.+ *+ * EOF is deliberately not treated as the end of the session: the binding is what ends a session, and+ * a client that has closed its pipe but not unbound is one that has stopped sending audio rather than+ * stopped casting. Whatever partial frame is left over is held until enough arrives to complete it,+ * because Opus wants whole 20 ms frames and half of one encodes as a click.+ */+class PcmAudioEncoder(private val readEnd: ParcelFileDescriptor) : AudioStream {++ private var input: FileInputStream? = null+ private val opus = OpusEncoder()++ /** One 20 ms frame under construction; the app's write sizes are its own business. */+ private val frame = ByteArray(OpusEncoder.FRAME_BYTES)+ private var filled = 0++ override fun start(): Boolean {+ if (!opus.start()) return false+ return try {+ input = FileInputStream(readEnd.fileDescriptor)+ true+ } catch (e: Exception) {+ Log.w(TAG, "could not open the PCM pipe", e)+ release()+ false+ }+ }++ override fun pump(): List<EncodedChunk> {+ val stream = input ?: return emptyList()+ val available = try {+ stream.available()+ } catch (e: Exception) {+ Log.w(TAG, "the PCM pipe went away", e)+ return emptyList()+ }+ if (available <= 0) return emptyList()+ val read = try {+ stream.read(frame, filled, minOf(frame.size - filled, available))+ } catch (e: Exception) {+ Log.w(TAG, "PCM read failed", e)+ return emptyList()+ }+ if (read <= 0) return emptyList()+ filled += read+ if (filled < frame.size) return emptyList()+ filled = 0+ return opus.encode(frame, frame.size)+ }++ override fun release() {+ runCatching { input?.close() }+ runCatching { readEnd.close() }+ input = null+ opus.release()+ }+}
cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.ktnew file mode 100644index 0000000000..00ebfe4039--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -0,0 +1,180 @@+package com.vayunmathur.cast.service++import android.app.Service+import android.content.Intent+import android.os.Bundle+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.os.Message+import android.os.Messenger+import android.os.ParcelFileDescriptor+import android.os.RemoteException+import android.util.Log+import com.vayunmathur.cast.platform.CastController+import com.vayunmathur.cast.platform.ContentSessionResult+import com.vayunmathur.sdk.cast.CastContract+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++private const val TAG = "ContentCastService"++/**+ * Streams another app's content, on behalf of `:sdk:cast`.+ *+ * The exported half of the broker. `CastService` stays `exported="false"` and stays the+ * foreground-service owner: an SDK session needs `mediaPlayback` only, which its+ * `enterForeground(withProjection = false)` already provides, and duplicating that here would mean two+ * services fighting over one notification.+ *+ * **Binding is the session's lifetime.** [onUnbind] is the death notification, for free: if the client+ * is killed mid-cast the binding drops and the session is torn down, where the repo's+ * `startForegroundService` + `ResultReceiver` idiom would have needed a `linkToDeath` token bolted on+ * to notice. A cast session is long-lived, so it wants a long-lived binding.+ *+ * Gated by `CastContract.PERMISSION` in the manifest, which is signature-level. That is the only+ * enforcement, and it means any first-party app can stream - so nothing the client says about itself is+ * trusted. In particular the app's *name* never crosses this channel: `CastPickerActivity` resolves it+ * from the framework's `callingPackage`, because `Message` dispatch goes through a [Handler] and the+ * Binder calling identity is gone by the time the handler runs.+ */+class ContentCastService : Service() {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++ /** Where [CastContract.MSG_SESSION_READY] and `MSG_SESSION_ENDED` go. */+ private var client: Messenger? = null++ /** True between a successful open and the session ending, so nothing is reported twice. */+ private var sessionOpen = false++ private val incoming = Messenger(+ Handler(Looper.getMainLooper()) { msg ->+ when (msg.what) {+ CastContract.MSG_OPEN_SESSION -> {+ openSession(msg.replyTo, msg.data)+ true+ }+ CastContract.MSG_CLOSE_SESSION -> {+ closeSession(CastContract.REASON_CLIENT_CLOSED, notify = true)+ true+ }+ else -> false+ }+ },+ )++ override fun onBind(intent: Intent?): IBinder = incoming.binder++ override fun onUnbind(intent: Intent?): Boolean {+ // The client asked, or died. Either way nothing is drawing into the surface any more, so the+ // TV should go back to idle rather than hold the last frame. Not notified: there is nobody+ // left to tell.+ closeSession(CastContract.REASON_CLIENT_CLOSED, notify = false)+ // false: no onRebind, so a client that binds again gets a fresh onBind and a fresh session.+ return false+ }++ override fun onDestroy() {+ closeSession(CastContract.REASON_CLIENT_CLOSED, notify = false)+ scope.cancel()+ super.onDestroy()+ }++ private fun openSession(replyTo: Messenger?, data: Bundle?) {+ if (replyTo == null) {+ Log.w(TAG, "MSG_OPEN_SESSION with no replyTo; there is nowhere to send the surface")+ return+ }+ client = replyTo+ // A second open on the same binding replaces the first, which is also what happens when+ // another app takes the single session.+ if (sessionOpen) closeSession(CastContract.REASON_PREEMPTED, notify = false)++ val width = data?.getInt(CastContract.KEY_WIDTH) ?: 0+ val height = data?.getInt(CastContract.KEY_HEIGHT) ?: 0+ val wantAudio = data?.getBoolean(CastContract.KEY_WANT_AUDIO) ?: false++ scope.launch {+ val result = CastController.startContentSession(+ context = this@ContentCastService,+ width = width,+ height = height,+ wantAudio = wantAudio,+ // Established by the picker from callingPackage, not by anything the client sent.+ appLabel = CastController.contentAppLabel,+ )+ when (result) {+ is ContentSessionResult.Failed -> send(sessionEnded(result.reason))+ is ContentSessionResult.Started -> {+ sessionOpen = true+ // Registered only now: startContentSession itself preempts whatever was running,+ // and a callback set any earlier would be the one it cancelled.+ CastController.onContentSessionEnded = { reason ->+ scope.launch { closeSession(reason, notify = true) }+ }+ sendReady(result)+ }+ }+ }+ }++ /**+ * Answer with the surface, the pipe and the numbers the TV actually agreed.+ *+ * The write end is closed **after** the send: a `ParcelFileDescriptor` is duplicated by the Binder+ * transaction, so holding our copy open would keep the pipe alive from this side and the reader+ * would never notice the client stop writing.+ */+ private fun sendReady(started: ContentSessionResult.Started) {+ val message = Message.obtain(null, CastContract.MSG_SESSION_READY).apply {+ data = Bundle().apply {+ putParcelable(CastContract.KEY_SURFACE, started.surface)+ started.audioWriteEnd?.let { putParcelable(CastContract.KEY_AUDIO_FD, it) }+ putInt(CastContract.KEY_GRANTED_WIDTH, started.width)+ putInt(CastContract.KEY_GRANTED_HEIGHT, started.height)+ putInt(CastContract.KEY_GRANTED_FRAME_RATE, started.frameRate)+ putString(CastContract.KEY_RECEIVER_NAME, started.receiverName)+ }+ }+ val sent = send(message)+ closeWriteEnd(started.audioWriteEnd)+ if (!sent) {+ // The client went away between opening and being answered; nothing is going to draw.+ closeSession(CastContract.REASON_CLIENT_CLOSED, notify = false)+ }+ }++ private fun closeSession(reason: Int, notify: Boolean) {+ if (!sessionOpen) return+ sessionOpen = false+ CastController.onContentSessionEnded = null+ // Back to a paired-but-idle TV rather than a dropped session: the pairing is per device and+ // worth keeping, and the user may well cast again straight away.+ CastController.stopMirroring(this)+ if (notify) send(sessionEnded(reason))+ }++ private fun sessionEnded(reason: Int): Message =+ Message.obtain(null, CastContract.MSG_SESSION_ENDED).apply {+ data = Bundle().apply { putInt(CastContract.KEY_END_REASON, reason) }+ }++ /** Returns false if the client is gone. */+ private fun send(message: Message): Boolean {+ val remote = client ?: return false+ return try {+ remote.send(message)+ true+ } catch (_: RemoteException) {+ false+ }+ }++ private fun closeWriteEnd(pfd: ParcelFileDescriptor?) {+ runCatching { pfd?.close() }+ }+}
cast/src/main/java/com/vayunmathur/cast/ui/CastPickerContent.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastPickerContent.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastPickerContent.ktnew file mode 100644index 0000000000..af1d6e8a30--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastPickerContent.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.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+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.CastConnection+import com.vayunmathur.cast.platform.CastUiState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * Pick a TV on behalf of another app.+ *+ * The same device list and the same pair-code card as [CastContent], with everything about mirroring+ * removed: the caller has its own content to send, and offering to mirror the screen here would be+ * offering to do the opposite of what it asked for.+ *+ * [appName] is the framework's answer for who is asking - resolved from `callingPackage`, not+ * self-reported - so naming it in the title is a claim the calling app could not have made up.+ */+@Composable+fun CastPickerContent(+ state: CastUiState,+ actions: CastActions,+ appName: String,+ onCancel: () -> Unit,+ modifier: Modifier = Modifier,+) {+ AppScaffold(+ title = if (appName.isBlank()) {+ stringResource(R.string.cast_picker_title_generic)+ } else {+ stringResource(R.string.cast_picker_title, appName)+ },+ modifier = modifier,+ actions = {+ if (state.isScanning) {+ CircularProgressIndicator(+ modifier = Modifier.padding(horizontal = 16.dp).size(24.dp),+ )+ } else {+ IconButton(onClick = actions::startScan) { IconRefresh() }+ }+ },+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ LazyColumn(+ modifier = Modifier.fillMaxSize().padding(padding),+ contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ // Nothing else on the screen can be acted on until the code has been typed, so anything+ // above it would only be in the way.+ if (state.connection == CastConnection.AwaitingCode) {+ item { CastPairCodeCard(state, actions) }+ }+ item { PickerHeader(state) }+ items(state.devices, key = { it.id }) { device ->+ CastDeviceRow(+ device = device,+ isConnected = state.connectedDevice?.id == device.id,+ onClick = { actions.connect(device) },+ )+ }+ item {+ TextButton(onClick = onCancel) {+ Text(stringResource(R.string.cast_picker_cancel))+ }+ }+ }+ }+}++/**+ * Why the list is empty, or what is happening to the TV that was tapped.+ *+ * Deliberately not [CastContent]'s `SectionHeader`: this one has no disconnect button, because a+ * connected TV finishes the picker rather than becoming a state to manage.+ */+@Composable+private fun PickerHeader(state: CastUiState) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ HorizontalDivider()+ val name = state.connectedDevice?.friendlyName ?: ""+ val text = when {+ state.connection == CastConnection.Connecting ->+ stringResource(R.string.cast_connecting_to, name)+ state.connection == CastConnection.AwaitingCode ->+ stringResource(R.string.cast_pairing_with, name)+ state.connection == CastConnection.Failed ->+ state.failure ?: stringResource(R.string.cast_protocol_error)+ state.localNetworkBlocked -> stringResource(R.string.cast_local_network_blocked)+ state.devices.isNotEmpty() -> stringResource(R.string.cast_devices_heading)+ state.isScanning -> stringResource(R.string.cast_searching)+ else -> stringResource(R.string.cast_no_devices)+ }+ Text(+ text,+ style = MaterialTheme.typography.titleSmall,+ color = if (state.connection == CastConnection.Failed || state.localNetworkBlocked) {+ MaterialTheme.colorScheme.error+ } else {+ MaterialTheme.colorScheme.onSurface+ },+ )+ if (state.devices.isEmpty() && !state.isScanning) {+ Text(+ stringResource(R.string.cast_no_devices_hint),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}
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 07f9bb484b..1fdf08cea0 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -68,4 +68,13 @@ <string name="cast_notification_text_mirroring">Mirroring your screen</string> <string name="cast_notification_text_failed">Could not start mirroring</string> <string name="cast_notification_action_stop">Stop</string>++ <!-- The picker another app launches, and the permission it needs to. The permission's label and+ description are what the system shows in the app's permission list, so they have to read as+ something a user can decide about rather than as an API name. -->+ <string name="cast_stream_content_permission_label">Stream content to a television</string>+ <string name="cast_stream_content_permission_desc">Allows an app to send its own video and audio to a television you have paired with MA Cast, without pairing separately or seeing your network.</string>+ <string name="cast_picker_title">Cast %1$s to</string>+ <string name="cast_picker_title_generic">Choose a television</string>+ <string name="cast_picker_cancel">Cancel</string> </resources>
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 3a9b75fe2f..32f92fdeef 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -390,7 +390,14 @@ object ReceiverController { return } _state.update {- it.copy(phase = ReceiverPhase.Mirroring(senderName, config.width, config.height))+ it.copy(+ phase = ReceiverPhase.Mirroring(+ senderName = senderName,+ width = config.width,+ height = config.height,+ appLabel = config.appLabel,+ ),+ ) } Log.i( TAG,
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.ktindex c224c00be8..77da863c3b 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt@@ -30,7 +30,25 @@ sealed interface ReceiverPhase { val senderName: String, val width: Int, val height: Int,- ) : ReceiverPhase+ /**+ * The name of the app the frames are coming from, or empty when the phone is mirroring its+ * screen.+ *+ * Comes from `StreamConfig.appLabel`, which `:cast` fills in from the `callingPackage` the+ * framework attaches to its picker - never from anything the streaming app asserted about+ * itself.+ */+ val appLabel: String = "",+ ) : ReceiverPhase {+ /**+ * Who to name on screen: the app if there is one, otherwise the phone.+ *+ * "Receiving from YouPipe" is more use than "Receiving from Pixel 9" when it is YouPipe's+ * video on screen and not the phone's, and the phone's name is still the right answer for+ * screen mirroring.+ */+ val sourceName: String get() = appLabel.ifBlank { senderName }+ } /** Something the user has to know about, already a sentence rather than a code. */ data class Failed(val reason: ReceiverFailure) : ReceiverPhase
cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.ktindex 12ff58c0ad..ab911c10ba 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt@@ -127,7 +127,7 @@ class ReceiverService : Service() { private fun statusText(phase: ReceiverPhase): String = when (phase) { is ReceiverPhase.Pairing -> getString(R.string.tv_notification_text_pairing) is ReceiverPhase.Mirroring ->- getString(R.string.tv_notification_text_mirroring, phase.senderName)+ getString(R.string.tv_notification_text_mirroring, phase.sourceName) else -> getString(R.string.tv_notification_text_idle) }
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.ktindex 16dd9347b2..68b81d683b 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt@@ -18,6 +18,7 @@ import com.vayunmathur.cast.tv.platform.ReceiverUiState import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior /** * The idle and pairing screen: the whole of this app's UI.@@ -35,6 +36,7 @@ fun ReceiverContent(state: ReceiverUiState, modifier: Modifier = Modifier) { AppScaffold( title = stringResource(R.string.app_name), modifier = modifier,+ scrollBehavior = appBarScrollBehavior(), ) { padding -> Column( modifier = Modifier.fillMaxSize().padding(padding).padding(48.dp),@@ -88,7 +90,7 @@ fun ReceiverContent(state: ReceiverUiState, modifier: Modifier = Modifier) { // The mirror has its own full-screen Activity, so this is only ever seen for the // moment between the stream starting and that Activity coming up. is ReceiverPhase.Mirroring ->- Headline(stringResource(R.string.tv_mirroring, phase.senderName))+ Headline(stringResource(R.string.tv_mirroring, phase.sourceName)) is ReceiverPhase.Failed -> Headline( stringResource(