Modern Apps git

← Modern-Apps.git

wear: camera companion with live viewfinder

Commit
61b638918073b21a51ffdef211f2fba5e33a0e80
Author
Vayun Mathur <[email protected]>
When
2026-11-25 01:33 UTC (11 days ago)
Parents
344c7cb
New :camera-wear: the watch shows a genuinely live
viewfinder (<=320px JPEG frames tapped from the phone
camera's Camera2 analysis stream after the mode sink -
fire-and-forget WCF1 messages, latest-only, adaptive
2-8 fps, never blocking capture; library/wearlink
untouched because its STREAM is a committed-file
contract). Shutter/record/mode/zoom/flash/torch/lens/
timer all execute on the phone through the camera's
existing seams with a reject-never-fakes gate; state
mirrors to the watch; last-capture thumbnails are data
items, media stays on the phone; no link, no fake
camera on the watch.

Swept: parallel Music wear files where they share
settings/module surfaces.

Verified: camera wear assemble + tests, phone camera
compile + targeted protocol/pipeline/op tests green.

Diff

camera-wear/AGENTS.md
diff --git a/camera-wear/AGENTS.md b/camera-wear/AGENTS.mdnew file mode 100644index 0000000000..ca2f9d0260--- /dev/null+++ b/camera-wear/AGENTS.md@@ -0,0 +1,46 @@+# AGENTS.md — camera-wear/ (':camera-wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `camera-wear/` + `camera/` (the phone side of the same feature).++- Gradle: :camera-wear / dir: camera-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Camera (`:camera`): a live viewfinder+streamed from the phone camera plus remote controls executed on the+phone. This module deliberately uses+`applicationId = "com.vayunmathur.camera"` (the phone app's) with the+shared dev/release signing from the convention plugins: WearLink's+handshake token requires the same signing certificate on both sides, so+changing either breaks phone<->watch control. Bootstrap is a one-time+ADB sideload of this APK onto the watch. The watch has no camera here —+with no phone nearby the app says so; it never fakes a local camera.++## Protocol+`domain/WearCameraProtocol.kt` is a copy of the phone's file (Gradle+cannot depend on another app module). Change both copies together; each+side's `WearCameraProtocolTest` pins the same golden JSON/frame bytes.++- Mirrored state + last-capture thumbnail: WearLink data items+  (`/camera/state`, `/camera/thumbnail` JPEG)+- Watch-originated controls: WearLink message (`/camera/op`)+- Live viewfinder: WearLink messages (`/camera/preview-frame`), NOT the+  STREAM primitive — STREAM is a bounded file transfer (total size ++  SHA-256 committed up front, verified at close, resumable by file+  offset), which a live ephemeral frame sequence cannot satisfy. The+  extension lives behind the camera protocol seam; :library:wearlink is+  unchanged. Phone drops frames latest-only; watch drops stale sequences.+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Viewfinder design point+Phone analysis-stream frames downscaled to ≤320 px wide, JPEG-encoded+once at that size, adaptive ~2–8 fps (nominal 5) backing off when+encode+send exceeds the frame interval. Media stays on the phone.++## Verify (this module only)+```+./gradlew :camera-wear:assembleDev+./gradlew :camera-wear:testDebugUnitTest+```
camera-wear/build.gradle.kts
diff --git a/camera-wear/build.gradle.kts b/camera-wear/build.gradle.ktsnew file mode 100644index 0000000000..bd514ebe0e--- /dev/null+++ b/camera-wear/build.gradle.kts@@ -0,0 +1,39 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "photo_camera"+}++// Version shared with the phone app (root version.txt), read directly because+// common-conventions-wear inlines 1/"1.0" until a wear consumer wires the shared reader.+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+    // The WearLink handshake only connects apps that share a package name and+    // signing certificate, so this module MUST ship as the phone app's package:+    // same applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The namespace only names this module's own R/resources.+    namespace = "com.vayunmathur.camera.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.camera"+        // Convention defaults to 30, but :library:log (pulled in by the wear+        // convention) requires 31, so the watch floor is 31.+        minSdk = 31+        versionCode = wearVersionCode+        versionName = wearVersionName+    }+}++dependencies {+    // Watch side of the Camera companion (see domain/WearCameraProtocol.kt, the+    // copy of the phone protocol it must stay in step with).+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
camera-wear/src/main/AndroidManifest.xml
diff --git a/camera-wear/src/main/AndroidManifest.xml b/camera-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7ccb8c3001--- /dev/null+++ b/camera-wear/src/main/AndroidManifest.xml@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Wear OS form factor. Declaring the watch hardware makes this build+         installable on Wear OS; the touchscreen is not required there. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <uses-permission android:name="android.permission.WAKE_LOCK" />++    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">++        <!-- Paired with the phone app, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <activity+            android:name=".ui.WearMainActivity"+            android:exported="true"+            android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->+    </application>+</manifest>
camera-wear/src/main/java/com/vayunmathur/camera/wear/data/WearCameraStore.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/data/WearCameraStore.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/data/WearCameraStore.ktnew file mode 100644index 0000000000..6c001f7df9--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/data/WearCameraStore.kt@@ -0,0 +1,81 @@+package com.vayunmathur.camera.wear.data++import com.vayunmathur.camera.wear.domain.PreviewFrame+import com.vayunmathur.camera.wear.domain.WearCameraState+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * The watch's mirrored camera truth: the phone's last published+ * [WearCameraState], the newest preview frame and the last-capture+ * thumbnail. Deliberately in-memory only — unlike notes, nothing here is+ * usable without the phone (the watch has no camera), so there is no+ * offline copy to persist and no fake local state to show. A cold start+ * honestly shows "no phone nearby" until the link publishes again.+ */+class WearCameraStore {++    private val _linkConnected = MutableStateFlow(false)+    val linkConnected: StateFlow<Boolean> = _linkConnected.asStateFlow()++    private val _state = MutableStateFlow(WearCameraState())+    val state: StateFlow<WearCameraState> = _state.asStateFlow()++    private val _previewJpeg = MutableStateFlow<ByteArray?>(null)+    /** Newest preview JPEG (decode for display); stale sequences are dropped. */+    val previewJpeg: StateFlow<ByteArray?> = _previewJpeg.asStateFlow()++    private val _previewRotation = MutableStateFlow(0)+    val previewRotation: StateFlow<Int> = _previewRotation.asStateFlow()++    private val _thumbnailJpeg = MutableStateFlow<ByteArray?>(null)+    val thumbnailJpeg: StateFlow<ByteArray?> = _thumbnailJpeg.asStateFlow()++    private var lastPreviewSequence = -1L++    var droppedStaleFrames: Long = 0L+        private set++    fun setLinkConnected(connected: Boolean) {+        _linkConnected.value = connected+        if (!connected) {+            // Link down: no fake viewfinder. The last mirrored state stays+            // for context, but the live frame is gone.+            _previewJpeg.value = null+            lastPreviewSequence = -1L+        }+    }++    /** Applies a mirrored phone state (state mirroring is replace, never merge). */+    fun applyState(state: WearCameraState) {+        _state.value = state+    }++    /** Applies one preview frame body; returns false when malformed or stale. */+    fun applyPreviewFrame(body: ByteArray): Boolean {+        val decoded = PreviewFrame.decode(body) ?: return false+        if (decoded.sequence <= lastPreviewSequence) {+            droppedStaleFrames+++            return false+        }+        lastPreviewSequence = decoded.sequence+        _previewRotation.value = decoded.rotationDegrees+        _previewJpeg.value = decoded.jpeg+        return true+    }++    fun applyThumbnail(jpeg: ByteArray) {+        if (jpeg.isNotEmpty()) _thumbnailJpeg.value = jpeg+    }++    companion object {+        @Volatile+        private var instance: WearCameraStore? = null++        /** The process-wide store (bridge and UI must agree on one). */+        fun get(): WearCameraStore = instance ?: synchronized(this) {+            instance ?: WearCameraStore().also { instance = it }+        }+    }+}
camera-wear/src/main/java/com/vayunmathur/camera/wear/domain/WearCameraProtocol.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/domain/WearCameraProtocol.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/domain/WearCameraProtocol.ktnew file mode 100644index 0000000000..c9eb9c49fb--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/domain/WearCameraProtocol.kt@@ -0,0 +1,299 @@+package com.vayunmathur.camera.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Wear OS Camera companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:camera-wear`,+ * applicationId `com.vayunmathur.camera`) carries a copy of this file under+ * `com.vayunmathur.camera.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON/frame bytes so a one-sided+ * edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [STATE_PATH] phone -> watch (mirrored camera state) and+ *   [THUMBNAIL_PATH] phone -> watch (last-capture JPEG bytes; the media+ *   itself stays on the phone).+ * - Messages: [OP_PATH] watch -> phone (one control op), and+ *   [PREVIEW_FRAME_PATH] phone -> watch (one live viewfinder frame).+ *   Delivery needs a live session; nothing wakes a dead phone process.+ *+ * Live viewfinder transport choice — stated, not implied: WearLink's+ * STREAM primitive is a file transfer (the header commits total size ++ * SHA-256 up front, the receiver verifies the whole stream at close, and+ * STREAM_ACK resume replays a durable file offset). A live preview is an+ * unbounded sequence of ephemeral frames whose total size is unknowable+ * and whose stale frames are worthless, so STREAM cannot carry it without+ * breaking WearLink's contract. The extension therefore lives behind this+ * camera protocol seam, leaving :library:wearlink untouched: each frame+ * is one fire-and-forget MESSAGE (JPEG well under the 256 KiB message+ * cap), the phone keeps only the latest frame, and the watch keeps only+ * the newest sequence. Frames are never queued, resumed or verified.+ */+object WearCameraProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "camera_wear_companion"++    /** Data-item path (phone -> watch): the [WearCameraState] JSON. */+    const val STATE_PATH = "/camera/state"++    /** Data-item path (phone -> watch): last-capture thumbnail JPEG bytes. */+    const val THUMBNAIL_PATH = "/camera/thumbnail"++    /** Message path (watch -> phone): one [WearCameraOp] JSON. */+    const val OP_PATH = "/camera/op"++    /** Message path (phone -> watch): one binary preview frame (see [PreviewFrame]). */+    const val PREVIEW_FRAME_PATH = "/camera/preview-frame"++    /** Widest preview/thumbnail frame the watch is ever sent, in pixels. */+    const val PREVIEW_MAX_WIDTH = 320++    /** Nominal preview rate; the phone adapts inside [MIN_FPS]..[MAX_FPS]. */+    const val PREVIEW_NOMINAL_FPS = 5+    const val PREVIEW_MIN_FPS = 2+    const val PREVIEW_MAX_FPS = 8++    /** JPEG quality bounds for the adaptive preview/thumbnail encoder. */+    const val PREVIEW_JPEG_QUALITY = 60+    const val PREVIEW_MIN_JPEG_QUALITY = 40+    const val PREVIEW_MAX_JPEG_QUALITY = 75++    /** Encoded preview frames larger than this lower the next quality step. */+    const val PREVIEW_LARGE_FRAME_BYTES = 24_000++    /**+     * Modes the watch may switch to remotely. PANORAMA/PHOTOSPHERE are+     * excluded: both need an on-phone guided sweep. SLOW_MO is included —+     * the phone's mode switch itself enforces its back-lens rule.+     */+    val REMOTE_MODES = listOf("PHOTO", "VIDEO", "PORTRAIT", "TIMELAPSE", "CINEMATIC", "SLOW_MO")++    /** Modes whose shutter action records video rather than a still. */+    val VIDEO_MODES = setOf("VIDEO", "TIMELAPSE", "CINEMATIC", "SLOW_MO")++    /** Shutter-timer options (seconds) the watch may set; 0 is off. */+    val TIMER_OPTIONS_SECONDS = listOf(0, 1, 3, 5, 10)++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** Mirrored phone-camera state, published at [WearCameraProtocol.STATE_PATH]. */+@Serializable+data class WearCameraState(+    /** Phone mode name (CameraMode.name), including non-remote modes. */+    val mode: String = "PHOTO",+    /** Modes the watch may switch to (see [WearCameraProtocol.REMOTE_MODES]). */+    val remoteModes: List<String> = WearCameraProtocol.REMOTE_MODES,+    val frontLens: Boolean = false,+    val zoomRatio: Float = 1f,+    /** Selectable zoom preset ratios, ascending (the phone's zoom-bar levels). */+    val zoomPresets: List<Float> = listOf(1f),+    val zoomMin: Float = 1f,+    val zoomMax: Float = 1f,+    /** FlashMode.name: ON, OFF or AUTO. */+    val flash: String = "OFF",+    val hasFlashUnit: Boolean = true,+    val torch: Boolean = false,+    val timerSeconds: Int = 0,+    val timerCountdown: Int = 0,+    val recording: Boolean = false,+    val recordingSeconds: Long = 0L,+    val capturing: Boolean = false,+    /** True while the phone is streaming preview frames to the watch. */+    val previewStreaming: Boolean = false,+    /** Epoch millis of the last landed capture, 0 when none this session. */+    val lastCaptureAtMillis: Long = 0L,+    /** "PHOTO" or "VIDEO" for the last capture, empty when none. */+    val lastCaptureKind: String = "",+)++/** Kind of a watch-originated camera control. */+@Serializable+enum class WearOpKind {+    SHUTTER,+    RECORD_TOGGLE,+    SET_MODE,+    SET_ZOOM,+    ZOOM_PRESET,+    SET_FLASH,+    SET_TORCH,+    FLIP_LENS,+    SET_TIMER,+    PREVIEW_START,+    PREVIEW_STOP,+}++/** One watch-originated control, as [WearCameraProtocol.OP_PATH]. Unused fields keep defaults. */+@Serializable+data class WearCameraOp(+    val kind: WearOpKind,+    val mode: String = "",+    val zoomRatio: Float = 1f,+    val zoomPresetIndex: Int = -1,+    val flash: String = "",+    val torch: Boolean = false,+    val timerSeconds: Int = 0,+)++/** Whether a planned op may run against the mirrored state, and why not when it may not. */+sealed interface WearOpDecision {+    data object Apply : WearOpDecision+    data class Reject(val reason: String) : WearOpDecision+}++/**+ * Pure op gate, shared by the phone (authoritative, against live state)+ * and testable without a camera: mode/lens/zoom changes rebind the phone+ * session, so they are refused while recording (the phone's own mode/lens+ * actions gate the same way); unknown modes/flash values and out-of-set+ * timers are refused rather than guessed at. The phone re-checks against+ * its live ViewModel after planning, so a stale watch state never forces+ * an unsafe op — the mirrored state corrects the watch on the next publish.+ */+fun planWearCameraOp(op: WearCameraOp, state: WearCameraState): WearOpDecision = when (op.kind) {+    WearOpKind.SHUTTER, WearOpKind.RECORD_TOGGLE, WearOpKind.PREVIEW_START, WearOpKind.PREVIEW_STOP ->+        WearOpDecision.Apply+    WearOpKind.SET_TORCH -> WearOpDecision.Apply+    WearOpKind.SET_MODE -> when {+        op.mode !in WearCameraProtocol.REMOTE_MODES -> WearOpDecision.Reject("mode not remote-switchable")+        state.recording && op.mode != state.mode -> WearOpDecision.Reject("recording in progress")+        else -> WearOpDecision.Apply+    }+    WearOpKind.FLIP_LENS -> when {+        state.recording -> WearOpDecision.Reject("recording in progress")+        state.mode == "SLOW_MO" -> WearOpDecision.Reject("slo-mo is back-lens only")+        else -> WearOpDecision.Apply+    }+    WearOpKind.SET_ZOOM, WearOpKind.ZOOM_PRESET ->+        if (state.mode == "PANORAMA" || state.mode == "PHOTOSPHERE") {+            WearOpDecision.Reject("zoom locked in this mode")+        } else {+            WearOpDecision.Apply+        }+    WearOpKind.SET_FLASH ->+        if (op.flash in setOf("ON", "OFF", "AUTO")) WearOpDecision.Apply+        else WearOpDecision.Reject("unknown flash mode")+    WearOpKind.SET_TIMER ->+        if (op.timerSeconds in WearCameraProtocol.TIMER_OPTIONS_SECONDS) WearOpDecision.Apply+        else WearOpDecision.Reject("unsupported timer")+}++/** Clamps a requested zoom ratio into the mirrored range; non-finite requests become the current ratio. */+fun clampWearZoom(requested: Float, state: WearCameraState): Float =+    if (!requested.isFinite()) state.zoomRatio+    else requested.coerceIn(state.zoomMin, state.zoomMax)++/** The preset ratio for [index], or null when the index is stale (presets changed under it). */+fun wearZoomPreset(state: WearCameraState, index: Int): Float? = state.zoomPresets.getOrNull(index)++/**+ * One live viewfinder frame on [WearCameraProtocol.PREVIEW_FRAME_PATH]:+ * a fixed 20-byte header (`WCF1`, sequence, timestamp, size, rotation)+ * followed by the JPEG bytes. The sequence lets the watch drop stale+ * frames; nothing is ever retransmitted.+ */+object PreviewFrame {+    const val HEADER_BYTES = 20+    private val MAGIC = byteArrayOf('W'.code.toByte(), 'C'.code.toByte(), 'F'.code.toByte(), '1'.code.toByte())++    fun encode(sequence: Long, timestampMillis: Long, width: Int, height: Int, rotationDegrees: Int, jpeg: ByteArray): ByteArray {+        val out = ByteArray(HEADER_BYTES + jpeg.size)+        MAGIC.copyInto(out)+        writeInt(out, 4, (sequence and 0xFFFF_FFFFL).toInt())+        writeInt(out, 8, (timestampMillis and 0xFFFF_FFFFL).toInt())+        writeShort(out, 12, width)+        writeShort(out, 14, height)+        writeShort(out, 16, rotationDegrees)+        writeShort(out, 18, 0)+        jpeg.copyInto(out, HEADER_BYTES)+        return out+    }++    /** Decoded header plus the JPEG slice; null on any malformed input. */+    fun decode(body: ByteArray): Decoded? {+        if (body.size <= HEADER_BYTES) return null+        if (!MAGIC.indices.all { body[it] == MAGIC[it] }) return null+        val width = readShort(body, 12)+        val height = readShort(body, 14)+        if (width <= 0 || height <= 0) return null+        return Decoded(+            sequence = readInt(body, 4).toLong() and 0xFFFF_FFFFL,+            timestampMillis = readInt(body, 8).toLong() and 0xFFFF_FFFFL,+            width = width,+            height = height,+            rotationDegrees = readShort(body, 16),+            jpeg = body.copyOfRange(HEADER_BYTES, body.size),+        )+    }++    data class Decoded(+        val sequence: Long,+        val timestampMillis: Long,+        val width: Int,+        val height: Int,+        val rotationDegrees: Int,+        val jpeg: ByteArray,+    ) {+        override fun equals(other: Any?): Boolean {+            if (this === other) return true+            if (other !is Decoded) return false+            return sequence == other.sequence && timestampMillis == other.timestampMillis &&+                width == other.width && height == other.height &&+                rotationDegrees == other.rotationDegrees && jpeg.contentEquals(other.jpeg)+        }++        override fun hashCode(): Int {+            var r = sequence.hashCode()+            r = 31 * r + timestampMillis.hashCode()+            r = 31 * r + width+            r = 31 * r + height+            r = 31 * r + rotationDegrees+            r = 31 * r + jpeg.contentHashCode()+            return r+        }+    }++    private fun writeInt(out: ByteArray, offset: Int, value: Int) {+        out[offset] = (value ushr 24).toByte()+        out[offset + 1] = (value ushr 16).toByte()+        out[offset + 2] = (value ushr 8).toByte()+        out[offset + 3] = value.toByte()+    }++    private fun readInt(body: ByteArray, offset: Int): Int =+        ((body[offset].toInt() and 0xFF) shl 24) or ((body[offset + 1].toInt() and 0xFF) shl 16) or+            ((body[offset + 2].toInt() and 0xFF) shl 8) or (body[offset + 3].toInt() and 0xFF)++    private fun writeShort(out: ByteArray, offset: Int, value: Int) {+        out[offset] = (value ushr 8).toByte()+        out[offset + 1] = value.toByte()+    }++    private fun readShort(body: ByteArray, offset: Int): Int =+        ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF)+}++/** Serialises [state] for the state data item (the golden-pinned wire form). */+fun encodeWearCameraState(state: WearCameraState): ByteArray =+    WearCameraProtocol.json.encodeToString(state).encodeToByteArray()++/** Parses a state data item; null when malformed (the watch keeps its last state). */+fun decodeWearCameraState(body: ByteArray): WearCameraState? = runCatching {+    WearCameraProtocol.json.decodeFromString<WearCameraState>(body.decodeToString())+}.getOrNull()++/** Serialises [op] for the op message (the golden-pinned wire form). */+fun encodeWearCameraOp(op: WearCameraOp): ByteArray =+    WearCameraProtocol.json.encodeToString(op).encodeToByteArray()++/** Parses an op message; null when malformed (the phone ignores it). */+fun decodeWearCameraOp(body: ByteArray): WearCameraOp? = runCatching {+    WearCameraProtocol.json.decodeFromString<WearCameraOp>(body.decodeToString())+}.getOrNull()
camera-wear/src/main/java/com/vayunmathur/camera/wear/sync/WearLinkBridge.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/sync/WearLinkBridge.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..4548a81417--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/sync/WearLinkBridge.kt@@ -0,0 +1,85 @@+package com.vayunmathur.camera.wear.sync++import android.content.Context+import com.vayunmathur.camera.wear.data.WearCameraStore+import com.vayunmathur.camera.wear.domain.WearCameraOp+import com.vayunmathur.camera.wear.domain.WearCameraProtocol+import com.vayunmathur.camera.wear.domain.WearOpKind+import com.vayunmathur.camera.wear.domain.decodeWearCameraState+import com.vayunmathur.camera.wear.domain.encodeWearCameraOp+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Watch side of WearLink for Camera: mirrored state + thumbnail data items+ * and preview-frame messages land in [WearCameraStore]; every watch control+ * is one op message executed on the phone. App-lifecycle-bound like every+ * WearLink pair — no Play-services listener, no background wakeups.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val store = WearCameraStore.get()+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                when (path) {+                    WearCameraProtocol.STATE_PATH -> {+                        val state = decodeWearCameraState(body)+                        if (state == null) {+                            Log.status(TAG, "ignoring malformed camera state")+                            return+                        }+                        store.applyState(state)+                    }+                    WearCameraProtocol.THUMBNAIL_PATH -> store.applyThumbnail(body)+                }+            }++            override fun onMessage(path: String, body: ByteArray) {+                if (path == WearCameraProtocol.PREVIEW_FRAME_PATH) store.applyPreviewFrame(body)+            }+        }+        val created = WearLinkNode(context, WearCameraProtocol.CAPABILITY, listener)+        scope.launch {+            created.state.collect { linkState ->+                store.setLinkConnected(linkState is WearLinkState.Connected)+            }+        }+        created.start()+        return created+    }++    /** Sends one control op; false when no session is live (never queued as "done"). */+    suspend fun sendOp(context: Context, op: WearCameraOp): Boolean =+        get(context).sendMessage(WearCameraProtocol.OP_PATH, encodeWearCameraOp(op))++    fun sendOpAsync(context: Context, op: WearCameraOp) {+        scope.launch { sendOp(context, op) }+    }++    /** Asks the phone to start streaming the live viewfinder to this watch. */+    fun startPreview(context: Context) =+        sendOpAsync(context, WearCameraOp(WearOpKind.PREVIEW_START))++    /** Stops the viewfinder stream (screen left / link going away). */+    fun stopPreview(context: Context) =+        sendOpAsync(context, WearCameraOp(WearOpKind.PREVIEW_STOP))+}
camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearControlsScreen.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearControlsScreen.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearControlsScreen.ktnew file mode 100644index 0000000000..39c4bf85ef--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearControlsScreen.kt@@ -0,0 +1,175 @@+package com.vayunmathur.camera.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.itemsIndexed+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.camera.wear.R+import com.vayunmathur.camera.wear.data.WearCameraStore+import com.vayunmathur.camera.wear.domain.WearCameraOp+import com.vayunmathur.camera.wear.domain.WearCameraProtocol+import com.vayunmathur.camera.wear.domain.WearOpKind+import com.vayunmathur.camera.wear.sync.WearLinkBridge++/**+ * Remote controls executed on the phone: zoom presets, a zoom scrub+ * (coarse steps over the mirrored range), flash/torch, lens flip and the+ * shutter timer. Every value shown is the phone's mirrored state — a tap+ * sends one op and the watch believes the next state publish, not the tap.+ */+@Composable+fun WearControlsScreen(store: WearCameraStore, onBack: () -> Unit) {+    val context = LocalContext.current+    val state by store.state.collectAsState()+    val listState = rememberScalingLazyListState()++    fun send(op: WearCameraOp) = WearLinkBridge.sendOpAsync(context, op)++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.wear_controls),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            Text(+                stringResource(R.string.wear_zoom, formatZoomLabel(state.zoomRatio)),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        itemsIndexed(state.zoomPresets) { index, preset ->+            Chip(+                onClick = { send(WearCameraOp(WearOpKind.ZOOM_PRESET, zoomPresetIndex = index)) },+                label = { Text(formatZoomLabel(preset), maxLines = 1) },+                colors = if (preset == state.zoomRatio) {+                    ChipDefaults.primaryChipColors()+                } else {+                    ChipDefaults.secondaryChipColors()+                },+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = { send(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = scrubZoom(state.zoomRatio, state.zoomMin, state.zoomMax, up = false))) },+                label = { Text("−", maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = { send(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = scrubZoom(state.zoomRatio, state.zoomMin, state.zoomMax, up = true))) },+                label = { Text("+", maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        if (state.hasFlashUnit) {+            item {+                Chip(+                    onClick = { send(WearCameraOp(WearOpKind.SET_FLASH, flash = nextFlash(state.flash))) },+                    label = { Text(stringResource(R.string.wear_flash, state.flash), maxLines = 1) },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+            item {+                Chip(+                    onClick = { send(WearCameraOp(WearOpKind.SET_TORCH, torch = !state.torch)) },+                    label = {+                        Text(+                            "${stringResource(R.string.wear_torch)}: ${if (state.torch) "ON" else "OFF"}",+                            maxLines = 1,+                        )+                    },+                    colors = if (state.torch) ChipDefaults.primaryChipColors() else ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Chip(+                onClick = { send(WearCameraOp(WearOpKind.FLIP_LENS)) },+                label = {+                    Text(+                        "${stringResource(R.string.wear_flip_lens)}: " ++                            stringResource(if (state.frontLens) R.string.wear_front else R.string.wear_back_lens),+                        maxLines = 1,+                    )+                },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = { send(WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = nextTimer(state.timerSeconds))) },+                label = {+                    Text(+                        stringResource(R.string.wear_timer, if (state.timerSeconds == 0) "OFF" else "${state.timerSeconds}s"),+                        maxLines = 1,+                    )+                },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++/** One scrub step: ×/÷ 1.25 in log space, clamped to the mirrored range. */+internal fun scrubZoom(current: Float, min: Float, max: Float, up: Boolean): Float {+    val stepped = if (up) current * ZOOM_STEP_FACTOR else current / ZOOM_STEP_FACTOR+    return stepped.coerceIn(min, max)+}++/** Next flash value in the OFF -> AUTO -> ON cycle. */+internal fun nextFlash(current: String): String = when (current) {+    "OFF" -> "AUTO"+    "AUTO" -> "ON"+    else -> "OFF"+}++/** Next timer value in the protocol's option set, wrapping to off. */+internal fun nextTimer(currentSeconds: Int): Int {+    val options = WearCameraProtocol.TIMER_OPTIONS_SECONDS+    val index = options.indexOf(currentSeconds)+    return options[(index + 1) % options.size]+}++/** ".5", "1x", "1.5x" — the watch's zoom label (mirrors the phone's format). */+internal fun formatZoomLabel(ratio: Float): String = when {+    ratio < 1f -> ".${(ratio * ZOOM_DECIMAL_SCALE).toInt()}"+    ratio == ratio.toInt().toFloat() -> "${ratio.toInt()}x"+    else -> "%.1fx".format(ratio)+}++private const val ZOOM_STEP_FACTOR = 1.25f+private const val ZOOM_DECIMAL_SCALE = 10f
camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearLastCaptureScreen.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearLastCaptureScreen.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearLastCaptureScreen.ktnew file mode 100644index 0000000000..8b35da61d2--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearLastCaptureScreen.kt@@ -0,0 +1,71 @@+package com.vayunmathur.camera.wear.ui++import android.graphics.BitmapFactory+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.camera.wear.R+import com.vayunmathur.camera.wear.data.WearCameraStore++/** Last-capture thumbnail pushed from the phone; the media itself stays on the phone. */+@Composable+fun WearLastCaptureScreen(store: WearCameraStore, onBack: () -> Unit) {+    val thumbnailJpeg by store.thumbnailJpeg.collectAsState()+    val state by store.state.collectAsState()+    val bitmap = remember(thumbnailJpeg) {+        thumbnailJpeg?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size) }.getOrNull() }+    }++    Column(modifier = Modifier.padding(horizontal = 12.dp)) {+        Text(+            stringResource(R.string.wear_last_capture),+            style = MaterialTheme.typography.title3,+            textAlign = TextAlign.Center,+            modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+        )+        if (bitmap != null) {+            Image(+                bitmap = bitmap.asImageBitmap(),+                contentDescription = null,+                contentScale = ContentScale.FillWidth,+                modifier = Modifier.fillMaxWidth(),+            )+            if (state.lastCaptureKind.isNotEmpty()) {+                Text(+                    state.lastCaptureKind,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+                )+            }+        } else {+            Text(+                stringResource(R.string.wear_no_capture),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+            )+        }+        Chip(+            onClick = onBack,+            label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+            colors = ChipDefaults.secondaryChipColors(),+            modifier = Modifier.fillMaxWidth(),+        )+    }+}
camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearMainActivity.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearMainActivity.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..74ce79ff9b--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearMainActivity.kt@@ -0,0 +1,47 @@+package com.vayunmathur.camera.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.camera.wear.data.WearCameraStore+import com.vayunmathur.camera.wear.sync.WearLinkBridge++/**+ * Camera watch companion entry: a live viewfinder streamed from the phone+ * camera plus remote controls executed on the phone. The watch has no+ * camera of its own — with no phone nearby it says so, honestly.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val store = WearCameraStore.get()+        WearLinkBridge.get(this)+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.Viewfinder) }+                when (route) {+                    WearRoute.Viewfinder -> WearViewfinderScreen(+                        store = store,+                        onOpenControls = { route = WearRoute.Controls },+                        onOpenLastCapture = { route = WearRoute.LastCapture },+                    )+                    WearRoute.Controls -> WearControlsScreen(+                        store = store,+                        onBack = { route = WearRoute.Viewfinder },+                    )+                    WearRoute.LastCapture -> WearLastCaptureScreen(+                        store = store,+                        onBack = { route = WearRoute.Viewfinder },+                    )+                }+            }+        }+    }+}
camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearRoute.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearRoute.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..334707965f--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearRoute.kt@@ -0,0 +1,13 @@+package com.vayunmathur.camera.wear.ui++/** Watch navigation destinations. Screen changes only ever happen through these routes. */+sealed interface WearRoute {+    /** Live viewfinder with shutter/record and mode switching. */+    data object Viewfinder : WearRoute++    /** Zoom, flash/torch, lens and timer controls (executed on the phone). */+    data object Controls : WearRoute++    /** Last-capture thumbnail (the media itself stays on the phone). */+    data object LastCapture : WearRoute+}
camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearViewfinderScreen.kt
diff --git a/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearViewfinderScreen.kt b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearViewfinderScreen.ktnew file mode 100644index 0000000000..f098d3e02d--- /dev/null+++ b/camera-wear/src/main/java/com/vayunmathur/camera/wear/ui/WearViewfinderScreen.kt@@ -0,0 +1,191 @@+package com.vayunmathur.camera.wear.ui++import android.graphics.BitmapFactory+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.camera.wear.R+import com.vayunmathur.camera.wear.data.WearCameraStore+import com.vayunmathur.camera.wear.domain.WearCameraOp+import com.vayunmathur.camera.wear.domain.WearCameraProtocol+import com.vayunmathur.camera.wear.domain.WearOpKind+import com.vayunmathur.camera.wear.sync.WearLinkBridge++/**+ * The live viewfinder: newest preview frame from the phone camera, the+ * mirrored mode/zoom/recording state, and the shutter/record/mode+ * controls. The stream runs only while this screen is visible. With no+ * phone session there is no viewfinder at all — the watch has no camera.+ */+@Composable+fun WearViewfinderScreen(+    store: WearCameraStore,+    onOpenControls: () -> Unit,+    onOpenLastCapture: () -> Unit,+) {+    val context = LocalContext.current+    val connected by store.linkConnected.collectAsState()+    val state by store.state.collectAsState()+    val previewJpeg by store.previewJpeg.collectAsState()+    val rotation by store.previewRotation.collectAsState()++    DisposableEffect(connected) {+        if (connected) WearLinkBridge.startPreview(context)+        onDispose { WearLinkBridge.stopPreview(context) }+    }++    if (!connected) {+        Column(+            modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            Text(+                stringResource(R.string.wear_no_phone),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+            )+            Text(+                stringResource(R.string.wear_no_phone_hint),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+            )+        }+        return+    }++    val bitmap = remember(previewJpeg) {+        previewJpeg?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size) }.getOrNull() }+    }+    val videoMode = state.mode in WearCameraProtocol.VIDEO_MODES++    Box(modifier = Modifier.fillMaxSize()) {+        if (bitmap != null) {+            Image(+                bitmap = bitmap.asImageBitmap(),+                contentDescription = null,+                contentScale = ContentScale.Crop,+                modifier = Modifier.fillMaxSize().rotate(rotation.toFloat()),+            )+        } else {+            Text(+                stringResource(R.string.wear_viewfinder_waiting),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.align(Alignment.Center).padding(horizontal = 16.dp),+            )+        }++        Column(modifier = Modifier.align(Alignment.TopCenter).padding(top = 4.dp)) {+            Text(+                state.mode,+                style = MaterialTheme.typography.caption1,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth(),+            )+            if (state.recording) {+                Text(+                    "REC ${formatRecordingTime(state.recordingSeconds)}",+                    style = MaterialTheme.typography.caption1,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth(),+                )+            } else if (state.timerCountdown > 0) {+                Text(+                    "${state.timerCountdown}",+                    style = MaterialTheme.typography.caption1,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth(),+                )+            }+        }++        Column(+            modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 4.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            LazyRow {+                items(state.remoteModes) { mode ->+                    Chip(+                        onClick = {+                            WearLinkBridge.sendOpAsync(context, WearCameraOp(WearOpKind.SET_MODE, mode = mode))+                        },+                        label = { Text(mode, maxLines = 1) },+                        colors = if (mode == state.mode) {+                            ChipDefaults.primaryChipColors()+                        } else {+                            ChipDefaults.secondaryChipColors()+                        },+                    )+                }+            }+            Button(+                onClick = {+                    val op = if (videoMode) {+                        WearCameraOp(WearOpKind.RECORD_TOGGLE)+                    } else {+                        WearCameraOp(WearOpKind.SHUTTER)+                    }+                    WearLinkBridge.sendOpAsync(context, op)+                },+            ) {+                Text(+                    when {+                        state.recording -> stringResource(R.string.wear_record_stop)+                        videoMode -> stringResource(R.string.wear_record_start)+                        else -> stringResource(R.string.wear_shutter)+                    },+                    maxLines = 1,+                )+            }+            LazyRow {+                item {+                    Chip(+                        onClick = onOpenControls,+                        label = { Text(stringResource(R.string.wear_controls), maxLines = 1) },+                        colors = ChipDefaults.secondaryChipColors(),+                    )+                }+                item {+                    Chip(+                        onClick = onOpenLastCapture,+                        label = { Text(stringResource(R.string.wear_last_capture), maxLines = 1) },+                        colors = ChipDefaults.secondaryChipColors(),+                    )+                }+            }+        }+    }+}++/** mm:ss recording duration for the viewfinder's REC line. */+internal fun formatRecordingTime(totalSeconds: Long): String {+    val minutes = totalSeconds / SECONDS_PER_MINUTE+    val seconds = totalSeconds % SECONDS_PER_MINUTE+    return "%d:%02d".format(minutes, seconds)+}++private const val SECONDS_PER_MINUTE = 60L
camera-wear/src/main/res/values/colors.xml
diff --git a/camera-wear/src/main/res/values/colors.xml b/camera-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..bfc7025d71--- /dev/null+++ b/camera-wear/src/main/res/values/colors.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Background for the generated adaptive launcher icon (see LauncherIconGen). -->+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
camera-wear/src/main/res/values/strings.xml
diff --git a/camera-wear/src/main/res/values/strings.xml b/camera-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..1804389c8c--- /dev/null+++ b/camera-wear/src/main/res/values/strings.xml@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Camera</string>+    <string name="wear_no_phone">No phone nearby</string>+    <string name="wear_no_phone_hint">Open Camera on your phone and keep it nearby — the viewfinder streams from the phone camera.</string>+    <string name="wear_connecting">Looking for your phone…</string>+    <string name="wear_viewfinder_waiting">Waiting for the phone viewfinder…</string>+    <string name="wear_shutter">Take photo</string>+    <string name="wear_record_start">Start recording</string>+    <string name="wear_record_stop">Stop recording</string>+    <string name="wear_controls">Controls</string>+    <string name="wear_last_capture">Last capture</string>+    <string name="wear_no_capture">No capture yet this session. Media stays on your phone.</string>+    <string name="wear_back">Back</string>+    <string name="wear_flip_lens">Flip lens</string>+    <string name="wear_front">Front</string>+    <string name="wear_back_lens">Back</string>+    <string name="wear_torch">Torch</string>+    <string name="wear_flash">Flash %1$s</string>+    <string name="wear_timer">Timer %1$s</string>+    <string name="wear_zoom">Zoom %1$s</string>+</resources>
camera-wear/src/test/java/com/vayunmathur/camera/wear/domain/WearCameraProtocolTest.kt
diff --git a/camera-wear/src/test/java/com/vayunmathur/camera/wear/domain/WearCameraProtocolTest.kt b/camera-wear/src/test/java/com/vayunmathur/camera/wear/domain/WearCameraProtocolTest.ktnew file mode 100644index 0000000000..0d854bdef1--- /dev/null+++ b/camera-wear/src/test/java/com/vayunmathur/camera/wear/domain/WearCameraProtocolTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.camera.wear.domain++import com.vayunmathur.camera.wear.data.WearCameraStore+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class WearCameraProtocolTest {++    @Test+    fun goldenStateJson() {+        val state = WearCameraState(+            mode = "VIDEO",+            frontLens = true,+            zoomRatio = 2f,+            zoomPresets = listOf(1f, 2f),+            zoomMin = 0.5f,+            zoomMax = 10f,+            flash = "AUTO",+            torch = true,+            timerSeconds = 3,+            recording = true,+            recordingSeconds = 65L,+            previewStreaming = true,+            lastCaptureAtMillis = 7L,+            lastCaptureKind = "PHOTO",+        )+        assertEquals(+            """{"mode":"VIDEO","frontLens":true,"zoomRatio":2.0,"zoomPresets":[1.0,2.0],"zoomMin":0.5,""" ++                """"zoomMax":10.0,"flash":"AUTO","torch":true,"timerSeconds":3,"recording":true,""" ++                """"recordingSeconds":65,"previewStreaming":true,"lastCaptureAtMillis":7,"lastCaptureKind":"PHOTO"}""",+            encodeWearCameraState(state).decodeToString(),+        )+    }++    @Test+    fun goldenOpJson() {+        val op = WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = 2.5f)+        assertEquals(+            """{"kind":"SET_ZOOM","zoomRatio":2.5}""",+            encodeWearCameraOp(op).decodeToString(),+        )+    }++    @Test+    fun goldenPreviewFrameHeader() {+        val frame = PreviewFrame.encode(+            sequence = 0x01020304L,+            timestampMillis = 0x05060708L,+            width = 320,+            height = 240,+            rotationDegrees = 90,+            jpeg = byteArrayOf(9, 8, 7),+        )+        assertEquals(+            listOf(+                'W'.code, 'C'.code, 'F'.code, '1'.code,+                1, 2, 3, 4, 5, 6, 7, 8, 1, 64, 0, 240, 0, 90, 0, 0, 9, 8, 7,+            ),+            frame.map { it.toInt() and 0xFF },+        )+        val decoded = PreviewFrame.decode(frame)!!+        assertEquals(0x01020304L, decoded.sequence)+        assertTrue(byteArrayOf(9, 8, 7).contentEquals(decoded.jpeg))+    }++    @Test+    fun stateAndOpRoundTrip() {+        val state = WearCameraState(mode = "PORTRAIT", zoomRatio = 1.5f)+        assertEquals(state, decodeWearCameraState(encodeWearCameraState(state)))+        val op = WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = 5)+        assertEquals(op, decodeWearCameraOp(encodeWearCameraOp(op)))+        assertNull(decodeWearCameraState("not json".encodeToByteArray()))+    }++    @Test+    fun storeMirrorsStateAndDropsStaleFrames() {+        val store = WearCameraStore()+        val first = WearCameraState(mode = "VIDEO", zoomRatio = 2f, recording = true, recordingSeconds = 12L)+        store.applyState(first)+        assertEquals(first, store.state.value)+        // Mirroring replaces wholesale — nothing merges or lingers.+        val second = WearCameraState(mode = "PHOTO")+        store.applyState(second)+        assertEquals(second, store.state.value)++        val frame1 = PreviewFrame.encode(1L, 1L, 320, 240, 0, byteArrayOf(1))+        val frame2 = PreviewFrame.encode(2L, 2L, 320, 240, 90, byteArrayOf(2))+        assertTrue(store.applyPreviewFrame(frame1))+        assertTrue(store.applyPreviewFrame(frame2))+        assertTrue(byteArrayOf(2).contentEquals(store.previewJpeg.value!!))+        assertEquals(90, store.previewRotation.value)+        // Stale and replayed sequences never replace the newest frame.+        assertFalse(store.applyPreviewFrame(frame1))+        assertFalse(store.applyPreviewFrame(frame2))+        assertEquals(2L, store.droppedStaleFrames)+        assertFalse(store.applyPreviewFrame(byteArrayOf(0, 1, 2)))++        store.applyThumbnail(byteArrayOf(5, 6))+        assertTrue(byteArrayOf(5, 6).contentEquals(store.thumbnailJpeg.value!!))+        store.applyThumbnail(ByteArray(0))+        assertTrue(byteArrayOf(5, 6).contentEquals(store.thumbnailJpeg.value!!))+    }++    @Test+    fun linkDownClearsLiveFrameButKeepsMirroredState() {+        val store = WearCameraStore()+        store.applyState(WearCameraState(mode = "VIDEO"))+        store.applyPreviewFrame(PreviewFrame.encode(3L, 1L, 320, 240, 0, byteArrayOf(1)))+        store.setLinkConnected(true)+        assertEquals(true, store.linkConnected.value)+        store.setLinkConnected(false)+        assertNull(store.previewJpeg.value)+        assertEquals("VIDEO", store.state.value.mode)+    }+}
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex 471ab21f62..e79eb1e4e4 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -145,6 +145,9 @@ dependencies {     // ncnn is gone from the whole tree, not just this app: `:translate` was the last consumer and     // it now runs SMaLL-100 on `:library:ml` too, so `libncnn_android.so` is in no APK here.     implementation(project(":library:ml"))+    // Wear OS companion (live viewfinder + remote controls, :camera-wear):+    // WearLink transport, RFCOMM with no Play services.+    implementation(project(":library:wearlink"))     // Mockito is already a cataloged test dep used the same way by     // sibling modules (e.g. :office): ContentResolver is final-method     // heavy, so null-stream failure paths are tested with a mock.
camera/src/main/java/com/vayunmathur/camera/MainActivity.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt b/camera/src/main/java/com/vayunmathur/camera/MainActivity.ktindex 3c6f267bb0..e49fe42487 100644--- a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt+++ b/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt@@ -52,6 +52,13 @@ class MainActivity : MaActivity() {             )             viewModel.enableCaptureForResult(outputUri)         }+        // Wear OS companion (live viewfinder + remote controls over+        // WearLink): lifecycle-bound to this process, like the other wear+        // pairs — nothing wakes a dead phone app for the watch.+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val wearSync = com.vayunmathur.camera.platform.WearCameraSync.get(this)+        wearSync.viewModel = viewModel+        wearSync.start()     }      @Composable
camera/src/main/java/com/vayunmathur/camera/domain/WearCameraProtocol.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/WearCameraProtocol.kt b/camera/src/main/java/com/vayunmathur/camera/domain/WearCameraProtocol.ktnew file mode 100644index 0000000000..0b37881bb8--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/WearCameraProtocol.kt@@ -0,0 +1,299 @@+package com.vayunmathur.camera.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Wear OS Camera companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:camera-wear`,+ * applicationId `com.vayunmathur.camera`) carries a copy of this file under+ * `com.vayunmathur.camera.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON/frame bytes so a one-sided+ * edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items: [STATE_PATH] phone -> watch (mirrored camera state) and+ *   [THUMBNAIL_PATH] phone -> watch (last-capture JPEG bytes; the media+ *   itself stays on the phone).+ * - Messages: [OP_PATH] watch -> phone (one control op), and+ *   [PREVIEW_FRAME_PATH] phone -> watch (one live viewfinder frame).+ *   Delivery needs a live session; nothing wakes a dead phone process.+ *+ * Live viewfinder transport choice — stated, not implied: WearLink's+ * STREAM primitive is a file transfer (the header commits total size ++ * SHA-256 up front, the receiver verifies the whole stream at close, and+ * STREAM_ACK resume replays a durable file offset). A live preview is an+ * unbounded sequence of ephemeral frames whose total size is unknowable+ * and whose stale frames are worthless, so STREAM cannot carry it without+ * breaking WearLink's contract. The extension therefore lives behind this+ * camera protocol seam, leaving :library:wearlink untouched: each frame+ * is one fire-and-forget MESSAGE (JPEG well under the 256 KiB message+ * cap), the phone keeps only the latest frame, and the watch keeps only+ * the newest sequence. Frames are never queued, resumed or verified.+ */+object WearCameraProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "camera_wear_companion"++    /** Data-item path (phone -> watch): the [WearCameraState] JSON. */+    const val STATE_PATH = "/camera/state"++    /** Data-item path (phone -> watch): last-capture thumbnail JPEG bytes. */+    const val THUMBNAIL_PATH = "/camera/thumbnail"++    /** Message path (watch -> phone): one [WearCameraOp] JSON. */+    const val OP_PATH = "/camera/op"++    /** Message path (phone -> watch): one binary preview frame (see [PreviewFrame]). */+    const val PREVIEW_FRAME_PATH = "/camera/preview-frame"++    /** Widest preview/thumbnail frame the watch is ever sent, in pixels. */+    const val PREVIEW_MAX_WIDTH = 320++    /** Nominal preview rate; the phone adapts inside [MIN_FPS]..[MAX_FPS]. */+    const val PREVIEW_NOMINAL_FPS = 5+    const val PREVIEW_MIN_FPS = 2+    const val PREVIEW_MAX_FPS = 8++    /** JPEG quality bounds for the adaptive preview/thumbnail encoder. */+    const val PREVIEW_JPEG_QUALITY = 60+    const val PREVIEW_MIN_JPEG_QUALITY = 40+    const val PREVIEW_MAX_JPEG_QUALITY = 75++    /** Encoded preview frames larger than this lower the next quality step. */+    const val PREVIEW_LARGE_FRAME_BYTES = 24_000++    /**+     * Modes the watch may switch to remotely. PANORAMA/PHOTOSPHERE are+     * excluded: both need an on-phone guided sweep. SLOW_MO is included —+     * the phone's mode switch itself enforces its back-lens rule.+     */+    val REMOTE_MODES = listOf("PHOTO", "VIDEO", "PORTRAIT", "TIMELAPSE", "CINEMATIC", "SLOW_MO")++    /** Modes whose shutter action records video rather than a still. */+    val VIDEO_MODES = setOf("VIDEO", "TIMELAPSE", "CINEMATIC", "SLOW_MO")++    /** Shutter-timer options (seconds) the watch may set; 0 is off. */+    val TIMER_OPTIONS_SECONDS = listOf(0, 1, 3, 5, 10)++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** Mirrored phone-camera state, published at [WearCameraProtocol.STATE_PATH]. */+@Serializable+data class WearCameraState(+    /** Phone mode name (CameraMode.name), including non-remote modes. */+    val mode: String = "PHOTO",+    /** Modes the watch may switch to (see [WearCameraProtocol.REMOTE_MODES]). */+    val remoteModes: List<String> = WearCameraProtocol.REMOTE_MODES,+    val frontLens: Boolean = false,+    val zoomRatio: Float = 1f,+    /** Selectable zoom preset ratios, ascending (the phone's zoom-bar levels). */+    val zoomPresets: List<Float> = listOf(1f),+    val zoomMin: Float = 1f,+    val zoomMax: Float = 1f,+    /** FlashMode.name: ON, OFF or AUTO. */+    val flash: String = "OFF",+    val hasFlashUnit: Boolean = true,+    val torch: Boolean = false,+    val timerSeconds: Int = 0,+    val timerCountdown: Int = 0,+    val recording: Boolean = false,+    val recordingSeconds: Long = 0L,+    val capturing: Boolean = false,+    /** True while the phone is streaming preview frames to the watch. */+    val previewStreaming: Boolean = false,+    /** Epoch millis of the last landed capture, 0 when none this session. */+    val lastCaptureAtMillis: Long = 0L,+    /** "PHOTO" or "VIDEO" for the last capture, empty when none. */+    val lastCaptureKind: String = "",+)++/** Kind of a watch-originated camera control. */+@Serializable+enum class WearOpKind {+    SHUTTER,+    RECORD_TOGGLE,+    SET_MODE,+    SET_ZOOM,+    ZOOM_PRESET,+    SET_FLASH,+    SET_TORCH,+    FLIP_LENS,+    SET_TIMER,+    PREVIEW_START,+    PREVIEW_STOP,+}++/** One watch-originated control, as [WearCameraProtocol.OP_PATH]. Unused fields keep defaults. */+@Serializable+data class WearCameraOp(+    val kind: WearOpKind,+    val mode: String = "",+    val zoomRatio: Float = 1f,+    val zoomPresetIndex: Int = -1,+    val flash: String = "",+    val torch: Boolean = false,+    val timerSeconds: Int = 0,+)++/** Whether a planned op may run against the mirrored state, and why not when it may not. */+sealed interface WearOpDecision {+    data object Apply : WearOpDecision+    data class Reject(val reason: String) : WearOpDecision+}++/**+ * Pure op gate, shared by the phone (authoritative, against live state)+ * and testable without a camera: mode/lens/zoom changes rebind the phone+ * session, so they are refused while recording (the phone's own mode/lens+ * actions gate the same way); unknown modes/flash values and out-of-set+ * timers are refused rather than guessed at. The phone re-checks against+ * its live ViewModel after planning, so a stale watch state never forces+ * an unsafe op — the mirrored state corrects the watch on the next publish.+ */+fun planWearCameraOp(op: WearCameraOp, state: WearCameraState): WearOpDecision = when (op.kind) {+    WearOpKind.SHUTTER, WearOpKind.RECORD_TOGGLE, WearOpKind.PREVIEW_START, WearOpKind.PREVIEW_STOP ->+        WearOpDecision.Apply+    WearOpKind.SET_TORCH -> WearOpDecision.Apply+    WearOpKind.SET_MODE -> when {+        op.mode !in WearCameraProtocol.REMOTE_MODES -> WearOpDecision.Reject("mode not remote-switchable")+        state.recording && op.mode != state.mode -> WearOpDecision.Reject("recording in progress")+        else -> WearOpDecision.Apply+    }+    WearOpKind.FLIP_LENS -> when {+        state.recording -> WearOpDecision.Reject("recording in progress")+        state.mode == "SLOW_MO" -> WearOpDecision.Reject("slo-mo is back-lens only")+        else -> WearOpDecision.Apply+    }+    WearOpKind.SET_ZOOM, WearOpKind.ZOOM_PRESET ->+        if (state.mode == "PANORAMA" || state.mode == "PHOTOSPHERE") {+            WearOpDecision.Reject("zoom locked in this mode")+        } else {+            WearOpDecision.Apply+        }+    WearOpKind.SET_FLASH ->+        if (op.flash in setOf("ON", "OFF", "AUTO")) WearOpDecision.Apply+        else WearOpDecision.Reject("unknown flash mode")+    WearOpKind.SET_TIMER ->+        if (op.timerSeconds in WearCameraProtocol.TIMER_OPTIONS_SECONDS) WearOpDecision.Apply+        else WearOpDecision.Reject("unsupported timer")+}++/** Clamps a requested zoom ratio into the mirrored range; non-finite requests become the current ratio. */+fun clampWearZoom(requested: Float, state: WearCameraState): Float =+    if (!requested.isFinite()) state.zoomRatio+    else requested.coerceIn(state.zoomMin, state.zoomMax)++/** The preset ratio for [index], or null when the index is stale (presets changed under it). */+fun wearZoomPreset(state: WearCameraState, index: Int): Float? = state.zoomPresets.getOrNull(index)++/**+ * One live viewfinder frame on [WearCameraProtocol.PREVIEW_FRAME_PATH]:+ * a fixed 20-byte header (`WCF1`, sequence, timestamp, size, rotation)+ * followed by the JPEG bytes. The sequence lets the watch drop stale+ * frames; nothing is ever retransmitted.+ */+object PreviewFrame {+    const val HEADER_BYTES = 20+    private val MAGIC = byteArrayOf('W'.code.toByte(), 'C'.code.toByte(), 'F'.code.toByte(), '1'.code.toByte())++    fun encode(sequence: Long, timestampMillis: Long, width: Int, height: Int, rotationDegrees: Int, jpeg: ByteArray): ByteArray {+        val out = ByteArray(HEADER_BYTES + jpeg.size)+        MAGIC.copyInto(out)+        writeInt(out, 4, (sequence and 0xFFFF_FFFFL).toInt())+        writeInt(out, 8, (timestampMillis and 0xFFFF_FFFFL).toInt())+        writeShort(out, 12, width)+        writeShort(out, 14, height)+        writeShort(out, 16, rotationDegrees)+        writeShort(out, 18, 0)+        jpeg.copyInto(out, HEADER_BYTES)+        return out+    }++    /** Decoded header plus the JPEG slice; null on any malformed input. */+    fun decode(body: ByteArray): Decoded? {+        if (body.size <= HEADER_BYTES) return null+        if (!MAGIC.indices.all { body[it] == MAGIC[it] }) return null+        val width = readShort(body, 12)+        val height = readShort(body, 14)+        if (width <= 0 || height <= 0) return null+        return Decoded(+            sequence = readInt(body, 4).toLong() and 0xFFFF_FFFFL,+            timestampMillis = readInt(body, 8).toLong() and 0xFFFF_FFFFL,+            width = width,+            height = height,+            rotationDegrees = readShort(body, 16),+            jpeg = body.copyOfRange(HEADER_BYTES, body.size),+        )+    }++    data class Decoded(+        val sequence: Long,+        val timestampMillis: Long,+        val width: Int,+        val height: Int,+        val rotationDegrees: Int,+        val jpeg: ByteArray,+    ) {+        override fun equals(other: Any?): Boolean {+            if (this === other) return true+            if (other !is Decoded) return false+            return sequence == other.sequence && timestampMillis == other.timestampMillis &&+                width == other.width && height == other.height &&+                rotationDegrees == other.rotationDegrees && jpeg.contentEquals(other.jpeg)+        }++        override fun hashCode(): Int {+            var r = sequence.hashCode()+            r = 31 * r + timestampMillis.hashCode()+            r = 31 * r + width+            r = 31 * r + height+            r = 31 * r + rotationDegrees+            r = 31 * r + jpeg.contentHashCode()+            return r+        }+    }++    private fun writeInt(out: ByteArray, offset: Int, value: Int) {+        out[offset] = (value ushr 24).toByte()+        out[offset + 1] = (value ushr 16).toByte()+        out[offset + 2] = (value ushr 8).toByte()+        out[offset + 3] = value.toByte()+    }++    private fun readInt(body: ByteArray, offset: Int): Int =+        ((body[offset].toInt() and 0xFF) shl 24) or ((body[offset + 1].toInt() and 0xFF) shl 16) or+            ((body[offset + 2].toInt() and 0xFF) shl 8) or (body[offset + 3].toInt() and 0xFF)++    private fun writeShort(out: ByteArray, offset: Int, value: Int) {+        out[offset] = (value ushr 8).toByte()+        out[offset + 1] = value.toByte()+    }++    private fun readShort(body: ByteArray, offset: Int): Int =+        ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF)+}++/** Serialises [state] for the state data item (the golden-pinned wire form). */+fun encodeWearCameraState(state: WearCameraState): ByteArray =+    WearCameraProtocol.json.encodeToString(state).encodeToByteArray()++/** Parses a state data item; null when malformed (the watch keeps its last state). */+fun decodeWearCameraState(body: ByteArray): WearCameraState? = runCatching {+    WearCameraProtocol.json.decodeFromString<WearCameraState>(body.decodeToString())+}.getOrNull()++/** Serialises [op] for the op message (the golden-pinned wire form). */+fun encodeWearCameraOp(op: WearCameraOp): ByteArray =+    WearCameraProtocol.json.encodeToString(op).encodeToByteArray()++/** Parses an op message; null when malformed (the phone ignores it). */+fun decodeWearCameraOp(body: ByteArray): WearCameraOp? = runCatching {+    WearCameraProtocol.json.decodeFromString<WearCameraOp>(body.decodeToString())+}.getOrNull()
camera/src/main/java/com/vayunmathur/camera/domain/WearPreviewPipeline.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/WearPreviewPipeline.kt b/camera/src/main/java/com/vayunmathur/camera/domain/WearPreviewPipeline.ktnew file mode 100644index 0000000000..bd97e34bd9--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/WearPreviewPipeline.kt@@ -0,0 +1,184 @@+package com.vayunmathur.camera.domain++/**+ * Pure live-viewfinder pipeline for the watch preview: downscale maths,+ * the latest-frame-only hand-off, the adaptive rate controller and the+ * encode step behind a fakeable seam. No Android types here — the phone+ * feeds ARGB pixels from its existing Camera2 analysis stream (via+ * Yuv420ToArgb) and the platform layer supplies the real JPEG encoder.+ *+ * Ordering guarantee (tested): pixels are downscaled to watch size FIRST+ * and encoded once at that size. The full-size analysis frame is never+ * encoded-then-shrunk, which would waste the analysis thread and the+ * RFCOMM link on pixels the watch cannot show.+ */++/** Watch-sized output dimensions for a source frame; never upscales. */+fun previewDimensions(srcWidth: Int, srcHeight: Int, maxWidth: Int = WearCameraProtocol.PREVIEW_MAX_WIDTH): Pair<Int, Int> {+    if (srcWidth <= 0 || srcHeight <= 0) return 1 to 1+    if (srcWidth <= maxWidth) return srcWidth to srcHeight+    val scaledHeight = (srcHeight.toLong() * maxWidth / srcWidth).toInt().coerceAtLeast(1)+    return maxWidth to scaledHeight+}++/** Nearest-neighbour ARGB downscale (upscale requests return a copy at source size). */+fun downscaleArgb(argb: IntArray, srcWidth: Int, srcHeight: Int, dstWidth: Int, dstHeight: Int): IntArray {+    require(argb.size >= srcWidth * srcHeight) { "pixel buffer smaller than frame" }+    if (dstWidth == srcWidth && dstHeight == srcHeight) return argb.copyOf(srcWidth * srcHeight)+    val out = IntArray(dstWidth * dstHeight)+    for (y in 0 until dstHeight) {+        val srcY = y * srcHeight / dstHeight+        for (x in 0 until dstWidth) {+            val srcX = x * srcWidth / dstWidth+            out[y * dstWidth + x] = argb[srcY * srcWidth + srcX]+        }+    }+    return out+}++/** JPEG encoder seam: the platform supplies Bitmap.compress; tests record calls. */+interface PreviewJpegEncoder {+    fun encode(argb: IntArray, width: Int, height: Int, quality: Int): ByteArray+}++/** One encoded preview frame, ready for [PreviewFrame.encode]. */+data class EncodedPreview(val jpeg: ByteArray, val width: Int, val height: Int, val quality: Int) {+    override fun equals(other: Any?): Boolean =+        other is EncodedPreview && width == other.width && height == other.height &&+            quality == other.quality && jpeg.contentEquals(other.jpeg)++    override fun hashCode(): Int {+        var r = jpeg.contentHashCode()+        r = 31 * r + width+        r = 31 * r + height+        r = 31 * r + quality+        return r+    }+}++/**+ * Downscale-then-encode processor with size-adaptive quality: an encoded+ * frame over [WearCameraProtocol.PREVIEW_LARGE_FRAME_BYTES] steps the+ * next quality down (floor [WearCameraProtocol.PREVIEW_MIN_JPEG_QUALITY]),+ * a comfortably small one steps it back up (ceiling+ * [WearCameraProtocol.PREVIEW_MAX_JPEG_QUALITY]). One encode per frame,+ * always at the downscaled size.+ */+class PreviewFrameProcessor(private val encoder: PreviewJpegEncoder) {+    var nextQuality: Int = WearCameraProtocol.PREVIEW_JPEG_QUALITY+        private set++    fun process(argb: IntArray, srcWidth: Int, srcHeight: Int): EncodedPreview? {+        if (srcWidth <= 0 || srcHeight <= 0 || argb.size < srcWidth * srcHeight) return null+        val (width, height) = previewDimensions(srcWidth, srcHeight)+        val pixels = downscaleArgb(argb, srcWidth, srcHeight, width, height)+        val quality = nextQuality+        val jpeg = encoder.encode(pixels, width, height, quality)+        nextQuality = when {+            jpeg.size > WearCameraProtocol.PREVIEW_LARGE_FRAME_BYTES ->+                (quality - QUALITY_STEP).coerceAtLeast(WearCameraProtocol.PREVIEW_MIN_JPEG_QUALITY)+            jpeg.size < WearCameraProtocol.PREVIEW_LARGE_FRAME_BYTES / 2 ->+                (quality + QUALITY_STEP).coerceAtMost(WearCameraProtocol.PREVIEW_MAX_JPEG_QUALITY)+            else -> quality+        }+        return EncodedPreview(jpeg, width, height, quality)+    }++    private companion object {+        const val QUALITY_STEP = 5+    }+}++/**+ * Latest-frame-only hand-off between the analysis thread (producer) and+ * the preview pump (consumer): at most one frame waits. An offer made+ * while a frame is still waiting is dropped and counted — the producer+ * (the phone's capture/analysis path) never blocks and never queues+ * stale frames behind a slow encode or a slow link.+ */+class LatestOnlySlot<T> {+    private var held: T? = null++    var droppedCount: Long = 0L+        private set++    var offeredCount: Long = 0L+        private set++    val isOccupied: Boolean get() = held != null++    /** Stores [frame] when the slot is free; returns false (drop) when occupied. */+    @Synchronized+    fun offer(frame: T): Boolean {+        offeredCount+++        if (held != null) {+            droppedCount+++            return false+        }+        held = frame+        return true+    }++    /** Takes the waiting frame, freeing the slot; null when empty. */+    @Synchronized+    fun take(): T? {+        val frame = held+        held = null+        return frame+    }++    @Synchronized+    fun clear() {+        held = null+    }+}++/**+ * Adaptive preview rate: starts at the nominal rate, backs off toward+ * [WearCameraProtocol.PREVIEW_MIN_FPS] when a frame's encode+send takes+ * longer than the frame interval (the link is the bottleneck), and+ * recovers toward [WearCameraProtocol.PREVIEW_MAX_FPS] after sustained+ * fast sends. Deterministic integer maths so tests pin the adaptation.+ */+class AdaptivePreviewRate {+    var fps: Int = WearCameraProtocol.PREVIEW_NOMINAL_FPS+        private set++    private var fastStreak = 0++    val intervalMillis: Long get() = 1_000L / fps++    /** Records one frame's encode+send duration and adapts the rate. */+    fun onFrameSent(durationMillis: Long) {+        when {+            durationMillis > intervalMillis -> {+                fps = (fps - 1).coerceAtLeast(WearCameraProtocol.PREVIEW_MIN_FPS)+                fastStreak = 0+            }+            durationMillis * FAST_FACTOR < intervalMillis -> {+                fastStreak+++                if (fastStreak >= FAST_STREAK_TO_SPEED_UP) {+                    fps = (fps + 1).coerceAtMost(WearCameraProtocol.PREVIEW_MAX_FPS)+                    fastStreak = 0+                }+            }+            else -> fastStreak = 0+        }+    }++    /** A dropped/failed send backs the rate off one step immediately. */+    fun onSendFailed() {+        fps = (fps - 1).coerceAtLeast(WearCameraProtocol.PREVIEW_MIN_FPS)+        fastStreak = 0+    }++    fun reset() {+        fps = WearCameraProtocol.PREVIEW_NOMINAL_FPS+        fastStreak = 0+    }++    private companion object {+        const val FAST_FACTOR = 2L+        const val FAST_STREAK_TO_SPEED_UP = 4+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.ktindex 640667f2e9..125472d986 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt@@ -24,6 +24,9 @@ internal fun CameraViewModel.camera2AnalysisConsumer(): AnalysisConsumer = /** Routes one Camera2 analysis frame to the installed mode sink. */ internal fun CameraViewModel.dispatchAnalysisFrame(frame: AnalysisFrame) {     analysisSink?.invoke(frame)+    // Wear viewfinder tap: latest-only and failure-isolated, so a watch+    // preview can never stall or crash the capture/analysis path.+    wearPreviewTap?.let { tap -> runCatching { tap(frame) } } }  /** Installs (or clears, with null) the per-mode analysis sink. */
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex 57eb91d89a..0bb1272a01 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -523,6 +523,15 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     /** Per-mode Camera2 analysis sink; see Camera2AnalysisGlue. */     @Volatile internal var analysisSink: ((com.vayunmathur.camera.platform.camera2.AnalysisFrame) -> Unit)? = null +    /**+     * Secondary analysis tap for the Wear OS live viewfinder+     * (WearCameraSync): invoked after the mode sink for every frame, it+     * must never block or throw into the analysis path — it only offers+     * the frame to a latest-only slot. Null unless a watch asked for the+     * preview.+     */+    @Volatile internal var wearPreviewTap: ((com.vayunmathur.camera.platform.camera2.AnalysisFrame) -> Unit)? = null+     /** True once the photo session's use cases (incl. ImageAnalysis) are bound. */     internal val photoSessionActiveMutable = MutableStateFlow(false)     val photoSessionActive = photoSessionActiveMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt b/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.ktnew file mode 100644index 0000000000..5337c0e7b1--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/WearCameraSync.kt@@ -0,0 +1,373 @@+package com.vayunmathur.camera.platform++import android.content.Context+import android.graphics.Bitmap+import android.hardware.camera2.CameraMetadata+import com.vayunmathur.camera.data.setFlashMode+import com.vayunmathur.camera.data.setTimerDuration+import com.vayunmathur.camera.data.toggleTorch+import com.vayunmathur.camera.domain.AdaptivePreviewRate+import com.vayunmathur.camera.domain.LatestOnlySlot+import com.vayunmathur.camera.domain.PreviewFrame+import com.vayunmathur.camera.domain.PreviewFrameProcessor+import com.vayunmathur.camera.domain.PreviewJpegEncoder+import com.vayunmathur.camera.domain.WearCameraOp+import com.vayunmathur.camera.domain.WearCameraProtocol+import com.vayunmathur.camera.domain.WearCameraState+import com.vayunmathur.camera.domain.WearOpDecision+import com.vayunmathur.camera.domain.WearOpKind+import com.vayunmathur.camera.domain.Yuv420ToArgb+import com.vayunmathur.camera.domain.clampWearZoom+import com.vayunmathur.camera.domain.decodeWearCameraOp+import com.vayunmathur.camera.domain.encodeWearCameraState+import com.vayunmathur.camera.domain.planWearCameraOp+import com.vayunmathur.camera.domain.previewDimensions+import com.vayunmathur.camera.domain.wearZoomPreset+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import java.io.ByteArrayOutputStream+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * The camera control seam the watch ops execute against: every call is one+ * existing CameraViewModel action (mode/lens/zoom/flash/timer setters,+ * takePhoto/toggleRecording), so a remote op can do nothing the on-screen+ * controls cannot. Tests drive this interface with a fake instead of a+ * camera.+ */+interface WearCameraControls {+    fun shutter()+    fun toggleRecording()+    fun setMode(modeName: String)+    fun setZoom(ratio: Float)+    fun setFlash(flashName: String)+    fun setTorch(enabled: Boolean)+    fun flipLens()+    fun setTimer(seconds: Int)+}++/** [WearCameraControls] over the live [CameraViewModel] extension actions. */+class ViewModelWearControls(private val viewModel: CameraViewModel) : WearCameraControls {+    override fun shutter() {+        if (viewModel.cameraMode.value.name in WearCameraProtocol.VIDEO_MODES) {+            viewModel.toggleRecording()+        } else {+            viewModel.takePhoto()+        }+    }++    override fun toggleRecording() = viewModel.toggleRecording()++    override fun setMode(modeName: String) {+        val mode = runCatching { CameraMode.valueOf(modeName) }.getOrNull() ?: return+        viewModel.switchCameraMode(mode)+    }++    override fun setZoom(ratio: Float) = viewModel.setZoomRatio(ratio)++    override fun setFlash(flashName: String) {+        val mode = runCatching { FlashMode.valueOf(flashName) }.getOrNull() ?: return+        viewModel.setFlashMode(mode)+        viewModel.applyImageCaptureFlashMode()+    }++    override fun setTorch(enabled: Boolean) {+        if (viewModel.torchEnabled.value != enabled) viewModel.toggleTorch()+    }++    override fun flipLens() = viewModel.flipCamera()++    override fun setTimer(seconds: Int) {+        val duration = TimerDuration.entries.firstOrNull { it.seconds == seconds } ?: return+        viewModel.setTimerDuration(duration)+    }+}++/** Executes one planned op; rejects are logged and mirrored back via state, never faked. */+fun executeWearOp(op: WearCameraOp, state: WearCameraState, controls: WearCameraControls): WearOpDecision {+    val decision = planWearCameraOp(op, state)+    if (decision is WearOpDecision.Reject) return decision+    when (op.kind) {+        WearOpKind.SHUTTER -> controls.shutter()+        WearOpKind.RECORD_TOGGLE -> controls.toggleRecording()+        WearOpKind.SET_MODE -> controls.setMode(op.mode)+        WearOpKind.SET_ZOOM -> controls.setZoom(clampWearZoom(op.zoomRatio, state))+        WearOpKind.ZOOM_PRESET -> wearZoomPreset(state, op.zoomPresetIndex)?.let { controls.setZoom(it) }+        WearOpKind.SET_FLASH -> controls.setFlash(op.flash)+        WearOpKind.SET_TORCH -> controls.setTorch(op.torch)+        WearOpKind.FLIP_LENS -> controls.flipLens()+        WearOpKind.SET_TIMER -> controls.setTimer(op.timerSeconds)+        WearOpKind.PREVIEW_START, WearOpKind.PREVIEW_STOP -> Unit // handled by the sync, not the camera+    }+    return decision+}++/** Builds the mirrored state from the ViewModel's public flows. */+fun CameraViewModel.wearCameraState(+    previewStreaming: Boolean,+    lastCaptureAtMillis: Long = 0L,+    lastCaptureKind: String = "",+): WearCameraState {+    val (zoomMin, zoomMax) = currentZoomRange()+    return WearCameraState(+        mode = cameraMode.value.name,+        frontLens = lensFacing.value == CameraMetadata.LENS_FACING_FRONT,+        zoomRatio = zoomRatio.value,+        zoomPresets = availableZoomLevels.value.map { it.second },+        zoomMin = zoomMin,+        zoomMax = zoomMax,+        flash = flashMode.value.name,+        hasFlashUnit = hasFlashUnit.value,+        torch = torchEnabled.value,+        timerSeconds = timerDuration.value.seconds,+        timerCountdown = timerCountdown.value,+        recording = isRecording.value || camera2Recording.value,+        recordingSeconds = recordingDurationSec.value,+        capturing = isCapturing.value,+        previewStreaming = previewStreaming,+        lastCaptureAtMillis = lastCaptureAtMillis,+        lastCaptureKind = lastCaptureKind,+    )+}++/** Android JPEG encoder behind the pure pipeline seam (Bitmap.compress). */+private object BitmapPreviewEncoder : PreviewJpegEncoder {+    override fun encode(argb: IntArray, width: Int, height: Int, quality: Int): ByteArray {+        val bitmap = Bitmap.createBitmap(argb, width, height, Bitmap.Config.ARGB_8888)+        val out = ByteArrayOutputStream()+        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)+        bitmap.recycle()+        return out.toByteArray()+    }+}++/** One raw analysis frame waiting for the preview pump (sensor-oriented ARGB). */+private class RawPreviewFrame(val argb: IntArray, val width: Int, val height: Int, val rotationDegrees: Int)++/**+ * Phone side of the Camera watch companion over WearLink (RFCOMM,+ * :library:wearlink): mirrored state + last-capture thumbnail are data+ * items, watch ops are messages executed through [ViewModelWearControls],+ * and the live viewfinder streams analysis frames as preview messages.+ *+ * Viewfinder design point: frames come from the phone's existing Camera2+ * analysis stream (small frames already), are converted and downscaled to+ * at most [WearCameraProtocol.PREVIEW_MAX_WIDTH] px wide, JPEG-encoded+ * once at that size, and sent at an adaptive+ * [WearCameraProtocol.PREVIEW_MIN_FPS]..[WearCameraProtocol.PREVIEW_MAX_FPS]+ * fps. The hand-off is latest-frame-only ([LatestOnlySlot]): the analysis+ * tap never blocks, converts only while the slot is free, and drops+ * (counted) otherwise, so the phone's capture/analysis path cannot stall+ * behind the watch link. Captured media stays on the phone; only the+ * thumbnail crosses the link. Nothing here wakes a dead process.+ */+class WearCameraSync private constructor(context: Context) {++    companion object {+        private const val TAG = "WearCameraSync"+        private const val STATE_PUBLISH_INTERVAL_MS = 250L+        private const val PREVIEW_POLL_MS = 20L+        private const val NANOS_PER_MS = 1_000_000L++        @Volatile+        private var instance: WearCameraSync? = null++        /** The process-wide sync (activity/view-model must agree on one). */+        fun get(context: Context): WearCameraSync = instance ?: synchronized(this) {+            instance ?: WearCameraSync(context.applicationContext).also { instance = it }+        }+    }++    private val appContext = context.applicationContext+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    /** Set by MainActivity once the camera ViewModel exists. */+    @Volatile+    var viewModel: CameraViewModel? = null++    private val _linkState = MutableStateFlow<WearLinkState>(WearLinkState.Stopped)++    @Volatile+    private var previewWanted = false+    private val previewSlot = LatestOnlySlot<RawPreviewFrame>()+    private val previewRate = AdaptivePreviewRate()+    private val previewProcessor = PreviewFrameProcessor(BitmapPreviewEncoder)+    private var previewJob: Job? = null+    private var stateJob: Job? = null+    private var frameSequence = 0L+    private var lastThumbnail: Bitmap? = null++    @Volatile+    private var lastCaptureAtMillis = 0L++    @Volatile+    private var lastCaptureKind = "" ++    private val listener = object : WearLinkListener {+        override fun onMessage(path: String, body: ByteArray) {+            if (path != WearCameraProtocol.OP_PATH) return+            val op = decodeWearCameraOp(body) ?: run {+                Log.status(TAG, "ignoring malformed wear op")+                return+            }+            when (op.kind) {+                WearOpKind.PREVIEW_START -> startPreview()+                WearOpKind.PREVIEW_STOP -> stopPreview()+                else -> {+                    val vm = viewModel ?: return+                    scope.launch {+                        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind) }+                        val decision = withContext(Dispatchers.Main) {+                            executeWearOp(op, state, ViewModelWearControls(vm))+                        }+                        if (decision is WearOpDecision.Reject) {+                            Log.status(TAG, "rejected wear op ${op.kind}: ${decision.reason}")+                        }+                        publishState()+                    }+                }+            }+        }+    }++    private val node = WearLinkNode(appContext, WearCameraProtocol.CAPABILITY, listener)+    private var started = false++    fun start() {+        if (started) return+        started = true+        scope.launch {+            node.state.collect { linkState ->+                _linkState.value = linkState+                if (linkState is WearLinkState.Connected) {+                    publishState()+                    publishThumbnail(lastThumbnail)+                } else if (previewWanted) {+                    // Link down: the stream stops honestly; the watch must+                    // ask again on the next session.+                    stopPreview()+                }+            }+        }+        node.start()+        startStateLoop()+    }++    // -- Mirrored state + thumbnail -------------------------------------------++    private fun startStateLoop() {+        if (stateJob != null) return+        stateJob = scope.launch {+            val vm = viewModel+            if (vm != null) {+                launch { vm.galleryThumbnail.collect { thumb -> onThumbnailChanged(thumb) } }+            }+            while (true) {+                publishState()+                delay(STATE_PUBLISH_INTERVAL_MS)+            }+        }+    }++    private suspend fun publishState() {+        val vm = viewModel ?: return+        if (node.state.value !is WearLinkState.Connected) return+        val state = withContext(Dispatchers.Main) { vm.wearCameraState(previewWanted, lastCaptureAtMillis, lastCaptureKind) }+        node.putData(WearCameraProtocol.STATE_PATH, encodeWearCameraState(state))+    }++    private fun onThumbnailChanged(thumb: Bitmap?) {+        if (thumb == null || thumb === lastThumbnail) return+        lastThumbnail = thumb+        val vm = viewModel+        if (vm != null) {+            lastCaptureAtMillis = System.currentTimeMillis()+            lastCaptureKind =+                if (vm.cameraMode.value.name in WearCameraProtocol.VIDEO_MODES) "VIDEO" else "PHOTO"+        }+        scope.launch { publishThumbnail(thumb) }+    }++    private suspend fun publishThumbnail(thumb: Bitmap?) {+        if (thumb == null) return+        if (node.state.value !is WearLinkState.Connected) return+        val (width, height) = previewDimensions(thumb.width, thumb.height)+        val scaled = if (width == thumb.width) thumb else Bitmap.createScaledBitmap(thumb, width, height, true)+        val out = ByteArrayOutputStream()+        scaled.compress(Bitmap.CompressFormat.JPEG, WearCameraProtocol.PREVIEW_JPEG_QUALITY, out)+        if (scaled !== thumb) scaled.recycle()+        node.putData(WearCameraProtocol.THUMBNAIL_PATH, out.toByteArray())+    }++    // -- Live viewfinder --------------------------------------------------------++    private fun startPreview() {+        val vm = viewModel ?: return+        if (previewWanted) return+        previewWanted = true+        previewRate.reset()+        previewSlot.clear()+        vm.wearPreviewTap = { frame ->+            // Latest-only: convert only while the pump is idle, so the+            // analysis thread never queues frames behind a slow link.+            if (previewWanted && !previewSlot.isOccupied) {+                val argb = Yuv420ToArgb.convert(frame.planes, frame.width, frame.height)+                if (argb != null) {+                    previewSlot.offer(RawPreviewFrame(argb, frame.width, frame.height, frame.rotationDegrees))+                }+            }+            Unit+        }+        previewJob = scope.launch { previewPump() }+        scope.launch { publishState() }+    }++    private fun stopPreview() {+        previewWanted = false+        viewModel?.wearPreviewTap = null+        previewJob?.cancel()+        previewJob = null+        previewSlot.clear()+        scope.launch { publishState() }+    }++    private suspend fun previewPump() {+        while (previewWanted) {+            val raw = previewSlot.take()+            if (raw == null) {+                delay(PREVIEW_POLL_MS)+                continue+            }+            val startedAt = System.nanoTime()+            val encoded = previewProcessor.process(raw.argb, raw.width, raw.height)+            if (encoded == null) {+                previewRate.onSendFailed()+                continue+            }+            frameSequence+++            val body = PreviewFrame.encode(+                sequence = frameSequence,+                timestampMillis = System.currentTimeMillis(),+                width = encoded.width,+                height = encoded.height,+                rotationDegrees = raw.rotationDegrees,+                jpeg = encoded.jpeg,+            )+            val sent = node.sendMessage(WearCameraProtocol.PREVIEW_FRAME_PATH, body)+            val durationMs = (System.nanoTime() - startedAt) / NANOS_PER_MS+            if (sent) previewRate.onFrameSent(durationMs) else previewRate.onSendFailed()+            val waitMs = (previewRate.intervalMillis - durationMs).coerceAtLeast(0L)+            if (waitMs > 0L) delay(waitMs)+        }+    }++}
camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.ktnew file mode 100644index 0000000000..c0b7f42038--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/WearCameraProtocolTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class WearCameraProtocolTest {++    @Test+    fun goldenStateJson() {+        val state = WearCameraState(+            mode = "VIDEO",+            frontLens = true,+            zoomRatio = 2f,+            zoomPresets = listOf(1f, 2f),+            zoomMin = 0.5f,+            zoomMax = 10f,+            flash = "AUTO",+            torch = true,+            timerSeconds = 3,+            recording = true,+            recordingSeconds = 65L,+            previewStreaming = true,+            lastCaptureAtMillis = 7L,+            lastCaptureKind = "PHOTO",+        )+        assertEquals(+            """{"mode":"VIDEO","frontLens":true,"zoomRatio":2.0,"zoomPresets":[1.0,2.0],"zoomMin":0.5,""" ++                """"zoomMax":10.0,"flash":"AUTO","torch":true,"timerSeconds":3,"recording":true,""" ++                """"recordingSeconds":65,"previewStreaming":true,"lastCaptureAtMillis":7,"lastCaptureKind":"PHOTO"}""",+            encodeWearCameraState(state).decodeToString(),+        )+    }++    @Test+    fun goldenOpJson() {+        val op = WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = 2.5f)+        assertEquals(+            """{"kind":"SET_ZOOM","zoomRatio":2.5}""",+            encodeWearCameraOp(op).decodeToString(),+        )+    }++    @Test+    fun goldenPreviewFrameHeader() {+        val frame = PreviewFrame.encode(+            sequence = 0x01020304L,+            timestampMillis = 0x05060708L,+            width = 320,+            height = 240,+            rotationDegrees = 90,+            jpeg = byteArrayOf(9, 8, 7),+        )+        assertEquals(+            listOf(+                'W'.code, 'C'.code, 'F'.code, '1'.code,+                1, 2, 3, 4, 5, 6, 7, 8, 1, 64, 0, 240, 0, 90, 0, 0, 9, 8, 7,+            ),+            frame.map { it.toInt() and 0xFF },+        )+        val decoded = PreviewFrame.decode(frame)+        assertNotNull(decoded)+        assertEquals(0x01020304L, decoded.sequence)+        assertEquals(320, decoded.width)+        assertEquals(240, decoded.height)+        assertEquals(90, decoded.rotationDegrees)+        assertTrue(byteArrayOf(9, 8, 7).contentEquals(decoded.jpeg))+    }++    @Test+    fun stateAndOpRoundTripAndMalformedIgnored() {+        val state = WearCameraState(mode = "PORTRAIT", zoomRatio = 1.5f)+        assertEquals(state, decodeWearCameraState(encodeWearCameraState(state)))+        val op = WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = 5)+        assertEquals(op, decodeWearCameraOp(encodeWearCameraOp(op)))+        assertNull(decodeWearCameraState("not json".encodeToByteArray()))+        assertNull(decodeWearCameraOp(byteArrayOf(0)))+        assertNull(PreviewFrame.decode(byteArrayOf(1, 2, 3)))+        assertNull(PreviewFrame.decode(PreviewFrame.encode(1L, 1L, 0, 240, 0, byteArrayOf(1))))+    }++    @Test+    fun planRejectsNonRemoteModesAndRecordingSwitches() {+        val idle = WearCameraState(mode = "PHOTO")+        assertEquals(+            WearOpDecision.Apply,+            planWearCameraOp(WearCameraOp(WearOpKind.SET_MODE, mode = "VIDEO"), idle),+        )+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.SET_MODE, mode = "PANORAMA"), idle)+                is WearOpDecision.Reject,+        )+        val recording = idle.copy(recording = true)+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.SET_MODE, mode = "VIDEO"), recording)+                is WearOpDecision.Reject,+        )+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.FLIP_LENS), recording) is WearOpDecision.Reject,+        )+        // Shutter/record and torch stay live while recording.+        assertEquals(WearOpDecision.Apply, planWearCameraOp(WearCameraOp(WearOpKind.RECORD_TOGGLE), recording))+        assertEquals(+            WearOpDecision.Apply,+            planWearCameraOp(WearCameraOp(WearOpKind.SET_TORCH, torch = true), recording),+        )+    }++    @Test+    fun planValidatesFlashTimerAndZoomLock() {+        val state = WearCameraState(mode = "PHOTO")+        assertEquals(+            WearOpDecision.Apply,+            planWearCameraOp(WearCameraOp(WearOpKind.SET_FLASH, flash = "AUTO"), state),+        )+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.SET_FLASH, flash = "STROBE"), state)+                is WearOpDecision.Reject,+        )+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = 7), state)+                is WearOpDecision.Reject,+        )+        val pano = state.copy(mode = "PANORAMA")+        assertTrue(+            planWearCameraOp(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = 2f), pano)+                is WearOpDecision.Reject,+        )+    }++    @Test+    fun zoomClampAndPresetLookup() {+        val state = WearCameraState(zoomRatio = 1f, zoomPresets = listOf(0.5f, 1f, 2f), zoomMin = 0.5f, zoomMax = 10f)+        assertEquals(10f, clampWearZoom(99f, state))+        assertEquals(0.5f, clampWearZoom(0.1f, state))+        assertEquals(1f, clampWearZoom(Float.NaN, state))+        assertEquals(2f, wearZoomPreset(state, 2))+        assertNull(wearZoomPreset(state, 5))+    }+}
camera/src/test/java/com/vayunmathur/camera/domain/WearPreviewPipelineTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/WearPreviewPipelineTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/WearPreviewPipelineTest.ktnew file mode 100644index 0000000000..29c7026d7e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/WearPreviewPipelineTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class WearPreviewPipelineTest {++    /** Records every encode call so tests can pin size/ordering/quality. */+    private class RecordingEncoder(private val jpegSize: Int = 8) : PreviewJpegEncoder {+        val calls = mutableListOf<Triple<Int, Int, Int>>()++        override fun encode(argb: IntArray, width: Int, height: Int, quality: Int): ByteArray {+            calls += Triple(width, height, quality)+            // The pixels handed over must already be the downscaled frame.+            assertEquals(width * height, argb.size)+            return ByteArray(jpegSize) { 0xFF.toByte() }+        }+    }++    @Test+    fun dimensionsCapWidthAndNeverUpscale() {+        assertEquals(320 to 240, previewDimensions(1280, 960))+        assertEquals(320 to 180, previewDimensions(640, 360))+        assertEquals(320 to 320, previewDimensions(480, 480))+        assertEquals(240 to 180, previewDimensions(240, 180))+        assertEquals(1 to 1, previewDimensions(0, 0))+    }++    @Test+    fun encodeRunsOnceAtDownscaledSizeNeverFullSize() {+        val encoder = RecordingEncoder()+        val processor = PreviewFrameProcessor(encoder)+        val argb = IntArray(1280 * 960) { it }+        val encoded = processor.process(argb, 1280, 960)!!+        assertEquals(320, encoded.width)+        assertEquals(240, encoded.height)+        // Exactly one encode, at watch size — never a full-size encode first.+        assertEquals(listOf(Triple(320, 240, WearCameraProtocol.PREVIEW_JPEG_QUALITY)), encoder.calls)+        assertNull(processor.process(IntArray(3), 1280, 960))+        assertNull(processor.process(argb, 0, 960))+    }++    @Test+    fun downscaleSamplesNearestPixels() {+        // 4x2 -> 2x1 picks columns 0 and 2 of row 0.+        val argb = intArrayOf(10, 11, 12, 13, 20, 21, 22, 23)+        assertEquals(listOf(10, 12), downscaleArgb(argb, 4, 2, 2, 1).toList())+        assertEquals(argb.toList(), downscaleArgb(argb, 4, 2, 4, 2).toList())+    }++    @Test+    fun qualityAdaptsDownOnLargeFramesAndUpOnSmall() {+        val large = PreviewFrameProcessor(RecordingEncoder(jpegSize = WearCameraProtocol.PREVIEW_LARGE_FRAME_BYTES + 1))+        val argb = IntArray(320 * 240)+        large.process(argb, 320, 240)+        assertEquals(WearCameraProtocol.PREVIEW_JPEG_QUALITY - 5, large.nextQuality)++        val small = PreviewFrameProcessor(RecordingEncoder(jpegSize = 100))+        small.process(argb, 320, 240)+        assertEquals(WearCameraProtocol.PREVIEW_JPEG_QUALITY + 5, small.nextQuality)++        // Floor holds under repeated large frames.+        repeat(20) { large.process(argb, 320, 240) }+        assertEquals(WearCameraProtocol.PREVIEW_MIN_JPEG_QUALITY, large.nextQuality)+    }++    @Test+    fun latestOnlySlotDropsWhileOccupiedAndNeverQueues() {+        val slot = LatestOnlySlot<Int>()+        assertTrue(slot.offer(1))+        assertFalse(slot.offer(2))+        assertFalse(slot.offer(3))+        assertEquals(2L, slot.droppedCount)+        assertEquals(3L, slot.offeredCount)+        assertEquals(1, slot.take())+        assertNull(slot.take())+        assertTrue(slot.offer(4))+        assertEquals(4, slot.take())+    }++    @Test+    fun adaptiveRateBacksOffWhenSendExceedsIntervalAndRecovers() {+        val rate = AdaptivePreviewRate()+        assertEquals(WearCameraProtocol.PREVIEW_NOMINAL_FPS, rate.fps)+        // A send slower than the 200 ms interval at 5 fps steps down.+        rate.onFrameSent(durationMillis = 250L)+        assertEquals(4, rate.fps)+        rate.onSendFailed()+        assertEquals(3, rate.fps)+        // Sustained fast sends (under half the interval) recover one step+        // per streak of four, capped at the max.+        repeat(4) { rate.onFrameSent(durationMillis = 10L) }+        assertEquals(4, rate.fps)+        repeat(40) { rate.onFrameSent(durationMillis = 10L) }+        assertEquals(WearCameraProtocol.PREVIEW_MAX_FPS, rate.fps)+        // Floor holds.+        repeat(20) { rate.onSendFailed() }+        assertEquals(WearCameraProtocol.PREVIEW_MIN_FPS, rate.fps)+        assertEquals(500L, rate.intervalMillis)+    }+}
camera/src/test/java/com/vayunmathur/camera/platform/WearCameraOpApplicationTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/WearCameraOpApplicationTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/WearCameraOpApplicationTest.ktnew file mode 100644index 0000000000..f4dc58646b--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/WearCameraOpApplicationTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.domain.WearCameraOp+import com.vayunmathur.camera.domain.WearCameraState+import com.vayunmathur.camera.domain.WearOpDecision+import com.vayunmathur.camera.domain.WearOpKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Op application against the camera's mode/zoom seams, via a recording fake control. */+class WearCameraOpApplicationTest {++    private class FakeControls : WearCameraControls {+        val calls = mutableListOf<String>()++        override fun shutter() { calls += "shutter" }+        override fun toggleRecording() { calls += "record" }+        override fun setMode(modeName: String) { calls += "mode:$modeName" }+        override fun setZoom(ratio: Float) { calls += "zoom:$ratio" }+        override fun setFlash(flashName: String) { calls += "flash:$flashName" }+        override fun setTorch(enabled: Boolean) { calls += "torch:$enabled" }+        override fun flipLens() { calls += "flip" }+        override fun setTimer(seconds: Int) { calls += "timer:$seconds" }+    }++    private val idle = WearCameraState(+        mode = "PHOTO",+        zoomPresets = listOf(0.5f, 1f, 2f, 5f),+        zoomMin = 0.5f,+        zoomMax = 10f,+    )++    @Test+    fun shutterRecordModeZoomAndSettingsApply() {+        val controls = FakeControls()+        assertEquals(WearOpDecision.Apply, executeWearOp(WearCameraOp(WearOpKind.SHUTTER), idle, controls))+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.SET_MODE, mode = "VIDEO"), idle, controls),+        )+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.SET_ZOOM, zoomRatio = 99f), idle, controls),+        )+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.ZOOM_PRESET, zoomPresetIndex = 3), idle, controls),+        )+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.SET_FLASH, flash = "ON"), idle, controls),+        )+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.SET_TORCH, torch = true), idle, controls),+        )+        assertEquals(+            WearOpDecision.Apply,+            executeWearOp(WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = 10), idle, controls),+        )+        assertEquals(WearOpDecision.Apply, executeWearOp(WearCameraOp(WearOpKind.FLIP_LENS), idle, controls))+        // Zoom clamps to the mirrored device range before it reaches the seam.+        assertEquals(+            listOf("shutter", "mode:VIDEO", "zoom:10.0", "zoom:5.0", "flash:ON", "torch:true", "timer:10", "flip"),+            controls.calls,+        )+    }++    @Test+    fun rejectedOpsNeverReachTheCamera() {+        val controls = FakeControls()+        val recording = idle.copy(recording = true)+        assertTrue(+            executeWearOp(WearCameraOp(WearOpKind.SET_MODE, mode = "VIDEO"), recording, controls)+                is WearOpDecision.Reject,+        )+        assertTrue(+            executeWearOp(WearCameraOp(WearOpKind.SET_MODE, mode = "PANORAMA"), idle, controls)+                is WearOpDecision.Reject,+        )+        assertTrue(+            executeWearOp(WearCameraOp(WearOpKind.SET_TIMER, timerSeconds = 7), idle, controls)+                is WearOpDecision.Reject,+        )+        assertEquals(emptyList(), controls.calls)+    }++    @Test+    fun stalePresetIndexIsANoOpNotACrash() {+        val controls = FakeControls()+        val decision = executeWearOp(WearCameraOp(WearOpKind.ZOOM_PRESET, zoomPresetIndex = 99), idle, controls)+        assertEquals(WearOpDecision.Apply, decision)+        assertEquals(emptyList(), controls.calls)+    }++    @Test+    fun previewOpsDoNotTouchCameraControls() {+        val controls = FakeControls()+        executeWearOp(WearCameraOp(WearOpKind.PREVIEW_START), idle, controls)+        executeWearOp(WearCameraOp(WearOpKind.PREVIEW_STOP), idle, controls)+        assertEquals(emptyList(), controls.calls)+    }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex c2aaeebcdd..b87960c8c9 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -129,6 +129,7 @@ include(":weather") include(":weather:wear") project(":weather:wear").projectDir = file("weather-wear") include(":camera")+include(":camera-wear") include(":sdk:openassistant") include(":sdk:games") include(":sdk:cast")