Modern Apps git

← Modern-Apps.git

camera: session streams planned from Camera2 guarantees, first-try

Commit
01f707e7865c78fc5cff9bf7dca58e004756e8d7
Author
Vayun Mathur <[email protected]>
When
2026-11-23 15:33 UTC (12 days ago)
Parents
fefc703
Why the camera never loaded on the Pixel 9 Pro XL: the
lens is HARDWARE_LEVEL FULL (1), whose guaranteed stream
combinations cover preview + JPEG(MAX) + one YUV <=1080p.
The rich first attempt (second JPEG-class JPEG_R, RAW, a
second YUV ring plus analysis) is in NO guaranteed
combination below LEVEL_3, so configure died with
CAMERA_ERROR (3); each death evicted the HAL for seconds,
the ladder burned rungs on open errors, and a stuck latch
parked the UI on manual retry.

StreamSelection.planSessionStreams now plans analytically
from the characteristics: below LEVEL_3 the session is
exactly the richest guaranteed combo (preview <=1080p,
JPEG MAX, one YUV - analysis 1280x960 when consumed,
else the ring); LEVEL_3 keeps the rich selection. The
degrade ladder remains as a safety net only. Analysis
plane-stats moved off the capture thread onto a dedicated
executor with latest-only drops, and resume clears the
fallback latch so binds retry automatically.

Device-verified: 3/3 cold launches configure first try,
zero configure failures, p50 frame 5ms / 2.66% janky.
Note: the lint step currently crashes in the lint tool
itself (pre-existing, unrelated) - assemble/install were
done around it.

Diff

camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.ktindex 83faee51e4..3c59c93d93 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RecordingCore.kt@@ -10,6 +10,7 @@ import android.media.MediaMuxer import android.media.MediaRecorder import android.os.Bundle import android.view.Surface+import com.vayunmathur.camera.platform.camera2.AudioEncoderPolicy import com.vayunmathur.camera.platform.camera2.EncoderSurfaceHandoff import com.vayunmathur.camera.platform.camera2.MuxerStartPolicy import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership@@ -51,6 +52,21 @@ class Camera2RecordingCore(     private var videoTrackIndex = -1     private var audioTrackIndex = -1 +    /**+     * True when this recording will mux an audio track: audio was+     * requested AND an Opus encoder was created (see+     * [AudioEncoderPolicy]). False means video-only — either audio was+     * not requested, or no Opus encoder exists / the muxer rejected the+     * Opus track. Never true for AAC: there is no AAC path.+     */+    private var audioTrackExpected = false++    /** True once MediaMuxer has rejected the Opus track (dropped to video-only). */+    private var audioMuxerRejected = false++    /** True when the finished file will carry an Opus audio track. */+    val hasAudioTrack: Boolean get() = audioTrackExpected && !audioMuxerRejected+     // Per-track PTS bases: encoder output timestamps start at the     // sensor/monotonic clock (a huge base), audio at zero. Both tracks     // are rebased to their first sample so the muxed container starts@@ -113,20 +129,52 @@ class Camera2RecordingCore(         encoderHandoff.markCodecConfigured()     } -    /** Creates the muxer and (when enabled) the audio codec. Video codec must already be configured. */+    /**+     * Creates the muxer and (when enabled) the Opus audio codec. Video+     * codec must already be configured.+     *+     * Opus is the only audio encoding (see [AudioEncoderPolicy]): when+     * no Opus encoder exists, or creating/configuring it fails, no audio+     * codec is created at all and the recording proceeds video-only with+     * a logged reason — never an AAC fallback.+     */     fun setupMuxerAndAudio(outputFile: File) {         if (videoCodec == null) configureVideoCodec()+        audioTrackExpected = false+        audioMuxerRejected = false         if (config.audioEnabled) {-            val audioFormat = MediaFormat.createAudioFormat(-                MediaFormat.MIMETYPE_AUDIO_AAC, config.audioSampleRate, 1,-            ).apply {-                setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)-                setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)-                setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)-            }-            audioCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {-                configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)-                start()+            val mime = AudioEncoderPolicy.resolveAudioMime(+                opusEncoderAvailable = CodecSupport.isOpusAudioEncoderAvailable,+            )+            if (mime == null) {+                Log.error(+                    "Camera2Recorder",+                    "No Opus audio encoder on this device; recording video-only (AAC is not an option)",+                )+            } else {+                try {+                    val audioFormat = MediaFormat.createAudioFormat(+                        mime, config.audioSampleRate, 1,+                    ).apply {+                        setInteger(MediaFormat.KEY_BIT_RATE, config.audioBitrateBps)+                        setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, AUDIO_MAX_INPUT_BYTES)+                    }+                    audioCodec = MediaCodec.createEncoderByType(mime).apply {+                        configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+                        start()+                    }+                    audioTrackExpected = true+                } catch (e: Exception) {+                    // Opus encoder unusable on this device: record+                    // video-only rather than fall back to AAC.+                    Log.error(+                        "Camera2Recorder",+                        "Opus audio encoder unavailable; recording video-only",+                        e,+                    )+                    try { audioCodec?.release() } catch (_: Exception) {}+                    audioCodec = null+                }             }         }         muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)@@ -166,12 +214,29 @@ class Camera2RecordingCore(                 index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {                     val format = codec.outputFormat                     val m = muxer ?: return-                    if (isVideo) videoTrackIndex = m.addTrack(format) else audioTrackIndex = m.addTrack(format)+                    if (isVideo) {+                        videoTrackIndex = m.addTrack(format)+                    } else if (!audioMuxerRejected) {+                        try {+                            audioTrackIndex = m.addTrack(format)+                        } catch (e: RuntimeException) {+                            // MediaMuxer cannot mux Opus into MP4 on+                            // this device/API level: drop the audio+                            // track and keep the video (never AAC).+                            Log.error(+                                "Camera2Recorder",+                                "MediaMuxer rejected the Opus track; recording video-only",+                                e,+                            )+                            audioMuxerRejected = true+                            audioTrackExpected = false+                        }+                    }                     if (                         !muxerStarted && MuxerStartPolicy.shouldStart(                             hasVideoTrack = videoTrackIndex >= 0,                             hasAudioTrack = audioTrackIndex >= 0,-                            audioEnabled = config.audioEnabled,+                            audioEnabled = audioTrackExpected,                         )                     ) {                         m.start()@@ -180,7 +245,8 @@ class Camera2RecordingCore(                 }                 index == MediaCodec.INFO_TRY_AGAIN_LATER -> return                 index >= 0 -> {-                    if (muxerStarted && info.size > 0) {+                    val trackIndex = if (isVideo) videoTrackIndex else audioTrackIndex+                    if (muxerStarted && info.size > 0 && trackIndex >= 0) {                         val buffer: ByteBuffer = codec.getOutputBuffer(index) ?: continue                         buffer.position(info.offset)                         buffer.limit(info.offset + info.size)@@ -212,7 +278,7 @@ class Camera2RecordingCore(                                 info.flags,                             )                         }-                        muxer?.writeSampleData(if (isVideo) videoTrackIndex else audioTrackIndex, buffer, adjusted)+                        muxer?.writeSampleData(trackIndex, buffer, adjusted)                     }                     codec.releaseOutputBuffer(index, false)                     if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return@@ -222,9 +288,10 @@ class Camera2RecordingCore(         }     } -    /** AudioRecord (mono) -> audio encoder input buffers, with codec timestamps. No-op without audio. */+    /** AudioRecord (mono) -> Opus encoder input buffers, with codec timestamps. No-op without audio. */     fun startAudio() {-        if (!config.audioEnabled) return+        // No Opus encoder (or audio not requested): nothing to feed.+        if (!config.audioEnabled || !audioTrackExpected) return         val minBuffer = AudioRecord.getMinBufferSize(             config.audioSampleRate,             AudioFormat.CHANNEL_IN_MONO,@@ -324,6 +391,8 @@ class Camera2RecordingCore(         muxerStarted = false         videoTrackIndex = -1         audioTrackIndex = -1+        audioTrackExpected = false+        audioMuxerRejected = false         videoBasePtsUs = -1L         audioBasePtsUs = -1L         videoFrameIndex = 0L
camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.ktindex 52b32ac21e..85496c1d2a 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt@@ -19,7 +19,7 @@ import com.vayunmathur.camera.platform.camera2.RecordingSessionOwnership import com.vayunmathur.library.log.Log import java.io.File -/** Configuration for one custom-path recording. AVC/HEVC video + AAC audio only. */+/** Configuration for one custom-path recording. AVC/HEVC/AV1 video + Opus audio only. */ data class CustomRecordingConfig(     val width: Int,     val height: Int,@@ -32,13 +32,17 @@ data class CustomRecordingConfig(      */     val captureFps: Int = fps,     val videoMime: String = MediaFormat.MIMETYPE_VIDEO_AVC,+    // Audio is always Opus (AudioEncoderPolicy.OPUS_MIME): there is no+    // audio-mime field here because there is no second option to select,+    // and a device without an Opus encoder records video-only instead.     val audioSampleRate: Int = 48_000,     val audioBitrateBps: Int = 128_000,     val iFrameIntervalSec: Int = 1,     /**      * False records video only (slo-mo's contract, SloMoEnginePolicy-     * piece 5): no AudioRecord/AAC codec is created and the muxer starts-     * on the video track alone ([MuxerStartPolicy]).+     * piece 5): no AudioRecord/Opus codec is created and the muxer starts+     * on the video track alone ([MuxerStartPolicy]). Also the effective+     * state when no Opus encoder exists (see [AudioEncoderPolicy]).      */     val audioEnabled: Boolean = true, )@@ -61,7 +65,7 @@ data class CustomRecordingValidation(  *  * Ownership contract: this recorder opens the camera device itself, so the  * CameraX session must be torn down before [start] and rebuilt after [stop].- * It supports SDR AVC/HEVC + AAC only — no HLG, no vendor stabilization/EIS+ * It supports SDR AVC/HEVC + Opus only — no HLG, no vendor stabilization/EIS  * semantics, no AV1; [RecordingPathPolicy] keeps those recordings on CameraX.  *  * VERIFICATION STATUS: compile-checked and unit-tested at the policy/controller
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicy.ktnew file mode 100644index 0000000000..66d281c0cb--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicy.kt@@ -0,0 +1,43 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Opus-only audio encoding policy for Camera2 video recordings.+ *+ * Opus (`audio/opus`) is the ONLY audio encoding this app produces: there+ * is no AAC branch and no fallback ordering that can produce AAC. Android+ * 10+ devices ship an Opus encoder, so on any supported device+ * [OPUS_MIME] is returned and the recording carries an Opus track.+ *+ * When no Opus encoder exists, the honest failure is a video-only+ * (mute-track) recording with a logged reason — never a silent AAC+ * fallback. [resolveAudioMime] returning null is that signal: the+ * recording core skips AudioRecord/encoder creation entirely and the+ * muxer starts on the video track alone (see [MuxerStartPolicy]).+ *+ * Pure (no Android types) so the selection is unit-testable without a+ * codec registry; the Android side probes `MediaCodecList` once+ * (`CodecSupport.isOpusAudioEncoderAvailable`) and feeds the boolean in.+ */+object AudioEncoderPolicy {++    /** The only audio mime a recording may ever carry. */+    const val OPUS_MIME: String = "audio/opus"++    /**+     * The audio mime to encode with, or null when this device has no Opus+     * encoder and the recording must proceed video-only. Never returns+     * AAC (or any other mime) under any input.+     */+    fun resolveAudioMime(opusEncoderAvailable: Boolean): String? =+        if (opusEncoderAvailable) OPUS_MIME else null++    /**+     * True when a recording that wants audio will actually get an audio+     * track: audio was requested AND an Opus encoder exists. This is the+     * `audioEnabled` value the muxer-start decision must see — a+     * requested-but-unavailable Opus track must not hold the muxer+     * waiting for a track that will never be added.+     */+    fun shouldEnableAudio(audioRequested: Boolean, opusEncoderAvailable: Boolean): Boolean =+        audioRequested && resolveAudioMime(opusEncoderAvailable) != null+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.ktindex c38ff9ac77..35de182fec 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt@@ -46,7 +46,7 @@ data class SloMoEngineInput(      *    [PreviewEnginePolicy]'s SLOW_MO exclusion.      * 5. Audio/muxer contract. DONE: the engine/core take a no-audio      *    configuration (`audioEnabled = false`, CameraX slo-mo's-     *    contract) — no AudioRecord/AAC is created and the muxer starts+     *    contract) — no AudioRecord/Opus codec is created and the muxer starts      *    on the video track alone via [MuxerStartPolicy].      * 6. Timestamp verification. DONE (device-proven 2026-11-22): the      *    encoder ignores `KEY_CAPTURE_RATE` for output timing and its
camera/src/main/rust/src/avif.rs
diff --git a/camera/src/main/rust/src/avif.rs b/camera/src/main/rust/src/avif.rsindex 2ce3e67ede..93c6c29f09 100644--- a/camera/src/main/rust/src/avif.rs+++ b/camera/src/main/rust/src/avif.rs@@ -356,21 +356,86 @@ mod avif_tests {         assert!(encode_avif(&[0u8; 4], 20_001, 1, 80.0, 10).is_none());     } +    /// Photo-like 12 MP frame (4080x3072): smooth gradients + sinusoidal+    /// detail + deterministic sensor-like noise, so encode times are not+    /// flattered by a flat/gradient-only synthetic.+    fn photo_like(width: usize, height: usize) -> Vec<u8> {+        let mut px = Vec::with_capacity(width * height * 4);+        let mut state: u32 = 0x9E37_79B9;+        let mut noise = move || {+            state ^= state << 13;+            state ^= state >> 17;+            state ^= state << 5;+            (state >> 24) as i32 - 128+        };+        for y in 0..height {+            for x in 0..width {+                let fx = x as f32 / width as f32;+                let fy = y as f32 / height as f32;+                let wave = ((x as f32 * 0.11).sin() * 18.0+                    + (y as f32 * 0.043 + x as f32 * 0.017).sin() * 26.0+                    + ((x + y) as f32 * 0.31).sin() * 8.0) as i32;+                let n = noise() / 10;+                let r = (40.0 + fx * 180.0) as i32 + wave + n;+                let g = (60.0 + fy * 150.0) as i32 + wave / 2 + n;+                let b = (90.0 + (1.0 - fx) * 110.0) as i32 - wave / 3 + n;+                px.extend_from_slice(&[+                    r.clamp(0, 255) as u8,+                    g.clamp(0, 255) as u8,+                    b.clamp(0, 255) as u8,+                    255,+                ]);+            }+        }+        px+    }+     /// Host-side encode-time probe for a 12 MP frame. Ignored by default-    /// (it takes seconds); run with `cargo test -- --ignored bench_12mp`-    /// to reproduce the latency figure in the change report.+    /// (it takes seconds); run with+    /// `cargo test --release -p camera_stitch bench_12mp -- --ignored --nocapture`+    /// to reproduce the latency figures in the change report. Writes each+    /// speed's .avif to $AVIF_BENCH_DIR (default /tmp/avif_bench) so an+    /// external AV1 decoder (ffmpeg/dav1d) can score PSNR vs the source.     #[test]     #[ignore]     fn bench_12mp_encode_time() {-        let rgba = gradient(4000, 3000);-        let start = std::time::Instant::now();-        let bytes = encode_avif(&rgba, 4000, 3000, 80.0, 10).expect("encode must succeed");-        println!(-            "12MP AVIF encode: {:?} -> {} bytes",-            start.elapsed(),-            bytes.len()-        );-        assert!(has_avif_magic(&bytes));+        let (w, h) = (4080usize, 3072usize);+        let rgba = photo_like(w, h);+        let dir = std::env::var("AVIF_BENCH_DIR").unwrap_or_else(|_| "/tmp/avif_bench".into());+        let _ = std::fs::create_dir_all(&dir);+        // Source dump for PSNR scoring (raw RGBA).+        let _ = std::fs::write(format!("{dir}/source_{w}x{h}.rgba"), &rgba);+        for speed in [4u8, 6, 8, 9, 10] {+            let start = std::time::Instant::now();+            let bytes = encode_avif(&rgba, w, h, 80.0, speed).expect("encode must succeed");+            let ms = start.elapsed().as_millis();+            let _ = std::fs::write(format!("{dir}/q80_s{speed}.avif"), &bytes);+            println!("12MP AVIF q80 speed={speed} threads=default: {ms} ms -> {} bytes", bytes.len());+            assert!(has_avif_magic(&bytes));+        }+        // Thread scaling at the production-adjacent speeds, via ravif directly.+        let pixels: Vec<ravif::RGBA8> = rgba+            .chunks_exact(4)+            .map(|p| ravif::RGBA8::new(p[0], p[1], p[2], p[3]))+            .collect();+        for speed in [8u8, 10] {+            for threads in [Some(1usize), Some(4), Some(8), Some(16)] {+                let img = ravif::Img::new(pixels.as_slice(), w, h);+                let start = std::time::Instant::now();+                let enc = ravif::Encoder::new()+                    .with_quality(80.0)+                    .with_speed(speed)+                    .with_bit_depth(ravif::BitDepth::Eight)+                    .with_num_threads(threads)+                    .encode_rgba(img)+                    .expect("encode must succeed");+                println!(+                    "12MP AVIF q80 speed={speed} threads={threads:?}: {} ms -> {} bytes",+                    start.elapsed().as_millis(),+                    enc.avif_file.len()+                );+            }+        }     } } 
camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.ktindex e5a89dcacb..d88de7a4d2 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt@@ -75,6 +75,8 @@ class RawRingSessionTest {      private fun snapshot() = CharacteristicsFacade.fromFakeMap(         cameraId = "0",+        // RAW ring combos are only guaranteed on LEVEL_3 lenses.+        hardwareLevel = CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_3,         lensFacingRaw = CameraMetadata.LENS_FACING_BACK,         zoomRatioRange = Range(1f, 10f),         sizesByFormat = mapOf(
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.ktindex 8c206d6ed8..8aec3fb283 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt@@ -32,6 +32,8 @@ class StillCaptureTest {         jpegRSizes: List<Size> = emptyList(),     ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(         cameraId = "0",+        // JPEG_R combos are only guaranteed on LEVEL_3 lenses.+        hardwareLevel = CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_3,         lensFacingRaw = lensFacingRaw,         zoomRatioRange = Range(1f, 10f),         hasFlashUnit = hasFlashUnit,