camera: convert Motion Photo frames to YUV in bulk, not per pixel (#914)
- Commit
c158abe90e8170568c0f07fad0b5cd7b2326cfe3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 05:05 UTC (24 days ago)
- Parents
ed175f2
Symptom (#914, Pixel 9 Pro XL / GrapheneOS, v2.6.11b): a noticeable delay between pressing the shutter and getting the picture, longer than the stock GrapheneOS and Pixel cameras. Root cause (part): every default shot (Photo mode, 4:3, flash off) is a Motion Photo, and the shot was only finished after its clip was built. Building the clip converts up to 24 ring-buffer frames (1280x960 ARGB) to YUV 4:2:0 for MediaCodec, and MotionPhotoEncoder.fillI420() did that pixel by pixel: one absolute ByteBuffer.put() on the codec's direct buffer per luma sample plus two per chroma sample, about 44M indexed puts for a 24-frame clip, each with its own bounds check and branch. Changes: - New pure-JVM domain/ArgbToI420Converter: converts one source row into scratch arrays, then writes each plane row with a single bulk ByteBuffer.put(). Planes with pixelStride > 1 (semi-planar NV12/NV21, where U and V alias one buffer) are bulk-read, patched and written back per row, so the other chroma plane's interleaved bytes survive whatever order U and V are written in. The span read stops at the last sample, because the final row of an Image plane is not padded. Writes go through duplicate() so the plane's position/limit are not disturbed. - Same BT.601 fixed-point weights and the same 2x2 top-left chroma sampling as before, so encoded clips are bit-identical to the old path (checked by a test against the old loop). - MotionPhotoEncoder reads each bitmap with one getPixels() into an IntArray reused across frames, and reuses one converter per encode. The old fillI420/writeChromaPixel and their constants are gone. Alternatives considered: - Feeding the encoder straight from the analysis ImageProxy planes (skipping ARGB entirely) would avoid the conversion but means keeping YUV copies in the ring buffer instead of bitmaps, changing PhotoAnalyzer, the ring buffer and the night/pano users of toBitmap; too broad for this fix. - Averaging each 2x2 block for chroma is marginally better quality but changes output; kept bit-exact to limit risk. - libyuv/RenderScript: no new native dependency for this. User-visible effect: Motion Photo clips are built faster (less CPU per shot); the clip content is unchanged. On its own this shortens the time the shutter stays pressed; the next commit removes the wait from the shutter path entirely. Verification: :camera:compileDevKotlin, :camera:testDevUnitTest (new ArgbToI420ConverterTest: BT.601 values for R/G/B/white/black, colour order, row padding left untouched, NV12 aliased planes, odd width, plane position preserved, bit-for-bit match with the old per-pixel loop for pixelStride 1 and 2), :camera:lint and :camera:detekt clean for the touched files. Not timed on a device.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 59525c4377..f73bc19ce8 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -32,6 +32,7 @@ _Install: ./install camera (dev by default)._ ### domain/ — pure lens-selection logic - com/vayunmathur/camera/domain/LensModel.kt - com/vayunmathur/camera/domain/LensSelectionLogic.kt+- com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip ### platform/ — capability queries - com/vayunmathur/camera/platform/CameraCapabilities.kt - com/vayunmathur/camera/platform/LensSelector.kt
camera/src/main/java/com/vayunmathur/camera/domain/ArgbToI420Converter.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/ArgbToI420Converter.kt b/camera/src/main/java/com/vayunmathur/camera/domain/ArgbToI420Converter.ktnew file mode 100644index 0000000000..acc9659f14--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/ArgbToI420Converter.kt@@ -0,0 +1,114 @@+package com.vayunmathur.camera.domain++import java.nio.ByteBuffer++/**+ * One destination plane of a YUV 4:2:0 image: the backing [buffer] plus its strides, i.e. the+ * fields of `android.media.Image.Plane` without the Android type, so the conversion stays pure+ * JVM and unit-testable. Row `r`, sample `i` lives at `r * rowStride + i * pixelStride`.+ */+class YuvPlane(val buffer: ByteBuffer, val rowStride: Int, val pixelStride: Int)++/**+ * Converts ARGB_8888 pixels (as returned by `Bitmap.getPixels`) to BT.601 limited-range+ * YUV 4:2:0, writing into caller-provided planes of any layout the encoder hands out: fully+ * planar I420 (pixelStride 1) or semi-planar NV12/NV21, whose U and V planes alias one buffer+ * with pixelStride 2.+ *+ * Each source row is converted into a scratch row first and then written with one bulk+ * `ByteBuffer.put` per plane row, instead of one indexed `put` per sample (the old Motion Photo+ * path did ~1.8M absolute puts on a direct buffer per 1280x960 frame). For pixelStride > 1 the+ * destination row span is bulk-read, patched and bulk-written back, so the interleaved bytes+ * belonging to the other chroma plane survive and the U/V write order does not matter.+ *+ * Chroma takes the top-left pixel of each 2x2 block, and the fixed-point weights match the+ * previous per-pixel encoder exactly, so the encoded clip is bit-identical to before.+ * Instances hold per-size scratch buffers: reuse one per encode, not across threads.+ */+class ArgbToI420Converter(private val width: Int, private val height: Int) {++ init {+ require(width > 0 && height > 0) { "Invalid frame size ${width}x$height" }+ }++ private val chromaWidth = (width + 1) / 2+ private val yRow = ByteArray(width)+ private val uRow = ByteArray(chromaWidth)+ private val vRow = ByteArray(chromaWidth)+ private var strided = ByteArray(0)++ /** Converts [argb] (row-major, stride == width) into the [y], [u] and [v] planes. */+ fun convert(argb: IntArray, y: YuvPlane, u: YuvPlane, v: YuvPlane) {+ require(argb.size >= width * height) { "Need ${width * height} pixels, got ${argb.size}" }+ for (row in 0 until height) {+ val withChroma = row and 1 == 0+ convertRow(argb, row * width, withChroma)+ writeRow(y, row, yRow, width)+ if (withChroma) {+ writeRow(u, row shr 1, uRow, chromaWidth)+ writeRow(v, row shr 1, vRow, chromaWidth)+ }+ }+ }++ /** Fills [yRow] (and, on even rows, [uRow]/[vRow]) from one source row starting at [base]. */+ private fun convertRow(argb: IntArray, base: Int, withChroma: Boolean) {+ for (x in 0 until width) {+ val c = argb[base + x]+ val r = (c shr RED_SHIFT) and CHANNEL_MASK+ val g = (c shr GREEN_SHIFT) and CHANNEL_MASK+ val b = c and CHANNEL_MASK+ yRow[x] = clamp(((LUMA_R * r + LUMA_G * g + LUMA_B * b + ROUND) shr SHIFT) + LUMA_OFFSET)+ if (withChroma && x and 1 == 0) {+ val cx = x shr 1+ uRow[cx] = clamp(((U_R * r + U_G * g + U_B * b + ROUND) shr SHIFT) + CHROMA_OFFSET)+ vRow[cx] = clamp(((V_R * r + V_G * g + V_B * b + ROUND) shr SHIFT) + CHROMA_OFFSET)+ }+ }+ }++ /** Writes [count] samples of [src] into plane row [rowIndex], honouring both strides. */+ private fun writeRow(plane: YuvPlane, rowIndex: Int, src: ByteArray, count: Int) {+ // duplicate(): position changes stay local; the plane's own position/limit are untouched.+ val buf = plane.buffer.duplicate()+ val start = rowIndex * plane.rowStride+ if (plane.pixelStride == 1) {+ buf.position(start)+ buf.put(src, 0, count)+ return+ }+ // Span ends on the last sample, not on a full stride: the final row of an Image plane+ // is not padded, so reading (count * pixelStride) bytes would overrun the buffer.+ val span = (count - 1) * plane.pixelStride + 1+ if (strided.size < span) strided = ByteArray(span)+ buf.position(start)+ buf.get(strided, 0, span)+ for (i in 0 until count) strided[i * plane.pixelStride] = src[i]+ buf.position(start)+ buf.put(strided, 0, span)+ }++ private companion object {+ const val CHANNEL_MASK = 0xFF+ const val RED_SHIFT = 16+ const val GREEN_SHIFT = 8++ // BT.601 limited-range fixed-point (x256) weights, rounding bias and offsets.+ const val LUMA_R = 66+ const val LUMA_G = 129+ const val LUMA_B = 25+ const val U_R = -38+ const val U_G = -74+ const val U_B = 112+ const val V_R = 112+ const val V_G = -94+ const val V_B = -18+ const val ROUND = 128+ const val SHIFT = 8+ const val LUMA_OFFSET = 16+ const val CHROMA_OFFSET = 128+ const val SAMPLE_MAX = 255++ fun clamp(value: Int): Byte = value.coerceIn(0, SAMPLE_MAX).toByte()+ }+}
camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.ktindex 590288a221..d52692693a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessionSetup.kt@@ -228,7 +228,7 @@ internal fun CameraViewModel.buildPhotoCapture(maxRes: Boolean, ultraHdr: Boolea * resolution: PhotoAnalyzer samples average luminance, runs a ZXing decode * over the whole Y plane, and copies each frame via toBitmap() for the * Motion-Photo ring buffer, whose frames MotionPhotoEncoder then converts to- * I420 in a per-pixel loop. All of that is paid per frame and scales with+ * YUV 4:2:0 for the clip. All of that is paid per frame and scales with * area, so an uncapped stream made QR scanning and motion capture far more * expensive on high-end sensors for no quality gain. Night mode is unaffected: * captureNightBurst() shoots full-resolution frames through ImageCapture.
camera/src/main/java/com/vayunmathur/camera/util/MotionPhotoEncoder.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/MotionPhotoEncoder.kt b/camera/src/main/java/com/vayunmathur/camera/util/MotionPhotoEncoder.ktindex e9369ca819..d2aa2a2ac8 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/MotionPhotoEncoder.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/MotionPhotoEncoder.kt@@ -5,6 +5,8 @@ import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaMuxer+import com.vayunmathur.camera.domain.ArgbToI420Converter+import com.vayunmathur.camera.domain.YuvPlane import com.vayunmathur.library.log.Log import java.io.File import java.nio.ByteBuffer@@ -13,8 +15,9 @@ import java.nio.ByteBuffer * Encodes a short list of bitmaps into an H.264 MP4 (used as the trailing clip of a Motion Photo). * * Uses MediaCodec in ByteBuffer/Image mode with COLOR_FormatYUV420Flexible: each ARGB bitmap is- * converted to I420 into the codec's input [android.media.Image], respecting its plane strides, so- * the path stays portable across encoders without needing EGL. Runs synchronously on the caller's+ * read with one bulk getPixels() and converted by [ArgbToI420Converter] into the codec's input+ * [android.media.Image] row by row with bulk buffer writes, respecting its plane strides (planar+ * or semi-planar), so the path stays portable across encoders without needing EGL. Runs synchronously on the caller's * (background) thread. Rotation is carried by the muxer orientation hint rather than rotating pixels. */ object MotionPhotoEncoder {@@ -22,11 +25,10 @@ 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); channel mask. */+ /** Micros per second; YUV420 bytes per pixel (3/2). */ private const val MICROS_PER_SECOND = 1_000_000L private const val YUV420_NUMERATOR = 3 private const val YUV420_DENOMINATOR = 2- private const val CHANNEL_MASK = 0xFF /** * Encodes [frames] to [outputFile] at [fps]. All frames must share dimensions (the first@@ -101,6 +103,9 @@ object MotionPhotoEncoder { private set private var trackIndex = -1 private val bufferInfo = MediaCodec.BufferInfo()+ // Reused across frames: one pixel buffer and one converter (scratch rows) per encode.+ private val argb = IntArray(width * height)+ private val converter = ArgbToI420Converter(width, height) fun run() { var frameIndex = 0@@ -127,7 +132,14 @@ object MotionPhotoEncoder { val ptsUs = frameIndex * MICROS_PER_SECOND / fps val image = codec.getInputImage(inIndex) if (image != null) {- fillI420(image, frames[frameIndex], width, height)+ frames[frameIndex].getPixels(argb, 0, width, 0, 0, width, height)+ val planes = image.planes+ converter.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, ptsUs, 0)@@ -176,84 +188,4 @@ object MotionPhotoEncoder { bufferInfo.size > 0 } }-- /** BT.601 luma/chroma weights, rounding bias, and channel ranges. */- private const val LUMA_R_WEIGHT = 66- private const val LUMA_G_WEIGHT = 129- private const val LUMA_B_WEIGHT = 25- private const val CHROMA_RB_WEIGHT = 112- private const val CHROMA_GU_WEIGHT = -74- private const val CHROMA_GV_WEIGHT = -94- private const val CHROMA_RU_WEIGHT = -38- private const val CHROMA_BV_WEIGHT = -18- private const val FIXED_POINT_ROUND = 128- private const val FIXED_POINT_SHIFT = 8- private const val LUMA_OFFSET = 16- private const val CHROMA_OFFSET = 128- private const val CHANNEL_MIN = 0- private const val CHANNEL_MAX = 255- private const val CHROMA_SUBSAMPLE = 2-- /** Converts an ARGB_8888 [bitmap] into the YUV [image]'s I420 planes (BT.601). */- private fun fillI420(image: android.media.Image, bitmap: Bitmap, width: Int, height: Int) {- val argb = IntArray(width * height)- bitmap.getPixels(argb, 0, width, 0, 0, width, height)-- val yPlane = image.planes[0]- val uPlane = image.planes[1]- val vPlane = image.planes[2]- val yBuf = yPlane.buffer- val uBuf = uPlane.buffer- val vBuf = vPlane.buffer- val yRowStride = yPlane.rowStride- val uRowStride = uPlane.rowStride- val vRowStride = vPlane.rowStride- val uPixStride = uPlane.pixelStride- val vPixStride = vPlane.pixelStride-- for (y in 0 until height) {- for (x in 0 until width) {- val c = argb[y * width + x]- val r = (c shr 16) and CHANNEL_MASK- val g = (c shr 8) and CHANNEL_MASK- val b = c and CHANNEL_MASK- val yy = (- (LUMA_R_WEIGHT * r + LUMA_G_WEIGHT * g + LUMA_B_WEIGHT * b + FIXED_POINT_ROUND) shr- FIXED_POINT_SHIFT- ) + LUMA_OFFSET- yBuf.put(y * yRowStride + x, yy.coerceIn(CHANNEL_MIN, CHANNEL_MAX).toByte())- if (y and 1 == 0 && x and 1 == 0) {- writeChromaPixel(uBuf, vBuf, uRowStride, vRowStride, uPixStride, vPixStride, x, y, r, g, b)- }- }- }- }-- /** Writes the subsampled U/V pair for source pixel ([x], [y]). */- private fun writeChromaPixel(- uBuf: java.nio.ByteBuffer,- vBuf: java.nio.ByteBuffer,- uRowStride: Int,- vRowStride: Int,- uPixStride: Int,- vPixStride: Int,- x: Int,- y: Int,- r: Int,- g: Int,- b: Int- ) {- val u = (- (CHROMA_RU_WEIGHT * r + CHROMA_GU_WEIGHT * g + CHROMA_RB_WEIGHT * b + FIXED_POINT_ROUND) shr- FIXED_POINT_SHIFT- ) + CHROMA_OFFSET- val v = (- (CHROMA_RB_WEIGHT * r + CHROMA_GV_WEIGHT * g + CHROMA_BV_WEIGHT * b + FIXED_POINT_ROUND) shr- FIXED_POINT_SHIFT- ) + CHROMA_OFFSET- val cx = x / CHROMA_SUBSAMPLE- val cy = y / CHROMA_SUBSAMPLE- uBuf.put(cy * uRowStride + cx * uPixStride, u.coerceIn(CHANNEL_MIN, CHANNEL_MAX).toByte())- vBuf.put(cy * vRowStride + cx * vPixStride, v.coerceIn(CHANNEL_MIN, CHANNEL_MAX).toByte())- } }
camera/src/test/java/com/vayunmathur/camera/domain/ArgbToI420ConverterTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/ArgbToI420ConverterTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/ArgbToI420ConverterTest.ktnew file mode 100644index 0000000000..5aa3ddae74--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/ArgbToI420ConverterTest.kt@@ -0,0 +1,200 @@+package com.vayunmathur.camera.domain++import java.nio.ByteBuffer+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++/**+ * Known-frame checks for the Motion Photo ARGB → YUV 4:2:0 conversion: colour order, BT.601+ * values, row/pixel stride handling (padding bytes untouched), semi-planar aliasing and+ * bit-exactness against the previous per-pixel encoder loop.+ */+class ArgbToI420ConverterTest {++ private companion object {+ const val RED = 0xFFFF0000.toInt()+ const val GREEN = 0xFF00FF00.toInt()+ const val BLUE = 0xFF0000FF.toInt()+ const val WHITE = 0xFFFFFFFF.toInt()+ const val BLACK = 0xFF000000.toInt()+ const val PAD: Byte = 0x5A++ /** BT.601 (Y, U, V) for the primaries above, as produced by the fixed-point weights. */+ val RED_YUV = intArrayOf(82, 90, 240)+ val GREEN_YUV = intArrayOf(144, 54, 34)+ val BLUE_YUV = intArrayOf(41, 240, 110)+ val WHITE_YUV = intArrayOf(235, 128, 128)+ val BLACK_YUV = intArrayOf(16, 128, 128)+ }++ private fun padded(size: Int) = ByteBuffer.allocate(size).also { buf ->+ repeat(size) { buf.put(it, PAD) }+ }++ private fun ByteBuffer.at(i: Int) = get(i).toInt() and 0xFF++ @Test+ fun solidColoursMapToBt601Values() {+ for ((argb, yuv) in listOf(RED to RED_YUV, GREEN to GREEN_YUV, BLUE to BLUE_YUV,+ WHITE to WHITE_YUV, BLACK to BLACK_YUV)) {+ val y = padded(4)+ val u = padded(1)+ val v = padded(1)+ ArgbToI420Converter(2, 2).convert(+ IntArray(4) { argb }, YuvPlane(y, 2, 1), YuvPlane(u, 1, 1), YuvPlane(v, 1, 1)+ )+ repeat(4) { assertEquals(yuv[0], y.at(it), "Y of ${Integer.toHexString(argb)}") }+ assertEquals(yuv[1], u.at(0), "U of ${Integer.toHexString(argb)}")+ assertEquals(yuv[2], v.at(0), "V of ${Integer.toHexString(argb)}")+ }+ }++ @Test+ fun planarWithRowPaddingKeepsOrderAndLeavesPaddingUntouched() {+ // 4x2: left 2x2 block red/green (top-left red), right block blue/white (top-left blue).+ val argb = intArrayOf(+ RED, GREEN, BLUE, WHITE,+ GREEN, RED, WHITE, BLUE,+ )+ val yStride = 6+ val cStride = 3+ val y = padded(yStride + 4)+ val u = padded(2)+ val v = padded(2)+ // Over-sized chroma buffers to check bytes past the last sample stay untouched too.+ val uBig = padded(cStride + 2)+ val vBig = padded(cStride + 2)+ ArgbToI420Converter(4, 2).convert(+ argb, YuvPlane(y, yStride, 1), YuvPlane(u, cStride, 1), YuvPlane(v, cStride, 1)+ )+ ArgbToI420Converter(4, 2).convert(argb, YuvPlane(padded(yStride + 4), yStride, 1),+ YuvPlane(uBig, cStride, 1), YuvPlane(vBig, cStride, 1))++ val expectedY = intArrayOf(82, 144, 41, 235, -1, -1, 144, 82, 235, 41)+ expectedY.forEachIndexed { i, e ->+ if (e < 0) assertEquals(PAD, y.get(i), "row padding at $i") else assertEquals(e, y.at(i), "Y[$i]")+ }+ // Chroma comes from each block's top-left pixel: red then blue.+ assertEquals(RED_YUV[1], u.at(0))+ assertEquals(BLUE_YUV[1], u.at(1))+ assertEquals(RED_YUV[2], v.at(0))+ assertEquals(BLUE_YUV[2], v.at(1))+ assertEquals(PAD, uBig.get(2))+ assertEquals(PAD, vBig.get(cStride + 1))+ }++ @Test+ fun semiPlanarAliasedPlanesInterleaveUv() {+ // NV12: one buffer, U at even offsets and V at odd offsets (V plane = U plane + 1).+ val argb = intArrayOf(+ RED, RED, BLUE, BLUE,+ RED, RED, BLUE, BLUE,+ GREEN, GREEN, WHITE, WHITE,+ GREEN, GREEN, WHITE, WHITE,+ )+ val rowStride = 6 // 4 interleaved bytes + 2 padding+ val uv = padded(rowStride + 4)+ val u = uv.duplicate()+ val v = uv.duplicate().apply { position(1) }.slice()+ val y = padded(16)+ ArgbToI420Converter(4, 4).convert(argb, YuvPlane(y, 4, 1), YuvPlane(u, rowStride, 2), YuvPlane(v, rowStride, 2))++ val expected = intArrayOf(+ RED_YUV[1], RED_YUV[2], BLUE_YUV[1], BLUE_YUV[2], -1, -1,+ GREEN_YUV[1], GREEN_YUV[2], WHITE_YUV[1], WHITE_YUV[2],+ )+ expected.forEachIndexed { i, e ->+ if (e < 0) assertEquals(PAD, uv.get(i), "row padding at $i") else assertEquals(e, uv.at(i), "UV[$i]")+ }+ }++ @Test+ fun oddWidthRoundsChromaUp() {+ val argb = intArrayOf(+ RED, GREEN, BLUE,+ WHITE, BLACK, WHITE,+ BLUE, GREEN, RED,+ )+ val y = padded(9)+ val u = padded(4)+ val v = padded(4)+ ArgbToI420Converter(3, 3).convert(argb, YuvPlane(y, 3, 1), YuvPlane(u, 2, 1), YuvPlane(v, 2, 1))+ assertEquals(listOf(RED_YUV[1], BLUE_YUV[1], BLUE_YUV[1], RED_YUV[1]), (0 until 4).map { u.at(it) })+ assertEquals(listOf(RED_YUV[2], BLUE_YUV[2], BLUE_YUV[2], RED_YUV[2]), (0 until 4).map { v.at(it) })+ assertEquals(BLACK_YUV[0], y.at(4))+ }++ @Test+ fun matchesPreviousPerPixelEncoderBitForBit() {+ val w = 10+ val h = 6+ val rnd = Random(914)+ val argb = IntArray(w * h) { 0xFF000000.toInt() or rnd.nextInt(0x1000000) }+ for (pixelStride in listOf(1, 2)) {+ val yStride = 16+ val cStride = 12+ val actual = Triple(padded(yStride * h), padded(cStride * h / 2), padded(cStride * h / 2))+ val expected = Triple(padded(yStride * h), padded(cStride * h / 2), padded(cStride * h / 2))+ ArgbToI420Converter(w, h).convert(+ argb, YuvPlane(actual.first, yStride, 1),+ YuvPlane(actual.second, cStride, pixelStride), YuvPlane(actual.third, cStride, pixelStride)+ )+ referencePerPixel(+ argb, w, h, expected.first, yStride, expected.second, expected.third, cStride, pixelStride+ )+ assertContentEquals(expected.first.array(), actual.first.array(), "Y, pixelStride=$pixelStride")+ assertContentEquals(expected.second.array(), actual.second.array(), "U, pixelStride=$pixelStride")+ assertContentEquals(expected.third.array(), actual.third.array(), "V, pixelStride=$pixelStride")+ }+ }++ @Test+ fun planePositionIsNotDisturbed() {+ val y = padded(4).apply { position(3) }+ val u = padded(1)+ val v = padded(1)+ ArgbToI420Converter(2, 2).convert(+ IntArray(4) { WHITE }, YuvPlane(y, 2, 1), YuvPlane(u, 1, 1), YuvPlane(v, 1, 1)+ )+ assertEquals(3, y.position())+ assertEquals(WHITE_YUV[0], y.at(0))+ }++ @Test+ fun rejectsShortPixelArray() {+ assertFailsWith<IllegalArgumentException> {+ ArgbToI420Converter(2, 2).convert(IntArray(3), YuvPlane(padded(4), 2, 1),+ YuvPlane(padded(1), 1, 1), YuvPlane(padded(1), 1, 1))+ }+ }++ /** The pre-#914 MotionPhotoEncoder.fillI420 loop, verbatim apart from the Image plumbing. */+ @Suppress("LongParameterList")+ private fun referencePerPixel(+ argb: IntArray, width: Int, height: Int,+ yBuf: ByteBuffer, yRowStride: Int,+ uBuf: ByteBuffer, vBuf: ByteBuffer, cRowStride: Int, cPixStride: Int,+ ) {+ for (y in 0 until height) {+ for (x in 0 until width) {+ val c = argb[y * width + x]+ val r = (c shr 16) and 0xFF+ val g = (c shr 8) and 0xFF+ val b = c and 0xFF+ val yy = ((66 * r + 129 * g + 25 * b + 128) shr 8) + 16+ yBuf.put(y * yRowStride + x, yy.coerceIn(0, 255).toByte())+ if (y and 1 == 0 && x and 1 == 0) {+ val u = ((-38 * r + -74 * g + 112 * b + 128) shr 8) + 128+ val v = ((112 * r + -94 * g + -18 * b + 128) shr 8) + 128+ val cx = x / 2+ val cy = y / 2+ uBuf.put(cy * cRowStride + cx * cPixStride, u.coerceIn(0, 255).toByte())+ vBuf.put(cy * cRowStride + cx * cPixStride, v.coerceIn(0, 255).toByte())+ }+ }+ }+ }+}