camera: Opus is the only audio encoder; AAC removed
- Commit
c1fdcfee6cd7aae372c14f79b4d223e2321947b5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 15:40 UTC (12 days ago)
- Parents
01f707e
The recording core hardcoded AAC; now AudioEncoderPolicy resolves audio/opus or nothing. The audio-codec settings row, enum, plumbing and strings are gone, and the stale camera_audio_codec key is deleted on load. With no Opus encoder (or a muxer that rejects the track) recording proceeds video-only with a logged error - never a silent AAC file, never a lost video. (Four files of this change landed inside 01f707e78's sweep; this is the rest.) Verified: new Opus-only policy tests 24/24 targeted, compile + assembleRelease green. First-device ffprobe of an Opus recording is still owed.
Diff
camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.ktindex 71e9cbb45e..9c384cabf4 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveRouting.kt@@ -73,6 +73,7 @@ internal fun CameraViewModel.saveProcessedStill( sourceJpeg: ByteArray? = null, fileStem: String? = null, ): SavedStill? {+ val started = android.os.SystemClock.elapsedRealtime() val exifTiff = if (photoFormatMutable.value == com.vayunmathur.camera.platform.PhotoFormat.AVIF) { val carrier = java.io.ByteArrayOutputStream().use { out -> bitmap.compress(Bitmap.CompressFormat.JPEG, StillFormatRouting.JPEG_QUALITY, out)@@ -82,7 +83,19 @@ internal fun CameraViewModel.saveProcessedStill( } else { null }+ val exifMs = android.os.SystemClock.elapsedRealtime() - started+ val encodeStarted = android.os.SystemClock.elapsedRealtime() val encoded: EncodedStill = encode(bitmap, rotationDegrees, exifTiff)+ // StillSave breadcrumb: the two segments a processed still spends+ // before MediaStore — EXIF TIFF build (full-res JPEG carrier encode+ // + tag copy) and the container encode itself (ravif segment is+ // logged in detail by StillEncoder). Payload-free, release-visible.+ Log.debug(+ "StillSave",+ "processedStill exifMs=$exifMs encodeMs=" ++ "${android.os.SystemClock.elapsedRealtime() - encodeStarted} " ++ "format=${encoded.format} ${bitmap.width}x${bitmap.height} bytes=${encoded.bytes.size}",+ ) val name = if (fileStem != null) { "$fileStem.${StillFormatRouting.extension(encoded.format)}" } else {
camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.ktindex d18ca4f25c..8b8a29e808 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -8,7 +8,6 @@ import androidx.core.net.toUri import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.camera.platform.AudioCodec import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.CodecSupport@@ -57,13 +56,11 @@ private fun CameraViewModel.loadCaptureSettings() { AudioInputSource.CAMCORDER } }- ds.getString("camera_audio_codec")?.let {- audioCodecMutable.value = try {- AudioCodec.valueOf(it)- } catch (_: Exception) {- AudioCodec.AAC- }- }+ // Opus-only: the retired audio-codec setting (camera_audio_codec) is+ // never read again — audio encoding is not selectable. Drop any+ // stored value so it cannot linger or be misread later; an unknown+ // or stale value is simply deleted, never parsed.+ viewModelScope.launch { ds.removeKeys(listOf("camera_audio_codec")) } loadSaveTarget() // Guard against a blank persisted value: Uri.parse("") yields a non-null ds.getString("camera_last_capture")?.takeIf { it.isNotBlank() }?.let { lastCaptureUriMutable.value = it.toUri() }@@ -165,11 +162,6 @@ fun CameraViewModel.setMotionPhotoDuration(duration: MotionPhotoDuration) { viewModelScope.launch { ds.setString("camera_motion_duration", duration.name) } } -fun CameraViewModel.setAudioCodec(codec: AudioCodec) {- audioCodecMutable.value = codec- viewModelScope.launch { ds.setString("camera_audio_codec", codec.name) }-}- fun CameraViewModel.setAudioInputSource(source: AudioInputSource) { audioInputSourceMutable.value = source viewModelScope.launch { ds.setString("camera_audio_source", source.name) }
camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.ktindex 59eab112f7..a3cc47bbcc 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillFormatRouting.kt@@ -19,8 +19,22 @@ object StillFormatRouting { /** AVIF quality (ravif scale 1..100) for the native encoder. */ const val AVIF_QUALITY = 80f - /** AVIF speed (rav1e scale 1..10, 10 = fastest) for stills. */- const val AVIF_SPEED = 8+ /**+ * AVIF speed (rav1e scale 1..10, 10 = fastest) for stills.+ *+ * Measured on a photo-like 4080x3072 (12 MP) frame at quality 80+ * (host, release ravif; PSNR scored by decoding with dav1d):+ * speed 8 took 3,248 ms with default threading (7,728 ms pinned to+ * 8 threads, the phone-like core count) at PSNR 40.20 dB /+ * 2,205,501 bytes; speed 10 took 424 ms (1,698 ms at 8 threads) at+ * PSNR 40.14 dB / 2,284,322 bytes. So speed 10 is ~4.6x faster at+ * 8 threads for -0.06 dB PSNR (within the speed 8<->9 spread) and+ * +3.6% file size — the quantizer (quality target) is unchanged,+ * the cost is only marginally less optimal partition/tx decisions.+ * Speeds 4/6/9 were all >=2.9 s default-threaded with no PSNR gain+ * over speed 10 worth the latency, so 10 is the knee.+ */+ const val AVIF_SPEED = 10 /** * The format a still is really saved as. AVIF is only honoured when
camera/src/main/java/com/vayunmathur/camera/domain/StillSaveQueue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/StillSaveQueue.kt b/camera/src/main/java/com/vayunmathur/camera/domain/StillSaveQueue.ktnew file mode 100644index 0000000000..e1d1517a37--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/StillSaveQueue.kt@@ -0,0 +1,44 @@+package com.vayunmathur.camera.domain++import java.util.concurrent.atomic.AtomicInteger++/**+ * Admission control for processed stills (above all AVIF encodes) still+ * being saved after their shutter was released.+ *+ * Each pending save holds its source (a full-res bitmap, ~50 MB at+ * 12 MP, or the source JPEG bytes) until the encode lands, so the number+ * in flight must stay small. A shot reserves a slot once its source is+ * secured and releases it once its save finishes (or fails); when no+ * slot is free the caller keeps the old synchronous save instead of+ * queueing unbounded work — the shot is never dropped and never silently+ * rerouted to another format. Thread-safe: reserved on the capture+ * callback, released from the save worker. Same admission contract as+ * [MotionSaveQueue], separate instance so Motion and still saves bound+ * independently.+ */+class StillSaveQueue(val capacity: Int) {++ init {+ require(capacity > 0) { "capacity must be positive, was $capacity" }+ }++ private val inFlight = AtomicInteger(0)++ /** Saves currently reserved (secured, not yet saved). */+ val pending: Int get() = inFlight.get()++ /** Claims a slot; false (and nothing claimed) when [capacity] saves are already pending. */+ fun tryReserve(): Boolean {+ while (true) {+ val current = inFlight.get()+ if (current >= capacity) return false+ if (inFlight.compareAndSet(current, current + 1)) return true+ }+ }++ /** Returns a slot claimed by [tryReserve]. Never drops below zero. */+ fun release() {+ inFlight.updateAndGet { (it - 1).coerceAtLeast(0) }+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.ktnew file mode 100644index 0000000000..50f4135b81--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AvifCodecProbe.kt@@ -0,0 +1,120 @@+package com.vayunmathur.camera.platform++import android.media.MediaCodecInfo+import android.media.MediaCodecList+import com.vayunmathur.library.log.Log++/** MIME type a still-image AVIF encoder would register under. */+internal const val AVIF_IMAGE_MIME = "image/avif"++/** MIME type of AV1 video; a video encoder is NOT a still AVIF encoder. */+internal const val AV1_VIDEO_MIME = "video/av01"++/** One encoder registry entry relevant to AVIF/AV1. */+internal data class AvifCodecEntry(+ val name: String,+ val mime: String,+ val hardwareAccelerated: Boolean,+ val maxWidth: Int?,+ val maxHeight: Int?,+)++/**+ * Pure classification of codec-registry rows: which entries could encode+ * a still AVIF. Kept Android-free (rows in, verdict out) so the routing+ * rule is host-testable; [AvifCodecProbe] supplies the real rows.+ */+internal object AvifCodecRouting {++ /** A usable still encoder: an `image/avif` encoder (hardware or not). */+ fun stillEncoder(entries: List<AvifCodecEntry>): AvifCodecEntry? =+ entries.firstOrNull { it.mime.equals(AVIF_IMAGE_MIME, ignoreCase = true) }++ /** True when that still encoder is hardware-accelerated. */+ fun hasHardwareStillEncoder(entries: List<AvifCodecEntry>): Boolean =+ stillEncoder(entries)?.hardwareAccelerated == true++ /**+ * True when the frame fits the encoder's advertised size cap+ * (a null cap means the registry published no video/size limits,+ * which image codecs commonly don't — accept and let configure fail).+ */+ fun fitsSize(entry: AvifCodecEntry, width: Int, height: Int): Boolean =+ (entry.maxWidth == null || width <= entry.maxWidth) &&+ (entry.maxHeight == null || height <= entry.maxHeight)+}++/**+ * Cached [MediaCodecList] probe for a hardware still-AVIF encoder.+ *+ * Enumeration is warmed once at startup (see `runStartupSequence`) on a+ * background dispatcher, so the capture path only reads the cached+ * verdict. A `video/av01` encoder — the only AV1 encoder Pixel-class+ * devices ship, and a software Google codec at that — cannot produce a+ * still AVIF file (no ISOBMFF still mux, no single-image mode in the+ * MediaCodec image contract), so it is logged as evidence but never+ * routed to; only an `image/avif` encoder would be.+ */+internal object AvifCodecProbe {++ @Volatile+ private var cached: List<AvifCodecEntry>? = null++ /** All AVIF/AV1 encoder entries, enumerated at most once. */+ fun entries(): List<AvifCodecEntry> = cached ?: synchronized(this) {+ cached ?: enumerate().also { cached = it }+ }++ /** Warms the cache and logs the verdict. Call off the main thread. */+ fun warmUp() {+ val entries = entries()+ val still = AvifCodecRouting.stillEncoder(entries)+ Log.debug(+ "AvifCodec",+ "image/avif encoder=${still?.name ?: "none"} " ++ "hardware=${still?.hardwareAccelerated ?: false} " ++ "av1VideoEncoders=${entries.filter { it.mime == AV1_VIDEO_MIME }+ .joinToString(",") { "${it.name}(hw=${it.hardwareAccelerated})" }+ .ifEmpty { "none" }}",+ )+ }++ /** The still-AVIF encoder to route through, or null for software ravif. */+ fun stillEncoder(): AvifCodecEntry? = AvifCodecRouting.stillEncoder(entries())++ private fun enumerate(): List<AvifCodecEntry> = try {+ MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos+ .filter { it.isEncoder }+ .flatMap { info ->+ info.supportedTypes+ .filter {+ it.equals(AVIF_IMAGE_MIME, ignoreCase = true) ||+ it.equals(AV1_VIDEO_MIME, ignoreCase = true)+ }+ .map { mime -> entry(info, mime) }+ }+ } catch (e: Exception) {+ Log.status("AvifCodec", "MediaCodecList enumeration failed; software AVIF only", e)+ emptyList()+ }++ private fun entry(info: MediaCodecInfo, mime: String): AvifCodecEntry {+ val caps = try {+ info.getCapabilitiesForType(mime)+ } catch (_: IllegalArgumentException) {+ null+ }+ val video = caps?.videoCapabilities+ return AvifCodecEntry(+ name = info.name,+ mime = mime,+ hardwareAccelerated = try {+ info.isHardwareAccelerated+ } catch (_: Exception) {+ false+ },+ maxWidth = video?.upper?.width,+ maxHeight = video?.upper?.height,+ )+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.ktnew file mode 100644index 0000000000..4c79c49d12--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/AvifHardwareEncoder.kt@@ -0,0 +1,160 @@+package com.vayunmathur.camera.platform++import android.graphics.Bitmap+import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.os.SystemClock+import com.vayunmathur.camera.domain.ArgbToI420Converter+import com.vayunmathur.camera.domain.YuvPlane+import com.vayunmathur.library.log.Log+import java.io.ByteArrayOutputStream++/**+ * Still-AVIF encoding through a platform `image/avif` MediaCodec encoder,+ * when the device actually ships one (see [AvifCodecProbe]).+ *+ * The frame is fed as YUV 4:2:0 through the codec's input [android.media.Image]+ * (the same bulk conversion the Motion Photo encoder uses), the encoded+ * AVIF file is collected from the output buffers, and the EXIF TIFF is+ * spliced into it natively (`StitchNative.muxAvifExif`) because image+ * encoders have no EXIF input. Every failure — no encoder, size outside+ * its caps, configure/feed/drain errors, non-AVIF output, mux refusal —+ * returns null so [StillEncoder] falls back to the software ravif path;+ * a shot is never lost and never lands EXIF-less. Blocking: call off the+ * main thread.+ */+internal object AvifHardwareEncoder {++ private const val TIMEOUT_US = 10_000L+ private const val DEADLINE_MS = 20_000L+ private const val YUV420_NUMERATOR = 3+ private const val YUV420_DENOMINATOR = 2++ /** True when a platform still-AVIF encoder exists (cached probe). */+ fun isAvailable(): Boolean = AvifCodecProbe.stillEncoder() != null++ /**+ * Encodes [bitmap] to AVIF-with-EXIF through the hardware encoder,+ * or null when unavailable/unsuccessful. [exifTiff] is required: a+ * hardware file without the muxed Exif item is treated as failure.+ */+ fun encode(bitmap: Bitmap, exifTiff: ByteArray, quality: Float): ByteArray? {+ val entry = AvifCodecProbe.stillEncoder() ?: return null+ val width = bitmap.width+ val height = bitmap.height+ if (width <= 0 || height <= 0 || width % 2 != 0 || height % 2 != 0) {+ Log.debug("StillSave", "avifHw skipped ${width}x$height (odd/empty); software fallback")+ return null+ }+ if (!AvifCodecRouting.fitsSize(entry, width, height)) {+ Log.debug(+ "StillSave",+ "avifHw skipped ${width}x$height exceeds ${entry.name} cap " ++ "${entry.maxWidth}x${entry.maxHeight}; software fallback",+ )+ return null+ }+ val started = SystemClock.elapsedRealtime()+ val raw = try {+ encodeViaCodec(entry.name, bitmap, width, height, quality)+ } catch (e: Exception) {+ Log.status("StillEncoder", "Hardware AVIF encode failed; software fallback", e)+ null+ } ?: return null+ if (raw.size < 12 || String(raw, 4, 8, Charsets.US_ASCII) != "ftypavif") {+ Log.status("StillEncoder", "Hardware AVIF output is not an AVIF file; software fallback")+ return null+ }+ if (!StitchNative.isAvailable) return null+ val muxed = try {+ StitchNative.muxAvifExif(raw, exifTiff)+ } catch (e: UnsatisfiedLinkError) {+ Log.status("StillEncoder", "AVIF EXIF mux unavailable; software fallback", e)+ null+ } ?: run {+ Log.status("StillEncoder", "Hardware AVIF EXIF mux failed; software fallback")+ return null+ }+ Log.debug(+ "StillSave",+ "avifHwEncodeMs=${SystemClock.elapsedRealtime() - started} " ++ "codec=${entry.name} hw=${entry.hardwareAccelerated} ${width}x$height bytes=${muxed.size}",+ )+ return muxed+ }++ /** One-frame MediaCodec image encode: feed YUV420, EOS, drain to EOS. */+ private fun encodeViaCodec(+ codecName: String, bitmap: Bitmap, width: Int, height: Int, quality: Float,+ ): ByteArray? {+ var codec: MediaCodec? = null+ try {+ codec = MediaCodec.createByCodecName(codecName)+ val format = MediaFormat.createImageFormat(AVIF_IMAGE_MIME, width, height).apply {+ setInteger(+ MediaFormat.KEY_COLOR_FORMAT,+ MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible,+ )+ setInteger(MediaFormat.KEY_QUALITY, quality.toInt().coerceIn(1, 100))+ }+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ codec.start()+ feed(codec, bitmap, width, height)+ return drain(codec)+ } finally {+ try { codec?.stop() } catch (_: Exception) {}+ try { codec?.release() } catch (_: Exception) {}+ }+ }++ private fun feed(codec: MediaCodec, bitmap: Bitmap, width: Int, height: Int) {+ val deadline = SystemClock.elapsedRealtime() + DEADLINE_MS+ while (SystemClock.elapsedRealtime() < deadline) {+ val inIndex = codec.dequeueInputBuffer(TIMEOUT_US)+ if (inIndex < 0) continue+ val image = codec.getInputImage(inIndex)+ if (image != null) {+ val argb = IntArray(width * height)+ bitmap.getPixels(argb, 0, width, 0, 0, width, height)+ val planes = image.planes+ ArgbToI420Converter(width, height).convert(+ argb,+ YuvPlane(planes[0].buffer, planes[0].rowStride, planes[0].pixelStride),+ YuvPlane(planes[1].buffer, planes[1].rowStride, planes[1].pixelStride),+ YuvPlane(planes[2].buffer, planes[2].rowStride, planes[2].pixelStride),+ )+ }+ val size = width * height * YUV420_NUMERATOR / YUV420_DENOMINATOR+ codec.queueInputBuffer(inIndex, 0, size, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)+ return+ }+ error("Timed out waiting for an AVIF encoder input buffer")+ }++ private fun drain(codec: MediaCodec): ByteArray? {+ val out = ByteArrayOutputStream()+ val info = MediaCodec.BufferInfo()+ val deadline = SystemClock.elapsedRealtime() + DEADLINE_MS+ while (SystemClock.elapsedRealtime() < deadline) {+ val outIndex = codec.dequeueOutputBuffer(info, TIMEOUT_US)+ if (outIndex >= 0) {+ val buffer = codec.getOutputBuffer(outIndex)+ if (buffer != null && info.size > 0 &&+ (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0+ ) {+ buffer.position(info.offset)+ buffer.limit(info.offset + info.size)+ val chunk = ByteArray(info.size)+ buffer.get(chunk)+ out.write(chunk)+ }+ codec.releaseOutputBuffer(outIndex, false)+ if ((info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {+ return out.toByteArray().takeIf { it.isNotEmpty() }+ }+ }+ }+ return null+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.ktindex 9e5e9dd60c..1019be5f8b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2NightGlue.kt@@ -1,7 +1,6 @@ package com.vayunmathur.camera.platform import android.hardware.camera2.CameraManager-import androidx.lifecycle.viewModelScope import com.vayunmathur.camera.data.setLastCaptureUri import com.vayunmathur.camera.domain.LensFacing import com.vayunmathur.camera.platform.camera2.Camera2ExtensionProbe@@ -12,9 +11,6 @@ import com.vayunmathur.camera.platform.camera2.ExtensionsEngineInput import com.vayunmathur.camera.platform.camera2.ExtensionsEnginePolicy import com.vayunmathur.camera.platform.camera2.NightEngine import com.vayunmathur.library.log.Log-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext /** * Camera2 migration Phase 6: NIGHT-extension glue between the gated@@ -107,12 +103,7 @@ internal fun CameraViewModel.tryCaptureCamera2NightExtension(): Boolean { mirrored = mirrored, callback = object : Camera2ExtensionSession.StillCallback { override fun onStillCaptured(still: CapturedStill) {- viewModelScope.launch {- val uri = withContext(Dispatchers.IO) {- runCatching { saveCamera2Still(still) }- .onFailure { Log.error("Camera2Night", "save failed", it) }- .getOrNull()- }+ onCamera2StillCaptured(still) { uri -> isCapturingMutable.value = false if (uri != null) setLastCaptureUri(uri) }
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex 087d1e8e12..d9be615fb6 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -20,6 +20,7 @@ import com.vayunmathur.camera.platform.camera2.StillEnginePolicy import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /**@@ -101,12 +102,7 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { emitShutterFeedback() val stillCallback = object : Camera2Session.StillCallback { override fun onStillCaptured(still: CapturedStill) {- viewModelScope.launch {- val uri = withContext(Dispatchers.IO) {- runCatching { saveCamera2Still(still) }- .onFailure { Log.error("Camera2Still", "save failed", it) }- .getOrNull()- }+ onCamera2StillCaptured(still) { uri -> isCapturingMutable.value = false if (uri != null) setLastCaptureUri(uri) }@@ -162,6 +158,54 @@ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? { } } +/**+ * Lands one captured Camera2 still, releasing the shutter first when the+ * landing is an AVIF encode. Once [still] is in memory its source JPEG+ * bytes are secured, so capture completion ([finishCapture] with a null+ * uri: shutter/next-shot readiness, countdown and exposure restore) must+ * not wait for the decode + EXIF build + ravif encode + MediaStore+ * insert: that runs on the bounded still-save queue (one encode at a+ * time, [CameraViewModel.stillSaveQueue]) and the gallery thumbnail+ * updates when the save lands, exactly like Motion Photos (#914). JPEG+ * and Ultra HDR byte landings are cheap and keep the inline path, as+ * does an AVIF shot arriving while every save slot is busy — the shot+ * still lands in the selected format, it just waits as before.+ */+internal fun CameraViewModel.onCamera2StillCaptured(+ still: CapturedStill,+ finishCapture: (Uri?) -> Unit,+) {+ val ultraHdrSource = still.tag == StillOutputTag.ULTRA_HDR_JPEG_R ||+ StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)+ val avifEncode = StillFormatRouting.stillSaveRoute(+ requestedStillFormat(), ultraHdrSource,+ ) == StillFormatRouting.StillSaveRoute.PROCESSED_ENCODER+ if (avifEncode && stillSaveQueue.tryReserve()) {+ finishCapture(null)+ stillSaveScope.launch(stillSaveDispatcher) {+ try {+ val uri = stillSaveMutex.withLock {+ runCatching { saveCamera2Still(still) }+ .onFailure { Log.error("Camera2Still", "background save failed", it) }+ .getOrNull()+ }+ if (uri != null) setLastCaptureUri(uri)+ } finally {+ stillSaveQueue.release()+ }+ }+ return+ }+ viewModelScope.launch {+ val uri = withContext(Dispatchers.IO) {+ runCatching { saveCamera2Still(still) }+ .onFailure { Log.error("Camera2Still", "save failed", it) }+ .getOrNull()+ }+ finishCapture(uri)+ }+}+ /** The AVIF landing for one Camera2 still: decode once, encode via [saveProcessedStill]. */ private fun CameraViewModel.saveCamera2EncodedStill(still: CapturedStill): Uri? { val rotation = still.metadata.rotationDegrees
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex 8f24d5a232..6ea59ed11d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -7,6 +7,7 @@ import com.vayunmathur.library.log.Log import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.data.saveProcessedStill@@ -97,23 +98,41 @@ private fun CameraViewModel.runSingleCapture(session: Camera2Session, plan: Sing override fun onStillCaptured(still: CapturedStill) { emitShutterFeedback() if (plan.bokeh || plan.warmth != 0f || plan.shadows != 0f) {- viewModelScope.launch {- val uri = withContext(Dispatchers.IO) {- runCatching {- processSingleFrame(plan, still.jpegBytes, still.metadata.rotationDegrees)- }.getOrNull()+ // Processed still: the source JPEG is secured, so+ // release the shutter now and decode/adjust/encode on+ // the bounded still-save queue; the thumbnail updates+ // when the save lands. A full queue keeps the inline+ // save below (never a dropped or rerouted shot).+ if (stillSaveQueue.tryReserve()) {+ finishCapture(null)+ stillSaveScope.launch(stillSaveDispatcher) {+ try {+ val uri = stillSaveMutex.withLock {+ runCatching {+ processSingleFrame(+ plan, still.jpegBytes, still.metadata.rotationDegrees,+ )+ }.onFailure {+ Log.error("CameraViewModel", "Single capture save failed", it)+ }.getOrNull()+ }+ if (uri != null) setLastCaptureUri(uri)+ } finally {+ stillSaveQueue.release()+ } }- finishCapture(uri)- }- } else {- viewModelScope.launch {- val uri = withContext(Dispatchers.IO) {- runCatching { saveCamera2Still(still) }- .onFailure { Log.error("CameraViewModel", "Single capture save failed", it) }- .getOrNull()+ } else {+ viewModelScope.launch {+ val uri = withContext(Dispatchers.IO) {+ runCatching {+ processSingleFrame(plan, still.jpegBytes, still.metadata.rotationDegrees)+ }.getOrNull()+ }+ finishCapture(uri) }- finishCapture(uri) }+ } else {+ onCamera2StillCaptured(still) { uri -> finishCapture(uri) } } }
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 5c789270e3..9d081a960f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -384,12 +384,7 @@ fun CameraViewModel.captureVideoSnapshot() { mirrored = mirrorCaptures, callback = object : com.vayunmathur.camera.platform.camera2.Camera2Session.StillCallback { override fun onStillCaptured(still: com.vayunmathur.camera.platform.camera2.CapturedStill) {- viewModelScope.launch {- val uri = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- runCatching { saveCamera2Still(still) }- .onFailure { Log.error("CameraViewModel", "Video snapshot save failed", it) }- .getOrNull()- }+ onCamera2StillCaptured(still) { uri -> if (uri != null) setLastCaptureUri(uri) } }
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 0c06fedfa9..a1be970c83 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -87,6 +87,13 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { // small: one encoding plus one waiting. A press beyond it takes a plain still. const val MAX_PENDING_MOTION_SAVES = 2 + // Processed stills (AVIF encodes above all) still saving after+ // their shutter was released. Each holds a full-res source until+ // encoded, so keep this small: one encoding plus one waiting. A+ // press beyond it keeps the synchronous save rather than dropping+ // or rerouting the shot.+ const val MAX_PENDING_STILL_SAVES = 2+ val EXPOSURE_TIME_STOPS: List<ExposureTimeStop> = EXPOSURE_TIME_STOPS_TABLE /**@@ -212,10 +219,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val audioInputSourceMutable = MutableStateFlow(AudioInputSource.CAMCORDER) val audioInputSource = audioInputSourceMutable.asStateFlow() - // Recording audio codec. Default AAC preserves the long-standing Recorder- // default; Opus is opt-in and only used when the Recorder reports support.- internal val audioCodecMutable = MutableStateFlow(AudioCodec.AAC)- val audioCodec = audioCodecMutable.asStateFlow()+ // No recording audio-codec state: audio is always Opus+ // (AudioEncoderPolicy), with a video-only recording when a device+ // has no Opus encoder. There is nothing for the user to select. internal val saveTargetMutable = MutableStateFlow<SaveTarget>(SaveTarget.MediaStoreDefault) val saveTarget = saveTargetMutable.asStateFlow()@@ -274,6 +280,19 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal var motionSaveDispatcher: CoroutineDispatcher = Dispatchers.IO internal var motionPhotoSaver: suspend (MotionSaveRequest) -> Uri? = { assembleAndSaveMotionPhoto(it) } + // Background processed-still saves: the encode + MediaStore landing+ // runs after the shutter is released, one at a time (the mutex), in+ // this scope so a shot taken just before leaving still lands. The+ // dispatcher is a var only so tests can drive the state machine.+ internal val stillSaveQueue = com.vayunmathur.camera.domain.StillSaveQueue(MAX_PENDING_STILL_SAVES)+ internal val stillSaveMutex = Mutex()+ internal val stillSaveScope = CoroutineScope(+ SupervisorJob() + CoroutineExceptionHandler { _, e ->+ Log.error("CameraViewModel", "Background still save failed", e)+ }+ )+ internal var stillSaveDispatcher: CoroutineDispatcher = Dispatchers.IO+ internal val locationEnabledMutable = MutableStateFlow(false) val locationEnabled = locationEnabledMutable.asStateFlow() @@ -389,8 +408,8 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { /** The user's chosen bind-time settings, before any recording deferral. */ private val desiredBindSettings = combine(- videoCodecMutable, audioCodecMutable, audioInputSourceMutable, mirrorFrontMutable- ) { video, audio, source, mirror -> BindTimeSettings(video, audio, source, mirror) }+ videoCodecMutable, audioInputSourceMutable, mirrorFrontMutable+ ) { video, source, mirror -> BindTimeSettings(video, source, mirror) } /** * The bind-time settings a session bind must actually use. Codec, audio source and@@ -407,13 +426,13 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { } .runningFold( BindTimeSettings(- CodecSupport.defaultVideoCodec, AudioCodec.AAC, AudioInputSource.CAMCORDER, true+ CodecSupport.defaultVideoCodec, AudioInputSource.CAMCORDER, true ) ) { held, gate -> if (gate.recording) held else gate.settings } .stateIn( viewModelScope, SharingStarted.Eagerly, BindTimeSettings(- CodecSupport.defaultVideoCodec, AudioCodec.AAC, AudioInputSource.CAMCORDER, true+ CodecSupport.defaultVideoCodec, AudioInputSource.CAMCORDER, true ) )
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.ktindex 9e298f96c7..57a0abffd2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelStartup.kt@@ -60,6 +60,11 @@ internal fun CameraViewModel.runStartupSequence() { viewModelScope.launch { sloMoSupportedMutable.value = probeSloMoSupport() }+ // Cache the MediaCodecList AVIF-encoder probe once, off the capture+ // path: StillEncoder only reads the verdict at shot time.+ viewModelScope.launch(Dispatchers.Default) {+ AvifCodecProbe.warmUp()+ } // DEBUG: Night mode resolution question – extension uses default resolution vs max-res, // may be lower so can't take full quality? startDebugLogging()
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 97fb8d25b8..81414d08ed 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -47,23 +47,6 @@ enum class PhotoFormat(@StringRes val labelRes: Int, @StringRes val descriptionR AVIF(R.string.photo_format_avif_label, R.string.photo_format_avif_description), } -/** Audio codecs selectable for video recording, with display text and Recorder mime. */-enum class AudioCodec(- @StringRes val labelRes: Int,- @StringRes val descriptionRes: Int,- val mimeType: String,-) {- AAC(- R.string.audio_codec_aac_label,- R.string.audio_codec_aac_description,- android.media.MediaFormat.MIMETYPE_AUDIO_AAC,- ),- OPUS(- R.string.audio_codec_opus_label,- R.string.audio_codec_opus_description,- android.media.MediaFormat.MIMETYPE_AUDIO_OPUS,- ),-} /** Motion-Photo clip durations (seconds). */ private const val MOTION_ONE_SECOND = 1 private const val MOTION_THREE_SECONDS = 3@@ -100,16 +83,17 @@ enum class AudioInputSource( } /**- * The bind-time recording settings snapshot: video/audio codec, audio source and- * front mirroring are baked into the Recorder/VideoCapture when the session binds- * and cannot change mid-recording. The user's chosen (desired) values live in the- * individual CameraViewModel flows and persist immediately; this snapshot is what+ * The bind-time recording settings snapshot: video codec, audio source and+ * front mirroring are baked into the recording engine when the session binds+ * and cannot change mid-recording. (Audio is always Opus — see+ * AudioEncoderPolicy — so there is no audio-codec value to snapshot.)+ * The user's chosen (desired) values live in the individual+ * CameraViewModel flows and persist immediately; this snapshot is what * a bind actually uses, held unchanged while a recording is in progress and * released to the desired values when it stops (see CameraViewModel.bindTimeSettings). */ data class BindTimeSettings( val videoCodec: VideoCodec,- val audioCodec: AudioCodec, val audioInputSource: AudioInputSource, val mirrorFront: Boolean, )
camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.ktindex 60442f1a43..f1eff71880 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt@@ -41,7 +41,12 @@ object CodecSupport { /** The Recorder can encode HEVC/H.265 (`video/hevc`) on this device. */ val isHevcEncoderAvailable: Boolean by lazy { supports(MediaFormat.MIMETYPE_VIDEO_HEVC) } - /** The Recorder can encode Opus (`audio/opus`) on this device. */+ /**+ * An Opus (`audio/opus`) encoder exists on this device. Opus is the+ * only audio encoding the recording core will ever use (see+ * AudioEncoderPolicy): false means recordings proceed video-only,+ * never AAC.+ */ val isOpusAudioEncoderAvailable: Boolean by lazy { supportsAudio(MediaFormat.MIMETYPE_AUDIO_OPUS) }
camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.ktindex 408e1b2fb9..f7440082da 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StillEncoder.kt@@ -56,6 +56,18 @@ internal object StillEncoder { } else { val upright = uprightCopy(bitmap, rotationDegrees, 0) try {+ // Hardware still encoder first when the device ships+ // one (cached MediaCodecList probe, warmed at startup);+ // on this class of device there is none, so the tuned+ // software ravif path below is the producer.+ val hw = if (AvifHardwareEncoder.isAvailable()) {+ AvifHardwareEncoder.encode(+ upright, exifTiff, StillFormatRouting.AVIF_QUALITY,+ )+ } else {+ null+ }+ hw?.let { return EncodedStill(it, StillFormat.AVIF) } encodeAvif(upright, exifTiff)?.let { return EncodedStill(it, StillFormat.AVIF) } } finally { if (upright !== bitmap) upright.recycle()@@ -81,7 +93,8 @@ internal object StillEncoder { rgba[i * 4 + 2] = (px and 0xFF).toByte() rgba[i * 4 + 3] = (px ushr 24 and 0xFF).toByte() }- return try {+ val started = android.os.SystemClock.elapsedRealtime()+ val encoded = try { StitchNative.encodeAvifExif( rgba, width, height, StillFormatRouting.AVIF_QUALITY, StillFormatRouting.AVIF_SPEED,@@ -91,6 +104,16 @@ internal object StillEncoder { Log.status("StillEncoder", "AVIF native call failed; JPEG fallback", e) null }+ // StillSave breadcrumb (debug level: visible in release, see+ // CameraSaveRouting) so shutter-to-saved timing is provable from+ // logcat: this is the encode segment, on top of capture/decode.+ Log.debug(+ "StillSave",+ "avifEncodeMs=${android.os.SystemClock.elapsedRealtime() - started} " ++ "speed=${StillFormatRouting.AVIF_SPEED} ${width}x$height " ++ "bytes=${encoded?.size ?: -1} source=ravif",+ )+ return encoded } private fun encodeJpeg(bitmap: Bitmap): ByteArray =
camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.ktindex 004db08ee0..d77df57078 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -92,6 +92,15 @@ object StitchNative { rgba: ByteArray, width: Int, height: Int, quality: Float, speed: Int, exif: ByteArray, ): ByteArray? + /**+ * Splices [exif] (a TIFF payload) into an already-encoded AVIF file+ * (e.g. from a hardware `image/avif` MediaCodec encoder, which has no+ * EXIF input) as its ISOBMFF Exif item. Null on any failure — the+ * caller then falls back to the software encoder rather than saving+ * an EXIF-less AVIF.+ */+ external fun muxAvifExif(avif: ByteArray, exif: ByteArray): ByteArray?+ // --- Zero-copy luma on-ramp (Camera2 migration Phase 3) --- /**
camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.ktindex 80d11cd77d..397945cf5b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraCodecSettings.kt@@ -15,7 +15,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R-import com.vayunmathur.camera.platform.AudioCodec import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CodecSupport import com.vayunmathur.camera.platform.VideoCodec@@ -29,17 +28,16 @@ import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.Text /**- * Codec and audio-source pickers owned by [SettingsPage]: the video codec,- * audio codec and audio input source dropdowns. Stateless: the caller passes- * values plus change callbacks.+ * Codec and audio-source pickers owned by [SettingsPage]: the video codec+ * and audio input source dropdowns. (There is no audio-codec picker:+ * recording audio is always Opus.) Stateless: the caller passes values+ * plus change callbacks. */ @Composable fun CameraCodecSettings( videoCodec: VideoCodec,- audioCodec: AudioCodec, audioInputSource: AudioInputSource, onVideoCodecChange: (VideoCodec) -> Unit,- onAudioCodecChange: (AudioCodec) -> Unit, onAudioInputSourceChange: (AudioInputSource) -> Unit, modifier: Modifier = Modifier, ) {@@ -103,79 +101,6 @@ fun CameraCodecSettings( } } - val availableAudioCodecs = remember {- buildList {- add(AudioCodec.AAC)- if (CodecSupport.isOpusAudioEncoderAvailable) add(AudioCodec.OPUS)- }- }- // A stored Opus choice on a device with no Opus encoder falls back to AAC in- // the video session (CameraVideoSession); keep the row visible in that case so- // the summary can name the effective codec instead of silently showing Opus.- val opusUnavailable = audioCodec == AudioCodec.OPUS &&- !CodecSupport.isOpusAudioEncoderAvailable- val effectiveAudioCodec = if (opusUnavailable) AudioCodec.AAC else audioCodec- if (availableAudioCodecs.size > 1 || opusUnavailable) {- SettingsSection(title = stringResource(R.string.settings_audio_codec)) {- // Built from [OutlinedButton] + [DropdownMenu] rather than the library's- // `ExposedDropdownMenu` wrapper, which currently recurses into itself.- var audioCodecExpanded by remember { mutableStateOf(false) }- Box(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp)- ) {- OutlinedButton(- onClick = { audioCodecExpanded = true },- modifier = Modifier.fillMaxWidth()- ) {- Text(- if (opusUnavailable) {- stringResource(- R.string.audio_codec_fallback_summary,- stringResource(effectiveAudioCodec.labelRes),- stringResource(effectiveAudioCodec.descriptionRes),- stringResource(audioCodec.labelRes),- )- } else {- "${stringResource(audioCodec.labelRes)} — ${stringResource(audioCodec.descriptionRes)}"- },- modifier = Modifier.weight(1f),- textAlign = TextAlign.Start,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- )- IconArrowDropDown()- }- DropdownMenu(- expanded = audioCodecExpanded,- onDismissRequest = { audioCodecExpanded = false }- ) {- availableAudioCodecs.forEach { codec ->- SelectableDropdownMenuItem(- selected = codec == effectiveAudioCodec,- onClick = {- onAudioCodecChange(codec)- audioCodecExpanded = false- },- text = {- Column {- Text(stringResource(codec.labelRes))- Text(- stringResource(codec.descriptionRes),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- }- },- selectedLeadingIcon = { IconCheck() },- )- }- }- }- }- }- SettingsSection(title = stringResource(R.string.settings_audio_source)) { // Built from [OutlinedButton] + [DropdownMenu] rather than the library's // `ExposedDropdownMenu` wrapper, which currently recurses into itself.
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex 8c47d0fc01..2eb6264287 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -6,7 +6,6 @@ import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.MutableState import androidx.compose.runtime.setValue import com.vayunmathur.camera.platform.AspectRatioOption-import com.vayunmathur.camera.platform.AudioCodec import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.CameraViewModel@@ -31,7 +30,6 @@ import com.vayunmathur.camera.platform.VideoCodec val flashMode: FlashMode, val torchEnabled: Boolean, val videoCodec: VideoCodec,- val audioCodec: AudioCodec = AudioCodec.AAC, val audioInputSource: AudioInputSource, val isRecording: Boolean, val recordingDuration: Long,
camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.ktindex 4361dc666c..ca1ff5b441 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/RememberCameraScreenState.kt@@ -24,7 +24,6 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val flashMode by viewModel.flashMode.collectAsState() val torchEnabled by viewModel.torchEnabled.collectAsState() val videoCodec by viewModel.videoCodec.collectAsState()- val audioCodec by viewModel.audioCodec.collectAsState() val audioInputSource by viewModel.audioInputSource.collectAsState() val isRecording by viewModel.isRecording.collectAsState() val recordingDuration by viewModel.recordingDurationSec.collectAsState()@@ -87,7 +86,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val deviceRotationState = remember { mutableIntStateOf(0) } return remember(- cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, videoCodec, audioCodec, audioInputSource, mirrorFront, isRecording, recordingDuration,+ cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, videoCodec, audioInputSource, mirrorFront, isRecording, recordingDuration, timerCountdown, qrResult, aspectRatio, zoomRatio, timerDuration, isCapturing, burstActive, burstCount, focusLocked, recordingPaused, micMuted, videoSnapshotSupported, lastCaptureUri, gridEnabled, levelEnabled, roll,@@ -110,7 +109,6 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen flashMode = flashMode, torchEnabled = torchEnabled, videoCodec = videoCodec,- audioCodec = audioCodec, audioInputSource = audioInputSource, isRecording = isRecording, recordingDuration = recordingDuration,
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex 3017681ce0..e2796df8e7 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -35,7 +35,6 @@ import com.vayunmathur.camera.platform.MotionPhotoDuration import com.vayunmathur.camera.data.SafDocuments import com.vayunmathur.camera.data.SaveTarget import com.vayunmathur.camera.data.clearSaveTreeUri-import com.vayunmathur.camera.data.setAudioCodec import com.vayunmathur.camera.data.setAudioInputSource import com.vayunmathur.camera.data.setEdgeSharpeningEnabled import com.vayunmathur.camera.data.setLocationEnabled@@ -59,7 +58,6 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM val locationEnabled by viewModel.locationEnabled.collectAsState() val videoCodec by viewModel.videoCodec.collectAsState() val photoFormat by viewModel.photoFormat.collectAsState()- val audioCodec by viewModel.audioCodec.collectAsState() val audioInputSource by viewModel.audioInputSource.collectAsState() val mirrorFront by viewModel.mirrorFront.collectAsState() val noiseReductionEnabled by viewModel.noiseReductionEnabled.collectAsState()@@ -141,10 +139,8 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM ) CameraCodecSettings( videoCodec = videoCodec,- audioCodec = audioCodec, audioInputSource = audioInputSource, onVideoCodecChange = { viewModel.setVideoCodec(it); noteIfDeferred() },- onAudioCodecChange = { viewModel.setAudioCodec(it); noteIfDeferred() }, onAudioInputSourceChange = { viewModel.setAudioInputSource(it); noteIfDeferred() }, )
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 5a394382a8..eeadbfb7ae 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -99,22 +99,6 @@ <item quantity="other">%1$d seconds</item> </plurals> - <!-- Audio codec settings: codec used for video recording audio -->- <!-- SettingsPage: section header for audio codec selection -->- <string name="settings_audio_codec">Audio codec</string>- <!-- SettingsPage: audio codec summary when the stored codec is unavailable on this device- and recording falls back to the effective codec. %1$s = effective codec label,- %2$s = effective codec description, %3$s = stored (unavailable) codec label -->- <string name="audio_codec_fallback_summary">%1$s — %2$s (%3$s unavailable)</string>- <!-- Audio codec option label: AAC -->- <string name="audio_codec_aac_label">AAC</string>- <!-- Audio codec description: most compatible -->- <string name="audio_codec_aac_description">Most compatible</string>- <!-- Audio codec option label: Opus -->- <string name="audio_codec_opus_label">Opus</string>- <!-- Audio codec description: more efficient than AAC -->- <string name="audio_codec_opus_description">More efficient</string>- <!-- Audio input source settings (SettingsPage): mic source used for video recordings --> <!-- SettingsPage: section header for audio input source selection --> <string name="settings_audio_source">Audio input source</string>
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 93c6c29f09..69f09fdefb 100644--- a/camera/src/main/rust/src/avif.rs+++ b/camera/src/main/rust/src/avif.rs@@ -87,9 +87,17 @@ pub fn encode_avif_with_exif( }) .collect(); let img = Img::new(pixels.as_slice(), width, height);+ // Explicit thread count: rav1e tiles the frame across threads, and the+ // default (`None`) silently inherits whatever size the global rayon+ // pool happened to be created with. Pinning it to the device's+ // parallelism makes the tile/thread split deterministic on every call.+ let threads = std::thread::available_parallelism()+ .map(|n| n.get())+ .unwrap_or(1); let mut encoder = Encoder::new() .with_quality(quality.clamp(QUALITY_MIN, QUALITY_MAX)) .with_speed(speed.clamp(SPEED_MIN, SPEED_MAX))+ .with_num_threads(Some(threads)) .with_bit_depth(ravif::BitDepth::Eight); if let Some(exif) = exif { encoder = encoder.with_exif(exif.to_vec());@@ -140,53 +148,6 @@ pub fn avif_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { )) } -/// One parsed ISOBMFF box: type plus absolute payload span in the file.-#[cfg(test)]-struct BoxSpan {- typ: [u8; 4],- payload: std::ops::Range<usize>,-}--#[cfg(test)]-fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {- let mut out = Vec::new();- let mut off = span.start;- while off + 8 <= span.end && off + 8 <= bytes.len() {- let size32 = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]);- let (size, header) = if size32 == 1 && off + 16 <= bytes.len() {- (- u64::from_be_bytes(bytes[off + 8..off + 16].try_into().unwrap()) as usize,- 16usize,- )- } else if size32 == 0 {- (span.end.saturating_sub(off), 8usize)- } else {- (size32 as usize, 8usize)- };- if size < header || off + size > bytes.len() {- break;- }- let mut typ: [u8; 4] = bytes[off + 4..off + 8].try_into().unwrap();- let payload_start = if typ == *b"uuid" { off + header + 16 } else { off + header };- if typ == *b"uuid" {- typ = *b"uuid";- }- out.push(BoxSpan { typ, payload: payload_start..off + size });- off += size;- }- out-}--#[cfg(test)]-fn read_uint(bytes: &[u8], pos: &mut usize, size: usize) -> Option<u64> {- let mut value = 0u64;- for _ in 0..size {- value = (value << 8) | *bytes.get(*pos)? as u64;- *pos += 1;- }- Some(value)-}- /// Reconstructs the Exif item's data (`[u32 TIFF offset][TIFF…]`) by /// walking `meta` → `iinf` (find the `Exif` infe id) → `iloc` (that id's /// extents into the file). `None` when the file carries no Exif item.@@ -275,169 +236,8 @@ pub fn avif_exif_tiff(bytes: &[u8]) -> Option<Vec<u8>> { } #[cfg(test)]-mod avif_tests {- use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};-- /// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,- /// then a marker tail so content assertions can find the payload.- fn test_tiff() -> Vec<u8> {- let mut tiff = Vec::new();- tiff.extend_from_slice(b"II\x2a\0");- tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8- tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry- tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation- tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT- tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1- tiff.extend_from_slice(&1u16.to_le_bytes()); // value 1 (Normal)- tiff.extend_from_slice(&[0, 0]);- tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD- tiff.extend_from_slice(b"GPSMARK");- tiff- }-- fn gradient(width: usize, height: usize) -> Vec<u8> {- let mut px = Vec::with_capacity(width * height * 4);- for y in 0..height {- for x in 0..width {- px.extend_from_slice(&[- (x % 256) as u8,- (y % 256) as u8,- ((x + y) % 256) as u8,- 255,- ]);- }- }- px- }-- #[test]- fn encodes_synthetic_rgba_with_avif_header_and_dimensions() {- let rgba = gradient(64, 48);- let bytes = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");- assert!(has_avif_magic(&bytes), "missing ftypavif magic");- assert_eq!(avif_dimensions(&bytes), Some((64, 48)));- }-- #[test]- fn exif_item_round_trips_through_isobmff_boxes() {- let rgba = gradient(64, 48);- let tiff = test_tiff();- let bytes = encode_avif_with_exif(&rgba, 64, 48, 80.0, 10, Some(&tiff))- .expect("encode with exif must succeed");- assert!(has_avif_magic(&bytes));- assert_eq!(avif_dimensions(&bytes), Some((64, 48)));- // Item framing: [u32 offset=0][TIFF], located via iinf+iloc.- let item = avif_exif_item(&bytes).expect("Exif item must be present via iinf/iloc");- assert_eq!(&item[..4], &[0, 0, 0, 0]);- let parsed = avif_exif_tiff(&bytes).expect("TIFF payload must parse back");- assert_eq!(parsed, tiff);- assert!(parsed.starts_with(b"II\x2a\0"));- assert!(parsed.windows(7).any(|w| w == b"GPSMARK"));- }-- #[test]- fn no_exif_item_when_no_payload_given() {- let rgba = gradient(32, 32);- let bytes = encode_avif(&rgba, 32, 32, 80.0, 10).expect("encode must succeed");- assert!(avif_exif_item(&bytes).is_none());- }-- #[test]- fn non_tiff_exif_is_rejected_so_kotlin_falls_back_to_jpeg() {- let rgba = gradient(32, 32);- assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"not a tiff")).is_none());- assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"")).is_none());- }-- #[test]- fn rejects_mismatched_and_oversized_input() {- assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());- assert!(encode_avif(&[], 0, 0, 80.0, 10).is_none());- 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 --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 (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()- );- }- }- }-}+#[path = "avif_tests.rs"]+mod avif_tests; /// JNI entry for `StitchNative.encodeAvifExif`: RGBA frame + TIFF Exif /// payload in (empty array = no payload), AVIF bytes with a muxed Exif
camera/src/main/rust/src/avif_mux.rs
diff --git a/camera/src/main/rust/src/avif_mux.rs b/camera/src/main/rust/src/avif_mux.rsnew file mode 100644index 0000000000..723f7d478a--- /dev/null+++ b/camera/src/main/rust/src/avif_mux.rs@@ -0,0 +1,343 @@+//! Post-encode EXIF mux for already-encoded AVIF files (see+//! [`mux_avif_exif`]): splices a TIFF Exif item into a bare AVIF, e.g.+//! one produced by a hardware `image/avif` MediaCodec encoder.++use crate::avif::looks_like_exif;++/// One parsed ISOBMFF box: type plus absolute payload span in the file.+struct BoxSpan {+ typ: [u8; 4],+ start: usize,+ payload: std::ops::Range<usize>,+}++fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<BoxSpan> {+ let mut out = Vec::new();+ let mut off = span.start;+ while off + 8 <= span.end && off + 8 <= bytes.len() {+ let size32 = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]);+ let (size, header) = if size32 == 1 && off + 16 <= bytes.len() {+ (+ u64::from_be_bytes(bytes[off + 8..off + 16].try_into().unwrap()) as usize,+ 16usize,+ )+ } else if size32 == 0 {+ (span.end.saturating_sub(off), 8usize)+ } else {+ (size32 as usize, 8usize)+ };+ if size < header || off + size > bytes.len() {+ break;+ }+ let mut typ: [u8; 4] = bytes[off + 4..off + 8].try_into().unwrap();+ let payload_start = if typ == *b"uuid" { off + header + 16 } else { off + header };+ if typ == *b"uuid" {+ typ = *b"uuid";+ }+ out.push(BoxSpan { typ, start: off, payload: payload_start..off + size });+ off += size;+ }+ out+}++fn read_uint(bytes: &[u8], pos: &mut usize, size: usize) -> Option<u64> {+ let mut value = 0u64;+ for _ in 0..size {+ value = (value << 8) | *bytes.get(*pos)? as u64;+ *pos += 1;+ }+ Some(value)+}++/// Serialises one ISOBMFF box with a 32-bit size header.+fn box_bytes(typ: &[u8; 4], payload: &[u8]) -> Option<Vec<u8>> {+ let size = u32::try_from(payload.len().checked_add(8)?).ok()?;+ let mut out = Vec::with_capacity(size as usize);+ out.extend_from_slice(&size.to_be_bytes());+ out.extend_from_slice(typ);+ out.extend_from_slice(payload);+ Some(out)+}++/// Inserts [exif] (a TIFF payload) into an already-encoded AVIF file as+/// its Exif item, returning the rewritten file. This is the post-mux a+/// hardware `image/avif` MediaCodec encoder needs: such encoders emit a+/// bare AVIF with no way to attach EXIF at configure time, so the item+/// (`iinf`/`iloc`/`iref` entries plus the framed item data in a trailing+/// `mdat`) is spliced in here. Returns `None` for anything this splicer+/// does not understand — a file that already has an Exif item, no+/// primary item (`pitm`), an `iloc` using idat construction, oversized+/// boxes — so the caller falls back to the software encoder rather than+/// shipping a malformed or EXIF-less file.+pub fn mux_avif_exif(avif: &[u8], exif: &[u8]) -> Option<Vec<u8>> {+ if avif.len() < 12 || &avif[4..8] != b"ftyp" || exif.is_empty() || !looks_like_exif(exif) {+ return None;+ }+ let top = parse_boxes(avif, 0..avif.len());+ let meta = top.iter().find(|b| &b.typ == b"meta")?;+ let meta_children_span = (meta.payload.start + 4)..meta.payload.end;+ let children = parse_boxes(avif, meta_children_span.clone());+ let raw_child = |b: &BoxSpan| avif[b.start..b.payload.end].to_vec();++ // Primary item id (for the cdsc reference) from `pitm`.+ let pitm = children.iter().find(|b| &b.typ == b"pitm")?;+ let pitm_version = *avif.get(pitm.payload.start)?;+ let primary_id: u32 = if pitm_version == 1 {+ u32::from_be_bytes(avif.get(pitm.payload.start + 4..pitm.payload.start + 8)?.try_into().ok()?)+ } else {+ u16::from_be_bytes(avif.get(pitm.payload.start + 4..pitm.payload.start + 6)?.try_into().ok()?) as u32+ };++ // `iinf`: bump the entry count and append an Exif `infe` (v2).+ let iinf = children.iter().find(|b| &b.typ == b"iinf")?;+ let iinf_version = *avif.get(iinf.payload.start)?;+ let (count_len, entry_count) = if iinf_version == 1 { (4usize, {+ u32::from_be_bytes(avif.get(iinf.payload.start + 4..iinf.payload.start + 8)?.try_into().ok()?) as usize+ }) } else { (2usize, {+ u16::from_be_bytes(avif.get(iinf.payload.start + 4..iinf.payload.start + 6)?.try_into().ok()?) as usize+ }) };+ let infes = parse_boxes(avif, (iinf.payload.start + 4 + count_len)..iinf.payload.end);+ let mut max_id: u32 = primary_id;+ for infe in &infes {+ let p = infe.payload.start + 4;+ let id = u16::from_be_bytes(avif.get(p..p + 2)?.try_into().ok()?) as u32;+ max_id = max_id.max(id);+ if avif.get(p + 4..p + 8)? == b"Exif" {+ return None; // already carries an Exif item+ }+ }+ let _ = entry_count;+ let new_id = max_id.checked_add(1)?;+ if new_id > u16::MAX as u32 {+ return None;+ }+ let mut infe_payload = Vec::new();+ infe_payload.extend_from_slice(&2u32.to_be_bytes()); // version 2, flags 0+ infe_payload.extend_from_slice(&(new_id as u16).to_be_bytes());+ infe_payload.extend_from_slice(&0u16.to_be_bytes()); // protection index+ infe_payload.extend_from_slice(b"Exif");+ infe_payload.push(0); // empty item name+ let infe_box = box_bytes(b"infe", &infe_payload)?;+ let mut iinf_payload = Vec::new();+ iinf_payload.extend_from_slice(avif.get(iinf.payload.start..iinf.payload.start + 4)?);+ if iinf_version == 1 {+ iinf_payload.extend_from_slice(&((entry_count + 1) as u32).to_be_bytes());+ } else {+ iinf_payload.extend_from_slice(&((entry_count + 1) as u16).to_be_bytes());+ }+ for infe in &infes {+ iinf_payload.extend_from_slice(&raw_child(infe));+ }+ iinf_payload.extend_from_slice(&infe_box);+ let iinf_box = box_bytes(b"iinf", &iinf_payload)?;++ // `iref`: add (or extend) with a `cdsc` reference Exif -> primary.+ let make_ref_box = |id_bytes: usize| -> Option<Vec<u8>> {+ let mut payload = Vec::new();+ payload.extend_from_slice(&0u32.to_be_bytes()); // version/flags+ if id_bytes == 4 {+ payload.extend_from_slice(&new_id.to_be_bytes());+ payload.extend_from_slice(&1u16.to_be_bytes());+ payload.extend_from_slice(&primary_id.to_be_bytes());+ } else {+ payload.extend_from_slice(&(new_id as u16).to_be_bytes());+ payload.extend_from_slice(&1u16.to_be_bytes());+ payload.extend_from_slice(&(primary_id as u16).to_be_bytes());+ }+ box_bytes(b"cdsc", &payload)+ };+ let (iref_box, iref_is_new) = match children.iter().find(|b| &b.typ == b"iref") {+ Some(iref) => {+ let version = *avif.get(iref.payload.start)?;+ let id_bytes = if version == 1 { 4 } else { 2 };+ let mut payload = avif.get(iref.payload.start..iref.payload.end)?.to_vec();+ payload.extend_from_slice(&make_ref_box(id_bytes)?);+ (box_bytes(b"iref", &payload)?, false)+ }+ None => {+ let mut payload = Vec::new();+ payload.extend_from_slice(&0u32.to_be_bytes()); // iref version 0+ payload.extend_from_slice(&make_ref_box(2)?);+ (box_bytes(b"iref", &payload)?, true)+ }+ };++ // Rebuilt meta size decides how far every post-meta extent shifts.+ // `iloc` is rebuilt below at a fixed layout; compute its size first.+ let iloc_old = children.iter().find(|b| &b.typ == b"iloc")?;+ let iloc_items = parse_iloc(avif, iloc_old)?;+ // New iloc: version 1, offset/length 4 bytes, no base offset/index.+ let iloc_payload_len = 8 + (iloc_items.len() + 1) * (2 + 2 + 2 + 2 + 2 * 4);+ let iloc_box_len = iloc_payload_len + 8;++ let mut meta_len = 4usize; // version/flags+ for child in &children {+ meta_len += match &child.typ {+ b"iinf" => iinf_box.len(),+ b"iloc" => iloc_box_len,+ b"iref" => iref_box.len(),+ _ => child.payload.end - child.start,+ };+ }+ if iref_is_new {+ meta_len += iref_box.len();+ }+ let new_meta_total = meta_len + 8;+ let old_meta_total = meta.payload.end - meta.start;+ let delta = new_meta_total as i64 - old_meta_total as i64;++ // Exif item data lives in a trailing mdat: [u32 offset = 0][TIFF].+ let framed_len = 4 + exif.len();+ let mdat_start = (avif.len() as i64 + delta) as usize;+ let exif_extent_offset = mdat_start + 8;++ // Rebuild `iloc` with shifted extents plus the new Exif item.+ let mut iloc_payload = Vec::new();+ iloc_payload.extend_from_slice(&[1u8, 0, 0, 0]); // version 1, flags 0+ iloc_payload.push((4 << 4) | 4); // offset_size=4, length_size=4+ iloc_payload.push(0); // base_offset_size=0, index_size=0+ iloc_payload.extend_from_slice(&((iloc_items.len() + 1) as u16).to_be_bytes());+ let shift = |offset: u64| -> Option<u32> {+ let adjusted = if offset as usize >= meta.payload.end {+ offset as i64 + delta+ } else {+ offset as i64+ };+ u32::try_from(adjusted).ok()+ };+ for item in &iloc_items {+ if item.construction_method != 0 {+ return None; // idat-constructed items are not spliced+ }+ iloc_payload.extend_from_slice(&(item.item_id as u16).to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes()); // construction: file+ iloc_payload.extend_from_slice(&0u16.to_be_bytes()); // data reference+ iloc_payload.extend_from_slice(&(item.extents.len() as u16).to_be_bytes());+ for &(offset, length) in &item.extents {+ iloc_payload.extend_from_slice(&shift(offset)?.to_be_bytes());+ iloc_payload.extend_from_slice(&(length as u32).to_be_bytes());+ }+ }+ iloc_payload.extend_from_slice(&(new_id as u16).to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&0u16.to_be_bytes());+ iloc_payload.extend_from_slice(&1u16.to_be_bytes()); // one extent+ iloc_payload.extend_from_slice(&(exif_extent_offset as u32).to_be_bytes());+ iloc_payload.extend_from_slice(&(framed_len as u32).to_be_bytes());+ let iloc_box = box_bytes(b"iloc", &iloc_payload)?;+ debug_assert_eq!(iloc_box.len(), iloc_box_len);++ // Reassemble: prefix, rebuilt meta, suffix, trailing mdat.+ let mut out = Vec::with_capacity(mdat_start + 8 + framed_len);+ out.extend_from_slice(&avif[..meta.start]);+ let meta_box = {+ let mut payload = Vec::with_capacity(meta_len);+ payload.extend_from_slice(avif.get(meta.payload.start..meta.payload.start + 4)?);+ for child in &children {+ match &child.typ {+ b"iinf" => payload.extend_from_slice(&iinf_box),+ b"iloc" => payload.extend_from_slice(&iloc_box),+ b"iref" => payload.extend_from_slice(&iref_box),+ _ => payload.extend_from_slice(&raw_child(child)),+ }+ }+ if iref_is_new {+ payload.extend_from_slice(&iref_box);+ }+ box_bytes(b"meta", &payload)?+ };+ out.extend_from_slice(&meta_box);+ out.extend_from_slice(&avif[meta.payload.end..]);+ debug_assert_eq!(out.len(), mdat_start);+ let mut mdat_payload = Vec::with_capacity(framed_len);+ mdat_payload.extend_from_slice(&0u32.to_be_bytes());+ mdat_payload.extend_from_slice(exif);+ out.extend_from_slice(&box_bytes(b"mdat", &mdat_payload)?);+ Some(out)+}++/// One `iloc` item before rewriting: id, construction method, extents.+struct IlocItem {+ item_id: u32,+ construction_method: u16,+ extents: Vec<(u64, u64)>,+}++/// Parses the items of an `iloc` box (versions 0-2) into absolute+/// (offset, length) extents. `None` on any layout surprise.+fn parse_iloc(bytes: &[u8], iloc: &BoxSpan) -> Option<Vec<IlocItem>> {+ let mut pos = iloc.payload.start + 4; // version/flags+ let version = *bytes.get(iloc.payload.start)?;+ let sizes = *bytes.get(pos)?;+ pos += 1;+ let offset_size = (sizes >> 4) as usize;+ let length_size = (sizes & 0x0F) as usize;+ let base_sizes = *bytes.get(pos)?;+ pos += 1;+ let base_offset_size = (base_sizes >> 4) as usize;+ let index_size = (base_sizes & 0x0F) as usize;+ let item_count = if version == 2 {+ read_uint(bytes, &mut pos, 4)? as usize+ } else {+ read_uint(bytes, &mut pos, 2)? as usize+ };+ let mut items = Vec::with_capacity(item_count);+ for _ in 0..item_count {+ let item_id = read_uint(bytes, &mut pos, 2)? as u32;+ let construction = if version == 1 || version == 2 {+ read_uint(bytes, &mut pos, 2)? as u16+ } else {+ 0+ };+ read_uint(bytes, &mut pos, 2)?; // data_reference_index+ let base_offset = read_uint(bytes, &mut pos, base_offset_size)?;+ let extent_count = read_uint(bytes, &mut pos, 2)? as usize;+ let mut extents = Vec::with_capacity(extent_count);+ for _ in 0..extent_count {+ if (version == 1 || version == 2) && index_size > 0 {+ read_uint(bytes, &mut pos, index_size)?;+ }+ let offset = read_uint(bytes, &mut pos, offset_size)?;+ let length = read_uint(bytes, &mut pos, length_size)?;+ extents.push((base_offset + offset, length));+ }+ items.push(IlocItem { item_id, construction_method: construction, extents });+ }+ Some(items)+}++/// JNI entry for `StitchNative.muxAvifExif`: splices a TIFF Exif item+/// into an already-encoded (e.g. hardware-encoded) AVIF file. Null on+/// any failure so Kotlin falls back to the software encoder.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_muxAvifExif<'l>(+ mut env: jni::EnvUnowned<'l>,+ _class: jni::objects::JClass<'l>,+ avif: jni::objects::JByteArray<'l>,+ exif: jni::objects::JByteArray<'l>,+) -> jni::sys::jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jbyteArray> {+ let null = std::ptr::null_mut();+ let bytes = match env.convert_byte_array(&avif) {+ Ok(b) => b,+ Err(_) => return Ok(null),+ };+ let exif_bytes = match env.convert_byte_array(&exif) {+ Ok(b) => b,+ Err(_) => return Ok(null),+ };+ let muxed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ mux_avif_exif(&bytes, &exif_bytes)+ }))+ .unwrap_or(None);+ match muxed {+ Some(b) => match env.byte_array_from_slice(&b) {+ Ok(arr) => Ok(arr.into_raw()),+ Err(_) => Ok(null),+ },+ None => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}+
camera/src/main/rust/src/avif_tests.rs
diff --git a/camera/src/main/rust/src/avif_tests.rs b/camera/src/main/rust/src/avif_tests.rsnew file mode 100644index 0000000000..a996835393--- /dev/null+++ b/camera/src/main/rust/src/avif_tests.rs@@ -0,0 +1,184 @@+use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};+use crate::avif_mux::mux_avif_exif;++ use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};++ /// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,+ /// then a marker tail so content assertions can find the payload.+ fn test_tiff() -> Vec<u8> {+ let mut tiff = Vec::new();+ tiff.extend_from_slice(b"II\x2a\0");+ tiff.extend_from_slice(&8u32.to_le_bytes()); // IFD0 at offset 8+ tiff.extend_from_slice(&1u16.to_le_bytes()); // one entry+ tiff.extend_from_slice(&0x0112u16.to_le_bytes()); // Orientation+ tiff.extend_from_slice(&3u16.to_le_bytes()); // SHORT+ tiff.extend_from_slice(&1u32.to_le_bytes()); // count 1+ tiff.extend_from_slice(&1u16.to_le_bytes()); // value 1 (Normal)+ tiff.extend_from_slice(&[0, 0]);+ tiff.extend_from_slice(&0u32.to_le_bytes()); // no next IFD+ tiff.extend_from_slice(b"GPSMARK");+ tiff+ }++ fn gradient(width: usize, height: usize) -> Vec<u8> {+ let mut px = Vec::with_capacity(width * height * 4);+ for y in 0..height {+ for x in 0..width {+ px.extend_from_slice(&[+ (x % 256) as u8,+ (y % 256) as u8,+ ((x + y) % 256) as u8,+ 255,+ ]);+ }+ }+ px+ }++ #[test]+ fn encodes_synthetic_rgba_with_avif_header_and_dimensions() {+ let rgba = gradient(64, 48);+ let bytes = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");+ assert!(has_avif_magic(&bytes), "missing ftypavif magic");+ assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+ }++ #[test]+ fn exif_item_round_trips_through_isobmff_boxes() {+ let rgba = gradient(64, 48);+ let tiff = test_tiff();+ let bytes = encode_avif_with_exif(&rgba, 64, 48, 80.0, 10, Some(&tiff))+ .expect("encode with exif must succeed");+ assert!(has_avif_magic(&bytes));+ assert_eq!(avif_dimensions(&bytes), Some((64, 48)));+ // Item framing: [u32 offset=0][TIFF], located via iinf+iloc.+ let item = avif_exif_item(&bytes).expect("Exif item must be present via iinf/iloc");+ assert_eq!(&item[..4], &[0, 0, 0, 0]);+ let parsed = avif_exif_tiff(&bytes).expect("TIFF payload must parse back");+ assert_eq!(parsed, tiff);+ assert!(parsed.starts_with(b"II\x2a\0"));+ assert!(parsed.windows(7).any(|w| w == b"GPSMARK"));+ }++ #[test]+ fn mux_splices_exif_into_encoded_avif() {+ let rgba = gradient(64, 48);+ let tiff = test_tiff();+ let bare = encode_avif(&rgba, 64, 48, 80.0, 10).expect("encode must succeed");+ assert!(avif_exif_item(&bare).is_none());+ let muxed = mux_avif_exif(&bare, &tiff).expect("mux must succeed");+ if let Ok(dir) = std::env::var("AVIF_BENCH_DIR") {+ let _ = std::fs::write(format!("{dir}/muxed64.avif"), &muxed);+ }+ assert!(has_avif_magic(&muxed));+ assert_eq!(avif_dimensions(&muxed), Some((64, 48)));+ let parsed = avif_exif_tiff(&muxed).expect("muxed TIFF must parse back via iinf/iloc");+ assert_eq!(parsed, tiff);+ // A second mux (file already has an Exif item) and bad inputs refuse.+ assert!(mux_avif_exif(&muxed, &tiff).is_none());+ assert!(mux_avif_exif(&bare, b"not a tiff").is_none());+ assert!(mux_avif_exif(b"not an avif", &tiff).is_none());+ }++ #[test]+ fn no_exif_item_when_no_payload_given() {+ let rgba = gradient(32, 32);+ let bytes = encode_avif(&rgba, 32, 32, 80.0, 10).expect("encode must succeed");+ assert!(avif_exif_item(&bytes).is_none());+ }++ #[test]+ fn non_tiff_exif_is_rejected_so_kotlin_falls_back_to_jpeg() {+ let rgba = gradient(32, 32);+ assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"not a tiff")).is_none());+ assert!(encode_avif_with_exif(&rgba, 32, 32, 80.0, 10, Some(b"")).is_none());+ }++ #[test]+ fn rejects_mismatched_and_oversized_input() {+ assert!(encode_avif(&[0u8; 10], 64, 48, 80.0, 10).is_none());+ assert!(encode_avif(&[], 0, 0, 80.0, 10).is_none());+ 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 --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 (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/domain/StillFormatRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.ktindex 5bd25d8408..e13d61965a 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillFormatRoutingTest.kt@@ -124,6 +124,15 @@ class StillFormatRoutingTest { assertFalse(StillFormatRouting.avifPrecludesMotionPhoto(StillFormat.JPEG, nativeAvailable = true)) } + @Test+ fun avifSpeedAndQualityTargetsArePinned() {+ // Quality target unchanged by the speed tuning; speed 10 is the+ // measured knee (see AVIF_SPEED doc: ~4.6x faster at 8 threads+ // for -0.06 dB PSNR, +3.6% size at quality 80).+ assertEquals(80f, StillFormatRouting.AVIF_QUALITY)+ assertEquals(10, StillFormatRouting.AVIF_SPEED)+ }+ @Test fun extensionAndMimeMatchContainer() { assertEquals("jpg", StillFormatRouting.extension(StillFormat.JPEG))
camera/src/test/java/com/vayunmathur/camera/domain/StillSaveQueueTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/StillSaveQueueTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/StillSaveQueueTest.ktnew file mode 100644index 0000000000..41adb67bb2--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/StillSaveQueueTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class StillSaveQueueTest {++ @Test+ fun reservesUpToCapacityThenRefuses() {+ val q = StillSaveQueue(2)+ assertTrue(q.tryReserve())+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ assertEquals(2, q.pending)+ }++ @Test+ fun releaseFreesASlot() {+ val q = StillSaveQueue(1)+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ q.release()+ assertEquals(0, q.pending)+ assertTrue(q.tryReserve())+ }++ @Test+ fun extraReleaseNeverGoesNegative() {+ val q = StillSaveQueue(1)+ q.release()+ assertEquals(0, q.pending)+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ }++ @Test+ fun concurrentReservationsNeverExceedCapacity() {+ val q = StillSaveQueue(3)+ val granted = java.util.concurrent.atomic.AtomicInteger()+ val threads = List(16) {+ Thread { repeat(100) { if (q.tryReserve()) granted.incrementAndGet() } }+ }+ threads.forEach { it.start() }+ threads.forEach { it.join() }+ assertEquals(3, granted.get())+ assertEquals(3, q.pending)+ }++ @Test+ fun rejectsNonPositiveCapacity() {+ assertFailsWith<IllegalArgumentException> { StillSaveQueue(0) }+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/AvifCodecRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/AvifCodecRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/AvifCodecRoutingTest.ktnew file mode 100644index 0000000000..1b7a943a07--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/AvifCodecRoutingTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.camera.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The hardware-AVIF routing rule: only an `image/avif` encoder counts.+ * Pixel-class devices ship a (software) `video/av01` encoder only — that+ * must never be mistaken for a still encoder.+ */+class AvifCodecRoutingTest {++ private fun videoAv1(name: String = "c2.google.av1.encoder") =+ AvifCodecEntry(name, AV1_VIDEO_MIME, hardwareAccelerated = false, maxWidth = 1920, maxHeight = 1080)++ @Test+ fun videoAv1EncoderAloneIsNotAStillEncoder() {+ val entries = listOf(videoAv1())+ assertNull(AvifCodecRouting.stillEncoder(entries))+ assertFalse(AvifCodecRouting.hasHardwareStillEncoder(entries))+ }++ @Test+ fun noEncodersMeansSoftwarePath() {+ assertNull(AvifCodecRouting.stillEncoder(emptyList()))+ assertFalse(AvifCodecRouting.hasHardwareStillEncoder(emptyList()))+ }++ @Test+ fun imageAvifEncoderIsSelectedOverVideoAv1() {+ val hw = AvifCodecEntry("c2.vendor.avif.encoder", AVIF_IMAGE_MIME, true, 8192, 8192)+ val entries = listOf(videoAv1(), hw)+ assertEquals(hw, AvifCodecRouting.stillEncoder(entries))+ assertTrue(AvifCodecRouting.hasHardwareStillEncoder(entries))+ }++ @Test+ fun softwareImageAvifEncoderIsUsableButNotHardware() {+ val sw = AvifCodecEntry("c2.android.avif.encoder", AVIF_IMAGE_MIME, false, null, null)+ assertEquals(sw, AvifCodecRouting.stillEncoder(listOf(sw)))+ assertFalse(AvifCodecRouting.hasHardwareStillEncoder(listOf(sw)))+ }++ @Test+ fun sizeCapIsRespectedAndUnknownCapAccepts() {+ val capped = AvifCodecEntry("enc", AVIF_IMAGE_MIME, true, 4000, 3000)+ assertTrue(AvifCodecRouting.fitsSize(capped, 4000, 3000))+ assertFalse(AvifCodecRouting.fitsSize(capped, 4080, 3072))+ val uncapped = AvifCodecEntry("enc", AVIF_IMAGE_MIME, true, null, null)+ assertTrue(AvifCodecRouting.fitsSize(uncapped, 4080, 3072))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.ktindex 3edafe8ce6..b514438254 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/StillEncoderNativeTest.kt@@ -49,6 +49,26 @@ class StillEncoderNativeTest { assertEquals(null, StitchNative.encodeAvifExif(rgba, width, height, 80f, 10, byteArrayOf(1, 2, 3))) } + @Test+ fun muxAvifExifSplicesExifItemIntoBareAvif() {+ if (!StitchNative.isAvailable) return+ val width = 64+ val height = 48+ val rgba = ByteArray(width * height * 4) { 0x80.toByte() }+ val bare = StitchNative.encodeAvif(rgba, width, height, 80f, 10)+ assertNotNull(bare)+ val tiff = "II*\u0000\u0008\u0000\u0000\u0000GPSMARK".toByteArray(Charsets.ISO_8859_1)+ val muxed = StitchNative.muxAvifExif(bare, tiff)+ assertNotNull(muxed)+ assertEquals("ftypavif", String(muxed, 4, 8, Charsets.US_ASCII))+ val asText = String(muxed, Charsets.ISO_8859_1)+ assertTrue("Exif" in asText)+ assertTrue("GPSMARK" in asText)+ // Non-TIFF payloads and double-muxing are refused (software fallback).+ assertEquals(null, StitchNative.muxAvifExif(bare, byteArrayOf(1, 2, 3)))+ assertEquals(null, StitchNative.muxAvifExif(muxed, tiff))+ }+ @Test fun encodeAvifRejectsMismatchedInput() { if (!StitchNative.isAvailable) return
camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicyTest.ktnew file mode 100644index 0000000000..3f30c60c87--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AudioEncoderPolicyTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.camera.platform.camera2++import android.media.MediaFormat+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Opus-only audio selection: the encoder choice can never produce AAC,+ * and a device without an Opus encoder records video-only (the muxer+ * must not wait for an audio track that will never arrive).+ */+class AudioEncoderPolicyTest {++ @Test fun opusIsTheOnlyAudioMime() {+ assertEquals("audio/opus", AudioEncoderPolicy.OPUS_MIME)+ assertEquals(MediaFormat.MIMETYPE_AUDIO_OPUS, AudioEncoderPolicy.OPUS_MIME)+ assertEquals(AudioEncoderPolicy.OPUS_MIME, AudioEncoderPolicy.resolveAudioMime(true))+ }++ @Test fun noOpusEncoderMeansNoAudioTrackNeverAac() {+ assertNull(AudioEncoderPolicy.resolveAudioMime(false))+ // No input produces AAC (or any non-Opus mime).+ for (available in listOf(true, false)) {+ val mime = AudioEncoderPolicy.resolveAudioMime(available)+ assertNotEquals(MediaFormat.MIMETYPE_AUDIO_AAC, mime)+ assertTrue(mime == null || mime == AudioEncoderPolicy.OPUS_MIME)+ }+ }++ @Test fun shouldEnableAudioRequiresRequestAndOpusEncoder() {+ assertTrue(AudioEncoderPolicy.shouldEnableAudio(audioRequested = true, opusEncoderAvailable = true))+ assertFalse(AudioEncoderPolicy.shouldEnableAudio(audioRequested = true, opusEncoderAvailable = false))+ assertFalse(AudioEncoderPolicy.shouldEnableAudio(audioRequested = false, opusEncoderAvailable = true))+ assertFalse(AudioEncoderPolicy.shouldEnableAudio(audioRequested = false, opusEncoderAvailable = false))+ }++ @Test fun muxerDoesNotWaitForMissingOpusTrack() {+ // Requested audio but no Opus encoder: the muxer-start decision+ // must see audio as disabled and start on the video track alone.+ val effectiveAudioEnabled = AudioEncoderPolicy.shouldEnableAudio(+ audioRequested = true, opusEncoderAvailable = false,+ )+ assertTrue(+ MuxerStartPolicy.shouldStart(+ hasVideoTrack = true, hasAudioTrack = false, audioEnabled = effectiveAudioEnabled,+ ),+ )+ // With an Opus encoder, the muxer still waits for both tracks.+ val opusAudioEnabled = AudioEncoderPolicy.shouldEnableAudio(+ audioRequested = true, opusEncoderAvailable = true,+ )+ assertFalse(+ MuxerStartPolicy.shouldStart(+ hasVideoTrack = true, hasAudioTrack = false, audioEnabled = opusAudioEnabled,+ ),+ )+ assertTrue(+ MuxerStartPolicy.shouldStart(+ hasVideoTrack = true, hasAudioTrack = true, audioEnabled = opusAudioEnabled,+ ),+ )+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.ktindex 64d09f62e7..2576fc7dac 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/HighSpeedCaptureTest.kt@@ -5,6 +5,7 @@ import android.util.Range import com.vayunmathur.camera.platform.toCustomRecordingConfig import android.util.Size import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.Test@@ -131,6 +132,8 @@ class HighSpeedCaptureTest { assertEquals(30, config.fps) assertEquals(240, config.captureFps) assertEquals(android.media.MediaFormat.MIMETYPE_VIDEO_AVC, config.videoMime)+ // Slo-mo stays no-audio under the Opus-only regime (piece 5).+ assertFalse(config.audioEnabled) } @Test fun sixtyFpsIsTheSlowestHonestPoint() {
camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.ktindex 72698d1442..b64cdf4ad2 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraCovC2SettingsTest.kt@@ -4,6 +4,7 @@ import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasScrollAction import androidx.compose.ui.test.isToggleable import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToNode@@ -17,6 +18,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey import kotlin.test.assertEquals import kotlin.test.assertNotEquals+import kotlin.test.assertTrue import kotlinx.serialization.Serializable import org.junit.Rule import org.junit.Test@@ -62,6 +64,21 @@ class CameraCovC2SettingsTest { assertEquals(other, viewModel.audioInputSource.value) } + @Test fun settingsPageHasNoAudioCodecRow() {+ // Opus-only: audio encoding is not selectable, so Settings must+ // not offer an audio-codec row (the audio *source* row stays).+ val viewModel = vm()+ val backStack = NavBackStack<TestRoute>(arrayOf(TestRoute.Home))+ rule.setContent { SettingsPage(backStack, viewModel) }+ rule.onNode(hasScrollAction()).performScrollToNode(+ hasText(str(com.vayunmathur.camera.R.string.settings_audio_source))+ )+ assertTrue(+ rule.onAllNodesWithText("Audio codec", substring = true).fetchSemanticsNodes().isEmpty(),+ "Settings must not show an audio-codec picker (Opus is the only option)",+ )+ }+ @Test fun postProcessingSettingsToggleAndDuration() { var noise = true var edge = false