Phone CPU usage optimization

This commit is contained in:
James Babcock committed 2026-09-22 14:19:23 -07:00
1 parent 44eddedc01
commit 9560f3ac8d
26 files changed
+606 -167

No files matched your search

@@ -1,9 +1,47 @@
package com.faceclaw.app
import kotlin.test.*
import kotlin.random.Random
class DisplayListTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test fun screenCopyPreservesOffsetsClippingPaddingAndAliasing() {
val random = Random(42)
val renderer = DisplayListRenderer(emptyMap())
for (sourceWidth in listOf(1, 2, 3, 7, 8, 640)) for (destinationWidth in listOf(1, 2, 3, 7, 8, 640)) {
for (shared in listOf(false, true)) for (shift in listOf(-3, 0, 2)) {
val sourceHeight = random.nextInt(1, 5); val destinationHeight = random.nextInt(1, 5)
val sourceOffset = random.nextInt(4); val destinationOffset = random.nextInt(4)
val size = maxOf(sourceOffset + (sourceWidth + 1) / 2 * sourceHeight,
destinationOffset + (destinationWidth + 1) / 2 * destinationHeight) + 3
val source = random.nextBytes(size)
val destination = if (shared) source else random.nextBytes(size)
val expectedSource = source.copyOf()
val expectedDestination = if (shared) expectedSource else destination.copyOf()
// Original per-pixel semantics, including cascading writes when
// views alias and ignoring shiftX when reading the source.
val referenceSource = DisplayListRenderer.Target(expectedSource, sourceWidth, sourceHeight, sourceOffset, 5)
val referenceDestination = DisplayListRenderer.Target(expectedDestination, destinationWidth, destinationHeight, destinationOffset, shift)
for (y in 0 until sourceHeight) for (x in 0 until sourceWidth)
referenceDestination.put(x, y, referenceSource.get(x, y))
assertEquals(emptySet(), renderer.render(DrawProtocol.SCREEN,
DisplayListRenderer.Target(source, sourceWidth, sourceHeight, sourceOffset, 5),
DisplayListRenderer.Target(destination, destinationWidth, destinationHeight, destinationOffset, shift)))
assertContentEquals(expectedDestination, destination, "$sourceWidth/$destinationWidth shared=$shared shift=$shift")
assertContentEquals(expectedSource, source)
}
}
val source = random.nextBytes(640 * 480 / 2)
val destination = ByteArray(source.size)
renderer.render(DrawProtocol.SCREEN, DisplayListRenderer.Target(source,640,480), DisplayListRenderer.Target(destination,640,480))
assertContentEquals(source, destination)
}
@Test fun invalidGraphDoesNotCopyScreenIntoComposition() {
val screen = hex("12345678"); val composition = hex("9abcdef0")
val resources = mapOf(1 to DrawProtocol.displayList(listOf(byteArrayOf(99,0))))
assertFails { DisplayListRenderer(resources).render(1, DisplayListRenderer.Target(screen,8,1), DisplayListRenderer.Target(composition,8,1)) }
assertContentEquals(hex("9abcdef0"), composition)
}
@Test fun oddPixelsRawRleClippingFontsNestedListsAndLut() {
val raw = DrawProtocol.rawImage(3, 3, hex("123045607890"))
val font = ByteArray(197); font[0]=1; font[67]=193.toByte(); hex("0801011f").copyInto(font,193)
@@ -0,0 +1,67 @@
package com.faceclaw.app
import kotlin.test.*
class PreviewPackingTest {
private fun level(value: Byte): Int = minOf(15, ((value.toInt() and 255) + 8) / 16)
@Test
fun everyPairOfGrayValuesHasTheSameWireEncoding() {
val pixels = ByteArray(65536 * 2) { if (it % 2 == 0) (it / 512).toByte() else (it / 2).toByte() }
val packed = BmpUtil.pack4bppFromGray8(pixels, 512, 256)
for (i in packed.indices) {
assertEquals((level(pixels[i * 2]) * 16 + level(pixels[i * 2 + 1])).toByte(), packed[i], "pair $i")
}
for (v in 0..255) assertEquals(level(v.toByte()), BmpUtil.nibbleForGray(v))
}
@Test
fun oddWidthsPadEveryRowAndIgnoreTrailingInput() {
for (width in listOf(1, 3, 5, 639, 641)) {
val height = 7
val pixels = ByteArray(width * height + 13) { (it * 73 + 19).toByte() }
val stride = (width + 1) / 2
val packed = BmpUtil.pack4bppFromGray8(pixels, width, height)
assertEquals(stride * height, packed.size)
for (y in 0 until height) {
for (x in 0 until width) {
val byte = packed[y * stride + x / 2].toInt() and 255
assertEquals(level(pixels[y * width + x]), if (x % 2 == 0) byte / 16 else byte % 16)
}
assertEquals(0, packed[(y + 1) * stride - 1].toInt() and 15)
}
}
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(null, 3, 2))
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(ByteArray(5) { -1 }, 3, 2))
assertTrue(BmpUtil.pack4bppFromGray8(null, 0, 2).isEmpty())
}
@Test
fun wireFramesSkipPreviewButExplicitReadbackIncludesLatestShellAndPixels() {
val compositor = SurfaceCompositor(false)
compositor.configureScreen(3, 2)
compositor.configureSurface("app", 0, 0, 3, 2, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
// One white 2x1 shell layer at (0,0), with no dimming or selection.
val header = listOf(1, 1, 0, 0, 2, 1, 256, 0, 0).flatMap { listOf(it.toByte(), (it shr 8).toByte()) }.toByteArray()
compositor.setShellScene(ArrayByteReader(header + byteArrayOf(-16, -16)))
val wire = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 32 }), 0, 0, 3, 2, "first")
assertSame(wire.screenGray, wire.gray) // ShellScene.preview allocates its own pixels.
assertContentEquals(ByteArray(6) { 32 }, wire.screenGray)
assertEquals(1, wire.shellScene.layers.size)
val preview = assertNotNull(compositor.previewComposite())
assertContentEquals(byteArrayOf(-16, -16, 32, 32, 32, 32), preview.gray)
assertEquals(wire.fingerprint, preview.fingerprint)
assertContentEquals(wire.screenGray, preview.screenGray)
// Updates while hidden retain the newest frame. Preview reads don't
// consume the wire sequence or affect the next submitted frame.
val newer = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 64 }), 0, 0, 3, 2, "second")
assertEquals(wire.seq + 1, newer.seq)
assertSame(newer.screenGray, newer.gray)
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
compositor.setBlanked(true)
assertContentEquals(ByteArray(6), compositor.previewComposite()!!.gray)
compositor.setBlanked(false)
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
}
}
@@ -126,6 +126,51 @@ class ResourceCacheTest {
assertNull(TexturePlanner.plan(null, ByteArray(packed.size), 8, 4, draws, cache, 1, true, 8, testPlatform()))
}
@Test fun imagePixelLoopsPreserveClippingTransparencyAndNeighborNibbles() {
val width = 12
val height = 8
for (imageWidth in listOf(3, 4, 5, 9)) {
val imageHeight = 5
val pixels = ByteArray(imageWidth * imageHeight) { i ->
if (i % 3 == 0) 0 else (((i % 15) + 1) * 16).toByte()
}
val id = ImageAtlas.ensure("pixel-loop-$imageWidth", imageWidth, imageHeight, ArrayByteReader(pixels))
for (left in listOf(-1, 0, 1, 2, 10, 11, 14)) for (top in listOf(-1, 0, 1, 7, 9)) {
val gray = ByteArray(width * height) { ((it % 15 + 1) * 16).toByte() }
val visibleInk = ArrayList<Int>()
for (row in 0 until imageHeight) for (col in 0 until imageWidth) {
val x = left + col; val y = top + row; val value = pixels[row * imageWidth + col]
if (x in 0 until width && y in 0 until height && value.toInt() != 0) {
gray[y * width + x] = value
visibleInk.add(y * width + x)
}
}
val expected = BmpUtil.pack4bppFromGray8(gray, width, height)
val draws = arrayOf(SurfaceCompositor.ScreenDraw.image(id, left, top))
val plan = TexturePlanner.plan(null, expected, width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform())
if (left < 0 || top < 0 || left >= width || top >= height) {
assertNull(plan) // The wire format cannot replay negative image origins.
continue
}
val result = assertNotNull(plan, "$imageWidth at $left,$top")
assertEquals(1, result.drawnImages)
val actual = ByteArray(expected.size) { 0x55 }
DisplayListRenderer(uploaded(result.resourceCommands)).execute(
DrawProtocol.sequence(DrawProtocol.fromOptimized(result.payload, width, height)),
DisplayListRenderer.Target(actual, width, height))
assertContentEquals(expected, actual, "$imageWidth at $left,$top")
// A conflicting visible ink pixel must reject the cached draw.
if (visibleInk.isNotEmpty()) {
val offset = visibleInk.first()
gray[offset] = 0
assertNull(TexturePlanner.plan(null, BmpUtil.pack4bppFromGray8(gray, width, height),
width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform()))
}
}
}
}
private fun registerFont(key: String, encodings: List<Int>, size: Int = 2): Int {
val out = ByteSink(); val name = key.encodeToByteArray()
out.write(name.size); out.write(name, 0, name.size); out.write(size)
@@ -0,0 +1,65 @@
package com.faceclaw.app
import kotlin.random.Random
import kotlin.test.*
class RleEncoderTest {
/** Deliberately simple per-pixel reference, independent of the byte scan. */
private fun reference(packed: ByteArray): ByteArray {
val output = ArrayList<Byte>()
var color = -1
var count = 0
fun flush() {
while (count > 0) {
val n = minOf(count, 65535)
when {
n <= 15 -> output.add((n * 16 + color).toByte())
n <= 255 -> { output.add(color.toByte()); output.add(n.toByte()) }
else -> { output.add(color.toByte()); output.add(0); output.add(n.toByte()); output.add((n / 256).toByte()) }
}
count -= n
}
}
for (byte in packed) for (pixel in listOf((byte.toInt() and 255) / 16, byte.toInt() and 15)) {
if (pixel != color) { flush(); color = pixel }
count++
}
flush()
return output.toByteArray()
}
@Test fun allTwoByteInputsPreserveExactTokensAcrossNibbleBoundaries() {
for (value in 0..65535) {
val packed = byteArrayOf((value / 256).toByte(), value.toByte())
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "input $value")
}
assertContentEquals(ByteArray(0), BleImageOptimizer.rleEncode(ByteArray(0)))
}
@Test fun longRunsAndEveryTokenBoundaryAtBothNibbleAlignments() {
for (length in listOf(1, 2, 14, 15, 16, 254, 255, 256, 65534, 65535, 65536, 131070, 131071)) {
for (prefix in 0..1) for (color in listOf(0, 7, 15)) {
val values = List(prefix) { (color + 1) % 16 } + List(length) { color } + listOf((color + 2) % 16)
val packed = ByteArray((values.size + 1) / 2) { i ->
(values[i * 2] * 16 + (values.getOrNull(i * 2 + 1) ?: 0)).toByte()
}
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "$prefix/$length/$color")
}
}
}
@Test fun noiseAndMixedRunsPreserveExactWireOutput() {
val random = Random(123)
repeat(100) {
val data = random.nextBytes(random.nextInt(1, 4096))
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
repeat(20) {
val start = random.nextInt(data.size)
data.fill((random.nextInt(16) * 17).toByte(), start, minOf(data.size, start + random.nextInt(1, 200)))
}
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
}
val screen = ByteArray(640 * 480 / 2) { 0x77 }
assertContentEquals(reference(screen), BleImageOptimizer.rleEncode(screen))
}
}