Modern Apps git

← Modern-Apps.git

camera: stamp motion clip frames at their captured times

Commit
52268b524b852ffa2a1b63afd0b30d4c632f29ba
Author
Vayun Mathur <[email protected]>
When
2026-12-05 16:11 UTC (20 hours ago)
Parents
e7e0fcc
A Motion Photo clip was stamped uniformly: frame i at
i * 1s / fps, with fps the average delivery rate rounded
and clamped to 5..30. Ring-buffer frames are not delivered
uniformly (the analysis conversion shares one executor
with the QR scanner), and any real rate outside the clamp
stretched or compressed the captured span in playback —
the reported very slow motion clip.

MotionClipTiming now stamps each frame at its actual
capture offset from the first frame, sets clip duration
to the captured span plus one frame interval, and only
uses the average rate as the encoder's frame-rate hint.
MotionPhotoEncoder consumes that timing (EOS at the clip
duration, so mvhd/tkhd cover the full span) instead of an
fps integer. Tests cover uniform, irregular, below-5fps
and above-30fps delivery and non-monotonic samples.

Verified: cargo test -p camera_stitch (152 passed);
./gradlew :camera:lint :camera:lintVitalRelease
:camera:testDevUnitTest green (944 tests).

Diff

camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex e09e6a5fb9..9021053628 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -73,6 +73,7 @@ for a direct open-on-phone broadcast. - com/vayunmathur/camera/domain/LensDiscovery.kt — offered-lens computation over pure `LensCandidate`s: every session-configurable camera the HAL exposes (top-level ids plus logical cameras' physical sub-cameras) is offered; a physical ultra-wide is never dropped for overlapping the logical zoom range; on logical-only devices the logical camera's zoom-ratio range synthesizes the ultra-wide (sub-1x) and telephoto (2x) stops no camera id exposes, anchored to the logical id (`PhysicalLens.synthesizedFromZoomRange`) - com/vayunmathur/camera/domain/LensSelectionLogic.kt - com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip+- com/vayunmathur/camera/domain/MotionClipTiming.kt — per-frame clip PTS from actual ring-buffer capture timestamps (duration = captured span plus one interval; no uniform-rate clamp), consumed by `MotionPhotoEncoder` - com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter - com/vayunmathur/camera/domain/StillCaptureModePolicy.kt — ZSL vs MINIMIZE_LATENCY choice - com/vayunmathur/camera/domain/CaptureRotation.kt — the one capture-rotation decision (sensor + physical display + facing) and EXIF convention
camera/src/main/java/com/vayunmathur/camera/domain/MotionClipTiming.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/MotionClipTiming.kt b/camera/src/main/java/com/vayunmathur/camera/domain/MotionClipTiming.ktnew file mode 100644index 0000000000..a95209f8d6--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/MotionClipTiming.kt@@ -0,0 +1,74 @@+package com.vayunmathur.camera.domain++import kotlin.math.ceil+import kotlin.math.roundToLong++/**+ * Presentation timing for a Motion Photo clip, derived from the ring+ * buffer's actual capture timestamps rather than a single uniform rate.+ *+ * The previous encoding stamped frame `i` at `i * 1s / fps`, where `fps`+ * was the average rate rounded to an integer and clamped to 5..30.+ * Frames are not delivered uniformly — the analysis conversion shares a+ * single-thread executor with the QR scanner, so copies arrive in+ * bursts with gaps — and any real rate outside the clamp (a slow+ * analysis stream below 5 fps, a fast one above 30) stretched or+ * compressed the whole clip: the same captured span played back over a+ * different duration, which reads as slow motion (or fast motion).+ * Stamping each frame at its captured offset makes the MP4's sample+ * timing equal the captured timing by construction, whatever rate the+ * frames actually arrived at.+ *+ * Pure arithmetic over nanosecond timestamps — no Android, no IO.+ */+object MotionClipTiming {++    /** One clip's timing: per-frame PTS (µs, first frame at 0), total+     * duration (µs, last frame's PTS plus one frame interval), and the+     * average frame rate to declare to the encoder as a hint. */+    data class Timing(+        val ptsUs: List<Long>,+        val durationUs: Long,+        val frameRate: Int,+    )++    private const val NANOS_PER_MICRO = 1_000L+    private const val MICROS_PER_SECOND = 1_000_000.0+    private const val MIN_FRAME_RATE = 1+    private const val MAX_FRAME_RATE = 60++    /**+     * Timing for frames captured at [timestampsNs] (monotonic sensor+     * timestamps, in capture order), or null when a clip cannot be+     * timed (fewer than two frames, or no positive span to spread them+     * over and no order to fall back on).+     */+    fun fromTimestamps(timestampsNs: List<Long>): Timing? {+        if (timestampsNs.size < 2) return null+        val first = timestampsNs.first()+        // Offsets from the first frame; a non-monotonic sample (a clock+        // reset across a session rebind) is pinned to its predecessor+        // so PTS never runs backwards in the muxed file.+        val ptsUs = ArrayList<Long>(timestampsNs.size)+        var previous = 0L+        for (timestamp in timestampsNs) {+            val offset = ((timestamp - first) / NANOS_PER_MICRO).coerceAtLeast(previous)+            ptsUs.add(offset)+            previous = offset+        }+        val spanUs = ptsUs.last()+        if (spanUs <= 0L) return null+        // The last frame displays for one average interval, so the+        // clip's duration is the captured span plus that interval:+        // (span / (n - 1)) per frame, times n frames.+        val intervalUs = (spanUs.toDouble() / (timestampsNs.size - 1)).roundToLong()+        val frameRate = ceil(MICROS_PER_SECOND / intervalUs.coerceAtLeast(1L).toDouble())+            .toInt()+            .coerceIn(MIN_FRAME_RATE, MAX_FRAME_RATE)+        return Timing(+            ptsUs = ptsUs,+            durationUs = spanUs + intervalUs,+            frameRate = frameRate,+        )+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex 488a3b9371..7956753b23 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -10,7 +10,6 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull-import kotlin.math.roundToInt import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.domain.MotionPhotoWriter import com.vayunmathur.camera.data.saveProcessedStill@@ -414,15 +413,23 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveReque         list.filter { it.bitmap.width == w && it.bitmap.height == h }     }.orEmpty() -    val mp4 = if (sized.size >= 2) {+    // Per-frame timing from the frames' actual capture timestamps:+    // the clip must play over the span it was captured in, at whatever+    // (irregular) rate the analysis stream delivered the frames.+    val timing = if (sized.size >= 2) {+        com.vayunmathur.camera.domain.MotionClipTiming.fromTimestamps(+            sized.map { it.timestampNanos }+        )+    } else {+        null+    }+    val mp4 = if (timing != null) {         val tmp = java.io.File(app.cacheDir, "motion_${System.currentTimeMillis()}.mp4")-        val spanNs = (sized.last().timestampNanos - sized.first().timestampNanos).coerceAtLeast(1)-        val fps = (sized.size * 1_000_000_000.0 / spanNs).roundToInt().coerceIn(5, 30)         // The clip's hint must agree with the still it trails: use the         // still's capture rotation, not an analysis frame's (the two         // are the same decision now, but the still is the authority).         val ok = MotionPhotoEncoder.encode(-            sized.map { it.bitmap }, tmp, request.rotationDegrees, fps+            sized.map { it.bitmap }, tmp, request.rotationDegrees, timing         )         if (ok && tmp.exists()) {             tmp.readBytes().also { tmp.delete() }
camera/src/main/java/com/vayunmathur/camera/platform/MotionPhotoEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/MotionPhotoEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/MotionPhotoEncoder.ktindex 917471ac24..beda4b7f0e 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/MotionPhotoEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/MotionPhotoEncoder.kt@@ -6,6 +6,7 @@ import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaMuxer import com.vayunmathur.camera.domain.ArgbToI420Converter+import com.vayunmathur.camera.domain.MotionClipTiming import com.vayunmathur.camera.domain.YuvPlane import com.vayunmathur.library.log.Log import java.io.File@@ -25,17 +26,25 @@ object MotionPhotoEncoder {     private const val TAG = "MotionPhotoEncoder"     private const val MIME = MediaFormat.MIMETYPE_VIDEO_AVC     private const val TIMEOUT_US = 10_000L-    /** Micros per second; YUV420 bytes per pixel (3/2). */-    private const val MICROS_PER_SECOND = 1_000_000L+    /** YUV420 bytes per pixel (3/2). */     private const val YUV420_NUMERATOR = 3     private const val YUV420_DENOMINATOR = 2      /**-     * Encodes [frames] to [outputFile] at [fps]. All frames must share dimensions (the first-     * frame's are used). Returns true on success. The caller owns recycling the bitmaps.+     * Encodes [frames] to [outputFile] with the per-frame presentation+     * times in [timing] (from [MotionClipTiming.fromTimestamps], so the+     * clip plays over the span the frames were captured in). All frames+     * must share dimensions (the first frame's are used) and+     * [MotionClipTiming.Timing.ptsUs] must carry one entry per frame.+     * Returns true on success. The caller owns recycling the bitmaps.      */-    fun encode(frames: List<Bitmap>, outputFile: File, rotationDegrees: Int, fps: Int = DEFAULT_FPS): Boolean {-        if (frames.isEmpty()) return false+    fun encode(+        frames: List<Bitmap>,+        outputFile: File,+        rotationDegrees: Int,+        timing: MotionClipTiming.Timing,+    ): Boolean {+        if (frames.isEmpty() || timing.ptsUs.size != frames.size) return false         // Encoders require even dimensions.         val width = frames[0].width and 1.inv()         val height = frames[0].height and 1.inv()@@ -45,10 +54,10 @@ object MotionPhotoEncoder {         var muxer: MediaMuxer? = null         var muxerStarted = false         try {-            codec = startEncoder(width, height, fps)+            codec = startEncoder(width, height, timing.frameRate)             muxer = MediaMuxer(outputFile.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)             muxer.setOrientationHint(rotationDegrees)-            val pump = FramePump(codec, muxer, frames, width, height, fps)+            val pump = FramePump(codec, muxer, frames, width, height, timing)             pump.run()             muxerStarted = pump.muxerStarted             return true@@ -69,9 +78,8 @@ object MotionPhotoEncoder {         }     } -    /** Minimum (even) encode dimension; encoder timeout; default fps. */+    /** Minimum (even) encode dimension; encoder timeout. */     private const val MIN_ENCODE_SIDE = 2-    private const val DEFAULT_FPS = 15      /** Creates, configures and starts the AVC encoder for [width]x[height]@[fps]. */     private fun startEncoder(width: Int, height: Int, fps: Int): MediaCodec {@@ -97,7 +105,7 @@ object MotionPhotoEncoder {         private val frames: List<Bitmap>,         private val width: Int,         private val height: Int,-        private val fps: Int+        private val timing: MotionClipTiming.Timing     ) {         var muxerStarted = false             private set@@ -129,7 +137,10 @@ object MotionPhotoEncoder {         }          private fun queueFrame(inIndex: Int, frameIndex: Int) {-            val ptsUs = frameIndex * MICROS_PER_SECOND / fps+            // The frame's captured offset, not its index over a uniform+            // rate: gaps and bursts in analysis delivery stay gaps and+            // bursts on screen, at natural speed.+            val ptsUs = timing.ptsUs[frameIndex]             val image = codec.getInputImage(inIndex)             if (image != null) {                 frames[frameIndex].getPixels(argb, 0, width, 0, 0, width, height)@@ -146,8 +157,11 @@ object MotionPhotoEncoder {         }          private fun queueEndOfStream(inIndex: Int, frameIndex: Int) {+            // End-of-stream PTS is the clip duration (last frame plus+            // one interval), so the muxer's mvhd/tkhd durations cover+            // the full captured span.             codec.queueInputBuffer(-                inIndex, 0, 0, frameIndex * MICROS_PER_SECOND / fps,+                inIndex, 0, 0, timing.durationUs,                 MediaCodec.BUFFER_FLAG_END_OF_STREAM             )         }
camera/src/test/java/com/vayunmathur/camera/domain/MotionClipTimingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/MotionClipTimingTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/MotionClipTimingTest.ktnew file mode 100644index 0000000000..7e80569926--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/MotionClipTimingTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Tests for [MotionClipTiming]: playback timing equals captured timing. */+class MotionClipTimingTest {++    private fun stamps(startNs: Long, intervalsNs: List<Long>): List<Long> {+        val out = mutableListOf(startNs)+        for (interval in intervalsNs) out.add(out.last() + interval)+        return out+    }++    @Test fun uniformFramesPlayOverCapturedSpanPlusOneInterval() {+        // 24 frames at a steady 125 ms (8 fps) over 2.875 s.+        val timing = MotionClipTiming.fromTimestamps(+            stamps(1_000_000_000L, List(23) { 125_000_000L })+        )!!+        assertEquals(0L, timing.ptsUs.first())+        assertEquals(2_875_000L, timing.ptsUs.last())+        assertEquals(3_000_000L, timing.durationUs, "duration is span plus one interval")+        assertEquals(8, timing.frameRate)+    }++    @Test fun irregularDeliveryKeepsEachFramesCapturedOffset() {+        // Bursts and gaps in analysis delivery stay bursts and gaps:+        // no uniform re-stamping over an averaged, rounded rate.+        val timing = MotionClipTiming.fromTimestamps(+            stamps(5_000L, listOf(10_000_000L, 400_000_000L, 20_000_000L, 570_000_000L))+        )!!+        assertEquals(listOf(0L, 10_000L, 410_000L, 430_000L, 1_000_000L), timing.ptsUs)+        assertEquals(1_250_000L, timing.durationUs)+    }++    @Test fun slowAnalysisRateIsNotClampedUpToFiveFps() {+        // Four frames over 3 s (~1.3 fps as delivered): the old clamp+        // to >=5 fps played this span in under a second. Per-frame+        // stamps keep the full 3 s (plus one interval).+        val timing = MotionClipTiming.fromTimestamps(+            stamps(0L, listOf(1_000_000_000L, 1_000_000_000L, 1_000_000_000L))+        )!!+        assertEquals(4_000_000L, timing.durationUs)+        assertEquals(1, timing.frameRate)+    }++    @Test fun fastRateIsNotClampedDownToThirtyFps() {+        // 40 fps capture (25 ms intervals): the old clamp to <=30 fps+        // stretched 1 s of capture over ~1.33 s of playback.+        val timing = MotionClipTiming.fromTimestamps(+            stamps(0L, List(40) { 25_000_000L })+        )!!+        assertEquals(1_025_000L, timing.durationUs)+        assertEquals(40, timing.frameRate)+    }++    @Test fun nonMonotonicSampleNeverMovesPtsBackwards() {+        val timing = MotionClipTiming.fromTimestamps(+            listOf(1_000_000_000L, 1_500_000_000L, 1_200_000_000L, 2_000_000_000L)+        )!!+        assertEquals(listOf(0L, 500_000L, 500_000L, 1_000_000L), timing.ptsUs)+        assertTrue(timing.durationUs > timing.ptsUs.last())+    }++    @Test fun untimeableInputsReturnNull() {+        assertNull(MotionClipTiming.fromTimestamps(emptyList()))+        assertNull(MotionClipTiming.fromTimestamps(listOf(42L)))+        assertNull(MotionClipTiming.fromTimestamps(listOf(42L, 42L)))+    }+}