Merge branch 'main' of https://github.com/jimrandomh/faceclaw into ring-health-fixes

This commit is contained in:
James Babcock committed 2026-09-25 23:12:20 -07:00
commit a2166c6a6c
822 files changed
+79614 -30124

No files matched your search

@@ -0,0 +1,52 @@
package com.faceclaw.app;
import java.util.Arrays;
public class CompassProtocolTest {
private static byte[] hex(String value) {
byte[] bytes = new byte[value.length() / 2];
for (int i = 0; i < bytes.length; i++) bytes[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return bytes;
}
private static BleProtocol.CompassEvent parse(byte[] payload) {
return parse(payload, BleProtocol.FLAG_NOTIFY);
}
private static BleProtocol.CompassEvent parse(byte[] payload, int flag) {
byte[] frame = BleProtocol.framePb(payload, 8, flag, 15).get(0);
return BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame));
}
public static void main(String[] args) {
// Golden packet also checked against the real C encoder in g2flash's host test.
byte[] packet = hex("080f1000520308e702a2060c434d010302038c0098badcfe");
BleProtocol.CompassEvent event = parse(packet);
assert event.headingDegrees == 359 && event.command == 15;
assert event.magneticAccuracy == 3 && event.magneticAnomalies == 2;
assert event.orientationSource == 3 && event.diagnosticFlags == 0x8c;
assert event.sampleTimeMs == 0xfedcba98L; // unsigned 32-bit timestamp through Java long
assert parse(packet, BleProtocol.FLAG_NOTIFY_ALT).headingDegrees == 359;
assert parse(packet, BleProtocol.FLAG_REQUEST) == null;
assert parse(packet, 0) == null;
byte[] legacy = Arrays.copyOf(packet, 9);
event = parse(legacy);
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
for (int n = 9; n < packet.length; ++n) {
event = parse(Arrays.copyOf(packet, n));
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
}
for (int offset : new int[] {12, 13, 14, 15, 16, 17, 19}) {
byte[] invalid = packet.clone(); invalid[offset] = 99;
event = parse(invalid);
assert event.headingDegrees == 359 && event.diagnosticFlags == -1;
}
packet[15] = packet[16] = (byte)255; packet[17] = 0; packet[18] = 0;
event = parse(packet);
assert event.magneticAccuracy == -1 && event.magneticAnomalies == -1;
assert event.orientationSource == 0 && event.diagnosticFlags == 0;
event = parse(hex("08101000"));
assert event.command == 16 && event.headingDegrees == -1 && event.diagnosticFlags == -1;
event = parse(hex("08111000"));
assert event.command == 17 && event.diagnosticFlags == -1;
assert parse(hex("080f1000520308e802")) == null; // 360 isn't a heading
assert BleProtocol.parseCompassEvent(null) == null;
System.out.println("Compass protocol checks passed");
}
}
@@ -0,0 +1,67 @@
package com.faceclaw.app;
import java.util.Arrays;
public class FaceclawGestureEventTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static byte[] pb(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseFrame(frame).pb;
}
/** G2SettingPackage{commandId=3, magic=0, field102=['F','C',1,event,source,0]}: the CFW's wire shape. */
private static byte[] packet(int event, int source) {
byte[] p = hex("08031000b20606464301000000");
p[10] = (byte)event; p[11] = (byte)source;
return p;
}
public static void main(String[] args) {
// Event codes map to the sys-events a live page would produce.
int[][] events = {
{2, BleProtocol.EVENT_CLICK},
{3, BleProtocol.EVENT_RING_LONG_PRESS},
{4, BleProtocol.EVENT_RING_LONG_PRESS_RELEASE},
};
int[][] sources = {
{0, BleProtocol.EVENT_SOURCE_GLASSES_L},
{1, BleProtocol.EVENT_SOURCE_GLASSES_R},
{4, BleProtocol.EVENT_SOURCE_RING},
{7, 0},
};
for (int[] e : events) for (int[] s : sources) {
BleProtocol.FaceclawGestureEvent g = BleProtocol.parseFaceclawGestureEvent(pb(packet(e[0], s[0])));
assert g != null && g.eventType == e[1] && g.eventSource == s[1] : e[0] + "/" + s[0];
}
// The double-tap wake event (1) and unknown codes are not gestures, and the
// wake parser does not mistake a gesture for a wake.
byte[] wake = packet(1, 0x34); wake[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(wake)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(wake)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(wake)) == 1;
// The head-up wake (5) shares the nonce handshake but keeps its own code.
byte[] headUp = packet(5, 0x34); headUp[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(headUp)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(headUp)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(headUp)) == BleProtocol.FACECLAW_WAKE_EVENT_HEAD_UP;
for (int code : new int[] {2, 3, 4, 6}) {
assert BleProtocol.parseFaceclawWakeEvent(pb(packet(code, 1))) == -1;
assert BleProtocol.parseFaceclawWakeEventCode(pb(packet(code, 1))) == -1;
}
for (int code : new int[] {0, 5, 6, 255})
assert BleProtocol.parseFaceclawGestureEvent(pb(packet(code, 1))) == null;
// Wrong protocol version, wrong magic letters, truncated payloads, plain settings.
byte[] bad = packet(2, 1); bad[9] = 2;
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
bad = packet(2, 1); bad[7] = 'X';
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
byte[] full = packet(2, 1);
for (int n = 0; n < full.length; ++n)
assert BleProtocol.parseFaceclawGestureEvent(pb(Arrays.copyOf(full, n))) == null : n;
assert BleProtocol.parseFaceclawGestureEvent(pb(hex("08031000"))) == null;
assert BleProtocol.parseFaceclawGestureEvent(null) == null;
System.out.println("FaceclawGestureEventTest ok");
}
}
@@ -0,0 +1,20 @@
package com.faceclaw.app;
import java.util.*;
/** Android's Java communicator and iOS share the same resource API and wire commands. */
public class ResourceCacheProtocolTest {
public static void main(String[] args) {
ResourceCacheState cache = new ResourceCacheState();
CachedResource image = new CachedResource(new byte[]{1, 1, 31});
assert cache.prepare(Collections.singletonList(image))[0] == 0;
List<byte[]> commands = cache.drainCommands(3600);
assert commands.size() == 2 && commands.get(0)[0] == 22;
assert Arrays.equals(commands.get(1), new byte[]{21,1,0,0,0,3,0,0,0,0,0,3,0,1,1,31});
assert cache.prepare(Collections.singletonList(image))[0] == 0;
assert cache.drainCommands(3600).isEmpty();
cache.reset();
assert cache.prepare(Collections.singletonList(image))[0] == 0;
assert cache.drainCommands(3600).get(0)[0] == 22;
}
}
@@ -0,0 +1,50 @@
package com.faceclaw.app;
import java.util.Arrays;
public class RingBatteryProtocolTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static BleProtocol.RingBatterySnapshot parse(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseRingBattery(BleProtocol.parseFrame(frame).pb);
}
public static void main(String[] args) {
// Same golden payload as g2flash/tests/ring_battery_test.c.
byte[] packet = hex("08031000d206055242010752");
BleProtocol.RingBatterySnapshot result = parse(packet);
assert result.battery == 82 && result.charging == 1;
packet[10] = 3;
for (int level = 0; level <= 100; ++level) {
packet[11] = (byte)level;
result = parse(packet);
assert result.battery == level && result.charging == 0;
}
for (int flags : new int[] {0, 1}) {
packet[10] = (byte)flags; packet[11] = (byte)255;
result = parse(packet);
assert result.battery == -1 && result.charging == -1;
}
packet = hex("08031000d206055242010752");
for (int n = 0; n < packet.length; ++n)
assert parse(Arrays.copyOf(packet, n)) == null;
for (int offset : new int[] {7, 8, 9, 10, 11}) {
byte previous = packet[offset]; packet[offset] = (byte)255;
assert parse(packet) == null;
packet[offset] = previous;
}
assert parse(hex("08031000")) == null; // older firmware
assert parse(hex("d206055242010252")) == null; // valid without connected
assert parse(hex("d206055242010352")).battery == 82;
assert parse(hex("d2060552420100ff")).battery == -1;
// Invalid unknown value and charging-without-valid must be rejected.
assert parse(hex("d206055242010052")) == null;
assert parse(hex("d2060552420105ff")) == null;
assert parse(hex("d206055242010364")).battery == 100;
assert parse(hex("d206055242010365")) == null;
assert BleProtocol.parseRingBattery(null) == null;
}
}
@@ -0,0 +1,530 @@
package com.faceclaw.app;
import java.util.Arrays;
import java.util.List;
/**
* Standalone self-test for {@link RingProtocol}. No Android APIs and no
* hardware: every byte-manipulation path is exercised against either frames
* copied from the reference capture or synthetic bodies built from the spec's
* field layout.
*
* <p>Run through JavaCompatibilityTest ({@code npm run test:kotlin}), which
* also checks that the Kotlin port keeps the Java-facing API the TypeScript
* health ingest reads.
*
* <p>The captured frames reproduced below are requests and page-ACKs only.
* Those carry a nonce, a command id and a sequence number — no biometric
* values. No captured DATA page appears here, deliberately.
*/
public final class RingProtocolSelfTest {
private static int checks;
private static int failures;
public static void main(String[] args) {
testCrcAndRequestRoundTrip();
testFiveHealthRequests();
testPageAckAgainstCapture();
testParseRejectsGarbage();
testFragmentReassembly();
testHourlyDecode();
testStepsDecode();
testSleepDecodeAndIdentities();
testDailyWireLayouts();
testDeviceStatus();
System.out.println();
System.out.println(failures == 0
? "PASS: all " + checks + " checks"
: "FAIL: " + failures + " of " + checks + " checks");
if (failures != 0) {
throw new AssertionError(failures + " of " + checks + " ring protocol checks failed");
}
}
// ------------------------------------------------------------------
/**
* Rebuild captured request pkt 9166 from its decoded fields alone. If the
* CRC-32C parameters or the header layout are wrong by even one bit this
* cannot reproduce the captured bytes.
*/
private static void testCrcAndRequestRoundTrip() {
section("CRC + request round-trip (captured pkt 9166)");
byte[] built = RingProtocol.buildRequest(
RingProtocol.CHAN_HEALTH,
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH,
0x06,
0x08ca);
expectHex("pkt 9166", "00db64265a64026406000001010c00ca08", built);
RingProtocol.Frame frame = RingProtocol.parse(built);
expect("parses back", frame != null && frame.crcOk);
expect("chan", frame.chan == RingProtocol.CHAN_HEALTH);
expect("kind REQ", frame.kind == RingProtocol.KIND_REQ);
expect("seq", frame.seq == 0x06);
expect("cmd 01:01", frame.cmdHi == 0x01 && frame.cmdLo == 0x01);
expect("payload is the 2-byte nonce", frame.payload.length == 2);
// A single flipped payload bit must invalidate the CRC.
byte[] tampered = built.clone();
tampered[15] ^= 0x01;
RingProtocol.Frame bad = RingProtocol.parse(tampered);
expect("tampered frame fails CRC", bad != null && !bad.crcOk);
}
/** The five ready-to-send health requests, seq=1, nonce=0. */
private static void testFiveHealthRequests() {
section("five health requests (spec section 9)");
String[][] expected = {
{"heart rate", "00450fe48f64026401000001010c000000"},
{"SpO2", "000d3fd33364026401000002010c000000"},
{"HRV", "00dc30615564026401000004010c000000"},
{"steps", "00e4208c3e64026401000005010c000000"},
{"sleep", "00ac10bb8264026401000006010c000000"},
};
int[] commands = {
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_HI_SPO2,
RingProtocol.CMD_HI_HRV,
RingProtocol.CMD_HI_STEPS,
RingProtocol.CMD_HI_SLEEP,
};
for (int i = 0; i < commands.length; i++) {
byte[] built = RingProtocol.buildHealthRequest(commands[i], 0x01, 0x0000);
expectHex(expected[i][0], expected[i][1], built);
}
// The convenience burst builder must produce the same first frame and
// then advance the shared sequence counter by one per frame.
List<byte[]> burst = RingProtocol.buildHealthRequestBurst(0x01, 0x0000);
expect("burst has five frames", burst.size() == 5);
expectHex("burst[0] == heart rate", expected[0][1], burst.get(0));
boolean seqRuns = true;
for (int i = 0; i < burst.size(); i++) {
RingProtocol.Frame f = RingProtocol.parse(burst.get(i));
if (f == null || !f.crcOk || f.seq != 0x01 + i) {
seqRuns = false;
}
}
expect("burst sequence numbers run 1..5 and all CRCs are valid", seqRuns);
}
/**
* Rebuild real captured page-ACKs. This is what pins down the two things
* the prose spec got wrong: the payload begins with the usual nonce (so the
* echoed page seq is at offset 6, not 4), and the frame's own SEQ is the
* phone's shared counter rather than the echoed page seq.
*/
private static void testPageAckAgainstCapture() {
section("page ACK 00:7E rebuilt from captured frames");
// seq, nonce, ackedCmdHi, ackedCmdLo, pageSeq, expected hex
Object[][] cases = {
{0x0d, 0x5f49, 0x01, 0x01, 0x03, "005e55d80b6401640d0001007e1600495f02010100030000000000"},
{0x13, 0xdc10, 0x04, 0x01, 0x07, "00a2bae3c4640164130001007e160010dc02040100070000000000"},
{0x17, 0x86e9, 0x02, 0x01, 0x09, "002c006c61640164170001007e1600e98602020100090000000000"},
{0x23, 0x634c, 0x06, 0x01, 0x13, "00b96c8823640164230001007e16004c6302060100130000000000"},
{0x25, 0x46f2, 0x05, 0x01, 0x14, "00474ee8b8640164250001007e1600f24602050100140000000000"},
{0x14, 0x7bc3, 0x05, 0x01, 0x3b, "00f3a5a917640164140001007e1600c37b020501003b0000000000"},
};
for (Object[] c : cases) {
byte[] built = RingProtocol.buildPageAck(
(Integer) c[0], (Integer) c[1], (Integer) c[2], (Integer) c[3], (Integer) c[4]);
expectHex("ack for cmd " + hex2((Integer) c[2]) + ":" + hex2((Integer) c[3])
+ " page seq " + hex2((Integer) c[4]), (String) c[5], built);
}
RingProtocol.Frame f = RingProtocol.parse(RingProtocol.buildPageAck(0x0d, 0x5f49, 0x01, 0x01, 0x03));
expect("ack rides the DEVICE channel", f.chan == RingProtocol.CHAN_DEVICE);
expect("ack kind is ACK", f.kind == RingProtocol.KIND_ACK);
expect("ack command is 00:7e", f.cmdHi == 0x00 && f.cmdLo == 0x7e);
expect("ack header seq differs from echoed page seq", f.seq != (f.payload[6] & 0xff));
expect("echoed page seq is at payload[6]", (f.payload[6] & 0xff) == 0x03);
}
private static void testParseRejectsGarbage() {
section("parser rejects non-frames");
expect("null", RingProtocol.parse(null) == null);
expect("too short", RingProtocol.parse(new byte[8]) == null);
expect("no magic", RingProtocol.parse(new byte[20]) == null);
// A 3-byte ring gesture frame must not look like a header.
expect("gesture frame is not a header",
!RingProtocol.looksLikeHeader(new byte[] {(byte) 0xff, 0x04, 0x01}));
// A frame whose PLEN disagrees with its actual length is rejected.
byte[] frame = RingProtocol.buildHealthRequest(RingProtocol.CMD_HI_HRV, 1, 0);
byte[] truncated = Arrays.copyOf(frame, frame.length - 1);
expect("length/PLEN mismatch rejected", RingProtocol.parse(truncated) == null);
}
/**
* Fragmentation, reproducing the shape the capture actually shows: an
* oversized frame split into a 244-byte FLAG=0x01 head and a headerless
* continuation, with an unrelated complete frame arriving in between.
*/
private static void testFragmentReassembly() {
section("fragment reassembly");
// Build a 252-byte steps-shaped frame: 15 header + 237 payload.
byte[] payload = new byte[237];
for (int i = 0; i < payload.length; i++) {
payload[i] = (byte) (i * 7 + 3);
}
byte[] whole = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA,
RingProtocol.CMD_HI_STEPS, RingProtocol.CMD_LO_HEALTH, 0x15, payload);
expect("test frame is 252 bytes", whole.length == 252);
byte[] head = Arrays.copyOf(whole, 244);
head[0] = (byte) RingProtocol.FLAG_FRAGMENTED;
byte[] continuation = new byte[RingProtocol.CONTINUATION_PREFIX_LEN + (whole.length - 244)];
System.arraycopy(whole, 244, continuation, RingProtocol.CONTINUATION_PREFIX_LEN, whole.length - 244);
expect("continuation is 5 + remaining bytes", continuation.length == 13);
byte[] interleaved = RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x01, 0x16, new byte[9]);
RingProtocol.Reassembler reassembler = new RingProtocol.Reassembler();
RingProtocol.Intake first = reassembler.accept(head);
expect("head consumed", first.consumed && first.frame == null);
expect("fragment outstanding", reassembler.hasPending());
RingProtocol.Intake middle = reassembler.accept(interleaved);
expect("interleaved frame still parses while a fragment is pending",
middle.consumed && middle.frame != null && middle.frame.crcOk);
expect("fragment survives the interleaved frame", reassembler.hasPending());
RingProtocol.Intake done = reassembler.accept(continuation);
expect("continuation completes the frame", done.consumed && done.frame != null);
expect("reassembled frame passes CRC", done.frame.crcOk);
expect("reassembled bytes are exact",
Arrays.equals(done.frame.raw, headJoined(head, whole)));
expect("no fragment left outstanding", !reassembler.hasPending());
expect("reassembled payload is intact", Arrays.equals(done.frame.payload, payload));
// Non-protocol traffic must pass straight through untouched.
RingProtocol.Intake gesture = reassembler.accept(new byte[] {(byte) 0xff, 0x04, 0x01});
expect("gesture frame is not consumed", !gesture.consumed);
}
private static byte[] headJoined(byte[] head, byte[] whole) {
byte[] expected = whole.clone();
expected[0] = head[0];
return expected;
}
// ------------------------------------------------------------------
// Synthetic record bodies, built directly from the spec's field layout.
// ------------------------------------------------------------------
private static void testHourlyDecode() {
section("hourly decode (heart rate W=1, HRV W=2, backlog page)");
// Anchored heart-rate page, W=1, three groups.
long anchor = 1788926400L; // 2026-09-09 00:00 local, the capture's anchor
int[][] groups = {{0, 61, 88, 55}, {1, 58, 71, 52}, {2, 63, 90, 57}};
byte[] body = hourlyBody(3, anchor, 12345L, 64, 1, groups);
RingProtocol.Frame frame = dataFrame(RingProtocol.CMD_HI_HEART_RATE, body);
RingProtocol.HourlyRecord hr = RingProtocol.decodeHourly(frame, 0L);
expect("HR decodes", hr != null);
expect("HR width resolved to 1", hr.valueWidth == 1);
expect("HR group count", hr.groups.length == 3);
expect("HR anchor", hr.anchorUnixSeconds == anchor);
expect("HR not backlog", !hr.isBacklog());
expect("HR current", hr.current == 64);
boolean values = true;
for (int i = 0; i < groups.length; i++) {
RingProtocol.HourlyGroup g = hr.groups[i];
values &= g.hourIndex == groups[i][0] && g.avg == groups[i][1]
&& g.max == groups[i][2] && g.min == groups[i][3]
&& g.unixSeconds == anchor + groups[i][0] * 3600L;
}
expect("HR values and hour timestamps round-trip", values);
// HRV uses two-byte values; the width must be resolved, not assumed.
int[][] hrvGroups = {{8, 300, 420, 210}, {9, 275, 380, 190}, {10, 512, 640, 400}};
byte[] hrvBody = hourlyBody(3, anchor, 22222L, 333, 2, hrvGroups);
RingProtocol.HourlyRecord hrv =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HRV, hrvBody), 0L);
expect("HRV decodes", hrv != null);
expect("HRV width resolved to 2", hrv.valueWidth == 2);
expect("HRV current", hrv.current == 333);
expect("HRV holds values above 255", hrv.groups[2].max == 640);
// Backlog page: anchor absent. The hour index must survive; the absolute
// time must NOT be invented.
byte[] backlogBody = hourlyBody(3, RingProtocol.UNKNOWN_TIME, 77777L, 60, 1, groups);
RingProtocol.HourlyRecord backlog =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HEART_RATE, backlogBody), 0L);
expect("backlog decodes", backlog != null);
expect("backlog flagged", backlog.isBacklog());
expect("backlog anchor unknown", backlog.anchorUnixSeconds == RingProtocol.UNKNOWN_TIME);
boolean noInventedTime = true;
for (RingProtocol.HourlyGroup g : backlog.groups) {
noInventedTime &= g.unixSeconds == RingProtocol.UNKNOWN_TIME;
}
expect("backlog groups carry no invented absolute time", noInventedTime);
expect("backlog keeps raw hour indices",
backlog.groups[0].hourIndex == 0 && backlog.groups[2].hourIndex == 2);
expect("backlog still decodes values", backlog.groups[1].avg == 58);
}
private static void testStepsDecode() {
section("steps decode");
long anchor = 1788926400L;
int[][] buckets = {{0, 120, 4, 16}, {3, 0, 0, 12}, {130, 45, 2, 14}};
byte[] body = stepsBody(anchor, buckets);
RingProtocol.StepsRecord steps =
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, body), 0L);
expect("steps decode", steps != null);
expect("bucket count", steps.buckets.length == 3);
expect("total steps", steps.totalSteps() == 165);
expect("raw index preserved, including the 130+ jump",
steps.buckets[2].index == 130);
expect("v2/v3 kept as unconfirmed calorie-shaped fields",
steps.buckets[0].calorieLike2 == 4 && steps.buckets[0].calorieLike3 == 16);
expect("steps anchor", steps.anchorUnixSeconds == anchor);
// Length must be exact: a truncated body is a decode failure, not a guess.
byte[] shortBody = Arrays.copyOf(body, body.length - 1);
expect("truncated steps body rejected",
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, shortBody), 0L) == null);
}
private static void testSleepDecodeAndIdentities() {
section("sleep decode + the spec's arithmetic identities");
// segments: (stage, halfMinutes). Stage sums: 0->10, 1->20, 2->70, 3->25.
int[][] segments = {{0, 4}, {1, 20}, {2, 40}, {0, 6}, {2, 30}, {3, 25}};
int totalHalfMinutes = 125;
int seconds = totalHalfMinutes * 30; // 3750
int wake = 10 * 30; // 300, stage 0
int rem = 20 * 30; // 600, stage 1
int light = 70 * 30; // 2100, stage 2
int deep = 25 * 30; // 750, stage 3
int total = seconds - wake; // 3450
long start = 100000L;
long end = start + seconds;
byte[] body = sleepBody(1, start, end, total, wake, rem, light, deep, segments);
RingProtocol.SleepRecord sleep =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, body), 0L);
expect("sleep decodes", sleep != null);
expect("real record", sleep.isRealRecord());
expect("segment count", sleep.segments.length == segments.length);
expect("segment stages and durations round-trip",
sleep.segments[2].stage == 2 && sleep.segments[2].halfMinutes == 40);
expect("identity: sum(half_minutes) x 30 == total_time + wake_time",
sleep.totalHalfMinutes() * 30 == sleep.totalTime + sleep.wakeTime);
expect("identity: sum(half_minutes) x 30 == end_ts - start_ts",
sleep.totalHalfMinutes() * 30 == (int) (sleep.endTs - sleep.startTs));
expect("identity: per-stage sums match the four stage totals",
sleep.halfMinutesForStage(0) * 30 == wake
&& sleep.halfMinutesForStage(1) * 30 == rem
&& sleep.halfMinutesForStage(2) * 30 == light
&& sleep.halfMinutesForStage(3) * 30 == deep);
expect("identitiesHold() agrees", sleep.identitiesHold());
expect("uncracked 6-byte field stored raw, not interpreted",
sleep.unknownPrefix.length == 6);
expect("relative timestamps kept as sent",
sleep.startTs == start && sleep.endTs == end);
// The empty end-of-list marker must decode without inventing a session.
byte[] marker = new byte[] {0x11, 0x22, 0x02};
RingProtocol.SleepRecord empty =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, marker), 0L);
expect("RECSTATE=2 marker decodes", empty != null && !empty.isRealRecord());
expect("marker has no segments", empty.segments.length == 0);
// A declared segment count that does not fill the body is a parse failure.
byte[] broken = body.clone();
broken[32] = (byte) (segments.length + 1);
expect("segment-count mismatch rejected",
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, broken), 0L) == null);
}
// ------------------------------------------------------------------
private static void testDailyWireLayouts() {
section("footer-free daily layouts and timezone anchors");
long anchor = 1789700400L;
byte[] hr = hourlyBody(2, anchor, anchor + 3600, 70, 1,
new int[][] {{0, 70, 80, 60}, {1, 72, 82, 62}});
expect("two-hour HR frame is 37 bytes", dataFrame(1, hr).raw.length == 37);
for (int timezone : new int[] {-420, -240, 0, 330, 840}) {
putLe(hr, 3, timezone, 2);
RingProtocol.HourlyRecord decoded = RingProtocol.decodeHourly(dataFrame(1, hr), 0);
expect("anchor works at timezone " + timezone,
decoded != null && decoded.anchorUnixSeconds == anchor && decoded.groups.length == 2);
}
byte[] spo2 = hourlyBody(1, anchor, anchor, 98, 1, new int[][] {{0, 98, 99, 97}});
expect("one-hour SpO2 frame is 33 bytes", dataFrame(2, spo2).raw.length == 33);
expect("SpO2 decodes without footer", RingProtocol.decodeHourly(dataFrame(2, spo2), 0).groups[0].avg == 98);
byte[] hrv = hourlyBody(1, anchor, anchor, 51, 2, new int[][] {{3, 51, 300, 40}});
RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0);
expect("one-hour HRV retains two-byte values", variability.valueWidth == 2
&& variability.groups[0].hourIndex == 3 && variability.groups[0].max == 300);
// Offline daily pages omit the five-byte latest-reading prefix.
byte[] offline = new byte[9 + 8];
System.arraycopy(hr, 0, offline, 0, 9);
System.arraycopy(hr, 14, offline, 9, 8);
RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(1, offline), 0);
expect("daily page without latest sample decodes", past != null
&& past.current == -1 && past.groups[1].avg == 72);
putLe(offline, 5, 0, 4);
expect("zero day remains unresolved", RingProtocol.anchorUnixSeconds(offline) == RingProtocol.UNKNOWN_TIME);
int[][] buckets = new int[8][4];
for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {i, i * 10, 1, 2};
byte[] activity = stepsBody(anchor, buckets);
expect("eight-bucket activity frame is 80 bytes", dataFrame(5, activity).raw.length == 80);
expect("activity decodes without footer", RingProtocol.decodeSteps(dataFrame(5, activity), 0).buckets.length == 8);
expect("trailing garbage rejected", RingProtocol.decodeSteps(dataFrame(5,
Arrays.copyOf(activity, activity.length + 4)), 0) == null);
}
private static void testDeviceStatus() {
section("direct device status battery");
byte[] payload = {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0};
for (int charge = 0; charge <= 3; charge++) {
payload[3] = (byte) charge;
RingProtocol.Frame frame = RingProtocol.parse(RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 1, payload));
RingProtocol.DeviceStatus status = RingProtocol.decodeDeviceStatus(frame);
expect("battery and charge enum " + charge, status != null && status.battery == 82
&& status.charging == (charge == 0 ? -1 : charge == 2 ? 0 : 1));
}
payload[2] = (byte) 255;
expect("invalid battery rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, payload))) == null);
expect("wrong channel rejected", RingProtocol.decodeDeviceStatus(dataFrame(1, payload)) == null);
expect("short response rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, new byte[2]))) == null);
}
// Synthetic body builders matching the recovered R1 serializers.
// ------------------------------------------------------------------
private static byte[] hourlyBody(int count, long anchor, long tag, int current,
int width, int[][] groups) {
byte[] body = new byte[13 + width + count * (1 + 3 * width)];
body[0] = 0x11;
body[1] = 0x22;
body[2] = (byte) count;
writeAnchor(body, anchor);
putLe(body, 9, tag, 4);
putLe(body, 13, current, width);
int offset = 13 + width;
for (int[] g : groups) {
body[offset++] = (byte) g[0];
putLe(body, offset, g[1], width);
offset += width;
putLe(body, offset, g[2], width);
offset += width;
putLe(body, offset, g[3], width);
offset += width;
}
return body;
}
private static byte[] stepsBody(long anchor, int[][] buckets) {
byte[] body = new byte[9 + buckets.length * 7];
body[0] = 0x33;
body[1] = 0x44;
body[2] = (byte) buckets.length;
writeAnchor(body, anchor);
int offset = 9;
for (int[] b : buckets) {
body[offset] = (byte) b[0];
putLe(body, offset + 1, b[1], 2);
putLe(body, offset + 3, b[2], 2);
putLe(body, offset + 5, b[3], 2);
offset += 7;
}
return body;
}
private static byte[] sleepBody(int recordState, long start, long end, int total, int wake,
int rem, int light, int deep, int[][] segments) {
byte[] body = new byte[34 + segments.length * 3];
body[0] = 0x55;
body[1] = 0x66;
body[2] = (byte) recordState;
for (int i = 3; i < 9; i++) {
body[i] = (byte) (0xA0 + i); // the uncracked 6-byte field
}
putLe(body, 9, 90210L, 4); // the uncracked u32 tag
body[13] = 0x00;
putLe(body, 14, start, 4);
putLe(body, 18, end, 4);
putLe(body, 22, total, 2);
putLe(body, 24, wake, 2);
putLe(body, 26, rem, 2);
putLe(body, 28, light, 2);
putLe(body, 30, deep, 2);
body[32] = (byte) segments.length;
body[33] = 0x00;
int offset = 34;
for (int[] s : segments) {
body[offset] = (byte) s[0];
putLe(body, offset + 1, s[1], 2);
offset += 3;
}
return body;
}
private static void writeAnchor(byte[] body, long anchor) {
if (anchor == RingProtocol.UNKNOWN_TIME) {
return; // six zero bytes = backlog page
}
body[3] = 0x10;
body[4] = (byte) 0xFF;
putLe(body, 5, anchor, 4);
}
private static void putLe(byte[] out, int offset, long value, int width) {
for (int i = 0; i < width; i++) {
out[offset + i] = (byte) ((value >>> (8 * i)) & 0xff);
}
}
private static RingProtocol.Frame dataFrame(int cmdHi, byte[] body) {
byte[] frame = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0x20, body);
return RingProtocol.parse(frame);
}
// ------------------------------------------------------------------
private static void section(String name) {
System.out.println();
System.out.println("-- " + name);
}
private static void expect(String what, boolean ok) {
checks++;
if (!ok) {
failures++;
}
System.out.println(" " + (ok ? "ok " : "FAIL") + " " + what);
}
private static void expectHex(String what, String expectedHex, byte[] actual) {
String actualHex = RingProtocol.hex(actual);
boolean ok = expectedHex.equals(actualHex);
checks++;
if (!ok) {
failures++;
System.out.println(" FAIL " + what);
System.out.println(" expected " + expectedHex);
System.out.println(" actual " + actualHex);
return;
}
System.out.println(" ok " + what + " " + actualHex);
}
private static String hex2(int value) {
return String.format(java.util.Locale.US, "%02x", value & 0xff);
}
}
@@ -0,0 +1,117 @@
package com.faceclaw.app
import java.io.ByteArrayOutputStream
import java.util.Collections
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.zip.Inflater
import kotlin.test.*
// Host tests have no Android clock; all other services use the production adapter.
internal actual fun testPlatform(): ProtocolPlatform =
object : ProtocolPlatform by AndroidProtocolPlatform {
override fun elapsedRealtimeMs() = System.nanoTime() / 1_000_000
}
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> {
val inflater = Inflater()
try {
return records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0) inflater.reset()
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
inflater.setInput(body)
val out = ByteArrayOutputStream()
val buffer = ByteArray(4096)
do {
val count = inflater.inflate(buffer)
out.write(buffer, 0, count)
} while (!inflater.needsInput())
out.toByteArray()
}
}
} finally {
inflater.end()
}
}
class AndroidProtocolTest {
@Test
fun javaGoldenCorpus() {
// SHA-256 of packets emitted by the pre-migration Java implementation.
val raw = java.security.MessageDigest.getInstance("SHA-256")
val compressed = java.security.MessageDigest.getInstance("SHA-256")
val transport = CfwTransport(testPlatform())
var state = 123456789
try {
repeat(120) { i ->
val size = intArrayOf(0, 1, 4, 247, 248, 252, 4095, 4096, 8192, 65535)[i % 10]
val data =
ByteArray(size) {
state = state xor (state shl 13)
state = state xor (state ushr 17)
state = state xor (state shl 5)
state.toByte()
}
if (i % 3 == 0) data.fill((i % 7).toByte())
val id = (i * 37) and 255
val lenses = 1 + (i / 7) % 3
val mtu = intArrayOf(23, 247, 512, 517)[i % 4]
if (i % 13 == 0) transport.reset()
CfwTransport.frame(data, id, lenses, mtu).forEach { raw.update(it) }
transport.encode(data, id, lenses, mtu).forEach { compressed.update(it) }
}
assertEquals(
"d0efdb99ac71763dd29b70fbd0021b80e1cfe514dfc8a60e2a8424892b16c9f5",
raw.digest().toHexString(),
)
assertEquals(
"eb5ce0cc6e41b8e84f0d9455f98f3f666b20be0643c3756c5f7aa9d9a66085e2",
compressed.digest().toHexString(),
)
} finally {
transport.close()
}
}
@Test
fun writeModeMapping() {
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
AndroidProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
AndroidProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
@Test
fun concurrentAllocationNeverDuplicatesAnInUseId() {
val pool = BleMagicPool(testPlatform())
val inUse = Collections.synchronizedSet(mutableSetOf<Int>())
val executor = Executors.newFixedThreadPool(8)
try {
val jobs =
List(8) {
executor.submit {
repeat(2000) {
val id = pool.allocate()
assertTrue(inUse.add(id))
Thread.yield()
assertTrue(inUse.remove(id))
pool.release(1, id, null, null)
}
}
}
jobs.forEach { it.get(30, TimeUnit.SECONDS) }
assertEquals(156, List(156) { pool.allocate() }.toSet().size)
} finally {
executor.shutdownNow()
}
}
}
internal actual fun digest(bytes: ByteArray): String =
BinaryEncoding.bytesToHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes))
@@ -0,0 +1,33 @@
package com.faceclaw.app
import java.util.Locale
import kotlin.test.Test
import kotlin.test.assertEquals
/** The shared export must match what the Java-era String.format("%+7d") produced. */
class FrameTimingsFormatTest {
private class FakeClock : ProtocolPlatform by AndroidProtocolPlatform {
var nowMs = 5_000L
override fun elapsedRealtimeMs(): Long = nowMs
}
@Test
fun lineOffsetsMatchJavaFormat() {
val clock = FakeClock()
val core = FrameTimingsCore(clock, wallClockMs = { 0L }, threadName = { "worker" }, formatWallClock = { "w" }, logInfo = {}, logWarn = {})
val offsets = listOf(-1_234_567L, -12L, -1L, 0L, 1L, 42L, 999L, 1_000L, 12_345L, 1_234_567L, 12_345_678L)
val root = core.startFrame("input:fmt")
for (offset in offsets) {
clock.nowMs = 5_000L + offset
core.log(root, "o=$offset")
}
clock.nowMs = 5_000L
core.finishFrame(root, "sent")
val export = core.buildExport()
for (offset in offsets) {
val javaLine = String.format(Locale.US, " %+7dms [%s] %s", offset, "worker", "o=$offset")
assert(export.contains("\n$javaLine\n")) { "missing <$javaLine> in\n$export" }
}
assertEquals(2, export.split("\n").count { it.contains("finished: sent") })
}
}
@@ -0,0 +1,29 @@
package com.faceclaw.app
import kotlin.test.Test
/** Existing wire fixtures also verify the Java API retained by the Kotlin port. */
class JavaCompatibilityTest {
@Test fun compass() = CompassProtocolTest.main(emptyArray())
@Test fun ringBattery() = RingBatteryProtocolTest.main(emptyArray())
@Test fun gestures() = FaceclawGestureEventTest.main(emptyArray())
@Test fun resourceCache() = ResourceCacheProtocolTest.main(emptyArray())
@Test fun ringHealthProtocol() = RingProtocolSelfTest.main(emptyArray())
}
class AndroidByteReaderTest {
@Test fun repeatedBridgeCrossingsHaveIndependentCursors() {
val buffer = java.nio.ByteBuffer.wrap(byteArrayOf(10, 20, 30))
val first = AndroidByteReader(buffer)
kotlin.test.assertEquals(10, first.get().toInt())
kotlin.test.assertEquals(0, buffer.position())
val second = AndroidByteReader(buffer)
kotlin.test.assertEquals(3, second.remaining())
kotlin.test.assertEquals(10, second.get().toInt())
kotlin.test.assertEquals(20, first.get().toInt())
}
}
@@ -0,0 +1,123 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private class FakeScheduler : AlarmScheduler {
val pending = LinkedHashMap<Any, Pair<Long, () -> Unit>>()
override fun postDelayed(token: Any, delayMs: Long, action: () -> Unit) { pending[token] = delayMs to action }
override fun cancel(token: Any) { pending.remove(token) }
override fun cancelAll() { pending.clear() }
fun fire(token: Any) { val entry = pending.remove(token) ?: error("no timer $token"); entry.second() }
}
private class FakeSink : RingingSink {
val events = ArrayList<String>()
var sounding = false
override fun showNotification(item: RingingItem) { events.add("notify ${item.id} " + (if (item.silenced) "silenced" else if (item.escalated) "ringing" else "glasses")) }
override fun itemRemoved(item: RingingItem) { events.add("removed ${item.id}") }
override fun ringingStarted() { events.add("wake") }
override fun startSound() { if (!sounding) { sounding = true; events.add("sound on") } }
override fun stopSound() { if (sounding) { sounding = false; events.add("sound off") } }
override fun reschedule(item: RingingItem, atMs: Long, minutes: Int) { events.add("reschedule ${item.id} $atMs $minutes") }
override fun cancelSchedule(id: Long) { events.add("cancel $id") }
override fun recordPhoneAction(id: Long, action: String, minutes: Int) { events.add("action $id $action $minutes") }
override fun log(line: String) { events.add("log $line") }
}
class AlarmRingingPolicyTest {
private var now = 5_000_000L
private val gate = GlassesStatusGate { now }
private val scheduler = FakeScheduler()
private val sink = FakeSink()
private val policy = AlarmRingingPolicy(gate, { now }, testPlatform()).also { it.attach(scheduler, sink) }
private fun item(id: Long, kind: String = AlarmSchedule.KIND_ALARM) = RingingItem(id, "Wake", "", kind, 9, now)
@Test
fun glassesUnavailableEscalatesImmediately() {
policy.ring(item(1))
assertEquals(listOf("log ring alarm 1 (no glasses status)", "wake", "notify 1 glasses", "log phone sound for 1: no glasses status", "notify 1 ringing", "sound on"), sink.events)
assertTrue(policy.isRinging(1))
assertEquals(setOf<Any>("silence:1"), scheduler.pending.keys)
scheduler.fire("silence:1")
assertEquals(listOf("log auto-silenced 1", "notify 1 silenced", "sound off"), sink.events.drop(6))
}
@Test
fun deliveryAndAcknowledgementTimersEscalate() {
gate.set(connected = true, worn = true, charging = false)
policy.ring(item(2))
assertEquals(listOf("log ring alarm 2 (glasses worn)", "wake", "notify 2 glasses"), sink.events)
assertEquals(setOf<Any>("delivery:2"), scheduler.pending.keys)
policy.markDelivered(2)
assertEquals("log delivered 2 to glasses", sink.events.last())
assertEquals(setOf<Any>("delivery:2", "ack:2"), scheduler.pending.keys)
scheduler.fire("delivery:2") // delivered in time: no escalation
assertFalse(policy.snapshot().single().escalated)
scheduler.fire("ack:2")
assertTrue(policy.snapshot().single().escalated)
assertTrue(sink.sounding)
// Acknowledged on the glasses afterwards: quiet stop, sound off.
policy.stopQuietly(2, "acknowledged")
assertEquals(listOf("log acknowledged 2", "removed 2", "sound off"), sink.events.takeLast(3))
assertFalse(policy.isAnythingRinging())
}
@Test
fun undeliveredRingEscalatesAfterDeliveryWait() {
gate.set(connected = true, worn = true, charging = false)
policy.ring(item(3))
scheduler.fire("delivery:3")
assertEquals("log phone sound for 3: not delivered to the glasses", sink.events[3])
assertTrue(sink.sounding)
}
@Test
fun snoozeAndDismissRecordActionsAndRearm() {
policy.ring(item(4, AlarmSchedule.KIND_TIMER))
policy.snooze(4)
assertEquals(listOf("action 4 snooze 9", "removed 4", "sound off", "reschedule 4 ${now + 9 * 60_000L} 9"), sink.events.takeLast(4))
policy.ring(item(5))
policy.dismiss(5)
assertEquals(listOf("action 5 dismiss 0", "removed 5", "sound off", "cancel 5"), sink.events.takeLast(4))
policy.dismiss(99) // unknown: no-op
assertEquals("cancel 5", sink.events.last())
}
@Test
fun earlySignalsAreConsumedOrExpire() {
gate.set(connected = true, worn = true, charging = false)
assertFalse(policy.deliveredOrDefer(6))
policy.ring(item(6))
assertEquals("log delivered 6 to glasses", sink.events.last())
assertEquals(setOf<Any>("ack:6"), scheduler.pending.keys)
assertFalse(policy.stopOrDefer(7))
policy.ring(item(7))
assertEquals("log ring 7 already acknowledged", sink.events.last())
assertFalse(policy.isRinging(7))
assertFalse(policy.stopOrDefer(8))
now += AlarmRingingPolicy.EARLY_SIGNAL_MAX_AGE_MS + 1
policy.ring(item(8))
assertTrue(policy.isRinging(8))
assertTrue(policy.stopOrDefer(8))
assertTrue(policy.deliveredOrDefer(8))
}
@Test
fun duplicateRingOnlyRefreshesNotificationAndDetachDropsTimers() {
policy.ring(item(9))
val before = sink.events.size
policy.ring(item(9))
assertEquals(listOf("notify 9 ringing"), sink.events.drop(before))
assertEquals(1, policy.snapshot().size)
policy.detach()
assertTrue(scheduler.pending.isEmpty())
policy.ring(item(10)) // no host: ignored
assertFalse(policy.isRinging(10))
}
}
@@ -0,0 +1,109 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
private class MemoryStore : AlarmStore {
val values = HashMap<String, String?>()
override fun read(key: String): String? = values[key]
override fun write(key: String, value: String?) { values[key] = value }
}
class AlarmScheduleTest {
private val store = MemoryStore()
private var now = 1_700_000_000_000L
private val schedule = AlarmSchedule(store, { now }, testPlatform())
@Test
fun persistsEntriesAsJsonAndReplacesById() {
schedule.put(AlarmEntry(7, now + 60_000, "Tea", "steep", AlarmSchedule.KIND_TIMER, 5))
schedule.put(AlarmEntry(8, now + 120_000, null, null, null, 10))
assertEquals("""[{"id":7,"at":${now + 60_000},"title":"Tea","text":"steep","kind":"timer","snoozeMinutes":5},{"id":8,"at":${now + 120_000},"title":"","text":"","kind":"alarm","snoozeMinutes":10}]""", store.values[AlarmSchedule.KEY_SCHEDULED])
schedule.put(AlarmEntry(7, now + 90_000, "Tea", "steep", AlarmSchedule.KIND_TIMER, 5))
assertEquals(listOf(8L, 7L), schedule.entries().map { it.id })
assertEquals(now + 90_000, schedule.find(7)?.at)
schedule.remove(8)
assertNull(schedule.find(8))
// A corrupt file reads as empty rather than failing.
store.values[AlarmSchedule.KEY_SCHEDULED] = "{nope"
assertTrue(schedule.entries().isEmpty())
}
@Test
fun replayRingsRecentDropsMissedArmsFuture() {
schedule.put(AlarmEntry(1, now - 60_000, "recent", "", null, 10))
schedule.put(AlarmEntry(2, now - AlarmSchedule.LATE_GRACE_MS - 1, "old", "", AlarmSchedule.KIND_TIMER, 10))
schedule.put(AlarmEntry(3, now + 60_000, "future", "", null, 10))
val rang = ArrayList<Long>()
val armed = ArrayList<Long>()
schedule.replay("boot", { rang.add(it.id) }, { armed.add(it.id) })
assertEquals(listOf(1L), rang)
assertEquals(listOf(3L), armed)
assertEquals(listOf(1L, 3L), schedule.entries().map { it.id })
val log = schedule.readLog()
assertTrue(log.contains("$now missed timer 2 (boot)"), log)
assertTrue(log.endsWith("$now rescheduled 1 (boot)"), log)
}
@Test
fun stalenessComparesSoonestPendingWithSystemAlarm() {
assertFalse(schedule.looksStale(null))
schedule.put(AlarmEntry(1, now - 1, "past", "", null, 10))
assertNull(schedule.soonestPendingAt())
schedule.put(AlarmEntry(2, now + 50_000, "", "", null, 10))
schedule.put(AlarmEntry(3, now + 20_000, "", "", null, 10))
assertEquals(now + 20_000, schedule.soonestPendingAt())
assertTrue(schedule.looksStale(null))
assertTrue(schedule.looksStale(now + 30_000))
assertFalse(schedule.looksStale(now + 20_500))
assertFalse(schedule.looksStale(now + 5_000))
}
@Test
fun journalAppendsAndDrains() {
schedule.appendJournal(5, "snooze", 10)
now += 1000
schedule.appendJournal(6, "dismiss", 0)
assertEquals("""[{"id":5,"action":"snooze","minutes":10,"at":${now - 1000}},{"id":6,"action":"dismiss","minutes":0,"at":$now}]""", schedule.drainJournal())
assertEquals("[]", schedule.drainJournal())
val log = schedule.readLog().lines()
assertEquals("${now - 1000} phone snooze 5 (10 min)", log[0])
assertEquals("$now phone dismiss 6", log[1])
}
@Test
fun logKeepsOnlyTheLastLines() {
for (index in 0 until AlarmSchedule.LOG_LINES + 5) schedule.log("line $index")
val lines = schedule.readLog().lines()
assertEquals(AlarmSchedule.LOG_LINES, lines.size)
assertEquals("$now line 5", lines.first())
assertEquals("$now line ${AlarmSchedule.LOG_LINES + 4}", lines.last())
}
@Test
fun glassesGateRequiresFreshWornConnectedNotCharging() {
var clock = 10_000L
val gate = GlassesStatusGate { clock }
assertFalse(gate.canCarryAlarm())
assertEquals("no glasses status", gate.description())
gate.set(connected = true, worn = true, charging = false)
assertTrue(gate.canCarryAlarm())
assertEquals("glasses worn", gate.description())
gate.set(connected = true, worn = false, charging = false)
assertEquals("glasses not worn", gate.description())
gate.set(connected = true, worn = true, charging = true)
assertEquals("glasses charging", gate.description())
gate.set(connected = false, worn = true, charging = false)
assertEquals("glasses not connected", gate.description())
gate.set(connected = true, worn = true, charging = false)
clock += GlassesStatusGate.MAX_AGE_MS + 1
assertFalse(gate.canCarryAlarm())
assertEquals("glasses status stale", gate.description())
assertEquals(0x7fffffff and (0x1_0000_0002L xor 1L).toInt(), AlarmSchedule.requestCode(0x1_0000_0002L))
assertNotNull(AlarmEntry.fromJson(Json.parse("""{"id":1,"at":2}""")))
}
}
@@ -0,0 +1,130 @@
package com.faceclaw.app
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class AudioHelpersTest {
@Test
fun cutPointLandsInQuietestWindowForFloatsAndShorts() {
// 1000 loud samples with a silent gap at 700..760; search the last 500 with a 40 window.
val floats = FloatArray(1000) { if (it in 700 until 760) 0f else 0.5f }
val cut = AudioSegmentation.quietestCutPoint(floats, floats.size, 500, 40)
assertTrue(cut in 700..760, "cut=$cut")
val shorts = ShortArray(1100) { if (it - 100 in 700 until 760) 0 else 16000 }
assertEquals(cut, AudioSegmentation.quietestCutPoint(shorts, 100, 1000, 500, 40))
// Too short to search: returns the length unchanged.
assertEquals(30, AudioSegmentation.quietestCutPoint(FloatArray(30) { 0.1f }, 30, 500, 40))
}
@Test
fun normalizePeakScalesUpButNeverDown() {
val quiet = floatArrayOf(0.01f, -0.02f, 0.005f)
AudioSegmentation.normalizePeak(quiet, 0.9f, 30f)
assertTrue(abs(quiet[1] + 0.6f) < 1e-6f, "capped at maxGain 30: ${quiet[1]}")
val loud = floatArrayOf(0.95f, -0.5f)
AudioSegmentation.normalizePeak(loud, 0.9f, 30f)
assertEquals(0.95f, loud[0])
val silent = FloatArray(4)
AudioSegmentation.normalizePeak(silent, 0.9f, 30f)
assertEquals(0f, AudioSegmentation.peakAmplitude(silent))
}
@Test
fun pcmConversionsRoundTrip() {
val samples = shortArrayOf(0, 1, -1, 32767, -32768, 256)
val le = AudioSegmentation.pcm16ToLittleEndian(samples, 0, samples.size)
assertEquals(listOf(0, 0, 1, 0, 0xff, 0xff, 0xff, 0x7f, 0, 0x80, 0, 1), le.map { it.toInt() and 0xff })
val floats = AudioSegmentation.pcm16leToFloat(le)
assertEquals(AudioSegmentation.pcm16ToFloat(samples, 0, samples.size).toList(), floats.toList())
assertEquals(32767 / 32768.0f, floats[3])
assertEquals(-1f, floats[4])
assertEquals(2.0, AudioSegmentation.rms(shortArrayOf(2, -2, 2, -2), 0, 4))
}
@Test
fun voicePrintMathAndBlobCodec() {
val v = floatArrayOf(3f, 4f)
VoicePrint.l2Normalize(v)
assertEquals(listOf(0.6f, 0.8f), v.toList())
assertTrue(abs(VoicePrint.dot(v, v) - 1.0) < 1e-6)
assertNull(VoicePrint.l2Normalize(null))
assertTrue(VoicePrint.isLongEnoughToEmbed(16000, 16000))
assertTrue(!VoicePrint.isLongEnoughToEmbed(15999, 16000))
val blob = SpeakerEmbeddings.floatsToBlob(floatArrayOf(1.5f, -2f))
assertEquals(listOf(0, 0, 0xc0, 0x3f, 0, 0, 0, 0xc0), blob.map { it.toInt() and 0xff })
assertEquals(listOf(1.5f, -2f), SpeakerEmbeddings.blobToFloats(blob)!!.toList())
assertNull(SpeakerEmbeddings.blobToFloats(byteArrayOf(1, 2, 3)))
assertNull(SpeakerEmbeddings.blobToFloats(null))
}
@Test
fun centroidUpdatesAndBlends() {
val first = SpeakerEmbeddings.runningMean(null, 0, floatArrayOf(1f, 0f), 5)
assertEquals(1, first.count)
assertEquals(listOf(1f, 0f), first.embedding.toList())
val second = SpeakerEmbeddings.runningMean(first.embedding, first.count, floatArrayOf(0f, 1f), 5)
assertEquals(2, second.count)
assertTrue(abs(second.embedding[0] - second.embedding[1]) < 1e-6f)
assertTrue(abs(VoicePrint.dot(second.embedding, second.embedding) - 1.0) < 1e-6)
// The cap limits the existing weight: count 100 capped at 1 behaves like an equal blend.
val capped = SpeakerEmbeddings.runningMean(floatArrayOf(1f, 0f), 100, floatArrayOf(0f, 1f), 1)
assertTrue(abs(capped.embedding[0] - capped.embedding[1]) < 1e-6f)
assertEquals(101, capped.count)
// Mismatched sizes restart the centroid.
assertEquals(1, SpeakerEmbeddings.runningMean(floatArrayOf(1f), 4, floatArrayOf(0f, 1f), 5).count)
val blended = SpeakerEmbeddings.blend(floatArrayOf(1f, 0f), 1, floatArrayOf(0f, 1f), 3)
assertNotNull(blended)
assertTrue(blended[1] > blended[0])
assertEquals(listOf(0f, 1f), SpeakerEmbeddings.blend(null, 0, floatArrayOf(0f, 1f), 3)!!.toList())
assertEquals(listOf(1f, 0f), SpeakerEmbeddings.blend(floatArrayOf(1f, 0f), 2, null, 0)!!.toList())
assertNull(SpeakerEmbeddings.blend(null, 0, null, 0))
assertTrue(SpeakerEmbeddings.shouldAdoptInsights(targetHasInsights = false, sourceHasInsights = true))
assertTrue(!SpeakerEmbeddings.shouldAdoptInsights(targetHasInsights = true, sourceHasInsights = true))
}
private fun wav(dataSize: Int, extraChunk: Boolean = false, channels: Int = 1, bits: Int = 16, format: Int = 1): ByteArray {
val out = ByteSink()
fun u16(v: Int) { out.write(v); out.write(v ushr 8) }
fun u32(v: Int) { u16(v); u16(v ushr 16) }
out.write("RIFF".encodeToByteArray()); u32(0); out.write("WAVE".encodeToByteArray())
if (extraChunk) { out.write("LIST".encodeToByteArray()); u32(4); u32(0) }
out.write("fmt ".encodeToByteArray()); u32(18)
u16(format); u16(channels); u32(16000); u32(16000 * channels * 2); u16(channels * 2); u16(bits); u16(0)
out.write("data".encodeToByteArray()); u32(dataSize)
return out.toByteArray()
}
@Test
fun wavHeaderParsesChunksAndRecoversZeroSize() {
val header = wav(4000)
val info = WavPcmReader.parseHeader(header, header.size + 4000L)
assertEquals(16000, info.sampleRate)
assertEquals(1, info.channels)
assertEquals(16, info.bitsPerSample)
assertEquals(header.size.toLong(), info.dataOffset)
assertEquals(4000L, info.dataBytes)
val withList = wav(100, extraChunk = true)
assertEquals(withList.size.toLong(), WavPcmReader.parseHeader(withList, withList.size + 100L).dataOffset)
val unpatched = wav(0)
assertEquals(1234L, WavPcmReader.parseHeader(unpatched, unpatched.size + 1234L).dataBytes)
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader("RIFX".encodeToByteArray() + ByteArray(20), 24) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10, bits = 8), 100) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10, format = 3), 100) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10).copyOf(20), 100) }
// The shared header matches the shared writer.
val written = BinaryEncoding.wavHeader(640, 16000, 1)
val parsed = WavPcmReader.parseHeader(written, 44 + 640L)
assertEquals(44L, parsed.dataOffset)
assertEquals(640L, parsed.dataBytes)
}
}
@@ -0,0 +1,44 @@
package com.faceclaw.app
import kotlin.test.*
internal expect fun digest(bytes: ByteArray): String
class AudioRecordingTest {
@Test
fun javaNoiseSuppressionGoldenAcrossChunksAndReset() {
val suppressor = FaceclawNoiseSuppressor(16000)
val output = ByteSink()
for (round in 0 until 80) {
val input = ByteArray(if (round % 7 == 0) 514 else 640)
for (i in 0 until input.size / 2) {
val value = ((round * 317 + i * 773) % 48000) - 24000
input[i * 2] = value.toByte()
input[i * 2 + 1] = (value shr 8).toByte()
}
if (round == 41) suppressor.reset()
output.write(assertNotNull(suppressor.process(input)))
}
// SHA-256 from the original Java DSP, including warmup and irregular chunks.
assertEquals(
"4a7e86b70d61d683b17c7051dbd6666f5ea62427fdd7fdb1d4c9a1772a1eb8ef",
digest(output.toByteArray()),
)
}
@Test
fun javaGifGoldenIncludingDedupAndLzwCodeGrowth() {
val recorder = SharedGifScreenRecorder()
assertTrue(recorder.encode().isEmpty())
for (round in 0 until 7) {
val pixels = ByteArray(33 * 17) { ((it * 73 + round * 117) % 256).toByte() }
recorder.addFrame(pixels, 33, 17, round * 133L)
recorder.addFrame(pixels, 33, 17, round * 133L + 10)
}
assertFalse(recorder.isOverflowed())
assertEquals(
"8c5dcb98fa03653972f7f7d5ddaaacff323dd633578905bc252ebe21f9d82780",
digest(recorder.encode()),
)
}
}
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.test.*
class BrightnessPolicyTest {
private fun report(lux: Int, reason: Int = 2, flags: Int = 11): ByteArray {
val b = ByteArray(24)
b[0] = 65; b[1] = 76; b[2] = 1; b[3] = reason.toByte(); b[4] = flags.toByte()
val raw = lux * 10
for (i in 0..3) b[6+i] = (raw ushr (8*i)).toByte()
return b
}
@Test fun defaultMatchesMeasuredLightingPreferences() {
val p = BrightnessPolicy()
for ((raw, expected) in listOf(0 to 20, 2 to 26, 15 to 46, 50 to 100, 500 to 100)) {
val b = report(0)
b[6] = raw.toByte(); b[7] = (raw shr 8).toByte()
p.resetSamples(); p.sample(b, 1000)
assertEquals(expected, p.target, "raw ALS=$raw")
}
}
@Test fun curveUsesConfiguredBoundsAndLogInterpolation() {
val p = BrightnessPolicy()
p.configure(true, 50, 10, 90, "0:0,99:100", 280)
p.sample(report(9), 1000)
assertEquals(50, p.target) // log(10) / log(100) = 1/2
p.resetSamples(); p.sample(report(0), 2000); assertEquals(10, p.target)
p.resetSamples(); p.sample(report(10000), 3000); assertEquals(90, p.target)
}
@Test fun onlySuccessfulPassivePollsDriveAuto() {
val p = BrightnessPolicy()
val initial = p.target
for (reason in listOf(0, 1, 3, 4)) assertFalse(p.sample(report(0, reason), 1000))
for (flags in listOf(0, 1, 3, 9, 10)) assertFalse(p.sample(report(0, flags = flags), 1000))
assertFalse(p.sample(byteArrayOf(), 1000))
assertEquals(initial, p.target)
assertTrue(p.sample(report(0), 1000)); assertEquals(20, p.target)
}
@Test fun manualPersistsAcrossSamplesAndModeChangesUseLatestLight() {
val p = BrightnessPolicy()
p.configure(false, 70, 2, 80, "0:0,100:100", 450)
p.sample(report(100), 1000); assertEquals(70, p.target)
p.setMode(true, 50); assertEquals(80, p.target)
p.setMode(false, 0); assertEquals(2, p.target)
assertEquals(450, p.fadeMs)
}
@Test fun brightensFasterThanItDimsAndResetsStaleSamples() {
val up = BrightnessPolicy(); val down = BrightnessPolicy()
for (p in listOf(up, down)) p.configure(true, 50, 2, 100, "0:0,100:100", 280)
up.sample(report(0), 1000); up.sample(report(100), 1500)
down.sample(report(100), 1000); down.sample(report(0), 1500)
assertTrue(up.target - 2 > 100 - down.target)
down.sample(report(0), 20000); assertEquals(2, down.target)
}
@Test fun autoHoldsSmallChangesUntilTheyAccumulateToFivePoints() {
val p = BrightnessPolicy()
p.configure(true, 50, 20, 40, "0:0,1:20,2:25,3:45,4:50,5:100", 280)
var now = 1000L
fun sample(lux: Int, changed: Boolean, target: Int) {
// Space readings beyond the smoothing window to isolate the deadband.
now += 11000
assertEquals(changed, p.sample(report(lux), now), "lux=$lux")
assertEquals(target, p.target, "lux=$lux")
}
sample(0, true, 20)
repeat(5) { sample(1, false, 20) } // Desired 24 stays suppressed.
sample(2, true, 25) // Exact five-point increase is accepted.
sample(3, false, 25) // Desired 29.
sample(4, true, 30)
sample(2, true, 25) // Exact five-point decrease is accepted too.
sample(1, false, 25)
sample(0, true, 20)
}
@Test fun boundsDoNotBypassDeadbandButExplicitChangesDo() {
for ((initial, lux) in listOf(24 to 0, 36 to 5)) {
val p = BrightnessPolicy()
p.configure(false, initial, 20, 40, "0:0,5:100", 280)
p.setMode(true, initial)
assertFalse(p.sample(report(lux), 1000))
assertEquals(initial, p.target)
p.setMode(false, initial + 1)
assertEquals(initial + 1, p.target) // Small manual changes remain exact.
p.setMode(true, initial)
assertEquals(if (lux == 0) 20 else 40, p.target)
}
val p = BrightnessPolicy()
p.sample(report(0), 1000)
p.configure(true, 50, 21, 100, BrightnessPolicy.DEFAULT_CURVE, 280)
assertEquals(21, p.target) // An explicit bounds edit applies immediately.
}
@Test fun invalidCurveDoesNotPartiallyChangeLivePolicy() {
val p = BrightnessPolicy()
for (curve in listOf("", "0:0", "1:0,100:100", "0:0,1:80,2:50,3:100", "0:0,0:100", "0:0,NaN:100", "0:0,1:99")) {
assertFailsWith<IllegalArgumentException> { p.configure(false, 90, 20, 80, curve, 0) }
assertTrue(p.automatic); assertEquals(280, p.fadeMs)
}
p.configure(true, 50, 80, 20, "0:0,100:100", 0)
p.sample(report(0), 1000); assertEquals(80, p.target)
}
}
@@ -0,0 +1,127 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class CaptionEngineCoreTest {
private class Sink : CaptionSegmentSink {
val starts = mutableListOf<Long>()
val utterances = mutableListOf<List<Any>>()
override fun onSpeechStart(startMs: Long) { starts.add(startMs) }
override fun onUtterance(samples: ShortArray, length: Int, startMs: Long, endMs: Long, peakRms: Double) {
utterances.add(listOf(length, startMs, endMs, samples[0].toInt()))
}
}
private fun chunk(amplitude: Int, samples: Int = 800): ShortArray =
ShortArray(samples) { if (it % 2 == 0) amplitude.toShort() else (-amplitude).toShort() }
@Test
fun segmenterUsesPreRollOnsetReleaseAndSilence() {
val sink = Sink()
val segmenter = CaptionSegmenter(sink)
repeat(10) { segmenter.processChunk(chunk(100), 800) } // 500 ms idle, noise floor ~100 -> threshold 220
repeat(10) { segmenter.processChunk(chunk(3000), 800) } // 500 ms speech
assertEquals(listOf(100L), sink.starts) // 500 ms - 400 ms pre-roll
repeat(15) { segmenter.processChunk(chunk(100), 800) } // 750 ms < 800 ms silence: still open
assertTrue(sink.utterances.isEmpty())
segmenter.processChunk(chunk(100), 800) // 800 ms of silence closes it
assertEquals(1, sink.utterances.size)
val (length, startMs, endMs, first) = sink.utterances[0]
assertEquals(100L, startMs)
assertEquals(6400 + 10 * 800 + 16 * 800, length) // pre-roll + speech + trailing silence
assertEquals(startMs as Long + (length as Int) * 1000L / 16000, endMs)
assertEquals(100, first) // the pre-roll audio leads the utterance
assertTrue(segmenter.isInUtterance.not())
}
@Test
fun segmenterDropsTooShortUtterancesAndCapsLength() {
val sink = Sink()
val segmenter = CaptionSegmenter(sink)
segmenter.silenceMs = 100 // clamps to 200
segmenter.processChunk(chunk(10), 800) // seeds the noise floor; becomes the 50 ms pre-roll
segmenter.processChunk(chunk(3000), 800) // onset
repeat(4) { segmenter.processChunk(chunk(0), 800) } // 200 ms silence
assertEquals(1, sink.starts.size)
assertTrue(sink.utterances.isEmpty()) // 300 ms < 350 ms minimum
repeat(400) { segmenter.processChunk(chunk(3000), 800) } // 20 s of speech: capped at 15 s
assertEquals(1, sink.utterances.size)
assertEquals(16000 * 15, sink.utterances[0][0])
segmenter.flush()
assertEquals(2, sink.utterances.size) // the remainder is flushed on stop
}
@Test
fun utteranceDecoderSplitsLongAudioAndEmbedsTenSeconds() {
val calls = mutableListOf<Int>()
val transcriber = object : OfflineTranscriber {
override fun recognize(samples: FloatArray, count: Int): String { calls.add(count); return if (calls.size == 2) ", b" else "a" }
override fun release() {}
}
var embedded = 0
val embedder = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? { embedded = pcm16le.size; return floatArrayOf(1f) }
override fun release() {}
}
val decoder = UtteranceDecoder(transcriber, embedder)
val utterance = ShortArray(16000 * 12) { if (it % 2 == 0) 2000 else -2000 }
assertEquals("a, b", decoder.recognize(utterance, utterance.size))
assertEquals(2, calls.size)
assertTrue(calls[0] <= UtteranceDecoder.DECODE_SEGMENT_MAX_SAMPLES)
assertEquals(utterance.size, calls.sum())
assertNotNull(decoder.embed(utterance, utterance.size))
assertEquals(16000 * 10 * 2, embedded)
assertEquals("", UtteranceDecoder(null, null).recognize(utterance, utterance.size))
assertNull(UtteranceDecoder(null, null).embed(utterance, utterance.size))
}
@Test
fun captionSessionRunsQueueThroughSegmenterAndDecoder() {
val startLatch = Latch(1, testPlatform())
val utteranceLatch = Latch(1, testPlatform())
val events = mutableListOf<String>()
val listener = object : FaceclawCaptionEngineListener {
override fun onUtterance(text: String?, embedding: FloatArray?, startMs: Long, endMs: Long, peakRms: Double) {
events.add("utterance:$text:${embedding?.size}:$startMs"); utteranceLatch.countDown()
}
override fun onSpeechStart(startMs: Long) { events.add("start:$startMs"); startLatch.countDown() }
override fun onStatus(status: String?) { events.add("status:$status") }
}
val host = object : CaptionHost {
override val dispatcher = CallbackDispatcher { it() }
override fun loadTranscriber(modelDir: String): OfflineTranscriber? = if (modelDir == "models") object : OfflineTranscriber {
override fun recognize(samples: FloatArray, count: Int): String = "hi"
override fun release() {}
} else null
override fun loadEmbedder(modelPath: String): SpeakerEmbedder? = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? = floatArrayOf(0.5f, 0.5f)
override fun release() {}
}
}
val session = CaptionSession(host, testPlatform(), "caption-test") { m, e -> error("$m: $e") }
session.setListener(listener)
session.setAsrModelDir("models")
session.setSpeakerModelPath("speaker")
session.setSilenceMs(300)
session.acceptPcm(ByteArray(1600)) // ignored before start
session.start()
val loud = AudioSegmentation.pcm16ToLittleEndian(chunk(3000), 0, 800)
val quiet = AudioSegmentation.pcm16ToLittleEndian(chunk(0), 0, 800)
val idle = AudioSegmentation.pcm16ToLittleEndian(chunk(10), 0, 800)
repeat(2) { session.acceptPcm(idle) } // seeds the noise floor and fills 100 ms of pre-roll
repeat(10) { session.acceptPcm(loud) }
assertTrue(startLatch.await(5000))
repeat(8) { session.acceptPcm(quiet) }
assertTrue(utteranceLatch.await(5000))
session.stop()
session.stop() // idempotent
assertEquals("status:Loading caption model...", events[0])
assertEquals("status:Captions listening...", events[1])
assertEquals("start:0", events[2])
assertEquals("utterance:hi:2:0", events[3])
}
}
@@ -0,0 +1,40 @@
package com.faceclaw.app
import kotlin.test.*
class CompassTest {
private fun hex(text: String) = text.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun receiverPayloadAndAndroidFrameDecodeTheSameCompassSample() {
val payload = hex("080f1000520308e702a2060c434d010302038c0098badcfe")
for (flag in listOf(1, 6)) {
val frame = BleProtocol.framePb(payload, 8, flag, 15).single()
val received = MessageReceiver().receive("R", frame, 0).single()
val shared = assertNotNull(BleProtocol.parseCompassPayload(received.sid, received.flag, received.payload))
val android = assertNotNull(BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame)))
assertEquals(359, shared.headingDegrees)
assertEquals(15, shared.command)
assertEquals(3, shared.magneticAccuracy)
assertEquals(2, shared.magneticAnomalies)
assertEquals(3, shared.orientationSource)
assertEquals(0x8c, shared.diagnosticFlags)
assertEquals(0xfedcba98L, shared.sampleTimeMs)
assertEquals(android.sampleTimeMs, shared.sampleTimeMs)
}
assertNull(BleProtocol.parseCompassPayload(9, 1, payload))
assertNull(BleProtocol.parseCompassPayload(8, 0x20, payload))
assertNull(BleProtocol.parseCompassPayload(8, 1, hex("080f1000520308e802")))
assertNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf()))
for (size in 9 until payload.size) {
val legacy = assertNotNull(BleProtocol.parseCompassPayload(8, 1, payload.copyOf(size)))
assertEquals(359, legacy.headingDegrees)
assertEquals(-1, legacy.diagnosticFlags)
}
for (command in listOf(16, 17)) {
val calibration = assertNotNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf(8, command.toByte(), 16, 0)))
assertEquals(command, calibration.command)
assertEquals(-1, calibration.headingDegrees)
}
}
}
@@ -0,0 +1,54 @@
package com.faceclaw.app
import kotlin.test.*
class DimDitherTest {
@Test fun contextMenuDimHalftonesLevelsThatWouldRoundAway() {
// CONTEXT_MENU_DIM = 0.25: level 1 becomes a 1/0 halftone instead of black or 1.
val (even, odd) = DimDither.tables(64)
assertContentEquals(intArrayOf(0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4), even)
assertContentEquals(intArrayOf(0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4), odd)
}
@Test fun everyFactorGivesMonotonicAdjacentPairsThatKeepVisiblePixels() {
for (factor in 0..256) {
val (even, odd) = DimDither.tables(factor)
assertEquals(0, even[0])
assertEquals(0, odd[0])
for (level in 1..15) {
val halfSteps = even[level] + odd[level]
assertTrue(even[level] - odd[level] in 0..1, "factor=$factor level=$level")
assertTrue(halfSteps in 1..2 * level, "factor=$factor level=$level")
assertTrue(halfSteps >= even[level - 1] + odd[level - 1], "factor=$factor level=$level")
}
}
val (even, odd) = DimDither.tables(256)
assertContentEquals(IntArray(16) { it }, even)
assertContentEquals(IntArray(16) { it }, odd)
}
@Test fun remapUsesTheEvenTableWhereShiftedXPlusYIsEven() {
val even = IntArray(16) { 15 - it }
val odd = IntArray(16) { it / 2 }
val call = DrawProtocol.remapColors(0, 0, 3, 2, even, odd)
assertContentEquals(byteArrayOf(DRAW_OP_REMAP_COLORS.toByte(), 0, 0, 0, 0, 0, 3, 0, 2, 0,
0xfe.toByte(), 0xdc.toByte(), 0xba.toByte(), 0x98.toByte(), 0x76, 0x54, 0x32, 0x10,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77), call)
for (shift in listOf(0, 1)) {
// Rows of 4 pixels: 4, 5, 6, 7 then 8, 9, 10, 11.
val pixels = byteArrayOf(0x45, 0x67, 0x89.toByte(), 0xab.toByte())
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(call)),
DisplayListRenderer.Target(pixels, 4, 2).shifted(shift))
val target = DisplayListRenderer.Target(pixels, 4, 2)
for (y in 0..1) for (x in 0..3) {
val source = 4 + y * 4 + x
val expected = when {
x !in shift until shift + 3 -> source
(x + y) % 2 == 0 -> even[source]
else -> odd[source]
}
assertEquals(expected, target.get(x, y), "shift=$shift x=$x y=$y")
}
}
}
}
@@ -0,0 +1,304 @@
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)
val resources = mutableMapOf(10 to raw, 11 to hex("0802024f"), 12 to font)
val nested = listOf(DrawProtocol.image(11, -1, 0), DrawProtocol.bbox(hex("0c000000"), 2, 1, 0, 1, 1, 10))
resources[20]=DrawProtocol.displayList(nested)
val calls = listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(20)), DrawProtocol.image(10,3,1),
DrawProtocol.call(DRAW_OP_TEXT,hex("0c0007030f0141")), DrawProtocol.lut(8,4,128))
resources[21]=DrawProtocol.displayList(calls)
// Like the C harness, seed composition with the screen: this list has no screen copy.
val screen=hex("123456789abcdef0123456789abcdef0"); val output=screen.copyOf()
val renderer=DisplayListRenderer(resources)
assertEquals(setOf(10,11,12,20,21),renderer.render(21,DisplayListRenderer.Target(screen,8,4),DisplayListRenderer.Target(output,8,4)))
// Shared with the C sanitizer harness: signed clipping, resource target override, font and LUT.
assertContentEquals(hex("81223344755162701122334445544578"),output)
val first=output.copyOf(); screen.copyInto(output); renderer.render(21,DisplayListRenderer.Target(screen,8,4),DisplayListRenderer.Target(output,8,4))
assertContentEquals(first,output)
assertContentEquals(hex("123456789abcdef0123456789abcdef0"),screen)
}
@Test fun rootListsComposeTheScreenCopyAndClearBeforeDepthShifts() {
val screen = ByteArray(640 * 480 / 2) { (0x12 + it * 0x22).toByte() }
val sourceTarget = DisplayListRenderer.Target(screen, 640, 480)
// Without a copy, a root presents only what it draws.
val empty = mapOf(1 to DrawProtocol.displayList(emptyList()))
val composition = ByteArray(screen.size) { 0x55 }
DisplayListRenderer(empty).render(1, sourceTarget, DisplayListRenderer.Target(composition, 640, 480))
assertTrue(composition.all { it == 0x55.toByte() })
for (depth in listOf(-64, -17, 0, 1, 32)) for (right in listOf(false, true)) {
val resources = mapOf(1 to DrawProtocol.displayList(DrawProtocol.screenCopy(640, 480, depth)))
val output = ByteArray(screen.size) { -1 }
val target = DisplayListRenderer.Target(output, 640, 480)
DisplayListRenderer(resources, rightLens = right).render(1, sourceTarget, target)
val shift = DrawProtocol.depthOffset(depth, right)
for (y in listOf(0, 479)) for (x in 0 until 640) {
val sx = x - shift
assertEquals(if (sx in 0 until 640) sourceTarget.get(sx, y) else 0, target.get(x, y), "depth=$depth right=$right x=$x")
}
}
// Clear fills the whole resource target, padding included, and ignores depth.
val raw = DrawProtocol.rawImage(3, 2, hex("1234ab12"))
DisplayListRenderer(mapOf(5 to raw)).execute(DrawProtocol.sequence(listOf(DrawProtocol.clear(7, target = 5))),
DisplayListRenderer.Target(ByteArray(1), 1, 1))
assertContentEquals(DrawProtocol.rawImage(3, 2, hex("77777777")), raw)
val rejected = DrawProtocol.call(DRAW_OP_CLEAR, hex("10"))
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(rejected)), DisplayListRenderer.Target(ByteArray(1), 1, 1)) }
}
@Test fun graphValidationPrecedesMutationAndCopyPreservesOverlap() {
val screen=hex("12345678"); val target=DisplayListRenderer.Target(screen,8,1)
val copy=DrawProtocol.call(DRAW_OP_RECT_COPY,hex("feff0000060001000200"))
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(copy)),target)
assertContentEquals(hex("12123456"),screen)
// Revision 29: an animated source row scrolls a raw strip; source bounds are checked each frame.
val strip=mapOf(9 to DrawProtocol.rawImage(2,4,hex("11223344")))
val scroll=DrawProtocol.rectCopy(9,DrawValue.Integer(0),DrawValue.animate(0,2,100),2,2,DrawValue.Integer(0),DrawValue.Integer(0))
for ((elapsed,rows) in listOf(0L to "1122",100L to "3344",500L to "3344")) {
val window=DisplayListRenderer.Target(ByteArray(2),2,2)
val renderer=DisplayListRenderer(strip)
renderer.execute(DrawProtocol.sequence(listOf(scroll)),window,elapsedMs=elapsed)
assertContentEquals(hex(rows),window.bytes); assertEquals(elapsed<100,renderer.animationPending)
}
val past=DrawProtocol.rectCopy(9,0,3,2,2,0,0)
assertFails { DisplayListRenderer(strip).execute(DrawProtocol.sequence(listOf(past)),DisplayListRenderer.Target(ByteArray(2),2,2)) }
val valid=DrawProtocol.bbox(hex("ffffffff"),4,0,0,8,1)
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(valid,byteArrayOf(99,0))),target) }
assertContentEquals(hex("12123456"),screen)
val cyclic=mapOf(1 to DrawProtocol.displayList(listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(2)))),
2 to DrawProtocol.displayList(listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(1)))))
assertFails { DisplayListRenderer(cyclic).render(1,target,target) }
}
@Test fun roundedRectsAndNestedOddNegativeDepthMatchFirmwareOnBothLenses() {
val resources = mapOf(
40 to hex("0404000200f00f0ff0"),
41 to hex("0202000d0008020201010c0008000300040a0800040202280005041f"),
42 to hex("02010005000702fd2900"))
val screen = hex("012345601234560112345601234560122345601234560123345601234560123445601234560123455601234f60123456601234560123456001234560123456011234560123456012234560123456012334560123456012344560123456012345")
val expected = listOf("01234560123456011aaaaaaaaaa56012aa45644444aa0123a4564444456a1234a564f44f564a2345a6444fff644a3456a4444456444a4560aa44456444aa56011aaaaaaaaaa56012234560123456012334560123456012344560123456012345", "012345601234560112aaaaaaaaaa60122aa56444445aa1233a5644444564a2344a644f44f644a3455a4444ff6444a4566a4444564444a5600aa44564444aa60112aaaaaaaaaa6012234560123456012334560123456012344560123456012345")
for (right in listOf(false, true)) {
val output = screen.copyOf() // the shared vector's list has no screen copy
DisplayListRenderer(resources, rightLens = right).render(42, DisplayListRenderer.Target(screen,16,12), DisplayListRenderer.Target(output,16,12))
assertContentEquals(hex(expected[if(right) 1 else 0]), output)
}
for (depth in -128..127) {
assertEquals(kotlin.math.floor(depth / 2.0).toInt(), DrawProtocol.depthOffset(depth, false))
assertEquals(-kotlin.math.floor((depth + 1) / 2.0).toInt(), DrawProtocol.depthOffset(depth, true))
}
}
@Test fun roundedFillPreservesBrighterTextAndDepthClipsWithoutNibbleDamage() {
val pixels = ByteArray(32) { 0x11 }; pixels[13] = 0xf1.toByte()
val target = DisplayListRenderer.Target(pixels,8,8)
val fill = DrawProtocol.roundedRect(-1,0,8,8,2,6,16,2)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(fill)),target)
assertEquals(15,target.get(2,3)); assertEquals(6,target.get(3,3)); assertEquals(1,target.get(0,0))
val bbox = DrawProtocol.call(DRAW_OP_BOUNDING_BOX,hex("00000002010f10"),depth=-1)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(bbox)),target)
assertEquals(15,target.get(0,0));assertEquals(1,target.get(7,0))
val before=pixels.copyOf()
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(byteArrayOf(8,2))),target) }
assertContentEquals(before,pixels)
}
@Test fun selectedMenuResourcesStayOutOfScreenAndReplayAtDepthTwo() {
val planner=ScenePlanner(ResourceCacheState()); val left=Glasses(); val right=Glasses(true)
val app=ByteArray(640*480/2) { 0x11 }
fun row(x:Int) = MenuSelection(x,8,8,4,1,4,9,2,hex("00ff0000000000000000000000000000"))
val scene=ShellScene(emptyList(),listOf(row(10)))
val first=planner.plan(app,640,480,null,scene,1);left.apply(first.commands);right.apply(first.commands)
assertContentEquals(app,left.screen);assertContentEquals(app,right.screen)
val l=DisplayListRenderer.Target(left.composition,640,480);val r=DisplayListRenderer.Target(right.composition,640,480)
assertEquals(15,l.get(13,8));assertEquals(15,r.get(11,8));assertEquals(1,l.get(9,8))
val moved=planner.plan(app,640,480,null,ShellScene(emptyList(),listOf(row(20))),1)
assertFalse(moved.commands.any { it[0].toInt()==26 || it[0].toInt()==29 })
left.apply(moved.commands);assertContentEquals(app,left.screen)
left.apply(planner.plan(app,640,480,null,ShellScene.EMPTY,1).commands)
assertContentEquals(app,left.composition)
}
@Test fun contextMenusAndSidebarDepthReplayOnBothLensesWithoutBakedCopies() {
fun record(kind: Int, x: Int, y: Int, w: Int, h: Int, depth: Int, gray: ByteArray): MenuSelection {
val bytes = DrawProtocol.word(x) + DrawProtocol.word(y) + DrawProtocol.word(w) + DrawProtocol.word(h) +
DrawProtocol.word(0) + byteArrayOf(16, 48, depth.toByte()) + DrawProtocol.word(0) + gray
return MenuSelection.read(ArrayByteReader(bytes), kind)
}
val menu = record(5, 10, 10, 8, 8, 4, ByteArray(64) { if (it == 0) 0 else 1 })
val selected = record(3, 12, 12, 4, 2, 6, ByteArray(8) { -1 })
val icon = record(4, 30, 10, 2, 2, -2, ByteArray(4) { -1 })
val app = ByteArray(640 * 480 / 2) { 0x66 }
val planner = ScenePlanner(ResourceCacheState())
val scene = ShellScene(emptyList(), listOf(menu, selected, icon))
val plan = planner.plan(app, 640, 480, null, scene, 1)
for (right in listOf(false, true)) {
val glasses = Glasses(right); glasses.apply(plan.commands)
assertContentEquals(app, glasses.screen)
val output = DisplayListRenderer.Target(glasses.composition,640,480)
val shift = if (right) -2 else 2
assertEquals(6, output.get(10 + shift,10)) // transparent corner
assertEquals(0, output.get(11 + shift,10)) // opaque black stays opaque
assertEquals(15, output.get(12 + (if (right) -3 else 3),12))
assertEquals(15, output.get(30 + (if (right) 1 else -1),10))
assertEquals(6, output.get(if (right) 30 else 31,10)) // no unshifted icon
val preview = scene.preview(ByteArray(640*480) { 96 },640,480,right)
assertContentEquals(glasses.composition, BmpUtil.pack4bppFromGray8(preview,640,480))
}
// The shell uses an independently owned surface with its own depth.
val shell = ShellScene(listOf(ShellScene.Layer(1,10,10,8,8,256,ByteArray(32),listOf(selected),4)))
val left = shell.preview(ByteArray(640*480) { 96 },640,480)
val right = shell.preview(ByteArray(640*480) { 96 },640,480,true)
assertEquals(0,left[10*640+12].toInt()); assertEquals(96,left[10*640+10].toInt())
assertEquals(0,right[10*640+8].toInt()); assertEquals(96,right[10*640+16].toInt())
}
private class Glasses(val right: Boolean = false) {
val resources=mutableMapOf<Int,ByteArray>(); val screen=ByteArray(640*480/2);val composition=ByteArray(screen.size)
var root=65535
fun apply(commands: List<ByteArray>) {
for(b in commands) when(b[0].toInt()) {
21 -> { var p=3;repeat(DrawProtocol.u16(b,1)) {
val id=DrawProtocol.u16(b,p); val total=DrawProtocol.u16(b,p+2) or (DrawProtocol.u16(b,p+4) shl 16)
val offset=DrawProtocol.u16(b,p+6);val n=DrawProtocol.u16(b,p+8)
b.copyInto(resources.getOrPut(id){ByteArray(total)},offset,p+10,p+10+n);p+=10+n
} }
22 -> repeat(DrawProtocol.u16(b,1)) { resources.remove(DrawProtocol.u16(b,3+it*2)) }
29 -> repeat(DrawProtocol.u16(b,1)) { val p=3+it*6;resources.getOrPut(DrawProtocol.u16(b,p)) { DrawProtocol.rawImage(DrawProtocol.u16(b,p+2),DrawProtocol.u16(b,p+4)) } }
26 -> DisplayListRenderer(resources, rightLens = right).execute(b.copyOfRange(1,b.size),DisplayListRenderer.Target(screen,640,480))
27 -> root=DrawProtocol.u16(b,1)
28 -> DisplayListRenderer(resources, rightLens = right).render(root,DisplayListRenderer.Target(screen,640,480),DisplayListRenderer.Target(composition,640,480))
else -> error("legacy command ${b[0]}")
}
}
}
@Test fun persistentShellUpdatesDoNotPolluteScreenAndClosingRevealsCurrentApp() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){0x99.toByte()}
val overlay=ShellScene(listOf(ShellScene.Layer(1,0,0,3,3,128,hex("fff0fff0fff0"))))
val first=planner.plan(app,640,480,null,overlay,1);glasses.apply(first.commands)
assertContentEquals(app,glasses.screen);assertEquals(255,glasses.composition[0].toInt() and 255)
// Half of level 9 is a 5/4 checkerboard; x=200 on row 0 is an even pixel.
assertEquals(0x54,glasses.composition[100].toInt() and 255)
val changed=ShellScene(listOf(ShellScene.Layer(1,0,0,3,3,128,hex("111011101110"))))
val repaint=planner.plan(app,640,480,null,changed,1)
assertFalse(repaint.commands.any { it[0].toInt() in listOf(21,22,29) })
glasses.apply(repaint.commands);assertContentEquals(app,glasses.screen)
val newer=app.copyOf();newer[0]=0x22
glasses.apply(planner.plan(newer,640,480,null,changed,1).commands)
glasses.apply(planner.plan(newer,640,480,null,ShellScene.EMPTY,1).commands)
assertContentEquals(newer,glasses.composition)
cache.reset();val reconnect=planner.plan(newer,640,480,null,changed,1)
assertTrue(reconnect.commands.any { it[0].toInt()==29 });glasses.apply(reconnect.commands)
assertContentEquals(newer,glasses.screen)
}
@Test fun fullScreenSurfaceDepthShiftsThePresentedScreenPerLens() {
val c = SurfaceCompositor()
c.configureScreen(640, 480)
c.configureSurface("app", 0, 0, 640, 480, 0, 0)
c.configureSurface("glance", 0, 0, 640, 480, 900, 0)
val board = ByteArray(640 * 480) { if (it % 640 in 100 until 110) 255.toByte() else 0 }
c.submitSurface("glance", ArrayByteReader(board), 0, 0, 640, 480, "board")
c.setSurfaceDepth("glance", 32)
assertEquals(32, c.composite().shellScene.screenDepth)
// Only the topmost visible surface counts, and only when it opaquely covers the screen.
c.configureSurface("partial", 0, 0, 10, 10, 950, 0)
assertEquals(0, c.composite().shellScene.screenDepth)
c.setSurfaceVisible("partial", false)
c.setSurfaceVisible("glance", false)
assertEquals(0, c.composite().shellScene.screenDepth)
c.setSurfaceVisible("glance", true)
val composite = c.composite()
val screen = BmpUtil.pack4bppFromGray8(composite.screenGray, 640, 480)
for (right in listOf(false, true)) {
val glasses = Glasses(right)
glasses.composition.fill(-1) // stale pixels from an earlier frame
glasses.apply(ScenePlanner(ResourceCacheState()).plan(screen, 640, 480, null, composite.shellScene, 1).commands)
assertContentEquals(screen, glasses.screen)
val output = DisplayListRenderer.Target(glasses.composition, 640, 480)
val shift = if (right) -16 else 16
assertEquals(15, output.get(100 + shift, 0)); assertEquals(0, output.get(99 + shift, 0))
assertEquals(15, output.get(109 + shift, 479)); assertEquals(0, output.get(110 + shift, 479))
assertEquals(0, output.get(if (right) 639 else 0, 240)) // cleared, not stale
}
}
@Test fun noisyFramesRemainBoundedAndResourceBudgetIs192KiB() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){(it*37).toByte()}
val plan=planner.plan(app,640,480,null,ShellScene.EMPTY,1)
assertTrue(plan.commands.all { it.size<=65535 });glasses.apply(plan.commands)
assertContentEquals(app,glasses.screen);assertContentEquals(app,glasses.composition)
assertEquals(196608,ResourceCacheState.CACHE_SIZE)
}
/** Revision 35. Same calls and expectations as ClipTest in g2flash/tests/test_display_list.py. */
@Test fun clipRectsNarrowEveryOpNestThroughListsAndMoveWithDepth() {
val font = ByteArray(198); font[0] = 1; font[1 + 33 * 2] = 193.toByte(); hex("000202ffff").copyInto(font, 193)
val resources = mutableMapOf(1 to hex("000404ffffffffffffffff"), 3 to font,
5 to hex("0202000700" + "0400010000000f" + "0f00" + "04040900000002000200010008000f"),
6 to hex("00040200000000"), 7 to hex("0201000e00080106000000040002000000" + "0f10"))
fun draw(call: String, right: Boolean = false): DisplayListRenderer.Target {
val target = DisplayListRenderer.Target(ByteArray(64) { 0x11 }, 16, 8)
DisplayListRenderer(resources, rightLens = right).execute(DrawProtocol.sequence(listOf(hex(call))), target)
return target
}
fun expect(target: DisplayListRenderer.Target, color: Int, inside: (Int, Int) -> Boolean) {
for (y in 0 until 8) for (x in 0 until 16) assertEquals(if (inside(x, y)) color else 1, target.get(x, y), "($x, $y)")
}
expect(draw("040403000200" + "0a000a00" + "0100" + "0201" + "0f"), 15) { x, y -> x in 3..5 && y in 2..4 }
expect(draw("0400" + "0100" + "ff020105" + "00" + "0f"), 15) { x, y -> x in 5..8 && y < 4 }
expect(draw("0504" + "0100000002000100" + "0300" + "0000" + "0f" + "02" + "4141"), 15) { x, y -> y == 0 && x in 1..2 }
expect(draw("0804" + "0400040004000200" + "0000" + "1000" + "0800" + "0000" + "0f10"), 15) { x, y -> x in 4..7 && y in 4..5 }
expect(draw("0904" + "fefffeff04000400" + "09"), 9) { x, y -> x < 2 && y < 2 }
expect(draw("0904" + "0300050003000100" + "09"), 9) { x, y -> y == 5 && x in 3..5 }
expect(draw("0604" + "0100010001000600" + "0000000010000800" + "77".repeat(16)), 7) { x, y -> x == 1 && y in 1..6 }
expect(draw("0204" + "0200020001000100" + "0100" + "0000" + "04000400" + "0000"), 15) { x, y -> x == 2 && y == 2 }
expect(draw("0104" + "0100010002000100" + "00" + "000001" + "01" + "8f"), 15) { x, y -> y == 1 && x in 1..2 }
expect(draw("0704" + "000000000a000300" + "0500"), 15) { x, y -> (x < 4 && y < 3) || (x == 9 && y < 2) }
val deep = "0806" + "02" + "0000000004000400" + "0000" + "1000" + "0800" + "0000" + "0f10"
expect(draw(deep), 15) { x, y -> x in 1..4 && y < 4 }
expect(draw(deep, right = true), 15) { x, y -> x < 3 && y < 4 }
// A target override starts unclipped: the whole resource fills, the screen stays.
expect(draw("0704" + "0000000001000100" + "0700"), 15) { _, _ -> false }
assertContentEquals(hex("000402ffffffff"), resources.getValue(6))
expect(draw("0804" + "0400040000000000" + "0000" + "1000" + "0800" + "0000" + "0f10"), 15) { _, _ -> false }
// Unknown flag bits, a truncated clip header, and the old s16 image layout all reject.
for (bad in listOf("090800", "0904000000000100", "04000100020001000f")) assertFails(bad) { draw(bad) }
}
}
@@ -0,0 +1,113 @@
package com.faceclaw.app
import kotlin.test.*
class DrawExpressionTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun evaluate(code: ByteArray, elapsed: Long = 0): Pair<Int, Boolean> {
val frame = DrawEvaluation(elapsed)
return DrawExpression.evaluate(DrawReader(code), frame) to frame.animationPending
}
@Test fun integerWidthsSignExtensionAndReservedPrefixes() {
val signed = mapOf(
0 to "00", 63 to "3f", -64 to "40", -1 to "7f", 64 to "8040", -65 to "bfbf",
8191 to "9fff", -8192 to "a000", 8192 to "c02000", -8193 to "dfdfff",
1048575 to "cfffff", -1048576 to "d00000", 1048576 to "e0100000",
-1048577 to "efefffff", 134217727 to "e7ffffff", -134217728 to "e8000000",
134217728 to "f008000000", Int.MAX_VALUE to "f07fffffff", Int.MIN_VALUE to "f080000000",
)
for ((number, bytes) in signed) {
assertContentEquals(hex(bytes), ExtendedVarint.signed(number))
assertEquals(number, ExtendedVarint.read(DrawReader(hex(bytes)), true))
}
for (value in listOf(0u, 127u, 128u, 16383u, 16384u, 2097151u, 2097152u, 268435455u, 268435456u, UInt.MAX_VALUE)) {
val bytes = ExtendedVarint.unsigned(value)
assertEquals(value, ExtendedVarint.read(DrawReader(bytes), false).toUInt())
for (n in 0 until bytes.size) assertFails { ExtendedVarint.read(DrawReader(bytes.copyOf(n)), false) }
}
for (prefix in 0xf1..0xff) assertFails { ExtendedVarint.read(DrawReader(byteArrayOf(prefix.toByte())), true) }
assertEquals(-1, ExtendedVarint.read(DrawReader(hex("bfff")), true)) // valid non-minimal form
assertFails { ExtendedVarint.evaluate(DrawReader(hex("ff05")), DrawEvaluation(0)) }
}
@Test fun arithmeticTypesStackErrorsAndTimeTracking() {
val vectors = listOf(
"0107010510" to 12, "0107010511" to 2, "0107010512" to 35,
"0179010213" to -3, "0179010214" to -1, "017915" to 7,
"0107010516" to 5, "0107010517" to 7, "01010109" to 9,
"01040310" to 8, "010401070504" to 7,
"010430010230202431" to -6,
"020000c03f02000000402231" to 3,
"01003001806430020000003f4031" to 50,
"01f07fffffff010110" to Int.MIN_VALUE,
"01f080000000017f13" to Int.MIN_VALUE,
"01f080000000017f14" to 0,
)
for ((code, expected) in vectors) assertEquals(expected to false, evaluate(hex(code)), code)
for (bad in listOf("", "10", "0101010013", "010130010110", "020000807f", "ff", "0180", "01013210")) {
assertEquals(0 to false, evaluate(hex(bad)), bad)
}
assertEquals(0 to false, evaluate(ByteArray(66) { if (it % 2 == 0) 1 else 0 })) // stack overflow
assertEquals(0 to false, evaluate(ByteArray(1025)))
for (op in DrawExpression.SMOOTHSTEP..DrawExpression.EASE_IN_OUT_CUBIC) {
assertEquals(0 to false, evaluate(hex("0200000000") + byteArrayOf(op.toByte(), 49)))
assertEquals(1 to false, evaluate(hex("020000803f") + byteArrayOf(op.toByte(), 49)))
}
assertEquals(499 to true, evaluate(hex("0181f432"), 499))
assertEquals(500 to false, evaluate(hex("0181f432"), 500))
assertEquals(500 to false, evaluate(hex("0181f432"), 900))
assertEquals(0 to false, evaluate(hex("0181f432ff"), 250)) // errors discard pending time
}
@Test fun smoothstepCoordinatesMatchFirmwareAndSurvivePresentTimeReset() {
val value = DrawValue.animate(10, 110, 500) as DrawValue.Expression
val code = "010a3001806e300181f432010010300181f43023414031"
assertContentEquals(hex(code), value.program)
for ((time, expected) in listOf(0L to 10, 125L to 25, 250L to 60, 375L to 94, 500L to 110, 900L to 110)) {
assertEquals(expected to (time < 500), evaluate(value.program, time))
}
val continued = DrawValue.animate(10, 110, 500, elapsedMs = 250) as DrawValue.Expression
assertEquals(60 to true, evaluate(continued.program, 0))
assertEquals(110 to false, evaluate(continued.program, 250))
}
@Test fun playerSchedulesOnlyUnfinishedFramesAndCancelsStaleCallbacks() {
val call = DrawProtocol.roundedRect(DrawValue.Integer(0), DrawValue.animate(0, 4, 300), 2, 2, 0, 15)
val renderer = DisplayListRenderer(mapOf(1 to DrawProtocol.displayList(DrawProtocol.screenCopy(4, 8) + call)))
val screen = DisplayListRenderer.Target(ByteArray(16), 4, 8)
val output = DisplayListRenderer.Target(ByteArray(16), 4, 8)
var now = 1000L
val queued = mutableListOf<() -> Unit>()
var cancelled = 0
var displayed = 0
val player = DisplayListPlayer(renderer, screen, output, { now }, { delay, callback ->
assertEquals(45, delay)
queued.add(callback);
{ cancelled++ }
}, { displayed++ })
player.present(1)
assertEquals(15, output.get(0, 0))
val first = queued.removeAt(0)
now += 150
first()
assertEquals(15, output.get(0, 2))
assertEquals(0, output.get(0, 0))
val stale = queued.removeAt(0)
player.present(1)
assertEquals(15, output.get(0, 0))
stale()
assertEquals(3, displayed)
now += 300
queued.removeAt(0)()
assertEquals(15, output.get(0, 4))
assertFalse(renderer.animationPending)
assertTrue(queued.isEmpty())
player.present(1)
val stopped = queued.removeAt(0)
player.stop()
stopped()
assertEquals(5, displayed)
assertTrue(cancelled >= 2)
}
}
@@ -0,0 +1,139 @@
package com.faceclaw.app
import kotlin.test.*
class DrawWireTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test fun encodersUseRevision35CoordinatesAndPreserveOtherWireBytes() {
// Literal vectors pin the firmware grammar independently of the reader.
val calls = listOf(
DrawProtocol.image(0x1234, -32768, 32767, 0x1f, target = 511, depth = -128) to
"0403ff01803412df8000c07fff1f",
DrawProtocol.rectCopy(DrawProtocol.CURRENT, 1, 2, 3, 4, -5, -6) to
"0200feff0102030004007b7a",
DrawProtocol.stockText(-1, 2, 15, hex("41c3a9")) to "0300ffff02000f0341c3a9",
DrawProtocol.text(511, -2, 3, 31, hex("01417f")) to "0500ff017e031f0301417f",
DrawProtocol.playList(511, depth = 127) to "07027fff01",
DrawProtocol.roundedRect(-1, 2, 640, 480, 65535, 15, 16) to
"08007f028002e001ffff0f10",
DrawProtocol.lut(640, 480, 256) to "0600000000008002e0010123456789abcdef0123456789abcdef",
DrawProtocol.bbox(hex("ffffffffffffffff"), 4, 0, 0, 8, 2) to "010000000002010f10",
DrawProtocol.bbox(hex("0f"), 1, 1, 0, 1, 1) to "01000101000000010001001f",
DrawProtocol.clear(15, target = 511) to "0901ff010f",
// Revision 35: the clip rect follows target and depth.
DrawProtocol.clear(3, target = 511, clip = DrawClip(-1, 2, 3, 4)) to "0905ff01ffff02000300040003",
DrawProtocol.image(7, 1, 2, depth = 2, clip = DrawClip(0, 0, 640, 480)) to "040602000000008002e001070001020f",
)
for ((call, expected) in calls) assertContentEquals(hex(expected), call)
assertContentEquals(hex("0100050007027fff01"), DrawProtocol.sequence(listOf(calls[4].first)))
assertContentEquals(hex("1a0100050007027fff01"), DrawProtocol.message(listOf(calls[4].first)))
assertContentEquals(hex("020100050007027fff01"), DrawProtocol.displayList(listOf(calls[4].first)))
assertContentEquals(hex("1bffff"), DrawProtocol.root(DrawProtocol.SCREEN))
val flat = DrawProtocol.screenCopy(640, 352)
assertEquals(1, flat.size)
assertContentEquals(hex("0200ffff0000800260010000"), flat[0])
val shifted = DrawProtocol.screenCopy(640, 352, -32)
assertEquals(2, shifted.size)
assertContentEquals(hex("090000"), shifted[0])
assertContentEquals(hex("0202e0ffff0000800260010000"), shifted[1])
}
@Test fun optimizerFieldsAreReencodedAndOpaqueBytesArePreserved() {
val records = listOf(
"1300020080ff7f1f" to "04000002df8000c07fff1f",
"14ff01ffff02000f0341017f" to "0500ff017f020f0341017f",
"0fffff02001f0341c3a9" to "0300ffff02001f0341c3a9",
"030001020134120f10" to "010000000102010f10",
"060f10" to "01000100000000080002000f10",
"090100020003000400fbfffaff" to "0200feff0102030004007b7a",
)
for ((record, expected) in records) {
val calls = DrawProtocol.fromOptimized(hex(record), 8, 2)
assertEquals(1, calls.size)
assertContentEquals(hex(expected), calls.single(), record)
}
val nested = hex("0802") + records.take(2).fold(byteArrayOf()) { bytes, (record, _) ->
val payload = hex(record)
bytes + DrawProtocol.word(payload.size) + payload
}
val calls = DrawProtocol.fromOptimized(nested)
assertEquals(2, calls.size)
for (i in calls.indices) assertContentEquals(hex(records[i].second), calls[i])
assertFails { DrawProtocol.fromOptimized(hex("1300020080ff7f")) }
assertFails { DrawProtocol.fromOptimized(hex("1300020080ff7f1f00")) }
assertFails { DrawProtocol.fromOptimized(hex("0fffff02001f0441c3a9")) }
}
@Test fun everyTruncatedOrOverlongCallIsRejectedBeforeMutation() {
val font = ByteArray(197)
font[0] = 1
font[67] = 193.toByte() // Glyph A.
hex("0801011f").copyInto(font, 193)
val resources = mapOf(
1 to hex("0401000100f0"),
2 to font,
3 to DrawProtocol.displayList(emptyList()),
)
val renderer = DisplayListRenderer(resources, builtin = { _, _ ->
DisplayListRenderer.BuiltinGlyph(hex("0801011f"), 1)
})
val calls = listOf(
DrawProtocol.image(1, 0, 0, target = 1, depth = -1),
DrawProtocol.rectCopy(DrawProtocol.CURRENT, 0, 0, 2, 2, 1, 1),
DrawProtocol.stockText(0, 0, 15, hex("41")),
DrawProtocol.text(2, 0, 0, 15, hex("41")),
DrawProtocol.playList(3),
DrawProtocol.roundedRect(0, 0, 4, 4, 1, 15),
DrawProtocol.lut(8, 4, 128),
DrawProtocol.bbox(ByteArray(16) { -1 }, 4, 0, 0, 8, 4),
)
val screen = ByteArray(16) { 0x12 }
val target = DisplayListRenderer.Target(screen, 8, 4)
val valid = DrawProtocol.roundedRect(0, 0, 4, 4, 0, 15)
for (call in calls) {
// Establish that each fixture is valid before testing malformed forms.
renderer.execute(DrawProtocol.sequence(listOf(call)), target)
screen.fill(0x12)
val savedResources = resources.mapValues { it.value.copyOf() }
val malformed = (0 until call.size).map { call.copyOf(it) } + listOf(call + byteArrayOf(0))
for (bad in malformed) {
assertFails { renderer.execute(DrawProtocol.sequence(listOf(valid, bad, valid)), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
for ((id, bytes) in savedResources) assertContentEquals(bytes, resources[id])
}
}
val sequence = DrawProtocol.sequence(listOf(valid))
for (length in 0 until sequence.size) {
assertFails { renderer.execute(sequence.copyOf(length), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
}
assertFails { renderer.execute(sequence + byteArrayOf(0), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
}
@Test fun batchesRespectEncodedLengthsAndCallBudget() {
val call = DrawProtocol.playList(511)
val messages = DrawProtocol.messages(List(3) { call }, maxBytes = 15)
assertEquals(listOf(15, 9), messages.map { it.size })
assertContentEquals(hex("1a020004000700ff0104000700ff01"), messages[0])
assertFails { DrawProtocol.messages(listOf(call), maxBytes = 8) }
val many = DrawProtocol.messages(List(4097) { call })
assertEquals(listOf(4096, 1), many.map { DrawProtocol.u16(it, 1) })
assertTrue(DrawProtocol.messages(emptyList()).isEmpty())
}
@Test fun resourceReaderViewsUseRelativeOffsetsAndCannotEscapeTheirBounds() {
val reader = ArrayByteReader(hex("ff123456ee"), 1, 4)
assertEquals(0x12.toByte(), reader.get(0))
assertEquals(0x3412.toShort(), reader.getShort())
assertEquals(1, reader.remaining())
assertFails { reader.get(ByteArray(2)) }
assertEquals(0x56.toByte(), reader.get())
assertEquals(0, reader.remaining())
assertFails { reader.get() }
assertFails { reader.get(3) }
assertFails { reader.get(-1) }
assertFails { ArrayByteReader(byteArrayOf(1), 1, 2) }
}
}
@@ -0,0 +1,47 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class EvenHubAssetServerTest {
@Test
fun resolvesPathsWithIndexDefaultAndEscapeChecks() {
assertEquals("index.html", EvenHubAssetServer.resolve(null)!!.relativePath)
assertEquals("index.html", EvenHubAssetServer.resolve("")!!.relativePath)
assertEquals("index.html", EvenHubAssetServer.resolve("/")!!.relativePath)
assertEquals("assets/app.js", EvenHubAssetServer.resolve("/assets/app.js")!!.relativePath)
assertEquals("assets/app.js", EvenHubAssetServer.resolve("/assets/./x/../app.js")!!.relativePath)
assertNull(EvenHubAssetServer.resolve("/../secret"))
assertNull(EvenHubAssetServer.resolve("/a/../../secret"))
assertNull(EvenHubAssetServer.resolve("/.."))
assertTrue(EvenHubAssetServer.resolve("/index.html")!!.isHtml)
assertTrue(EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/x/index.html"))
assertTrue(EvenHubAssetServer.isInsideRoot("/apps/x/", "/apps/x/a/b"))
assertEquals(false, EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/xy/index.html"))
assertEquals(false, EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/index.html"))
}
@Test
fun mimeTableCoversBothPlatformsTables() {
assertEquals("text/html", EvenHubAssetServer.mimeTypeFor("Index.HTM"))
assertEquals("text/javascript", EvenHubAssetServer.mimeTypeFor("bundle.mjs"))
assertEquals("application/wasm", EvenHubAssetServer.mimeTypeFor("core.wasm"))
assertEquals("font/woff2", EvenHubAssetServer.mimeTypeFor("a.woff2"))
assertEquals("image/svg+xml", EvenHubAssetServer.mimeTypeFor("icon.svg"))
assertEquals("text/plain", EvenHubAssetServer.mimeTypeFor("bundle.js.map"))
assertEquals("application/octet-stream", EvenHubAssetServer.mimeTypeFor("blob"))
assertEquals("application/octet-stream", EvenHubAssetServer.mimeTypeFor("weird.xyz"))
}
@Test
fun injectsShimAfterHeadOrAtStart() {
assertEquals(
"<!doctype html><HEAD lang=\"x\"><script>S</script><title>t</title></HEAD>",
EvenHubAssetServer.injectIntoHtml("<!doctype html><HEAD lang=\"x\"><title>t</title></HEAD>", "S"),
)
assertEquals("<script>S</script><body>x</body>", EvenHubAssetServer.injectIntoHtml("<body>x</body>", "S"))
assertEquals("<script>S</script><head", EvenHubAssetServer.injectIntoHtml("<head", "S"), "unterminated head tag")
}
}
@@ -0,0 +1,118 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class FirmwareImageTest {
private fun putU32(buf: ByteArray, offset: Int, value: Long) {
for (i in 0 until 4) buf[offset + i] = ((value ushr (8 * i)) and 0xff).toByte()
}
private class Component(val name: String, val payload: ByteArray)
/** Builds a checksum-fixed container; [tamper] runs before the CRCs are recorded. */
private fun container(components: List<Component>, tamper: (ByteArray) -> Unit = {}): ByteArray {
val count = components.size
val toc = FirmwareImage.HEADER_SIZE + count * FirmwareImage.TOC_ENTRY_SIZE
var offset = toc
val offsets = components.map { c -> offset.also { offset += FirmwareImage.SUBHEADER_SIZE + c.payload.size } }
val img = ByteArray(offset)
putU32(img, 8, count.toLong())
components.forEachIndexed { i, c ->
val off = offsets[i]
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 4, off.toLong())
putU32(img, off + 8, c.payload.size.toLong())
c.name.encodeToByteArray().copyInto(img, off + FirmwareImage.NAME_OFFSET)
c.payload.copyInto(img, off + FirmwareImage.SUBHEADER_SIZE)
}
tamper(img)
components.forEachIndexed { i, c ->
val off = offsets[i]
val crc = FirmwareImage.crc32cUnsigned(img, off + FirmwareImage.SUBHEADER_SIZE, c.payload.size)
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 12, crc)
putU32(img, off + 12, crc)
}
return img
}
private fun mainApp(size: Int): ByteArray {
val payload = ByteArray(size) { (it * 7).toByte() }
putU32(payload, 0, size.toLong())
putU32(payload, 0x14, FirmwareImage.APP_LOAD_ADDR)
return payload
}
private fun validComponents(): List<Component> =
listOf(
Component("ota/bootloader.bin", ByteArray(300) { it.toByte() }),
Component("ota/a.bin", ByteArray(64) { 1 }),
Component("ota/b.bin", ByteArray(128) { 2 }),
Component("ota/c.bin", ByteArray(32) { 3 }),
Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(600)),
)
@Test
fun crc32cMatchesKnownVector() {
// Castagnoli polynomial, MSB-first, init 0, no reflection or final xor (g2flash.py
// crc32c_msb); vectors from an independent Python implementation of that definition.
assertEquals(0xc052a8c8L, FirmwareImage.crc32cUnsigned("123456789".encodeToByteArray()))
assertEquals(0xd7b91914L, FirmwareImage.crc32cUnsigned(ByteArray(256) { it.toByte() }))
assertEquals(0L, FirmwareImage.crc32cUnsigned(ByteArray(0)))
assertEquals(FirmwareImage.crc32cUnsigned("23456789".encodeToByteArray()), FirmwareImage.crc32cUnsigned("123456789".encodeToByteArray(), 1, 8))
}
@Test
fun validImageParsesAllComponents() {
val segs = FirmwareImage.validate(container(validComponents()))
assertEquals(5, segs.size)
assertEquals(listOf(300, 64, 128, 32, 600), segs.map { it.ps })
assertEquals(FirmwareImage.REQUIRED_SEGMENT, segs[4].name)
assertTrue(segs.zipWithNext().all { (a, b) -> a.end <= b.off })
}
@Test
fun rejectsStaleCrc() {
val img = container(validComponents())
img[img.size - 1] = (img[img.size - 1] + 1).toByte()
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(img) }.message!!.contains("CRC32C"))
}
@Test
fun rejectsOverlappingComponents() {
val img = container(validComponents()) { buf ->
// Point component 1's TOC entry at component 0, so both claim the same bytes.
val off0 = FirmwareImage.readU32(buf, FirmwareImage.HEADER_SIZE + 4)
putU32(buf, FirmwareImage.HEADER_SIZE + 16 + 4, off0)
}
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(img) }.message!!.contains("overlap"))
}
@Test
fun rejectsTruncatedPayload() {
val img = container(validComponents())
val truncated = img.copyOf(img.size - 10)
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(truncated) }.message!!.contains("truncated"))
assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(ByteArray(0x10)) }
}
@Test
fun rejectsWrongComponentCountAndMissingMain() {
val four = validComponents().dropLast(1)
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(four)) }.message!!.contains("components"))
val noMain = validComponents().dropLast(1) + Component("ota/other.bin", ByteArray(40))
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(noMain)) }.message!!.contains("not found"))
}
@Test
fun rejectsMainAppBeyondMramCeiling() {
val ceiling = (FirmwareImage.APP_MAX_END - FirmwareImage.APP_LOAD_ADDR + FirmwareImage.APP_PREAMBLE).toInt()
val fits = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(ceiling))
FirmwareImage.validate(container(fits))
val tooBig = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(ceiling + 1))
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(tooBig)) }.message!!.contains("MRAM"))
val badAddr = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(600).also { putU32(it, 0x14, 0x1234L) })
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(badAddr)) }.message!!.contains("load address"))
}
}
@@ -0,0 +1,22 @@
package com.faceclaw.app
import kotlin.test.*
class FontTest {
@Test
fun bundledFontMatchesJavaMetricsAndGlyphs() {
assertContentEquals(byteArrayOf(25, 19), LvglFontFile.getMetrics(TEST_FONT_PATH))
val vectors =
mapOf(
0x25a6 to "b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04",
0x25c6 to "c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd",
0x4e2d to "9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003",
0xff21 to "0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d",
)
vectors.forEach { (codePoint, expected) ->
assertEquals(expected, digest(LvglFontFile.getGlyph(TEST_FONT_PATH, codePoint)))
}
assertTrue(LvglFontFile.getGlyph(TEST_FONT_PATH, 0x10ffff).isEmpty())
assertTrue(LvglFontFile.getMetrics("/nonexistent/faceclaw-font").isEmpty())
}
}
@@ -0,0 +1,69 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class FoundationTest {
@Test
fun jsonRoundTripsObjectsArraysAndNumbers() {
val text = """{"a":1,"b":[true,null,"x\ny"],"c":{"d":2.5,"e":-3}}"""
val value = Json.parseObject(text)
assertEquals(1, value["a"].asInt())
assertEquals(listOf(true, null, "x\ny"), value["b"].asArray())
assertEquals(2.5, value["c"].asObject()!!["d"].asDouble())
assertEquals(-3L, value["c"].asObject()!!["e"].asLong())
assertEquals(text, Json.write(value))
assertEquals("[1,2,\"q\\\"\"]", Json.write(listOf(1, 2L, "q\"")))
assertEquals("1", JsonNumber.of(1.0).text)
assertEquals("1.5", JsonNumber.of(1.5).text)
assertNull("x".asInt())
}
@Test
fun sha256MatchesKnownVector() {
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", sha256Hex("abc".encodeToByteArray()))
val incremental = Sha256Digest()
incremental.update("a".encodeToByteArray())
incremental.update("bc".encodeToByteArray())
assertEquals(sha256("abc".encodeToByteArray()).toList(), incremental.digest().toList())
}
@Test
fun latchAndQueueHandOffAcrossThreads() {
val platform = testPlatform()
val latch = Latch(1, platform)
val queue = BlockingQueue<String>(platform)
assertFalse(latch.await(20))
startThread("foundation-test", true) {
sleepMs(20)
queue.put("hello")
latch.countDown()
}
assertEquals("hello", queue.poll(2000))
assertTrue(latch.await(2000))
assertNull(queue.poll(10))
}
@Test
fun interruptibleSleepConsumesEarlyInterrupt() {
val platform = testPlatform()
val sleep = InterruptibleSleep(platform)
sleep.interrupt()
val start = platform.elapsedRealtimeMs()
assertFalse(sleep.sleep(500))
assertTrue(platform.elapsedRealtimeMs() - start < 400)
assertTrue(sleep.sleep(5))
startThread("foundation-wake", true) { sleepMs(30); sleep.interrupt() }
assertFalse(sleep.sleep(5000))
}
@Test
fun wallClockFormatsPattern() {
val text = formatLocalTime(0L, "yyyy")
assertTrue(text == "1970" || text == "1969", text)
assertTrue(currentTimeMillis() > 1_600_000_000_000L)
}
}
@@ -0,0 +1,149 @@
package com.faceclaw.app
import kotlin.test.*
class FrameDisplayListTest {
// Golden records emitted by display-list-authoring.test.cjs.
private val menu = "077e0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c302341403102000200010001030400000000000000001f"
private val multi = "0744000000030002000400010002000000000000000002000200010000ff010001006003000400000000000000001f0200000100000001000100020002feffffff7f00010001007f00"
private val scroll = "078a000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f030234140310100170100160400020000000103"
// Clipped clear, clipped rounded rect, and replayed glyph + icon records with
// placeholder atlas ids 0xbeef / 0xcafebabe, plus what they paint over a
// nibble-1 16x8 screen (display-list-authoring.test.cjs).
private val replay = "0780000000020003000800040000070000006400000000000300890000000000000600040002880000010001000200020000000400030000000510a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100"
private val replayPixels = "11111111111111111111111111111111111111111111111111fff28f111111111125522211111111112552221111111111222222111111111111111111111111"
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun read(bytes: ByteArray, now: Long = 1150): FrameDisplayList {
val reader = ArrayByteReader(bytes)
assertEquals(DrawRecordKind.DISPLAY_LIST, reader.get().toInt())
return FrameDisplayList.read(reader, now).also { assertEquals(0, reader.remaining()) }
}
@Test fun authoredExpressionsRebindOnPresentAndTranslateWithTheSurface() {
val row = read(hex(menu)).translated(10, 10)
assertEquals(1, row.resources.size)
fun coordinates(now: Long, elapsed: Long): Triple<Int, Int, Boolean> {
val call = DrawReader(row.calls(intArrayOf(7), now).first())
assertEquals(DRAW_OP_ROUNDED_RECT, call.readU8())
assertEquals(DRAW_FLAG_DEPTH, call.readU8())
assertEquals(2, call.readS8())
val frame = DrawEvaluation(elapsed)
val x = ExtendedVarint.evaluate(call, frame)
val y = ExtendedVarint.evaluate(call, frame)
return Triple(x, y, frame.animationPending)
}
assertEquals(Triple(12, 10, true), coordinates(1150, 0))
assertEquals(Triple(13, 12, false), coordinates(1150, 150))
assertEquals(coordinates(1150, 75), coordinates(1225, 0), "another PRESENT preserves progress")
assertEquals(Triple(13, 12, false), coordinates(1400, 0))
val later = hex(menu).also { it[18] = 200.toByte() } // envelope 5 + elapsed offset 13
assertEquals(read(hex(menu)).fingerprint, read(later).fingerprint)
val other = hex(menu).also { it[14] = 43 } // timeline token
assertNotEquals(read(hex(menu)).fingerprint, read(other).fingerprint)
}
@Test fun animatedCopySourcesRebindOnPresentAndDestinationsTranslate() {
// Emitted by menu-scroll-animation.test.cjs: a menu strip scrolling from row 0 to row 2.
val list = read(hex(scroll)).translated(10, 10)
fun copy(elapsed: Long): List<Int> {
val call = DrawReader(list.calls(intArrayOf(5), 1150).first())
assertEquals(DRAW_OP_RECT_COPY, call.readU8())
assertEquals(DRAW_FLAG_DEPTH, call.readU8())
assertEquals(0, call.readS8())
val frame = DrawEvaluation(elapsed)
val values = listOf(call.readU16(), ExtendedVarint.evaluate(call, frame), ExtendedVarint.evaluate(call, frame),
call.readU16(), call.readU16(), ExtendedVarint.evaluate(call, frame), ExtendedVarint.evaluate(call, frame))
call.requireDone()
return values + if (frame.animationPending) 1 else 0
}
// 150 of 240 ms elapsed before this PRESENT; the source row is not translated with the surface.
assertEquals(listOf(5, 0, 1, 2, 2, 14, 12, 1), copy(0))
assertEquals(listOf(5, 0, 2, 2, 2, 14, 12, 0), copy(90))
}
@Test fun localResourceIdsAreResolvedAndScreenCopiesStayAtScreenDepth() {
val list = read(hex(multi)).translated(10, 10)
val calls = list.calls(intArrayOf(41, 42), 1150)
assertContentEquals(DrawProtocol.image(41, 13, 12, 31, depth = 2), calls[0])
assertContentEquals(DrawProtocol.rectCopy(42, 0, 0, 1, 1, 15, 12, depth = 2), calls[1])
assertContentEquals(DrawProtocol.rectCopy(DrawProtocol.SCREEN, 12, 12, 1, 1, 12, 12, depth = 0), calls[2])
val scene = ShellScene(emptyList(), listOf(read(hex(multi))))
assertEquals(2, scene.retainedResources.size)
for (right in listOf(false, true)) {
val pixels = scene.preview(ByteArray(64) { 32 }, 8, 8, right)
assertEquals(240, pixels[16 + if (right) 3 else 5].toInt() and 255)
assertEquals(96, pixels[16 + if (right) 4 else 6].toInt() and 255)
assertEquals(32, pixels[18].toInt() and 255)
}
val cache = ResourceCacheState()
val planner = ScenePlanner(cache)
val screen = ByteArray(32) { 0x22 }
planner.plan(screen, 8, 8, null, scene, 1)
val ids = scene.retainedResources.map { cache.resourceId(it) }
assertTrue(ids.all { it >= 0 }); assertNotEquals(ids[0], ids[1])
planner.plan(screen, 8, 8, null, scene, 1)
assertEquals(ids, scene.retainedResources.map { cache.resourceId(it) })
}
@Test fun frameAndShellSubmissionUseTheSameGenericDecoder() {
val c = SurfaceCompositor()
c.configureScreen(8, 8)
c.configureSurface("app", 0, 0, 8, 8, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(64) { 32 }), 0, 0, 8, 8, "list",
ArrayByteReader(hex(multi)))
val frame = c.composite()
assertEquals(2, frame.shellScene.retainedResources.size)
assertEquals(240, frame.gray[21].toInt() and 255)
assertTrue(frame.screenGray.all { it.toInt() == 32 })
// One opaque 1x1 shell layer, with one generic list after its pixels.
val layer = DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(0) + DrawProtocol.word(0) +
DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(256) + DrawProtocol.word(1) +
DrawProtocol.word(0) + byteArrayOf(32) + hex(multi)
val shell = ShellScene.decode(ArrayByteReader(layer))
assertEquals(2, shell.retainedResources.size)
assertEquals(240, shell.preview(ByteArray(64) { 32 }, 8, 8)[21].toInt() and 255)
}
@Test fun rejectsTruncationBadResourcesAndTrailingData() {
val bytes = hex(multi)
for (end in 1 until bytes.size) assertFails { read(bytes.copyOf(end)) }
assertFails { read(bytes.copyOf().also { it[40] = 9 }) } // first image's local resource
val trailing = bytes + byteArrayOf(0)
trailing[1] = (trailing[1] + 1).toByte()
assertFails { read(trailing) }
}
/** The TS golden's placeholder ids, replaced by ids registered in this process. */
private fun registeredReplay(imageKnown: Boolean = true): ByteArray {
val key = "stub-font".encodeToByteArray()
val glyph = byteArrayOf(key.size.toByte()) + key + byteArrayOf(4, 1, 0, 65, 0, 0, 0, 0, 1, 3, 2) +
byteArrayOf(0xa0.toByte(), 0, 0, 0, 0xe0.toByte(), 0, 0, 0)
GlyphAtlas.register(ArrayByteReader(glyph))
val fontId = GlyphAtlas.fontId("stub-font")
val imageId = if (imageKnown) ImageAtlas.ensure("stub-replay-icon", 2, 2,
ArrayByteReader(byteArrayOf(255.toByte(), 0, 128.toByte(), 255.toByte()))) else 0x7fffffff
fun le(value: Int, bytes: Int) = (0 until bytes).joinToString("") { ((value ushr (8 * it)) and 255).toString(16).padStart(2, '0') }
return hex(replay.replace("efbe", le(fontId, 2)).replace("bebafeca", le(imageId, 4)))
}
@Test fun replayedDrawsCompileToClippedImageAndTextCallsThatPaintLikeTheSoftwareRenderer() {
val list = read(registeredReplay(), 1100)
assertEquals(2, list.resources.size, "the icon and a font snapshot")
val ids = intArrayOf(1, 2)
val calls = list.calls(ids, 1100)
assertEquals(listOf(DRAW_OP_CLEAR, DRAW_OP_ROUNDED_RECT, DRAW_OP_IMAGE, DRAW_OP_TEXT), calls.map { it[0].toInt() })
assertTrue(calls.all { it[1].toInt() and DRAW_FLAG_CLIP != 0 })
val resources = list.resources.withIndex().associate { (i, resource) -> ids[i] to resource.bytes }
val screen = ByteArray(64) { 0x11 }
val target = DisplayListRenderer.Target(screen, 16, 8)
DisplayListRenderer(resources).execute(DrawProtocol.sequence(calls), target)
val nibbles = (0 until 128).joinToString("") { target.get(it % 16, it / 16).toString(16) }
assertEquals(replayPixels, nibbles)
}
@Test fun replayWithAnUnknownRecordDrawsNothing() {
val list = read(registeredReplay(imageKnown = false), 1100)
assertTrue(list.resources.isEmpty())
assertTrue(list.calls(IntArray(0), 1100).isEmpty())
}
}
@@ -0,0 +1,139 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FrameTimingsCoreTest {
private class FakeClock : ProtocolPlatform by testPlatform() {
var nowMs = 1_000L
override fun elapsedRealtimeMs(): Long = nowMs
}
private fun core(clock: FakeClock, logs: MutableList<String> = ArrayList()) = FrameTimingsCore(
platform = clock,
wallClockMs = { 1_700_000_000_000L + clock.nowMs },
threadName = { "t" },
formatWallClock = { "wall@$it" },
logInfo = { logs.add("I $it") },
logWarn = { logs.add("W $it") },
)
@Test
fun exportRendersTreeAgainstRootClockByteForByte() {
val clock = FakeClock()
val logs = ArrayList<String>()
val core = core(clock, logs)
val root = core.startFrame("input:sys-event type=0")
clock.nowMs += 5
core.annotate(root, "fg=terminal")
core.log(root, "input event received on JS side")
clock.nowMs += 1
core.spanStart(root, "handle-input")
clock.nowMs += 10
val child = core.startFrame("render:shell", root)
clock.nowMs += 4
core.spanEnd(root, "handle-input")
core.spanEnd(root, "missing")
core.spanStart(child, "paint")
clock.nowMs += 30
core.finishFrame(child, "discarded: superseded")
clock.nowMs += 50
core.finishFrame(root, "sent")
core.finishFrame(root, "sent") // ignored: first finish wins
core.log(root, "late line is dropped")
clock.nowMs += 100
assertEquals(listOf(
"I frame#2 [render:shell] -> discarded: superseded in 34ms",
"I frame#1 [input:sys-event type=0 fg=terminal] -> sent in 100ms",
), logs)
assertEquals("frames started=2 sent=1 discarded=1 timeout=0 | input-to-display p50=100ms p90=100ms p99=100ms max=100ms", core.statsSummary())
val expected = """
|FrameTimings export at wall@1700000001200
|frames started=2 sent=1 discarded=1 timeout=0 open=0
|input-to-display latency (last 1): p50=100ms p90=100ms p99=100ms max=100ms
|
|Frames are trees: an input event's own frame is the root, and the renders it
|caused are indented under it with offsets measured from the root's start.
|
|=== slowest frames that reached the glasses ===
|frame#1 [input:sys-event type=0 fg=terminal] started wall@1700000001000 duration 100ms (tree 100ms) outcome sent
| +5ms [t] input event received on JS side
| +6ms [t] span handle-input start
| +16ms [t] spawned frame#2 (render:shell)
| +20ms [t] span handle-input end (14ms)
| +20ms [t] span missing end (start not recorded)
| +100ms [t] finished: sent
| frame#2 [render:shell] started +16ms duration 34ms outcome discarded: superseded
| +20ms [t] span paint start
| +50ms [t] span paint never ended (started at +4ms)
| +50ms [t] finished: discarded: superseded
|=== recent frames (oldest first) ===
|frame#1 [input:sys-event type=0 fg=terminal] started wall@1700000001000 duration 100ms (tree 100ms) outcome sent
| +5ms [t] input event received on JS side
| +6ms [t] span handle-input start
| +16ms [t] spawned frame#2 (render:shell)
| +20ms [t] span handle-input end (14ms)
| +20ms [t] span missing end (start not recorded)
| +100ms [t] finished: sent
| frame#2 [render:shell] started +16ms duration 34ms outcome discarded: superseded
| +20ms [t] span paint start
| +50ms [t] span paint never ended (started at +4ms)
| +50ms [t] finished: discarded: superseded
|""".trimMargin()
assertTrue(core.isExportDirty)
assertEquals(expected, core.takeExport())
assertFalse(core.isExportDirty)
assertEquals(null, core.takeExport())
assertEquals(expected, core.buildExport())
}
@Test
fun sweepFinishesStaleFramesAsTimeoutsAndIgnoresZeroAndUnknownIds() {
val clock = FakeClock()
val logs = ArrayList<String>()
val core = core(clock, logs)
val stale = core.startFrame("render:app")
clock.nowMs += FrameTimingsCore.FRAME_TIMEOUT_MS - 1
val fresh = core.startFrame("render:late")
assertEquals(0, core.sweepTimedOut())
clock.nowMs += 1
assertEquals(1, core.sweepTimedOut())
assertEquals(listOf("W frame#$stale [render:app] timed out after 30000ms without being finished"), logs)
core.log(0, "ignored")
core.log(999, "ignored")
core.spanStart(0, "x")
core.finishFrame(0, "sent")
core.finishFrame(fresh, "sent")
assertEquals("frames started=2 sent=1 discarded=0 timeout=1", core.statsSummary())
val export = core.buildExport()
assertTrue(export.contains("frame#$stale [render:app] started wall@"))
assertTrue(export.contains("outcome timeout: never reported finished\n"))
assertTrue(export.contains("render-to-display latency (last 1): p50=1ms p90=1ms p99=1ms max=1ms"))
assertTrue(export.contains("open=0"))
}
@Test
fun lineCapAndNegativeOffsetsFormatLikeJava() {
val clock = FakeClock()
val core = core(clock)
val root = core.startFrame("input:x")
clock.nowMs -= 12 // a line stamped before the root's start still formats with a sign
core.log(root, "early")
clock.nowMs += 12
repeat(250) { core.log(root, "line $it") }
core.finishFrame(root, "sent")
val export = core.buildExport()
assertTrue(export.contains("\n -12ms [t] early\n"), export)
// Printed once under "slowest" and once under "recent".
assertEquals(2, Regex("\\.\\.\\. line cap reached").findAll(export).count())
assertTrue(export.contains("line 198"))
assertFalse(export.contains("line 199"))
// Like the Java original, lines past the cap (including the finish line) are dropped.
assertFalse(export.contains("finished: sent"))
assertTrue(export.contains("outcome sent\n"))
}
}
@@ -0,0 +1,457 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
private const val RIGHT = "AA:00:00:00:00:01"
private const val LEFT = "AA:00:00:00:00:02"
/** The test platform with a clock the tests can jump forward (the real waits keep real time). */
private class ClockPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
@Volatile var offsetMs = 0L
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
}
private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val platform = testPlatform()
val deadline = platform.elapsedRealtimeMs() + timeoutMs
while (platform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(10)
}
return condition()
}
private fun ByteArray.containsSequence(needle: ByteArray): Boolean {
if (needle.isEmpty() || size < needle.size) return false
outer@ for (start in 0..size - needle.size) {
for (i in needle.indices) if (this[start + i] != needle[i]) continue@outer
return true
}
return false
}
/** One logical write as the fake link saw it: the frames, the decoded pb, and the in-flight message (if any). */
private class Write(
val address: String,
val sid: Int,
val frames: List<ByteArray>,
val pb: ByteArray,
val kind: String?,
val label: String?,
val magic: Int,
val message: ByteArray?,
)
/**
* A GATT link that records every write and, unless a kind is muted, answers it the way the
* firmware would: EvenHub/settings/auth requests get a matching ack frame, CFW stream
* messages get one ACK per lens.
*/
private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = platform.createLock()
private val writesList = ArrayList<Write>()
val muted = HashSet<String>()
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
var seq = 0
val writes: List<Write>
get() = lock.withLock { writesList.toList() }
/** Decoded CFW image messages (the drive loop's debug-flags control rides the same stream and is excluded). */
fun cfwMessages(): List<ByteArray> = writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }.mapNotNull { it.message }
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
return true
}
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
val sid = frames[0][6].toInt() and 255
val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq
// The in-flight entry gives the label/kind and the decoded CFW message.
val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } }
val pb = if (sid == CfwTransport.SID) ByteArray(0) else {
val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray()
joined.copyOf(maxOf(0, joined.size - 2))
}
val write = Write(address, sid, frames, pb, inFlight?.kind, inFlight?.label, magic, inFlight?.message?.copyOf())
lock.withLock { writesList.add(write) }
if (inFlight != null && inFlight.kind !in muted) {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return BleProtocol.framePb(body, sid, 0x00, seq++)[0]
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
}
override fun close() {
closed = true
}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = 11
packet[4] = 1
packet[5] = 1
packet[6] = CfwTransport.SID.toByte()
packet[8] = 1
packet[9] = streamId.toByte()
packet[12] = lens.toByte()
packet[13] = size.toByte()
packet[14] = (size ushr 8).toByte()
packet[15] = checksum.toByte()
packet[16] = (checksum ushr 8).toByte()
val crc = CfwTransport.crc(packet.copyOfRange(8, 17))
packet[17] = crc.toByte()
packet[18] = (crc ushr 8).toByte()
return packet
}
private class FakeHost(private val platform: ProtocolPlatform) : SessionHost {
private val lock = platform.createLock()
private val lines = ArrayList<String>()
private var done: Latch? = null
var wakeLock = false
fun logs(): List<String> = lock.withLock { lines.toList() }
fun hasLog(fragment: String): Boolean = logs().any { it.contains(fragment) }
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {
wakeLock = on
}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {
val latch = Latch(1, platform)
done = latch
startThread("test-session", true) {
try {
body()
} finally {
latch.countDown()
}
}
}
override fun joinWorker(timeoutMs: Long) {
done?.await(timeoutMs)
}
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {
lock.withLock { lines.add("$level $tag: $message") }
}
}
private class FakeListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
val events = ArrayList<String>()
val finished = ArrayList<String>()
val batteries = ArrayList<String>()
override fun onStateChange(phase: String?, status: String?) {
phases.add(phase ?: "")
}
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {
events.add("$kind:$eventType")
}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
batteries.add("$headsetBattery/$headsetCharging/$ringBattery/$ringCharging")
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {
finished.add("$frameId:$outcome")
}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
}
private class Session {
val platform = ClockPlatform(testPlatform())
val link = FakeLink(platform)
val host = FakeHost(platform)
val listener = FakeListener()
val frameTimings = FrameTimingsCore(platform)
val core = GlassesSessionCore(link, host, frameTimings, platform, RIGHT, LEFT, "")
init {
link.core = core
core.setListener(listener)
}
fun layoutCreated(): Boolean = core.monitor.withLock { core.fixedLayoutCreated }
fun startAndAwaitLayout() {
assertTrue(core.start())
assertTrue(waitUntil(5_000) { layoutCreated() }, "layout never created; logs=${host.logs().takeLast(20)}")
}
/** A 64x32 surface frame with a marker byte at [marker]; returns the expected composite fingerprint. */
fun submitFrame(marker: Int, value: Byte, frameId: Int): Unit {
val pixels = ByteArray(64 * 32)
pixels[marker] = value
core.submitSurfaceFrame(ArrayByteReader(pixels), "s", 0, 0, 64, 32, "content-$marker-$value", 0, frameId, null)
}
fun displayedMatchesDesired(): Boolean = core.monitor.withLock {
core.desiredTilesLock.locked { core.desiredFingerprint.isNotEmpty() && core.desiredFingerprint == core.displayedFingerprint }
}
}
class GlassesSessionCoreTest {
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
val s = Session()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(640, 480)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.startAndAwaitLayout()
s.core.monitor.withLock { s.core.customFirmwareDetected = true }
try {
s.submitFrame(1, 0x70, 1)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() })
fun outputs() = s.link.writes.filter { it.address == LEFT && it.kind == "brightness-output" }
assertTrue(waitUntil(5000) { outputs().isNotEmpty() })
val first = outputs().first().message!!
assertContentEquals(byteArrayOf(30, 1, 70, 1, 24, 1), first)
val writes = s.link.writes.filter { it.address == LEFT }
assertTrue(writes.indexOfFirst { it.kind == "als-control" } < writes.indexOfFirst { it.kind == "brightness-output" })
assertTrue(writes.indexOfFirst { it.kind == "brightness-output" } < writes.indexOfFirst { it.message?.firstOrNull() == 28.toByte() })
s.core.setScreenBlanked(true)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 0.toByte() })
s.core.setScreenBlanked(false)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 1.toByte() })
// The ordered CFW window may replay accepted commands; those must
// retain the same brightness and visibility, without an extra toggle.
val visibility = outputs().map { it.message!![3].toInt() }
val transitions = visibility.filterIndexed { i, v -> i == 0 || visibility[i-1] != v }
assertEquals(listOf(1, 0, 1), transitions)
assertTrue(outputs().all { it.message!![2] == 70.toByte() })
// The demo cannot restore the stock adjuster while Faceclaw owns brightness.
s.core.setAmbientLightPolling(false, 250, 0, 1000, true)
s.platform.offsetMs += 3000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5000) { s.link.writes.count { it.address == LEFT && it.kind == "als-control" } >= 2 })
assertTrue(s.link.writes.filter { it.kind == "als-control" }.all { it.message!![1] == 1.toByte() })
} finally { s.core.close() }
}
@Test
fun connectsAuthenticatesPreludesAndCreatesTheLayout() {
val s = Session()
s.startAndAwaitLayout()
val writes = s.link.writes
assertEquals(setOf(RIGHT, LEFT), writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.address }.toSet())
assertTrue(s.host.hasLog("security auth R=ok L=ok"), s.host.logs().toString())
assertEquals(1, writes.count { it.kind == "prelude" })
// The framebuffer lease is acquired on both arms (fire-and-forget settings writes, magic 0).
val fbAcquire = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())
assertEquals(setOf(RIGHT, LEFT), writes.filter { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(fbAcquire) }.map { it.address }.toSet())
assertEquals(1, writes.count { it.kind == "battery" }, "settings query for firmware info")
assertEquals(1, writes.count { it.kind == "create-layout" })
assertTrue(s.core.isSessionReady())
assertEquals(listOf("disconnected", "connecting", "connected"), s.listener.phases.distinct())
s.core.disconnect()
assertFalse(s.core.isSessionReady())
assertEquals("disconnected", s.listener.phases.last())
assertTrue(s.listener.phases.contains("disconnecting"))
assertTrue(s.link.closed)
assertEquals(listOf(RIGHT, LEFT), s.link.disconnected.takeLast(2))
assertFalse(s.host.wakeLock)
assertTrue(s.host.hasLog("communicator stop"))
}
@Test
fun imagePipelineSendsAKeyframeThenABoundingBoxDelta() {
val s = Session()
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(100, 0x80.toByte(), 1)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size >= 1 && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
assertTrue(s.listener.finished.contains("1:sent"), s.listener.finished.toString())
s.submitFrame(101, 0x80.toByte(), 2)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size >= 2 && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
val messages = s.link.cfwMessages()
assertEquals(CFW_MSG_FULL_FRAME, messages[0][0].toInt() and CFW_MSG_TYPE_MASK, "first frame is a keyframe")
assertEquals(CFW_MSG_BOUNDING_BOX, messages[1][0].toInt() and CFW_MSG_TYPE_MASK, "second frame is a delta")
assertTrue(s.listener.finished.contains("2:sent"))
// Identical content again: nothing is sent and the frame is finished as a no-change.
s.submitFrame(101, 0x80.toByte(), 3)
assertTrue(waitUntil(2_000) { s.listener.finished.any { it.startsWith("3:") } })
assertTrue(s.listener.finished.any { it == "3:discarded: no change from displayed image" }, s.listener.finished.toString())
assertEquals(2, s.link.cfwMessages().size)
s.core.disconnect()
}
@Test
fun heartbeatAndLeaseRenewalFollowTheClock() {
val s = Session()
s.startAndAwaitLayout()
// The first heartbeat follows the layout at once (nothing has been acked yet); the
// next one waits for HEARTBEAT_READY_MS since that ack.
assertTrue(waitUntil(3_000) { s.link.writes.count { it.kind == "heartbeat" } == 1 }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("Got ACK for heartbeat"))
sleepMs(300)
assertEquals(1, s.link.writes.count { it.kind == "heartbeat" })
s.platform.offsetMs += ConnectionOptions.HEARTBEAT_READY_MS + 100L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) { s.link.writes.count { it.kind == "heartbeat" } == 2 }, s.host.logs().takeLast(10).toString())
val leaseWritesBefore = s.link.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())) }
s.platform.offsetMs += GlassesSessionCore.FACECLAW_WAKE_LEASE_RENEW_MS + 100L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) {
s.link.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())) } == leaseWritesBefore + 2
}, "framebuffer lease renewed on both arms")
s.core.disconnect()
}
@Test
fun deferredWakeIsClaimedAndReadyIsSentAfterResume() {
val s = Session()
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(7, 0x40, 1)
assertTrue(waitUntil(5_000) { s.displayedMatchesDesired() })
assertTrue(s.core.suspendEvenHubSession())
assertTrue(s.core.monitor.withLock { s.core.shutdownRequested })
assertEquals(1, s.link.writes.count { it.kind == "shutdown" })
// CFW deferred double-tap wake on the right arm: field 102 [F,C,ver,event=1,nonce LE16].
val nonce = 0x1234
val event = byteArrayOf(70, 67, 1, 1, (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
val pb = BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, 0) + BleProtocol.encodeBytesField(BleProtocol.FACECLAW_WAKE_EVENT_FIELD, event)
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, BleProtocol.framePb(pb, BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_NOTIFY, 9)[0])
assertTrue(s.listener.events.contains("display-wake:${BleProtocol.EVENT_DOUBLE_CLICK}"), s.listener.events.toString())
val claim = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_WAKE_OP_CLAIM.toByte(), (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
assertTrue(waitUntil(3_000) { s.link.writes.count { it.pb.containsSequence(claim) } == 2 }, "CLAIM written to both arms")
assertEquals(RIGHT, s.link.writes.first { it.pb.containsSequence(claim) }.address, "right arm first")
assertTrue(s.core.resumeEvenHubSession())
assertEquals(2, s.link.writes.count { it.kind == "prelude" })
assertTrue(waitUntil(5_000) { s.layoutCreated() && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
assertTrue(s.core.awaitEvenHubSessionReady(5_000))
val ready = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_WAKE_OP_READY.toByte(), (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
assertEquals(2, s.link.writes.count { it.pb.containsSequence(ready) }, "READY written to both arms")
s.core.disconnect()
}
@Test
fun unexpectedAndDuplicateAcksAreLoggedNotApplied() {
val s = Session()
s.startAndAwaitLayout()
val unknown = BleProtocol.framePb(BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, 150), BleProtocol.SID_EVENHUB, 0, 5)[0]
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, unknown)
assertTrue(s.host.hasLog("unexpected ACK sid=${BleProtocol.SID_EVENHUB} magic=150"), s.host.logs().takeLast(5).toString())
val layout = s.link.writes.first { it.kind == "create-layout" }
val duplicate = BleProtocol.framePb(BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, layout.magic), layout.sid, 0, 6)[0]
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, duplicate)
assertTrue(s.host.hasLog("duplicate ACK for already-acked message sid=${layout.sid} magic=${layout.magic}"), s.host.logs().takeLast(5).toString())
assertTrue(s.layoutCreated())
s.core.disconnect()
}
@Test
fun ackTimeoutOnTheLayoutReconnects() {
val s = Session()
s.link.muted.add("create-layout")
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.link.writes.any { it.kind == "create-layout" } })
assertFalse(s.layoutCreated())
s.platform.offsetMs += ConnectionOptions.ACK_TIMEOUT_MS + ConnectionOptions.WRITE_TIMEOUT_MS + 1_000L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) { s.listener.phases.contains("retrying") }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("message timed out: create-layout"))
assertTrue(s.host.hasLog("Transport failure: ack timeout"))
assertTrue(s.link.disconnected.containsAll(listOf(RIGHT, LEFT)))
s.core.disconnect()
assertEquals("disconnected", s.listener.phases.last())
}
@Test
fun cfwNackTriggersReplayWithAFreshStreamId() {
val s = Session()
s.link.muted.add("image")
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(3, 0x20, 1)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size == 1 })
val first = s.link.writes.first { it.sid == CfwTransport.SID && it.kind == "image" }
val message = assertNotNull(s.core.monitor.withLock { s.core.inFlightMessages.firstOrNull { it.magic == first.magic } })
// A NACK from lens 1 marks the message for replay; the window re-sends it under a new id.
val nack = cfwAck(first.magic, 1, 0, 0).also { it[8] = 3; val crc = CfwTransport.crc(it.copyOfRange(8, 17)); it[17] = crc.toByte(); it[18] = (crc ushr 8).toByte() }
s.core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, nack)
assertTrue(waitUntil(3_000) { s.link.cfwMessages().size == 2 }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("CFW replay id=${first.magic}"))
val second = s.link.writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }[1]
assertTrue(second.magic != first.magic)
assertEquals(1, message.cfwRetries)
assertContentEquals(first.message, second.message)
s.core.disconnect()
}
}
@@ -0,0 +1,128 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GlyphAndIconSourceTest {
private fun u16(bytes: ByteArray, at: Int) = (bytes[at].toInt() and 0xff) or ((bytes[at + 1].toInt() and 0xff) shl 8)
private fun s16(bytes: ByteArray, at: Int) = u16(bytes, at).toShort().toInt()
// 6x4 raster: ink in columns 2..4, rows 1..2, one 128 edge pixel.
private val raster = byteArrayOf(
0, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, 0,
0, 0, 0, -1, 0x7f, 0,
0, 0, 0, 0, 0, 0,
)
@Test
fun gammaLutIsIdentityAtOneAndDarkensAboveOne() {
val linear = GlyphPacket.gammaLut(1.0)
for (i in 0 until 256) assertEquals(i, linear[i].toInt() and 0xff)
assertContentEquals(linear, GlyphPacket.gammaLut(0.0))
val squared = GlyphPacket.gammaLut(2.0)
assertEquals(64, squared[128].toInt() and 0xff)
assertEquals(255, squared[255].toInt() and 0xff)
}
@Test
fun inkScansFindPaintedBoxes() {
assertContentEquals(intArrayOf(2, 4), GlyphPacket.paintedColumnRange(raster, 6, 4))
assertContentEquals(intArrayOf(2, 1, 4, 2), GlyphPacket.inkBounds(raster, 6, 4))
assertNull(GlyphPacket.paintedColumnRange(ByteArray(12), 4, 3))
assertNull(GlyphPacket.inkBounds(ByteArray(12), 4, 3))
}
@Test
fun imagePacketsCarryLittleEndianHeaderAndGammaMappedRegion() {
val whole = GlyphPacket.packImage(raster, 6, 4, 1.0)
assertEquals(4 + 24, whole.size)
assertEquals(6, u16(whole, 0))
assertEquals(4, u16(whole, 2))
assertContentEquals(raster, whole.copyOfRange(4, whole.size))
val region = GlyphPacket.packImageRegion(raster, 6, 2, 1, 3, 2, 2.0)
assertEquals(3, u16(region, 0))
assertEquals(2, u16(region, 2))
assertContentEquals(byteArrayOf(-1, -1, 0, 0, -1, 63), region.copyOfRange(4, region.size))
}
@Test
fun glyphCellPacketsCropToInkAndEncodeSignedOffsets() {
val cell = GlyphPacket.packGlyphCell(GlyphPacket.advanceFixed(5.5), raster, 6, 4, penX = 3, baselineY = 3, ascent = 10, gamma = 1.0)
assertEquals(352, u16(cell, 0))
assertEquals(-1, s16(cell, 2)) // ink starts one pixel left of the pen
assertEquals(8, s16(cell, 4)) // ascent 10, ink top two rows above the baseline
assertEquals(3, u16(cell, 6))
assertEquals(2, u16(cell, 8))
assertContentEquals(byteArrayOf(-1, -1, 0, 0, -1, 0x7f), cell.copyOfRange(10, cell.size))
val empty = GlyphPacket.packGlyphCell(64, ByteArray(12), 4, 3, 0, 0, 10, 1.0)
assertContentEquals(byteArrayOf(64, 0, 0, 0, 0, 0, 0, 0, 0, 0), empty)
assertEquals(0xffff, GlyphPacket.advanceFixed(5000.0))
}
private fun nameTable(vararg records: Triple<Int, Int, String>): ByteArray {
// records: (platformId, nameId, value); platform 1 stored Latin-1, others UTF-16BE
val strings = ArrayList<ByteArray>()
for ((platform, _, value) in records) {
strings.add(if (platform == 1) ByteArray(value.length) { value[it].code.toByte() }
else ByteArray(value.length * 2) { if (it % 2 == 0) (value[it / 2].code shr 8).toByte() else value[it / 2].code.toByte() })
}
val out = ByteSink()
fun u16(v: Int) { out.write(v ushr 8); out.write(v) }
fun u32(v: Int) { u16(v ushr 16); u16(v and 0xffff) }
val nameOffset = 12 + 16
val nameLength = 6 + records.size * 12 + strings.sumOf { it.size }
u32(0x00010000); u16(1); u16(0); u16(0); u16(0) // offset table, 1 table
u32(0x6e616d65); u32(0); u32(nameOffset); u32(nameLength) // 'name' record
u16(0); u16(records.size); u16(6 + records.size * 12)
var offset = 0
for ((i, record) in records.withIndex()) {
u16(record.first); u16(0); u16(0); u16(record.second); u16(strings[i].size); u16(offset)
offset += strings[i].size
}
for (s in strings) out.write(s)
return out.toByteArray()
}
@Test
fun openTypeNamesPreferTypographicFamilyAndStyle() {
assertEquals("Roboto\nLight", OpenTypeNames.parse(nameTable(Triple(3, 1, "Roboto Light"), Triple(3, 2, "Regular"), Triple(3, 16, "Roboto"), Triple(1, 17, "Light"))))
assertEquals("Mono\n", OpenTypeNames.parse(nameTable(Triple(1, 1, " Mono "))))
assertEquals("", OpenTypeNames.parse(nameTable(Triple(3, 2, "Bold"))))
assertEquals("", OpenTypeNames.parse(ByteArray(8)))
}
@Test
fun svgIconsParseShapesStrokeRuleAndPlacement() {
val svg = """<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2"/>
<circle cx="12" cy="12" r="0"/><circle cx="12" cy="12" r="3"/><path d="M4 4h16"/><polygon points="1,2 3 4 5"/><line x1="0" y1="0" x2="1" y2="1"/></svg>"""
val icon = SvgIconSource.parse(svg)!!
assertTrue(icon.stroked)
assertEquals(listOf("Rect", "Circle", "PathData", "Polyline", "Line"), icon.shapes.map { it::class.simpleName })
val rect = icon.shapes[0] as SvgShape.Rect
assertEquals(2f, rect.rx); assertEquals(2f, rect.ry)
assertEquals(3f, (icon.shapes[1] as SvgShape.Circle).r)
assertEquals("M4 4h16", (icon.shapes[2] as SvgShape.PathData).d)
val polygon = icon.shapes[3] as SvgShape.Polyline
assertContentEquals(floatArrayOf(1f, 2f, 3f, 4f), polygon.points)
assertTrue(polygon.closed)
assertContentEquals(floatArrayOf(0f, 0f, 2f), icon.placement(48))
val filled = SvgIconSource.parse("""<svg viewBox="-2 0 40 20"><rect width="4" height="2"/></svg>""")!!
assertTrue(!filled.stroked)
assertContentEquals(floatArrayOf(0f, 5f, 0.5f), filled.placement(20))
assertEquals(-2f, filled.minX)
assertNull(SvgIconSource.parse("""<svg><circle r="0"/><rect width="0" height="3"/></svg>"""))
}
@Test
fun coverageQuantizesToThreeLevels() {
assertEquals(0, SvgIconSource.quantizeCoverage(63))
assertEquals(128, SvgIconSource.quantizeCoverage(64))
assertEquals(128, SvgIconSource.quantizeCoverage(191))
assertEquals(255, SvgIconSource.quantizeCoverage(192))
assertContentEquals(byteArrayOf(0, -128, -1), SvgIconSource.quantizeArgb(intArrayOf(0x10ffffff, 0x80000000.toInt(), 0xff000000.toInt())))
}
}
@@ -0,0 +1,99 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
class GraphicsCoresTest {
private fun checksum(bytes: ByteArray): Long {
var sum = 7L
for (b in bytes) sum = sum * 31 + (b.toInt() and 0xff)
return sum
}
@Test
fun grayPacketHeaderAndFlatConversion() {
// 3x2: opaque white, opaque mid, transparent white, half-alpha red, opaque black, opaque green
val pixels = intArrayOf(
0xffffffff.toInt(), 0xff808080.toInt(), 0x00ffffff,
0x80ff0000.toInt(), 0xff000000.toInt(), 0xff00ff00.toInt(),
)
val packet = GrayPacket.fromArgb(pixels, 3, 2, 1f, false)
assertEquals(4 + 6, packet.size)
assertContentEquals(byteArrayOf(3, 0, 2, 0), packet.copyOfRange(0, 4))
assertEquals(255, packet[4].toInt() and 0xff)
assertEquals(128, packet[5].toInt() and 0xff)
assertEquals(0, packet[6].toInt() and 0xff) // alpha 0 darkens to black
assertEquals(76 * 128 / 255, packet[7].toInt() and 0xff) // luma 76 at half alpha
assertEquals(0, packet[8].toInt() and 0xff)
assertEquals(149, packet[9].toInt() and 0xff)
val wide = GrayPacket.fromArgb(IntArray(300 * 2), 300, 2, 1f, false)
assertContentEquals(byteArrayOf(0x2c, 1, 2, 0), wide.copyOfRange(0, 4))
}
@Test
fun toneCurveDarkensMidtones() {
val identity = GrayPacket.toneCurve(1f)
assertEquals((0..255).toList(), identity.toList())
val curve = GrayPacket.toneCurve(2.2f)
assertEquals(0, curve[0])
assertEquals(255, curve[255])
assertEquals(56, curve[128])
assertTrue(curve.toList() == curve.sorted())
}
@Test
fun ditherIsDeterministicAndQuantized() {
// A horizontal ramp over 16x4 so the diffusion has somewhere to go.
val pixels = IntArray(16 * 4) { i -> val v = (i % 16) * 17; 0xff000000.toInt() or (v shl 16) or (v shl 8) or v }
val a = GrayPacket.fromArgb(pixels, 16, 4, 1f, true)
val b = GrayPacket.fromArgb(pixels, 16, 4, 1f, true)
assertContentEquals(a, b)
for (i in 4 until a.size) {
val v = a[i].toInt() and 0xff
assertTrue(v == 1 || (v % 16 == 0 && v in 16..240), "byte $i = $v")
}
// Mid-gray flat area dithers to a mix of two adjacent levels, never a solid.
val flat = GrayPacket.fromArgb(IntArray(8 * 8) { 0xff7f7f7f.toInt() }, 8, 8, 1f, true)
val levels = flat.drop(4).map { it.toInt() and 0xff }.toSet()
assertEquals(setOf(112, 128), levels)
assertEquals(2001783152304756847L, checksum(a))
}
@Test
fun previewPaletteValues() {
assertEquals(0xff000000.toInt(), PreviewPalette.argb(0, 0.7, false))
assertEquals(0xffffffff.toInt(), PreviewPalette.argb(255, 0.7, false))
assertEquals(0xff00ff00.toInt(), PreviewPalette.argb(255, 0.7, true))
val gray = PreviewPalette.argb(128, 0.7, false)
val v = gray and 0xff
assertEquals(157, v)
assertEquals(0xff000000.toInt() or (v shl 16) or (v shl 8) or v, gray)
assertEquals(0xff000000.toInt() or (v shl 8), PreviewPalette.argb(128, 0.7, true))
assertEquals(0xff808080.toInt(), PreviewPalette.argb(128, 1.0, false))
val lut = PreviewPalette.lookupTable(0.7, false)
assertSame(lut, PreviewPalette.lookupTable(0.7, false))
assertEquals(256, lut.size)
val expanded = PreviewPalette.expand(byteArrayOf(0, 0x80.toByte(), 0xff.toByte()), 0, 3, 0.7, false)
assertContentEquals(intArrayOf(lut[0], lut[128], lut[255]), expanded)
}
@Test
fun statusIconsAreStable() {
val wifi = StatusIconArt.wifi(4)
val cell = StatusIconArt.cell(2)
val hotspot = StatusIconArt.hotspot()
for (icon in listOf(wifi, cell, hotspot)) {
assertEquals(24 * 24, icon.size)
assertTrue(icon.any { it.toInt() != 0 })
}
assertTrue(StatusIconArt.wifi(0).count { it.toInt() != 0 } < wifi.count { it.toInt() != 0 })
assertEquals(StatusIconArt.wifi(2).toList(), StatusIconArt.wifi(2).toList())
assertEquals(listOf(-7515428168691714401L, -7643893777543336767L, 7675840471157348143L), listOf(checksum(wifi), checksum(cell), checksum(hotspot)))
val scaled = StatusIconArt.scale(wifi, 12)
assertEquals(144, scaled.size)
assertSame(wifi, StatusIconArt.scale(wifi, 24))
}
}
@@ -0,0 +1,67 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class Lc3PacketFramerTest {
private class FakeCodec(var fail: Boolean = false) : Lc3Codec {
var calls = 0
override fun decodeFrames(packet: ByteArray, offset: Int, length: Int, pcmOut: ShortArray): Int {
calls++
assertEquals(0, offset)
assertEquals(Lc3PacketFramer.LC3_BYTES, length)
return if (fail) -1 else Lc3PacketFramer.SAMPLES_PER_PACKET
}
}
private fun packet(counter: Int, ssr: Int = 0, angle: Int = 0): ByteArray {
val p = ByteArray(Lc3PacketFramer.PACKET_BYTES)
p[Lc3PacketFramer.COUNTER_OFFSET] = counter.toByte()
p[Lc3PacketFramer.SSR_OFFSET] = (ssr and 0xff).toByte()
p[Lc3PacketFramer.SSR_OFFSET + 1] = ((ssr shr 8) and 0xff).toByte()
p[Lc3PacketFramer.ANGLE_OFFSET] = (angle and 0xff).toByte()
p[Lc3PacketFramer.ANGLE_OFFSET + 1] = ((angle shr 8) and 0xff).toByte()
return p
}
@Test
fun countsRealDuplicateLateAndMissingPackets() {
val codec = FakeCodec()
val framer = Lc3PacketFramer(codec)
val pcm = ShortArray(Lc3PacketFramer.SAMPLES_PER_PACKET)
assertEquals(800, framer.decodePacket(packet(250), pcm))
assertEquals(800, framer.decodePacket(packet(251), pcm))
assertEquals(0, framer.decodePacket(packet(251), pcm)) // relayed by the other arm
assertEquals(0, framer.decodePacket(packet(250), pcm)) // late copy (gap 255)
assertEquals(800, framer.decodePacket(packet(254), pcm)) // 252, 253 lost
assertEquals(800, framer.decodePacket(packet(1), pcm)) // wraps past 255 -> 0; 255, 0 lost
assertEquals(0, framer.decodePacket(packet(129), pcm)) // gap 128 is late, not 127 losses
assertEquals(4, framer.realPackets)
assertEquals(3, framer.duplicatePackets)
assertEquals(4, framer.missingPackets)
assertEquals(0, framer.decodeErrors)
assertEquals(4, codec.calls)
}
@Test
fun parsesSignedTrailerAndRejectsBadInput() {
val codec = FakeCodec()
val framer = Lc3PacketFramer(codec)
val pcm = ShortArray(Lc3PacketFramer.SAMPLES_PER_PACKET)
framer.decodePacket(packet(7, ssr = -1234, angle = -45), pcm)
assertEquals(-1234, framer.lastSsr)
assertEquals(-45, framer.lastAngleDegrees)
assertEquals(0, framer.decodePacket(ByteArray(10), pcm))
assertEquals(0, framer.decodePacket(null, pcm))
assertEquals(2, framer.decodeErrors)
assertFailsWith<IllegalArgumentException> { framer.decodePacket(packet(8), ShortArray(10)) }
codec.fail = true
assertEquals(0, framer.decodePacket(packet(8), pcm))
assertEquals(3, framer.decodeErrors)
// A failed decode does not advance the counter, so 8 is still accepted afterwards.
codec.fail = false
assertEquals(800, framer.decodePacket(packet(8), pcm))
assertEquals(2, framer.realPackets)
}
}
@@ -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)
}
}
@@ -0,0 +1,297 @@
package com.faceclaw.app
import kotlin.random.Random
import kotlin.test.*
internal expect fun testPlatform(): ProtocolPlatform
internal expect fun inflateRecords(records: List<ByteArray>): List<ByteArray>
internal fun record(packets: List<ByteArray>): ByteArray =
packets.flatMap { it.slice(9 until it.size - 2) }.toByteArray()
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun u16(bytes: ByteArray, offset: Int) =
(bytes[offset].toInt() and 255) or ((bytes[offset + 1].toInt() and 255) shl 8)
class ProtocolTest {
@Test
fun javaGoldenPacketsAndCrc() {
assertEquals(0x29b1, CfwTransport.crc("123456789".encodeToByteArray()))
assertEquals(0xffff, CfwTransport.crc(byteArrayOf()))
// Captured from the Java implementation before migration, including sequence wrap.
val expected =
listOf(
"aa21ff0c0101f000830b0f0078c331323334862b",
"aa21000c0101f000033536373839616263648c7b",
"aa2101050101f000436566de70",
)
val actual = CfwTransport.frame("123456789abcdef".encodeToByteArray(), 255, 3, 23)
assertEquals(expected.size, actual.size)
expected.zip(actual).forEach { (a, b) -> assertContentEquals(hex(a), b) }
}
@Test
fun framingBoundariesAndValidation() {
for (size in listOf(0, 1, 247, 252, 253, 65535)) {
val data = ByteArray(size) { it.toByte() }
for (mtu in listOf(23, 247, 512, 517)) {
val packets = CfwTransport.frame(data, 255, 2, mtu)
packets.forEachIndexed { i, packet ->
assertTrue(packet.size <= mtu - 3)
assertEquals((255 + i) and 255, packet[2].toInt() and 255)
assertEquals(packet.size - 8, packet[3].toInt() and 255)
assertEquals(
2 or (if (i == 0) 128 else 0) or (if (i == packets.lastIndex) 64 else 0),
packet[8].toInt() and 255,
)
assertEquals(
CfwTransport.crc(packet.copyOfRange(8, packet.size - 2)),
u16(packet, packet.size - 2),
)
}
val stream = record(packets)
assertEquals(size, u16(stream, 1))
assertEquals(CfwTransport.crc(data), u16(stream, 3))
assertContentEquals(data, stream.copyOfRange(5, stream.size))
}
}
for (invalid in listOf<ByteArray?>(null, ByteArray(65536))) assertFailsWith<
IllegalArgumentException
> {
CfwTransport.frame(invalid, 0, 3, 23)
}
for (stream in listOf(-1, 256)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), stream, 3, 23)
}
for (lens in listOf(0, 4)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, lens, 23)
}
for (mtu in listOf(22, 518)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, 3, mtu)
}
}
@Test
fun streamingCompressionRoundTripsAndResets() {
val transport = CfwTransport(testPlatform())
try {
val text = "shared history 👓 ".repeat(300).encodeToByteArray()
val inputs = listOf(text, text, byteArrayOf(), byteArrayOf(), text, text)
val records = inputs.mapIndexed { i, data ->
if (i == 5) transport.reset()
record(transport.encode(data, i, if (i < 4) 3 else 1, 247))
}
assertTrue(records[1].size < records[0].size)
assertTrue(records[0][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertEquals(0, records[1][0].toInt() and CfwTransport.RESET_CONTEXT)
assertTrue(records[4][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertTrue(records[5][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
inputs.zip(inflateRecords(records)).forEach { (a, b) -> assertContentEquals(a, b) }
transport.close()
transport.close()
val reopened = record(transport.encode(text, 10, 1, 512))
assertTrue(reopened[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertContentEquals(text, inflateRecords(listOf(reopened)).single())
} finally {
transport.close()
}
}
@Test
fun incompressibleMaximumFallsBackWithoutPoisoningHistory() {
val transport = CfwTransport(testPlatform())
try {
val data = Random(42).nextBytes(65535)
val raw = record(transport.encode(data, 255, 3, 517))
assertEquals(3 or CfwTransport.RESET_CONTEXT, raw[0].toInt())
val next = record(transport.encode(data.copyOf(1000), 0, 3, 517))
assertTrue(next[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
val decoded = inflateRecords(listOf(raw, next))
assertContentEquals(data, decoded[0])
assertContentEquals(data.copyOf(1000), decoded[1])
} finally {
transport.close()
}
}
@Test
fun ackBatchesAndMalformedPackets() {
for (count in 1..4) {
val packet = ackPacket(count)
val acks = assertNotNull(CfwTransport.parseAcks(packet))
assertEquals(count, acks.size)
acks.forEachIndexed { i, ack ->
assertFalse(ack.nack)
assertEquals(255 - i, ack.streamId)
assertEquals(0x1234 + i, ack.messageId)
assertEquals(2, ack.lens)
assertEquals(0x4567 + i, ack.size)
assertEquals(0xabcd + i, ack.checksum)
}
assertEquals(255, assertNotNull(CfwTransport.parseAck(packet)).streamId)
// Every bit of the payload (including ACK trailers and CRC) is protected.
for (i in 8 until packet.size) {
val corrupt = packet.copyOf()
corrupt[i] = (corrupt[i].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
}
assertTrue(assertNotNull(CfwTransport.parseAck(ackPacket(1, 3))).nack)
assertNull(CfwTransport.parseAcks(ackPacket(2, 3)))
assertNull(CfwTransport.parseAcks(ackPacket(5)))
assertNull(CfwTransport.parseAcks(ackPacket(1, 2)))
for (index in listOf(0, 1, 3, 4, 5, 6, 7)) {
val corrupt = ackPacket(1)
corrupt[index] = (corrupt[index].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
val wrongLens = ackPacket(1)
wrongLens[12] = 3
sealAck(wrongLens)
assertNull(CfwTransport.parseAcks(wrongLens))
for (size in 0..18) assertNull(CfwTransport.parseAcks(ByteArray(size)))
assertNull(CfwTransport.parseAcks(null))
}
@Test
fun ackMatchingAndReplay() {
val input = byteArrayOf(1, 2, 3)
val message = message(input = input)
input[0] = 99
assertContentEquals(byteArrayOf(1, 2, 3), message.message)
fun ack(
lens: Int,
stream: Int = 100,
nack: Boolean = false,
size: Int = 3,
checksum: Int = message.cfwChecksum,
id: Int = 0,
) = CfwTransport.Ack(nack, stream, id, lens, size, checksum)
assertFalse(message.acceptCfwAck(null))
assertFalse(message.acceptCfwAck(ack(1, stream = 99)))
assertFalse(message.acceptCfwAck(ack(1, size = 4)))
assertFalse(message.acceptCfwAck(ack(1, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(3)))
assertFalse(message.acceptCfwAck(ack(1, id = 1)))
assertEquals(0, message.cfwAckLenses)
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1)))
assertTrue(message.acceptCfwAck(ack(2)))
assertFalse(message.acceptCfwAck(ack(1, nack = true, size = 0, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(2)))
message.ackDeadlineAtMs = 500
message.ackPayload = byteArrayOf(1)
message.prepareCfwReplay(101)
assertEquals(1, message.cfwRetries)
assertFalse(message.cfwRetryPending)
assertEquals(0, message.cfwAckLenses)
assertEquals(0L, message.ackDeadlineAtMs)
assertTrue(message.ackPayload.isEmpty())
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1, stream = 101)))
assertTrue(message.acceptCfwAck(ack(2, stream = 101)))
var callbacks = 0
message.onAck = MessageCallback { callbacks++ }
message.onAck!!.run()
assertEquals(1, callbacks)
}
@Test
fun evictionWaitsForAllEarlierReplayableCommands() {
val earlier = message(input = byteArrayOf(19, 0, 0))
val eviction = message(input = byteArrayOf(22, 1, 0, 0, 0))
val upload = message(input = byteArrayOf(21, 1, 0))
assertFalse(CfwMessageWindow.canSend(listOf(earlier), eviction))
earlier.cfwAckLenses = 3 // Still retained behind an unresolved window head.
assertFalse(CfwMessageWindow.canSend(listOf(earlier), eviction))
assertTrue(CfwMessageWindow.canSend(emptyList(), eviction))
assertTrue(CfwMessageWindow.canSend(listOf(message(sid = 1)), eviction))
assertTrue(CfwMessageWindow.canSend(listOf(earlier), upload))
assertTrue(CfwMessageWindow.canSend(listOf(eviction), upload))
}
@Test
fun orderedCompletionAndWholeWindowRecovery() {
val head = message()
val tail = message()
val stock = message(sid = 1)
val window = listOf(stock, head, tail)
tail.cfwAckLenses = 3
assertNull(CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
head.ackDeadlineAtMs = 100
assertTrue(CfwMessageWindow.replayWindow(window, 99).isEmpty())
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwAckLenses = 3
assertSame(head, CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
tail.cfwRetryPending = true
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwRetryPending = true
assertNull(CfwMessageWindow.acknowledgedHead(window))
}
@Test
fun magicPoolExhaustionLruAndReleaseRecords() {
var now = 123L
val platform =
object : ProtocolPlatform by testPlatform() {
override fun elapsedRealtimeMs() = now
}
val pool = BleMagicPool(platform)
assertEquals((100..255).toList(), List(156) { pool.allocate() })
assertFailsWith<IllegalStateException> { pool.allocate() }
pool.release(1, 101, "first", "ack")
pool.release(1, 100, null, null)
now = 456
pool.release(2, 101, "other", "timeout") // duplicate release must not allocate twice
assertEquals(101, pool.allocate())
assertEquals(100, pool.allocate())
assertFailsWith<IllegalStateException> { pool.allocate() }
val first = assertNotNull(pool.getReleaseRecord(1, 101))
assertEquals(123L, first.releasedAtMs)
assertEquals("first", first.label)
assertEquals(456L, assertNotNull(pool.getReleaseRecord(2, 101)).releasedAtMs)
assertEquals("", assertNotNull(pool.getReleaseRecord(1, 100)).reason)
for (invalid in listOf(-1, 99, 256)) {
pool.release(1, invalid, "bad", "bad")
assertNull(pool.getReleaseRecord(1, invalid))
}
}
}
private fun message(sid: Int = CfwTransport.SID, input: ByteArray = byteArrayOf(1, 2, 3)) =
OutboundMessage("test", "test", sid, 0, 100, input, 500, 0, false)
private fun ackPacket(count: Int, kind: Int = 1): ByteArray {
val packet = ByteArray(19 + (count - 1) * 7)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = (packet.size - 8).toByte()
packet[4] = 1
packet[5] = 1
packet[6] = 0xf0.toByte()
packet[8] = kind.toByte()
packet[12] = 2
fun put16(offset: Int, value: Int) {
packet[offset] = value.toByte()
packet[offset + 1] = (value ushr 8).toByte()
}
for (i in 0 until count) {
val offset = if (i == 0) 9 else 17 + (i - 1) * 7
packet[offset] = (255 - i).toByte()
put16(offset + 1, 0x1234 + i)
put16(offset + (if (i == 0) 4 else 3), 0x4567 + i)
put16(offset + (if (i == 0) 6 else 5), 0xabcd + i)
}
sealAck(packet)
return packet
}
private fun sealAck(packet: ByteArray) {
val crc = CfwTransport.crc(packet.copyOfRange(8, packet.size - 2))
packet[packet.size - 2] = crc.toByte()
packet[packet.size - 1] = (crc ushr 8).toByte()
}
@@ -0,0 +1,178 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
private class FakeConnection(input: String, private val bytesOverride: ByteArray? = null) : RemoteInputConnection {
private val bytes = bytesOverride ?: input.encodeToByteArray()
private var index = 0
private val written = ByteSink()
var closed = false
val output: String get() = written.toByteArray().decodeToString()
override fun readByte(timeoutMs: Long): Int = if (index < bytes.size) bytes[index++].toInt() and 255 else -1
override fun write(bytes: ByteArray) = written.write(bytes)
override fun close() { closed = true }
}
private class FakePort(platform: ProtocolPlatform) : LocalServerPort {
val connections = BlockingQueue<FakeConnection>(platform)
var localAddresses = setOf("127.0.0.1", "192.168.1.5")
var bindFails = false
var listener: FakeListener? = null
inner class FakeListener : RemoteInputListener {
override var isClosed = false
override fun accept(): RemoteInputConnection? {
while (!isClosed) {
val next = connections.poll(20)
if (next != null) return next
}
return null
}
override fun close() { isClosed = true }
}
override fun isLocalUnicastAddress(address: String): Boolean = address in localAddresses
override fun bind(address: String, port: Int): RemoteInputListener {
if (bindFails) throw IllegalStateException("in use")
return FakeListener().also { listener = it }
}
}
private fun waitFor(timeoutMs: Long = 3000, condition: () -> Boolean): Boolean {
val platform = testPlatform()
val deadline = platform.elapsedRealtimeMs() + timeoutMs
while (platform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(5)
}
return condition()
}
class RemoteInputSessionTest {
private val platform = testPlatform()
private val random = object : RandomSource { override fun nextBytes(count: Int) = ByteArray(count) { it.toByte() } }
private fun dispatchOnThread(action: () -> Unit) = startThread("remote-input-dispatch", true, action)
private fun session(port: FakePort, requestTimeoutMs: Long = 5000, readTimeoutMs: Long = 5000) =
RemoteInputSession(port, random, ::dispatchOnThread, platform, requestTimeoutMs = requestTimeoutMs, readTimeoutMs = readTimeoutMs)
@Test
fun startValidatesAddressesAndBindFailures() {
val port = FakePort(platform)
val session = session(port)
assertEquals("Invalid local address.", session.start(7000, "localhost"))
assertEquals("Address is not assigned to a local interface.", session.start(7000, "10.0.0.9"))
port.bindFails = true
assertEquals("Could not open local input port 7000.", session.start(7000, "127.0.0.1"))
port.bindFails = false
assertEquals("", session.start(7000, "127.0.0.1"))
assertEquals("", session.start(7000, "127.0.0.1"), "second start is a no-op")
session.stop()
assertTrue(waitFor { port.listener!!.isClosed })
assertTrue(RemoteInputSession.isNumericLocalAddress("fe80::1%en0"))
assertFalse(RemoteInputSession.isNumericLocalAddress("example.com"))
}
@Test
fun requestIsPublishedAnsweredAndWrittenBack() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("{\"token\":\"t\",\"text\":\"hi\"}\n")
port.connections.put(connection)
assertTrue(waitFor { notified == 1 })
val pending = Json.parseObject(session.nextRequest()!!)
assertEquals(1L, pending["id"].asLong())
assertEquals("{\"token\":\"t\",\"text\":\"hi\"}", pending["body"].asString())
assertTrue(pending["expiresAt"].asLong()!! > currentTimeMillis())
assertNull(session.nextRequest(), "consumed once")
session.complete(99L, "{\"ok\":false}")
assertFalse(waitFor(100) { connection.output.isNotEmpty() }, "wrong id is ignored")
session.complete(1L, "{\"ok\":true}")
assertTrue(waitFor { connection.output == "{\"ok\":true}\n" })
assertTrue(waitFor { connection.closed })
session.stop()
}
@Test
fun timeoutRepliesWithTheTimeoutResponse() {
val port = FakePort(platform)
val session = session(port, requestTimeoutMs = 150)
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("slow\n")
port.connections.put(connection)
assertTrue(waitFor { connection.output == RemoteInputSession.TIMEOUT_RESPONSE + "\n" })
assertNull(session.nextRequest(), "expired request is dropped")
session.stop()
}
@Test
fun oversizedAndIncompleteFramesGetNoReply() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val huge = FakeConnection("", ByteArray(RemoteInputSession.MAX_FRAME_BYTES + 2) { 'a'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() })
port.connections.put(huge)
assertTrue(waitFor { huge.closed })
assertEquals("", huge.output)
val partial = FakeConnection("no newline")
port.connections.put(partial)
assertTrue(waitFor { partial.closed })
assertEquals("", partial.output)
val invalidUtf8 = FakeConnection("", byteArrayOf(0xff.toByte(), 0xfe.toByte(), '\n'.code.toByte()))
port.connections.put(invalidUtf8)
assertTrue(waitFor { invalidUtf8.closed })
assertEquals("", invalidUtf8.output)
assertEquals(0, notified)
assertNull(session.nextRequest())
session.stop()
}
@Test
fun stopWhilePendingReleasesTheServingThread() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("pending\n")
port.connections.put(connection)
assertTrue(waitFor { notified == 1 })
session.stop()
assertTrue(waitFor { connection.closed })
assertNull(session.nextRequest())
assertEquals("", session.start(7001, "127.0.0.1"), "restart after stop")
session.stop()
}
@Test
fun helpersFilterInterfacesAndHashTokens() {
val all = listOf(
InterfaceAddress("lo0", "127.0.0.1", up = true, pointToPoint = false, loopback = true, linkLocal = false, anyLocal = false),
InterfaceAddress("wlan0", "192.168.1.5", up = true, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("wlan0", "fe80::1%wlan0", up = true, pointToPoint = false, loopback = false, linkLocal = true, anyLocal = false),
InterfaceAddress("tun0", "100.64.0.2", up = true, pointToPoint = true, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("eth0", "10.0.0.2", up = false, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("any", "0.0.0.0", up = true, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = true),
)
assertEquals(
"[{\"name\":\"wlan0\",\"address\":\"192.168.1.5\",\"pointToPoint\":false},{\"name\":\"tun0\",\"address\":\"100.64.0.2\",\"pointToPoint\":true}]",
RemoteInputSession.interfacesJson(all),
)
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", RemoteInputSession.tokenHash("abc"))
val session = session(FakePort(platform))
assertEquals("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", session.randomSecret())
}
}
@@ -0,0 +1,211 @@
package com.faceclaw.app
import kotlin.test.*
class ResourceCacheTest {
private fun resource(size: Int, value: Int) = CachedResource(ByteArray(size) { value.toByte() })
private fun u16(bytes: ByteArray, offset: Int) = (bytes[offset].toInt() and 255) or ((bytes[offset + 1].toInt() and 255) shl 8)
private fun u32(bytes: ByteArray, offset: Int) = u16(bytes, offset) or (u16(bytes, offset + 2) shl 16)
private fun uploaded(commands: List<ByteArray>): Map<Int, ByteArray> {
val resources = HashMap<Int, ByteArray>()
val received = HashMap<Int, Int>()
for (command in commands) {
assertTrue(command.size <= 3600)
if (command[0].toInt() != 21) continue
var pos = 3
val seen = HashSet<Int>()
repeat(u16(command, 1)) {
val id = u16(command, pos)
assertTrue(id in 0..511 && seen.add(id))
val total = u32(command, pos + 2)
val offset = u16(command, pos + 6)
val length = u16(command, pos + 8)
assertEquals(received[id] ?: 0, offset)
val bytes = resources.getOrPut(id) { ByteArray(total) }
command.copyInto(bytes, offset, pos + 10, pos + 10 + length)
received[id] = offset + length
pos += 10 + length
}
assertEquals(command.size, pos)
}
resources.forEach { (id, data) -> assertEquals(data.size, received[id]) }
return resources
}
@Test fun contentAddressingAndWireVector() {
val cache = ResourceCacheState()
val image = CachedResource(byteArrayOf(1, 1, 31))
val ids = cache.prepare(listOf(image, CachedResource(image.bytes)))
assertContentEquals(intArrayOf(0, 0), ids)
val commands = cache.drainCommands(3600)
assertEquals(22, commands.first()[0].toInt())
assertEquals(512, u16(commands.first(), 1))
assertEquals(511, u16(commands.first(), 1025))
assertContentEquals(byteArrayOf(21, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 1, 1, 31), commands.last())
assertContentEquals(image.bytes, uploaded(commands).getValue(0))
assertEquals(2068, cache.usedBytes())
assertEquals(0, cache.prepare(listOf(image))[0])
assertTrue(cache.drainCommands(3600).isEmpty())
cache.reset(); cache.prepare(listOf(image))
assertEquals(22, cache.drainCommands(3600).first()[0].toInt())
}
@Test fun exactly64KiBUploadsInBoundedContiguousChunks() {
val cache = ResourceCacheState()
val data = CachedResource(ByteArray(65536) { (it * 37).toByte() })
assertEquals(0, cache.prepare(listOf(data))[0])
val commands = cache.drainCommands(3600)
assertTrue(commands.count { it[0].toInt() == 21 } > 1)
assertContentEquals(data.bytes, uploaded(commands).getValue(0))
assertEquals(-1, cache.prepare(listOf(resource(65537, 1)))[0])
assertTrue(cache.drainCommands(3600).isEmpty())
assertEquals(0, cache.resourceId(data))
}
@Test fun lruEvictsByBytesAndProtectsAllCurrentFrameHits() {
val cache = ResourceCacheState()
val a = resource(60000, 1); val b = resource(60000, 2); val c = resource(60000, 3); val d = resource(60000, 4)
assertContentEquals(intArrayOf(0, 1, 2), cache.prepare(listOf(a, b, c)))
cache.drainCommands(3600)
cache.prepare(listOf(a)); cache.drainCommands(3600) // b is oldest now.
assertContentEquals(intArrayOf(1, 2), cache.prepare(listOf(d, c))) // protect later hit c before d.
val commands = cache.drainCommands(3600)
assertContentEquals(byteArrayOf(22, 1, 0, 1, 0), commands.first())
assertEquals(-1, cache.resourceId(b))
assertEquals(0, cache.resourceId(a)); assertEquals(2, cache.resourceId(c))
assertEquals(1, cache.resourceId(d))
assertContentEquals(d.bytes, uploaded(commands).getValue(1))
val tooLarge = cache.prepare(listOf(a, c, d, b))
assertEquals(-1, tooLarge.last())
assertTrue(cache.drainCommands(3600).isEmpty())
assertEquals(3, cache.residentCount())
}
@Test fun idPressureUsesLruEvenWhenBytesAreAvailable() {
val cache = ResourceCacheState()
val resources = (0..512).map { CachedResource(byteArrayOf(it.toByte(), (it ushr 8).toByte())) }
assertContentEquals(IntArray(512) { it }, cache.prepare(resources.take(512)))
cache.drainCommands(3600)
cache.prepare(listOf(resources[0])); cache.drainCommands(3600)
assertEquals(1, cache.prepare(listOf(resources[512]))[0])
val commands = cache.drainCommands(3600)
assertContentEquals(byteArrayOf(22, 1, 0, 1, 0), commands.first())
assertEquals(0, cache.resourceId(resources[0]))
assertEquals(-1, cache.resourceId(resources[1]))
}
@Test fun rejectedPlansRestoreResidencyAndLru() {
val cache = ResourceCacheState()
val resources = (0..3).map { resource(65536, it) }
cache.prepare(resources.take(3)); cache.drainCommands(3600)
val rollback = cache.checkpoint()
cache.prepare(listOf(resources[3]))
assertEquals(-1, cache.resourceId(resources[0]))
rollback()
assertEquals(0, cache.resourceId(resources[0])); assertEquals(-1, cache.resourceId(resources[3]))
assertTrue(cache.drainCommands(3600).isEmpty())
cache.prepare(listOf(resources[3]))
assertContentEquals(byteArrayOf(22, 1, 0, 0, 0), cache.drainCommands(3600).first())
}
@Test fun imagePlannerEmitsResourceIdsAndReusesResidency() {
val cache = ResourceCacheState()
val id = ImageAtlas.ensure("resource-test-white", 2, 2, ArrayByteReader(ByteArray(4) { -1 }))
val pixels = ByteArray(8 * 4)
for (y in 0..1) for (x in 0..1) pixels[y * 8 + x] = -1
val packed = BmpUtil.pack4bppFromGray8(pixels, 8, 4)
val draws = arrayOf(SurfaceCompositor.ScreenDraw.image(id, 0, 0))
fun plan() = assertNotNull(TexturePlanner.plan(null, packed, 8, 4, draws, cache, 1, true, 8, testPlatform()))
val cold = plan()
assertEquals(1, cold.drawnImages)
assertContentEquals(byteArrayOf(19, 0, 0, 0, 0, 0, 0, 31), cold.payload.takeLast(8).toByteArray())
assertTrue(cold.resourceCommands.isNotEmpty())
val warm = plan()
assertTrue(warm.resourceCommands.isEmpty()); assertContentEquals(cold.payload, warm.payload)
cache.reset(); assertTrue(plan().resourceCommands.isNotEmpty())
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)
out.write(encodings.size); out.write(0)
for (encoding in encodings) {
out.write(encoding); repeat(3) { out.write(0) }
out.write(0); out.write(0); out.write(size); out.write(size)
repeat(size * ((size + 1) / 2)) { out.write(0x12) }
}
GlyphAtlas.registerAa(ArrayByteReader(out.toByteArray()))
return GlyphAtlas.fontId(key)
}
@Test fun fontTablesUseRelativeU16OffsetsAndGrowOnDemand() {
val id = registerFont("resource-font-relative", listOf(65, 66))
val first = FontResourceAtlas.get(id, setOf(65))
assertEquals(193, u16(first.resource.bytes, 1 + (65 - 32) * 2))
assertEquals(0, u16(first.resource.bytes, 1 + (66 - 32) * 2))
assertSame(first, FontResourceAtlas.get(id, setOf(65)))
val second = FontResourceAtlas.get(id, setOf(66))
assertTrue(second.encodings.containsAll(setOf(65, 66)))
assertEquals(193 + GlyphAtlas.get(id, 65)!!.cachedBytes.size, u16(second.resource.bytes, 1 + (66 - 32) * 2))
val cache = ResourceCacheState()
cache.prepare(listOf(second.resource)); val commands = cache.drainCommands(3600)
assertContentEquals(second.resource.bytes, uploaded(commands).getValue(0))
}
@Test fun oversizedFontsPrioritizeTheCurrentFrameWithin64KiB() {
val id = registerFont("resource-font-limit", listOf(65, 66), 255)
val a = FontResourceAtlas.get(id, setOf(65))
assertEquals(setOf(65), a.encodings)
val b = FontResourceAtlas.get(id, setOf(66))
assertEquals(setOf(66), b.encodings)
assertTrue(b.resource.bytes.size <= 65536)
assertEquals(0, u16(b.resource.bytes, 1 + (65 - 32) * 2))
assertEquals(193, u16(b.resource.bytes, 1 + (66 - 32) * 2))
}
}
@@ -0,0 +1,149 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ResumableDownloadTest {
private class Storage : DownloadStorage {
val files = HashMap<String, ByteArray>()
override fun length(path: String): Long = files[path]?.size?.toLong() ?: -1L
override fun prepareParent(path: String) {}
override fun openWrite(path: String, append: Boolean): FileSink {
if (!append) files[path] = ByteArray(0)
return object : FileSink {
override fun write(bytes: ByteArray, offset: Int, length: Int) {
files[path] = (files[path] ?: ByteArray(0)) + bytes.copyOfRange(offset, offset + length)
}
override fun close() {}
}
}
override fun readAll(path: String, consumer: (ByteArray, Int) -> Boolean): Long {
val data = files[path] ?: return 0
var at = 0L
for (chunk in data.toList().chunked(7)) {
val bytes = chunk.toByteArray()
if (!consumer(bytes, bytes.size)) break
at += bytes.size
}
return at
}
override fun rename(from: String, to: String): Boolean { files[to] = files.remove(from) ?: return false; return true }
override fun delete(path: String): Boolean = files.remove(path) != null
}
private class Transport(val content: ByteArray, val honorRange: Boolean = true, val truncateAt: Int = -1) : DownloadTransport {
var lastRange = -1L
override fun open(url: String, rangeFrom: Long): DownloadResponse {
lastRange = rangeFrom
val start = if (honorRange) rangeFrom.toInt() else 0
val end = if (truncateAt >= 0) minOf(truncateAt, content.size) else content.size
val body = content.copyOfRange(start, end)
var at = 0
return object : DownloadResponse {
override val code: Int = if (honorRange && rangeFrom > 0) 206 else 200
override val contentLength: Long = body.size.toLong()
override fun read(buffer: ByteArray): Int {
if (at >= body.size) return -1
val n = minOf(5, body.size - at)
body.copyInto(buffer, 0, at, at + n)
at += n
return n
}
override fun close() {}
}
}
}
private class Events : FaceclawModelDownloaderListener {
val progress = ArrayList<Pair<Long, Long>>()
var done: String? = null
var error: String? = null
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { progress.add(bytesDownloaded to totalBytes) }
override fun onDone(path: String?) { done = path }
override fun onError(message: String?) { error = message }
}
private val content = ByteArray(40) { (it * 3).toByte() }
private val sha = sha256Hex(content)
private fun run(storage: Storage, transport: Transport, expectedSha: String? = sha, total: Long = content.size.toLong()): Events {
val events = Events()
var clock = 0L
ResumableDownload("http://x/m", "/dest/model", expectedSha, total, transport, storage, events) { clock += 600; clock }.run()
return events
}
@Test
fun freshDownloadVerifiesAndRenames() {
val storage = Storage()
val transport = Transport(content)
val events = run(storage, transport)
assertNull(events.error)
assertEquals("/dest/model", events.done)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
assertEquals(0L, transport.lastRange)
assertTrue(events.progress.isNotEmpty() && events.progress.last().second == 40L)
val again = run(storage, transport)
assertEquals("/dest/model", again.done)
}
@Test
fun resumesFromPartWhenServerHonorsRange() {
val storage = Storage()
storage.files["/dest/model.part"] = content.copyOfRange(0, 17)
val transport = Transport(content)
val events = run(storage, transport)
assertEquals(17L, transport.lastRange)
assertNull(events.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun restartsWhenServerIgnoresRange() {
val storage = Storage()
storage.files["/dest/model.part"] = ByteArray(17) { 1 }
val transport = Transport(content, honorRange = false)
val events = run(storage, transport)
assertEquals(17L, transport.lastRange)
assertNull(events.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun checksumMismatchDeletesPart() {
val storage = Storage()
val events = run(storage, Transport(content), expectedSha = "00".repeat(32))
assertEquals("Model download was corrupted (checksum mismatch); download it again", events.error)
assertNull(storage.files["/dest/model.part"])
assertNull(storage.files["/dest/model"])
}
@Test
fun shortBodyKeepsPartForResume() {
val storage = Storage()
val events = run(storage, Transport(content, truncateAt = 30))
assertEquals("Model download ended early (30 of 40 bytes); try again to resume", events.error)
assertEquals(30, storage.files["/dest/model.part"]!!.size)
val resumed = run(storage, Transport(content))
assertNull(resumed.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun httpErrorIsReported() {
val storage = Storage()
val transport = object : DownloadTransport {
override fun open(url: String, rangeFrom: Long): DownloadResponse = object : DownloadResponse {
override val code = 404
override val contentLength = -1L
override fun read(buffer: ByteArray) = -1
override fun close() {}
}
}
val events = Events()
ResumableDownload("u", "/dest/model", null, 0, transport, storage, events).run()
assertEquals("Model download failed: HTTP 404", events.error)
}
}
@@ -0,0 +1,240 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private const val RING = "CC:00:00:00:00:03"
/**
* A ring that answers health requests through the session's real notification
* path: each REQ gets DATA page `cmd*10+1`, then its RSP; the ACK for a page
* ending in 1 triggers page `+1`, so the transfer is ACK-paced like the real
* ring's backlog.
*/
private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = platform.createLock()
private val writesList = ArrayList<String>()
@Volatile var failAck = false
@Volatile var answer = true
@Volatile var delayRsp = false
@Volatile var requestStarted = false
val writes: List<String>
get() = lock.withLock { writesList.toList() }
private fun deliver(frame: ByteArray) = core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, frame)
private fun page(cmdHi: Int, pageSeq: Int) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, pageSeq, byteArrayOf(0, 0)))
private fun rsp(cmdHi: Int) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0, byteArrayOf(0, 0)))
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
assertEquals(RING, address)
assertEquals(BleProtocol.R1_WRITE_CHAR_UUID, characteristicUuid)
val frame = RingProtocol.parse(frames.single())!!
if (frame.kind == RingProtocol.KIND_ACK) {
if (failAck) return false
val pageSeq = frame.payload[6].toInt() and 0xff
val cmdHi = frame.payload[3].toInt() and 0xff
lock.withLock { writesList.add("ack:$pageSeq") }
// A write longer than the idle timeout: page two arrives only
// after page one's ACK has actually completed.
sleepMs(130)
if (pageSeq % 10 == 1) {
startThread("ring-page", true) {
sleepMs(5)
page(cmdHi, pageSeq + 1)
}
}
} else if (frame.chan == RingProtocol.CHAN_HEALTH && frame.kind == RingProtocol.KIND_REQ) {
requestStarted = true
lock.withLock { writesList.add("req:" + frame.cmdHi) }
if (answer) {
page(frame.cmdHi, frame.cmdHi * 10 + 1)
if (delayRsp) {
startThread("ring-rsp", true) {
sleepMs(20)
rsp(frame.cmdHi)
}
} else {
rsp(frame.cmdHi)
}
}
}
// Device-channel pings between health types are not answered.
return true
}
override fun connect(address: String, timeoutMs: Int): Boolean = true
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun disconnect(address: String) {}
override fun close() {}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class RingHost : SessionHost {
@Volatile var journalFails = false
val journal = ArrayList<String>()
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {}
override fun joinWorker(timeoutMs: Long) {}
override fun supportsRingHealth(): Boolean = true
override fun appendRingFrameJournal(line: String) {
if (journalFails) throw IllegalStateException("disk full")
synchronizedAdd(line)
}
private val lock = testPlatform().createLock()
private fun synchronizedAdd(line: String) = lock.withLock { journal.add(line) }
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {}
}
/** A core whose ring link is up, without running the glasses worker. */
private class RingSession {
val platform = testPlatform()
val link = FakeRingLink(platform)
val host = RingHost()
val core = GlassesSessionCore(link, host, FrameTimingsCore(platform), platform,
"AA:00:00:00:00:01", "AA:00:00:00:00:02", RING)
init {
link.core = core
core.ringHealthRspTimeoutMs = 500
core.ringHealthDataIdleMs = 100
core.monitor.withLock {
core.running = true
core.ringConnected = true
core.ringNotificationsReady = true
}
}
fun outboundSize(): Int = core.monitor.withLock { core.ringOutbound.size }
}
class RingHealthTransferTest {
@Test fun shutdownCancelsAnRspWait() {
val s = RingSession()
s.link.answer = false
s.core.ringHealthRspTimeoutMs = 10_000
val done = Latch(1, s.platform)
startThread("ring-pull", true) {
s.core.requestRingHealth()
done.countDown()
}
val deadline = s.platform.elapsedRealtimeMs() + 1000
while (!s.link.requestStarted && s.platform.elapsedRealtimeMs() < deadline) sleepMs(5)
assertTrue(s.link.requestStarted, "no request")
val start = s.platform.elapsedRealtimeMs()
s.core.monitor.withLock {
s.core.running = false
s.core.monitor.signalAll()
}
assertTrue(done.await(300), "ring pull did not stop")
assertTrue(s.platform.elapsedRealtimeMs() - start < 300, "session lock blocked")
}
@Test fun ackPacedPagesDrainBeforeTheNextType() {
val s = RingSession()
s.link.delayRsp = true
assertTrue(s.core.requestRingHealth(), "pull failed")
val expected = RingProtocol.HEALTH_COMMANDS.flatMap { command ->
listOf("req:$command", "ack:" + (command * 10 + 1), "ack:" + (command * 10 + 2))
}
assertEquals(expected, s.link.writes, "premature next type")
// Every intact frame (each page and each RSP) was journaled.
assertEquals(expected.count { it.startsWith("ack:") } + RingProtocol.HEALTH_COMMANDS.size, s.host.journal.size)
}
@Test fun failedAckAbortsAndStaysQueuedForRetry() {
val s = RingSession()
s.link.failAck = true
assertFalse(s.core.requestRingHealth(), "failed ACK completed pull")
assertEquals(1, s.link.writes.size, "advanced after failed ACK")
assertEquals(1, s.outboundSize(), "failed ACK was discarded")
s.link.failAck = false
assertTrue(s.core.awaitRingHealthDataIdle(s.core.ringHealthDataIdleMs), "retry failed")
assertEquals(0, s.outboundSize(), "retry did not drain ACKs")
}
@Test fun missingRspAbortsWithoutAdvancing() {
val s = RingSession()
s.link.answer = false
assertFalse(s.core.requestRingHealth(), "missing RSP completed pull")
assertEquals(1, s.link.writes.size, "advanced without RSP")
}
@Test fun disconnectFailsTheDataWait() {
val s = RingSession()
s.core.monitor.withLock { s.core.ringConnected = false }
assertFalse(s.core.awaitRingHealthDataIdle(100), "disconnect completed transfer")
}
@Test fun unjournaledPageIsNotAcknowledged() {
val s = RingSession()
s.host.journalFails = true
s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, 7, byteArrayOf(0, 0)))
assertEquals(0, s.outboundSize())
}
@Test fun batchWatermarkOnlyClearsWhatWasTaken() {
val s = RingSession()
// A decodable one-group heart-rate page: count 1, tz 0, anchor 1000, then [hour][avg][max][min].
val payload = byteArrayOf(0, 0, 1, 0, 0, 0xe8.toByte(), 0x03, 0, 0, 2, 60, 70, 50)
fun deliver(seq: Int) = s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, seq, payload))
deliver(1)
deliver(2)
val batch = s.core.takeRingHealthBatch()
assertEquals(2, batch.records.size)
assertEquals(2L, batch.watermark)
deliver(3)
assertEquals(2, s.core.clearRingHealthRecordsBelow(batch.watermark))
val rest = s.core.getRingHealthRecords()
assertEquals(1, rest.size)
val record = rest.single() as RingProtocol.HourlyRecord
assertEquals(60, record.groups.single().avg)
assertEquals(1000L + 2 * 3600L, record.groups.single().unixSeconds)
}
}
@@ -0,0 +1,37 @@
package com.faceclaw.app
import kotlin.test.*
class RingInputTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
// Exact packet emitted by the emulated CFW receiver, including a tick > INT_MAX.
private val packet = hex("08026a151a13080e1002a2060c524901010aabcd00efcdab89")
@Test fun preservesOriginalClockAndRawFieldsThroughTheNativeDecoder() {
val decoded = assertNotNull(G2Event.decodePayload(224, packet))
assertEquals("sys-event", decoded.kind)
assertEquals(14, decoded.eventType)
assertEquals(2, decoded.eventSource)
assertEquals(0x89abcdefL, decoded.ringTick)
assertEquals(10, decoded.ringType)
assertEquals(171, decoded.ringAux)
assertEquals(205, decoded.ringSpeed)
// Exercise framing and CRC removal too (Android's entry point).
val frame = BleProtocol.framePb(packet, 224, 1, 1).single()
val native = assertNotNull(G2Event.decode(BleProtocol.parseFrame(frame)))
assertEquals(decoded.ringTick, native.ringTick)
}
@Test fun legacyAndInvalidExtensionsNeverInventATimestamp() {
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, hex("08026a041a02080e"))).ringTick)
for (offset in listOf(9,13,14,15,16,20)) {
val bad = packet.copyOf(); bad[offset] = (bad[offset].toInt() + 1).toByte()
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, bad)).ringTick)
}
for (tick in listOf(0L,1L,0xffffffffL)) {
val p = packet.copyOf()
for (i in 0..3) p[21+i] = (tick shr (i*8)).toByte()
assertEquals(tick, assertNotNull(G2Event.decodePayload(224,p)).ringTick)
}
}
}
@@ -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))
}
}
@@ -0,0 +1,46 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SettingsChangeHubTest {
private class MemorySettings : SettingsStorage {
val values = HashMap<String?, Any?>()
override fun getString(key: String?, defaultValue: String?): String? = values[key] as? String ?: defaultValue
override fun putString(key: String?, value: String?) { values[key] = value }
override fun getBoolean(key: String?, defaultValue: Boolean): Boolean = values[key] as? Boolean ?: defaultValue
override fun putBoolean(key: String?, value: Boolean) { values[key] = value }
}
@Test
fun writesNotifyEachListenerThroughItsOwnDispatcher() {
val warnings = ArrayList<String>()
val hub = SettingsChangeHub(MemorySettings(), { warnings.add(it) }, testPlatform())
val queued = ArrayList<() -> Unit>()
val seen = ArrayList<String?>()
val listener = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { seen.add(key) } }
hub.register(listener) { queued.add(it) }
val silent = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { seen.add("silent") } }
hub.register(silent, null)
assertEquals(1, warnings.size)
hub.setString("font", "Inter")
hub.setBoolean("dark", true)
assertEquals("Inter", hub.getString("font", null))
assertTrue(hub.getBoolean("dark", false))
assertTrue(seen.isEmpty()) // delivered only when the dispatcher runs
queued.forEach { it() }
assertEquals(listOf<String?>("font", "dark"), seen)
val failing = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { throw IllegalStateException("boom") } }
hub.register(failing) { it() }
hub.setString("x", null)
assertTrue(warnings.last().contains("boom"))
hub.unregister(listener)
hub.unregister(failing)
queued.clear()
hub.setBoolean("dark", false)
assertTrue(queued.isEmpty())
}
}
@@ -0,0 +1,136 @@
package com.faceclaw.app
import kotlin.test.*
class SharedGraphicsTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun androidWireVectorsAndGrayQuantization() {
val vectors =
listOf(
BleProtocol.buildAuthenticationRequest(101) to "080410651a0408011004",
BleProtocol.PRELUDE_F5872_PAYLOAD to "0802109c01220a1a081206120408001000",
BleProtocol.buildCreateInputPage(102) to
"080010661a2308011a1c0800100018c00420a0024801520964617368626f617264580162012028904e",
BleProtocol.buildHeartbeat(103) to "080c106772020800",
BleProtocol.buildSettingsQuery(104) to "0802106822020801",
BleProtocol.buildShutdown(105, 1) to "080910695a020801",
BleProtocol.buildFaceclawWakeControl(5, 0) to "08011000aa0606464301050000",
)
vectors.forEach { (actual, expected) -> assertContentEquals(hex(expected), actual) }
val packed =
BmpUtil.pack4bppFromGray8(
byteArrayOf(0, 1, 7, 8, 15, 16, 23, 24, 127, -128, -9, -1),
3,
4,
)
assertContentEquals(hex("0000111012808ff0"), packed)
assertContentEquals(hex("40311011121810182f10"), BleImageOptimizer.rleEncode(packed))
assertContentEquals(
hex("aa21400c01018000080410651a04080110041024"),
BleProtocol.framePb(vectors.first().first, 128, 0, 64).single(),
)
}
@Test
fun splitStreamsExpiryAndCorruption() {
val payload =
BleProtocol.encodeVarintField(1, 3) +
BleProtocol.encodeVarintField(2, 110) +
BleProtocol.encodeBytesField(8, ByteArray(3900) { 55 })
val frames = BleProtocol.framePb(payload, 224, 32, 17, 185)
assertTrue(frames.all { it.size <= 185 })
val stream = frames.reduce { a, b -> a + b }
val receiver = MessageReceiver()
assertTrue(receiver.receive("L", stream.copyOf(7), 0).isEmpty())
val message = receiver.receive("L", stream.copyOfRange(7, stream.size), 1).single()
assertContentEquals(payload, message.payload)
assertEquals(3, message.command)
assertEquals(110, message.magic)
stream[stream.lastIndex] = (stream.last().toInt() xor 1).toByte()
assertTrue(receiver.receive("L", stream, 2).isEmpty())
receiver.receive("L", frames.first(), 10)
assertTrue(receiver.receive("R", frames.drop(1).reduce { a, b -> a + b }, 11).isEmpty())
assertTrue(receiver.receive("L", frames.drop(1).reduce { a, b -> a + b }, 5011).isEmpty())
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(payload, 1, 0, 1, 10) }
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(ByteArray(60000), 1, 0, 1) }
val invalid = BleProtocol.framePb(byteArrayOf(0x1a, 0x7f), 224, 0, 2).single()
assertTrue(receiver.receive("L", invalid, 6000).isEmpty())
}
@Test
fun eventDecodeAcceptsValidatedPayloadWithoutStrippingAgain() {
val event = BleProtocol.encodeVarintField(1, 12) + BleProtocol.encodeVarintField(2, 2)
val payload = BleProtocol.encodeBytesField(13, BleProtocol.encodeBytesField(3, event))
val received =
MessageReceiver()
.receive("L", BleProtocol.framePb(payload, 224, 1, 1).single(), 0)
.single()
val decoded = assertNotNull(G2Event.decodePayload(received.sid, received.payload))
assertEquals("sys-event", decoded.kind)
assertEquals(12, decoded.eventType)
assertEquals(2, decoded.eventSource)
}
@Test
fun retainedCompositionClippingDimmingAndBlanking() {
val c = SurfaceCompositor()
c.configureScreen(3, 2)
c.configureSurface("app", 0, 0, 3, 2, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(6) { 200.toByte() }), 0, 0, 3, 2, "1")
c.configureSurface("shell", 0, 0, 3, 2, 1, 1)
c.submitSurface("shell", ArrayByteReader(byteArrayOf(0, 1, -1, 0, 0, 0)), 0, 0, 3, 2, "2")
c.setUnderlayDim(1, 128)
assertContentEquals(byteArrayOf(100, 1, -1, 100, 100, 100), c.composite().gray)
c.setSurfaceVisible("shell", false)
assertContentEquals(ByteArray(6) { 100 }, c.composite().gray)
c.configureSurface("opaque", 1, 0, 1, 2, 2, 0)
c.submitSurface("opaque", ArrayByteReader(byteArrayOf(0, 0)), 0, 0, 1, 2, "3")
assertContentEquals(byteArrayOf(100, 0, 100, 100, 0, 100), c.composite().gray)
c.setBlanked(true)
assertContentEquals(ByteArray(6), c.composite().gray)
c.setBlanked(false)
c.removeSurface("opaque")
c.configureSurface("app", -1, 0, 3, 2, 0, 0)
c.setUnderlayDim(0, 256)
assertContentEquals(byteArrayOf(-56, -56, 0, -56, -56, 0), c.composite().gray)
}
@Test
fun pngChunksAndPixels() {
val png = SharedScreenshots.encode4BitGrayPng(byteArrayOf(0, 16, -1, 32, 48, 64), 3, 2)
assertContentEquals(hex("89504e470d0a1a0a"), png.copyOf(8))
fun intAt(offset: Int): Int =
(0..3).fold(0) { n, i -> (n shl 8) or (png[offset + i].toInt() and 255) }
var offset = 8
val types = mutableListOf<String>()
var compressed = ByteArray(0)
while (offset < png.size) {
val size = intAt(offset)
val type = png.copyOfRange(offset + 4, offset + 8).decodeToString()
types.add(type)
if (type == "IHDR") {
assertEquals(3, intAt(offset + 8))
assertEquals(2, intAt(offset + 12))
assertEquals(4, png[offset + 16].toInt())
assertEquals(0, png[offset + 17].toInt())
}
if (type == "IDAT") compressed += png.copyOfRange(offset + 8, offset + 8 + size)
offset += size + 12
}
assertEquals(listOf("IHDR", "IDAT", "IEND"), types)
assertContentEquals(hex("0001f0002340"), inflateData(compressed, 6))
}
@Test
fun wavHeaderAndHex() {
assertEquals("007f80ff", BinaryEncoding.bytesToHex(byteArrayOf(0, 127, -128, -1)))
assertContentEquals(
hex(
"524946462804000057415645666d74201000000001000100803e0000007d0000020010006461746104040000"
),
BinaryEncoding.wavHeader(1028, 16000, 1),
)
}
}
@@ -0,0 +1,87 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SseStreamTest {
private fun feed(stream: SseStream, vararg chunks: String) {
for (chunk in chunks) {
val bytes = chunk.encodeToByteArray()
stream.onChunk(bytes, 0, bytes.size)
}
}
@Test
fun splitsLinesAcrossChunksWithBomAndCrlf() {
val stream = SseStream()
stream.onStatus(200)
feed(stream, "event: a\r", "\ndata: {\"x\":1}\n\nda", "ta: tail")
assertEquals(listOf(SseEvent.Line("event: a"), SseEvent.Line("data: {\"x\":1}"), SseEvent.Line("")), stream.takeEvents())
stream.onComplete()
assertEquals(listOf(SseEvent.Line("data: tail"), SseEvent.Complete), stream.takeEvents())
assertTrue(stream.isFinished)
feed(stream, "late\n")
assertEquals(emptyList(), stream.takeEvents())
}
@Test
fun errorBodyIsBufferedAndCapped() {
val stream = SseStream()
stream.onStatus(429)
feed(stream, "{\"error\":", "\"slow down\"}\n")
assertEquals(emptyList(), stream.takeEvents())
stream.onComplete()
assertEquals(listOf(SseEvent.HttpError(429, "{\"error\":\"slow down\"}\n")), stream.takeEvents())
val capped = SseStream()
capped.onStatus(500)
val big = ByteArray(SseStream.ERROR_BODY_LIMIT + 100) { 'x'.code.toByte() }
capped.onChunk(big, 0, big.size)
capped.onComplete()
val event = capped.takeEvents().single() as SseEvent.HttpError
assertEquals(SseStream.ERROR_BODY_LIMIT, event.body.length)
}
@Test
fun queueOverflowAndOversizedLinesFail() {
val stream = SseStream()
stream.onStatus(200)
val line = "x".repeat(1023) + "\n"
val block = line.repeat(64).encodeToByteArray()
var fed = 0L
while (fed <= SseStream.QUEUE_BYTE_LIMIT + block.size) {
stream.onChunk(block, 0, block.size)
fed += block.size
}
val events = stream.takeEvents()
assertEquals(SseEvent.Failure("Streaming response queue overflow"), events.single())
val long = SseStream()
long.onStatus(200)
val huge = ByteArray(SseStream.LINE_LIMIT + 1) { 'y'.code.toByte() }
long.onChunk(huge, 0, huge.size)
assertEquals(SseEvent.Failure("Streaming response line too large"), long.takeEvents().single())
}
@Test
fun failureAndCancelAreTerminal() {
val stream = SseStream()
stream.onStatus(200)
feed(stream, "a\n")
stream.onFailure("boom")
assertEquals(listOf(SseEvent.Line("a"), SseEvent.Failure("boom")), stream.takeEvents())
val cancelled = SseStream()
cancelled.onStatus(200)
feed(cancelled, "a\n")
cancelled.cancel()
cancelled.onComplete()
assertEquals(emptyList(), cancelled.takeEvents())
}
@Test
fun unpacksFlatHeaderArrays() {
assertEquals(listOf("A" to "1", "C" to "3"), SseStream.unpackHeaders(arrayOf("A", "1", "", "2", "C", "3", "D")))
assertEquals(emptyList(), SseStream.unpackHeaders(null))
}
}
@@ -0,0 +1,420 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/** A stock-firmware lens pair behind the StockLink port; replies are scripted per written message. */
private class FakeStockLink : StockLink {
class Written(val address: String, val uuid: String, val sid: Int, val flag: Int, val seq: Int, val pb: ByteArray) {
/** Protobuf magic (field 2) of a control message; -1 for OTA payloads. */
val magic: Int get() = if (sid == 0xc0 || sid == 0xc1) -1 else BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(pb), 2, -1)
}
var inbound: StockLinkListener? = null
val connected = HashSet<String>()
val bond = HashMap<String, BondState>()
val writes = ArrayList<Written>()
var connectResult: (String) -> Boolean = { true }
var responder: (Written) -> Unit = {}
var closed = false
override fun setListener(listener: StockLinkListener?) { inbound = listener }
override fun connect(address: String, timeoutMs: Int): Boolean = connectResult(address).also { if (it) connected.add(address) }
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
override fun discoverServices(address: String, timeoutMs: Int): Boolean = address in connected
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean = address in connected
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (address !in connected) throw IllegalStateException("Not connected: $address")
val head = frames.first()
val body = ByteArray(frames.sumOf { it.size - 8 })
var at = 0
for (f in frames) { f.copyInto(body, at, 8); at += f.size - 8 }
val written = Written(address, characteristicUuid, head[6].toInt() and 0xff, head[7].toInt() and 0xff, head[2].toInt() and 0xff, body)
writes.add(written)
responder(written)
return true
}
override fun isConnected(address: String): Boolean = address in connected
override fun bondState(address: String): BondState = bond[address] ?: BondState.BONDED
override fun disconnect(address: String) { connected.remove(address) }
override fun close() { closed = true; connected.clear() }
/** Deliver a lens frame on the control notify characteristic. */
fun notify(address: String, pb: ByteArray, sid: Int, flag: Int = 0) {
for (frame in BleProtocol.framePb(pb, sid, flag, 7)) inbound!!.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, frame)
}
fun otaAck(address: String, op: Int, status: Int) {
inbound!!.onNotification(address, BleProtocol.OTA_DATA_NOTIFY_UUID, BleProtocol.framePb(byteArrayOf(op.toByte(), status.toByte()), 0xc1, 0, 1).single())
}
fun drop(address: String) { connected.remove(address); inbound!!.onConnectionStateChange(address, false) }
}
private fun varint(value: Int): ByteArray { var v = value; val out = ArrayList<Byte>(); do { var b = v and 0x7f; v = v ushr 7; if (v != 0) b = b or 0x80; out.add(b.toByte()) } while (v != 0); return out.toByteArray() }
private fun field(number: Int, bytes: ByteArray): ByteArray = varint((number shl 3) or 2) + varint(bytes.size) + bytes
private fun field(number: Int, text: String): ByteArray = field(number, text.encodeToByteArray())
private fun authSuccess(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, ByteArray(0))
private fun authPending(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, BleProtocol.encodeVarintField(1, 1))
private fun ack(magic: Int) = BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
private fun settingsAck(magic: Int, battery: Int = -1, left: String = "", right: String = "", extension: String = "", silentMode: Int = -1): ByteArray {
var request = ByteArray(0)
if (left.isNotEmpty()) request += field(5, left)
if (right.isNotEmpty()) request += field(6, right)
if (battery >= 0) request += BleProtocol.encodeVarintField(12, battery)
if (silentMode >= 0) request += BleProtocol.encodeVarintField(14, silentMode)
var pb = BleProtocol.encodeVarintField(1, 2) + BleProtocol.encodeVarintField(2, magic) + field(4, request)
if (extension.isNotEmpty()) pb += field(100, extension)
return pb
}
private fun listSelection(container: String, item: String, index: Int, eventType: Int): ByteArray =
field(13, field(1, field(2, container) + field(3, item) + BleProtocol.encodeVarintField(4, index) + BleProtocol.encodeVarintField(5, eventType)))
private val fast = StockFlowTimings(
securityAuthTimeoutMs = 300, securityAuthSoftTimeoutMs = 100, pairingWaitCapMs = 2_000, postBondGraceMs = 20, pollMs = 5,
armRetryDelayMs = 5, queryTimeoutMs = 40, preludeTimeoutMs = 40, heartbeatIntervalMs = 15, selectionTimeoutMs = 80, createAckTimeoutMs = 40,
batteryAckTimeoutMs = 40, blockAckTimeoutMs = 60, ctrlAckTimeoutMs = 60, firstLensConnectWindowMs = 200, secondLensConnectWindowMs = 200,
rebootSettleMs = 5, notifySettleMs = 5, otaRetryDelayMs = 5, componentRetryDelayMs = 5,
)
private const val R = "AA:00:00:00:00:01"
private const val L = "AA:00:00:00:00:02"
private class ProbeEvents : FaceclawDeviceInfoProbeListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); var result: List<String>? = null; var error: String? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onResult(leftVersion: String?, rightVersion: String?, extension: String?) { result = listOf(leftVersion ?: "", rightVersion ?: "", extension ?: "") }
override fun onError(message: String?) { error = message }
}
/** Standard lens behaviour: auth succeeds, prelude and settings are acked with the given versions/battery. */
private fun stockResponder(link: FakeStockLink, left: String = "2.2.9", right: String = "2.2.9", extension: String = "", battery: Int = 85): (FakeStockLink.Written) -> Unit = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, battery, left, right, extension), w.sid)
BleProtocol.SID_EVENHUB -> link.notify(w.address, ack(w.magic), w.sid)
}
}
class StockFlowsTest {
@Test
fun probeAuthenticatesBothArmsThenReadsVersions() {
val link = FakeStockLink()
link.responder = stockResponder(link, "L1", "R1", "Faceclaw/3")
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, L, events, fast, testPlatform()).run()
assertEquals(listOf("L1", "R1", "Faceclaw/3"), events.result)
assertEquals(null, events.error)
assertEquals(listOf("connecting:right", "authenticating:right", "connecting:left", "authenticating:left", "querying:right"), events.states)
// Right arm then left arm auth, then prelude + one settings read on the right arm only.
assertEquals(listOf(R, L), link.writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.address })
assertEquals(listOf(R), link.writes.filter { it.sid == BleProtocol.SID_UI_SETTING }.map { it.address })
assertTrue(link.closed)
}
@Test
fun probeUsesUnsolicitedSettingsPushAndFallsBackToLeftLens() {
// Right lens: auth ok, but the settings read is never acked; instead a push on a
// device-chosen magic carries the versions.
val pushed = FakeStockLink()
pushed.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> pushed.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> pushed.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> pushed.notify(w.address, settingsAck(250, -1, "P1", "P2", ""), w.sid)
}
}
var events = ProbeEvents()
DeviceInfoProbeFlow(pushed, R, "", events, fast, testPlatform()).run()
assertEquals(listOf("P1", "P2", ""), events.result)
assertTrue(events.logs.any { it.contains("unsolicited settings push") })
// Right lens silent on settings (both attempts); the left lens answers.
val silentRight = FakeStockLink()
silentRight.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> silentRight.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> silentRight.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> if (w.address == L) silentRight.notify(w.address, settingsAck(w.magic, -1, "LL", "RR", ""), w.sid)
}
}
events = ProbeEvents()
DeviceInfoProbeFlow(silentRight, R, L, events, fast, testPlatform()).run()
assertEquals(listOf("LL", "RR", ""), events.result)
assertTrue(events.logs.any { it.contains("probing the left lens") })
assertEquals(2, silentRight.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.address == R })
assertContains(events.states, "querying:left")
}
@Test
fun probeWaitsThroughPairingAndResendsAfterBond() {
// Unbonded phone: the first auth request is answered with the pre-encryption
// non-success result, the OS then pairs (no writes while BONDING), and once bonded the
// request is re-sent after the grace period and finally succeeds.
val link = FakeStockLink()
link.bond[R] = BondState.NONE
val authReplies = ArrayList<Int>()
link.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> { authReplies.add(w.magic); link.notify(w.address, if (authReplies.size == 1) authPending(w.magic) else authSuccess(w.magic), w.sid) }
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, -1, "a", "b", ""), w.sid)
}
}
startThread("bond-flip", true) { sleepMs(20); link.bond[R] = BondState.BONDING; sleepMs(40); link.bond[R] = BondState.BONDED }
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, "", events, fast, testPlatform()).run()
assertEquals(listOf("a", "b", ""), events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it.contains("is not the success result") })
assertTrue(events.logs.any { it.contains("is pairing with the right lens") })
assertTrue(events.logs.any { it.contains("bond established") })
assertTrue(events.logs.any { it.contains("re-sending the auth request after pairing") })
assertEquals(2, authReplies.size)
assertTrue(events.logs.any { it.contains("security auth complete: right lens") })
}
@Test
fun probeReportsUnreachableArmAndCancel() {
val link = FakeStockLink()
link.connectResult = { false }
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, L, events, fast, testPlatform()).run()
assertNotNull(events.error).let { assertTrue(it.contains("could not connect to the right lens"), it) }
assertEquals(3, events.states.count { it == "connecting:right" })
val cancelled = FakeStockLink()
cancelled.responder = { w -> if (w.sid == BleProtocol.SID_SECURITY_AUTH) cancelled.notify(w.address, authPending(w.magic), w.sid) }
val slow = StockFlowTimings(securityAuthTimeoutMs = 5_000, pollMs = 5)
val flow = DeviceInfoProbeFlow(cancelled, R, "", ProbeEvents().also { events.logs.clear() }, slow, testPlatform())
startThread("cancel", true) { sleepMs(30); flow.cancel() }
val start = testPlatform().elapsedRealtimeMs()
flow.run()
assertTrue(testPlatform().elapsedRealtimeMs() - start < 2_000)
assertTrue(flow.cancelled)
}
private class PromptEvents : FaceclawFlashPromptListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); var battery: Pair<Int, Int>? = null; var result: Boolean? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onBattery(rightPercent: Int, leftPercent: Int) { battery = rightPercent to leftPercent }
override fun onResult(approved: Boolean) { result = approved }
}
private fun promptResponder(link: FakeStockLink, selection: Int?, batteries: Map<String, Int>, silentMode: Int = -1): (FakeStockLink.Written) -> Unit = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, batteries[w.address] ?: -1, silentMode = silentMode), w.sid)
BleProtocol.SID_EVENHUB -> {
val cmd = BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(w.pb), 1, -1)
link.notify(w.address, ack(w.magic), w.sid)
// Cmd 0 = create page: the user taps a row right away (a scroll first, which must be ignored).
if (cmd == 0 && selection != null) {
link.notify(w.address, listSelection(FlashPromptFlow.LIST_NAME, "other", 0, BleProtocol.EVENT_SCROLL_TOP), BleProtocol.SID_EVENHUB, BleProtocol.FLAG_NOTIFY)
link.notify(w.address, listSelection(FlashPromptFlow.LIST_NAME, FlashPromptFlow.ITEMS[selection], selection, BleProtocol.EVENT_CLICK), BleProtocol.SID_EVENHUB, BleProtocol.FLAG_NOTIFY)
}
}
}
}
@Test
fun promptApprovalReadsBothBatteriesAndShutsDown() {
val link = FakeStockLink()
link.responder = promptResponder(link, 1, mapOf(R to 85, L to 70))
val events = PromptEvents()
FlashPromptFlow(link, R, L, "warning", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertEquals(85 to 70, events.battery)
assertEquals(listOf("connecting:", "connected:", "prompting:", "battery:", "result:approved"), events.states)
val hub = link.writes.filter { it.sid == BleProtocol.SID_EVENHUB }.map { BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(it.pb), 1, -1) }
assertEquals(0, hub.first()) // create page
assertEquals(9, hub.last()) // shutdown
assertTrue(link.writes.all { it.sid != BleProtocol.SID_EVENHUB || it.address == R })
assertTrue(link.closed)
}
@Test
fun promptDeclineTimeoutAndSkip() {
val declined = FakeStockLink()
declined.responder = promptResponder(declined, 0, mapOf())
var events = PromptEvents()
FlashPromptFlow(declined, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(false, events.result)
assertEquals("result:declined", events.states.last())
assertEquals(null, events.battery)
val silent = FakeStockLink()
silent.responder = promptResponder(silent, null, mapOf())
events = PromptEvents()
FlashPromptFlow(silent, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(null, events.result)
assertEquals("timeout:No response from the glasses.", events.states.last())
// Heartbeats (EvenHub cmd 12) kept the page alive while waiting (interval 15 ms, wait 80 ms).
assertTrue(silent.writes.count { it.sid == BleProtocol.SID_EVENHUB && BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(it.pb), 1, -1) == 12 } >= 2)
val skipped = FakeStockLink()
skipped.responder = promptResponder(skipped, null, mapOf(R to 50))
events = PromptEvents()
FlashPromptFlow(skipped, R, L, "w", true, events, fast, testPlatform()).run()
assertEquals(true, events.result)
assertEquals(50 to -1, events.battery)
assertFalse(skipped.writes.any { it.sid == BleProtocol.SID_EVENHUB })
val lost = FakeStockLink()
lost.responder = { w ->
promptResponder(lost, null, mapOf())(w)
if (w.sid == BleProtocol.SID_EVENHUB) lost.drop(R)
}
events = PromptEvents()
FlashPromptFlow(lost, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals("disconnected:Lost connection to the glasses.", events.states.last())
}
@Test
fun promptRefusesOnlyWhenTheLensReportsSilentMode() {
// Silent mode on: refused with the way out, before any page is written.
val silentOn = FakeStockLink()
silentOn.responder = promptResponder(silentOn, 1, mapOf(R to 85), silentMode = 1)
var events = PromptEvents()
FlashPromptFlow(silentOn, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(null, events.result)
assertEquals("error:${FlashPromptFlow.SILENT_MODE_MESSAGE}", events.states.last())
assertTrue(events.logs.any { it == "silent mode before prompt: on" })
assertFalse(silentOn.writes.any { it.sid == BleProtocol.SID_EVENHUB })
assertTrue(silentOn.closed)
// Silent mode off: the prompt is shown and answered as usual.
val silentOff = FakeStockLink()
silentOff.responder = promptResponder(silentOff, 1, mapOf(R to 85), silentMode = 0)
events = PromptEvents()
FlashPromptFlow(silentOff, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it == "silent mode before prompt: off" })
// Firmware whose ack omits the field: unknown is not a refusal.
val omitted = FakeStockLink()
omitted.responder = promptResponder(omitted, 1, mapOf(R to 85))
events = PromptEvents()
FlashPromptFlow(omitted, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it == "silent mode before prompt: unknown (ack omits the field)" })
// skipPrompt re-checks the battery only; silent mode does not block it.
val skipped = FakeStockLink()
skipped.responder = promptResponder(skipped, null, mapOf(R to 85), silentMode = 1)
events = PromptEvents()
FlashPromptFlow(skipped, R, "", "w", true, events, fast, testPlatform()).run()
assertEquals(true, events.result)
}
// ---- OTA ---------------------------------------------------------------
private fun putU32(buf: ByteArray, offset: Int, value: Long) { for (i in 0 until 4) buf[offset + i] = ((value ushr (8 * i)) and 0xff).toByte() }
private fun container(): ByteArray {
val mainApp = ByteArray(6000) { (it * 7).toByte() }.also { putU32(it, 0, 6000L); putU32(it, 0x14, FirmwareImage.APP_LOAD_ADDR) }
val components = listOf("ota/bootloader.bin" to ByteArray(300) { it.toByte() }, "ota/a.bin" to ByteArray(64) { 1 }, "ota/b.bin" to ByteArray(128) { 2 }, "ota/c.bin" to ByteArray(32) { 3 }, FirmwareImage.REQUIRED_SEGMENT to mainApp)
val toc = FirmwareImage.HEADER_SIZE + components.size * FirmwareImage.TOC_ENTRY_SIZE
var offset = toc
val offsets = components.map { c -> offset.also { offset += FirmwareImage.SUBHEADER_SIZE + c.second.size } }
val img = ByteArray(offset)
putU32(img, 8, components.size.toLong())
components.forEachIndexed { i, c ->
val off = offsets[i]
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 4, off.toLong())
putU32(img, off + 8, c.second.size.toLong())
c.first.encodeToByteArray().copyInto(img, off + FirmwareImage.NAME_OFFSET)
c.second.copyInto(img, off + FirmwareImage.SUBHEADER_SIZE)
val crc = FirmwareImage.crc32cUnsigned(c.second)
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 12, crc)
putU32(img, off + 12, crc)
}
return img
}
private class FlashEvents : FaceclawFirmwareFlasherListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); val progress = ArrayList<String>(); var complete: Pair<Boolean, String>? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) { progress.add("$lens $componentIndex/$componentCount $blockIndex/$blockCount $bytesSent/$bytesTotal") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onComplete(success: Boolean, detail: String?) { complete = success to (detail ?: "") }
}
/** OTA lens: NAKs one block once and fails one END once, exercising both retry paths. */
private class OtaLens(val link: FakeStockLink) {
val received = HashMap<String, ByteArray>()
var nakOnce = true
var failEndOnce = true
var component = ByteArray(0)
fun respond(w: FakeStockLink.Written) {
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
OtaFlashFlow.SID_CTRL -> {
val pb = BleProtocol.stripTrailingCrc(w.pb)
when (pb[0].toInt()) {
OtaFlashFlow.OP_BEGIN -> link.otaAck(w.address, OtaFlashFlow.OP_BEGIN, 0)
OtaFlashFlow.OP_FILE_CHECK -> { component = ByteArray(0); link.otaAck(w.address, OtaFlashFlow.OP_FILE_CHECK, 0) }
OtaFlashFlow.OP_END -> {
val status = if (failEndOnce) { failEndOnce = false; 5 } else { received[w.address] = (received[w.address] ?: ByteArray(0)) + component; 9 }
link.otaAck(w.address, OtaFlashFlow.OP_END, status)
}
OtaFlashFlow.OP_BLOCK -> {}
}
}
OtaFlashFlow.SID_DATA -> {
val block = BleProtocol.stripTrailingCrc(w.pb)
if (nakOnce) { nakOnce = false; link.otaAck(w.address, OtaFlashFlow.OP_BLOCK, 1) } else { component += block; link.otaAck(w.address, OtaFlashFlow.OP_BLOCK, 0) }
}
}
}
}
@Test
fun otaFlashesBothLensesWithBlockNakAndEndRetry() {
val img = container()
val segs = FirmwareImage.validate(img)
val link = FakeStockLink()
val lens = OtaLens(link)
link.responder = lens::respond
val events = FlashEvents()
OtaFlashFlow(link, R, L, "fw.bin", events, fast, testPlatform()) { img }.run()
assertEquals(true to "Both lenses flashed. The glasses are rebooting into the custom firmware.", events.complete, events.logs.joinToString("\n"))
assertEquals(listOf("validating:", "connecting:left", "flashing:left", "rebooting:Left lens done. Both lenses reboot briefly; reconnecting for the right lens.", "connecting:right", "flashing:right", "done:"), events.states)
// Every component payload arrived intact on both lenses, in order.
val expected = segs.fold(ByteArray(0)) { acc, s -> acc + img.copyOfRange(s.payloadStart, s.payloadStart + s.ps) }
assertContentEquals(expected, lens.received[L]!!)
assertContentEquals(expected, lens.received[R]!!)
assertTrue(events.logs.any { it.contains("NAK=1 resend 1/3") })
assertTrue(events.logs.any { it.contains("END verify FAILED (status 5)") })
assertTrue(events.logs.any { it.contains("re-flash attempt 2/3") })
assertEquals("left 5/5 2/2 6524/6524", events.progress.first { it.startsWith("left 5/5 2") })
// Marker + data share one envelope seq; the OTA stream restarts at 1 per lens.
val leftOta = link.writes.filter { it.address == L && it.uuid == BleProtocol.OTA_DATA_WRITE_UUID }
assertEquals(1, leftOta.first().seq)
val firstBlock = leftOta.indexOfFirst { it.sid == OtaFlashFlow.SID_DATA }
assertEquals(leftOta[firstBlock - 1].seq, leftOta[firstBlock].seq)
assertEquals(setOf(BleProtocol.WRITE_CHAR_UUID), link.writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.uuid }.toSet())
}
@Test
fun otaGivesUpWhenLensConnectWindowExpires() {
val link = FakeStockLink()
link.connectResult = { false }
val events = FlashEvents()
OtaFlashFlow(link, R, L, "fw.bin", events, fast, testPlatform()) { container() }.run()
assertEquals(false to "could not reach left lens: connect/discover incomplete", events.complete)
assertEquals("error:could not reach left lens: connect/discover incomplete", events.states.last())
assertTrue(events.logs.count { it.contains("left connect attempt") } >= 2)
assertTrue(link.closed)
val unreadable = FlashEvents()
OtaFlashFlow(FakeStockLink(), R, L, "/nonexistent/fw.bin", unreadable, fast, testPlatform()).run()
assertTrue(unreadable.complete!!.second.startsWith("could not read firmware"), unreadable.complete!!.second)
}
}
@@ -0,0 +1,273 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class VoiceCaptureSessionTest {
/** Real clock plus an offset the test can advance to force decode cadences. */
private class ShiftedPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
var offsetMs = 0L
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
}
private class Events : FaceclawVoiceControllerListener {
val statuses = mutableListOf<String?>()
val transcripts = mutableListOf<Pair<String?, Boolean>>()
val pcmChunks = mutableListOf<ByteArray>()
val frameMeta = mutableListOf<Pair<Int, Int>>()
var speechEnds = 0
var verified: Pair<Boolean, Float>? = null
val stopped = mutableListOf<Int>()
val stoppedLatch = Latch(1, testPlatform())
override fun onStatus(status: String?) { statuses.add(status) }
override fun onTranscript(text: String?, isFinal: Boolean) { transcripts.add(text to isFinal) }
override fun onStopped(captureId: Int) { stopped.add(captureId); stoppedLatch.countDown() }
override fun onPcm(pcm16le: ByteArray?) { pcmChunks.add(pcm16le!!) }
override fun onFrameMeta(angleDegrees: Int, ssr: Int) { frameMeta.add(angleDegrees to ssr) }
override fun onSpeechEnd() { speechEnds++ }
override fun onSpeakerVerified(isWearer: Boolean, similarity: Float) { verified = isWearer to similarity }
}
/** Scripted phone mic: each entry is a chunk amplitude; after the script the read fails (-1). */
private class ScriptedMic(private val amplitudes: List<Int>, private val onRead: () -> Unit = {}) : PcmAudioSource {
var index = 0
var closed = false
override fun read(pcm: ShortArray): Int {
onRead()
if (index >= amplitudes.size) return -1
val amplitude = amplitudes[index++]
for (i in pcm.indices) pcm[i] = (if (i % 2 == 0) amplitude else -amplitude).toShort()
return pcm.size
}
override fun close() { closed = true }
}
private class FakeTranscriber(private val text: (Int) -> String) : OfflineTranscriber {
val calls = mutableListOf<Int>()
var released = false
override fun recognize(samples: FloatArray, count: Int): String { calls.add(count); return text(count) }
override fun release() { released = true }
}
private class FakeHost(
val platform: ProtocolPlatform,
var mic: PcmAudioSource? = null,
var transcriber: OfflineTranscriber? = null,
var hasModel: Boolean = true,
var embedding: FloatArray? = null,
var g2Ready: Boolean = false,
) : VoiceCaptureHost {
override val dispatcher = CallbackDispatcher { it() }
var packetListener: FaceclawAudioPacketListener? = null
var g2Stops = 0
val recordings = mutableListOf<ByteArray>()
override fun onSessionStarting() {}
override fun isG2SessionReady(): Boolean = g2Ready
override fun isG2AudioCaptureActive(): Boolean = packetListener != null
override fun g2AudioSource(): PacketAudioSource? = if (!g2Ready) null else object : PacketAudioSource {
override fun start(listener: FaceclawAudioPacketListener): Boolean { packetListener = listener; return true }
override fun stop() { g2Stops++ }
override fun isActive(): Boolean = packetListener != null
}
override fun createPacketDecoder(): AudioPacketDecoder = object : AudioPacketDecoder {
override fun decodePacket(packet: ByteArray?, pcmOut: ShortArray?): Int {
if (packet == null || packet.size != Lc3PacketFramer.PACKET_BYTES) return 0
pcmOut!!.fill(packet[0].toShort())
lastAngleDegrees = Lc3PacketFramer.readTrailerS16(packet, Lc3PacketFramer.ANGLE_OFFSET)
lastSsr = Lc3PacketFramer.readTrailerS16(packet, Lc3PacketFramer.SSR_OFFSET)
realPackets++
return Lc3PacketFramer.SAMPLES_PER_PACKET
}
override var lastAngleDegrees = 0
override var lastSsr = 0
override var realPackets = 0L
override val duplicatePackets = 0L
override val missingPackets = 0L
override val decodeErrors = 0L
override fun close() {}
}
override fun openPhoneMic(): PcmAudioSource? = mic
override fun hasTranscriberModel(kind: VoiceModelKind): Boolean = hasModel
override fun loadTranscriber(kind: VoiceModelKind): OfflineTranscriber = transcriber ?: error("no transcriber")
override fun speakerEmbedder(modelPath: String): SpeakerEmbedder = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? = embedding
override fun release() {}
}
override fun recordingSink(): RecordingSink = RecordingSink { bytes, _ -> recordings.add(bytes) }
}
private val logs = mutableListOf<String>()
private fun session(host: VoiceCaptureHost, platform: ProtocolPlatform, name: String) =
VoiceCaptureSession(host, platform, name, { logs.add("I $it") }, { logs.add("W $it") }, { m, e -> logs.add("E $m ${e.message}") })
private fun packet(value: Int, angle: Int, ssr: Int): ByteArray {
val bytes = ByteArray(Lc3PacketFramer.PACKET_BYTES)
bytes[0] = value.toByte()
bytes[Lc3PacketFramer.SSR_OFFSET] = (ssr and 0xff).toByte()
bytes[Lc3PacketFramer.SSR_OFFSET + 1] = (ssr shr 8).toByte()
bytes[Lc3PacketFramer.ANGLE_OFFSET] = (angle and 0xff).toByte()
bytes[Lc3PacketFramer.ANGLE_OFFSET + 1] = (angle shr 8).toByte()
return bytes
}
@Test
fun beamGateWrapsAroundAndClampsHalfWidth() {
val session = session(FakeHost(testPlatform()), testPlatform(), "voice-test-beam")
session.setBeamFilter(true, 170, 30)
assertTrue(session.withinBeam(170))
assertTrue(session.withinBeam(-170)) // 20 degrees away across the wrap
assertFalse(session.withinBeam(120))
session.setBeamFilter(true, 0, 1) // clamps to 5
assertTrue(session.withinBeam(5))
assertFalse(session.withinBeam(6))
}
@Test
fun droppingQueueKeepsNewestAndCountsDrops() {
val queue = DroppingPacketQueue<Int>(3, testPlatform())
for (i in 1..5) queue.put(i)
assertEquals(2L, queue.droppedCount)
assertEquals(3, queue.take(10) { true })
assertEquals(4, queue.take(10) { true })
assertEquals(5, queue.take(10) { true })
assertNull(queue.take(10, { true }))
assertNull(queue.take(10, { false }))
}
@Test
fun g2PacketsAreCountedGatedAndForwarded() {
val platform = ShiftedPlatform(testPlatform())
val host = FakeHost(platform, g2Ready = true)
val events = Events()
val session = session(host, platform, "voice-test-g2")
session.setListener(events)
session.setBeamFilter(true, 0, 30)
session.start("cloud", 7)
val deadline = platform.elapsedRealtimeMs() + 3000
while (host.packetListener == null && platform.elapsedRealtimeMs() < deadline) sleepMs(5)
val listener = host.packetListener!!
listener.onAudioPacket(packet(1, 10, 5), "L", 1000)
listener.onAudioPacket(packet(2, 90, 5), "L", 1050) // outside the beam: meta only
listener.onAudioPacket(packet(3, 0, 0), "R", 1200) // wrong arm, late (150 ms gap), ssr 0 passes the gate
listener.onAudioPacket(ByteArray(3), "L", 1230) // bad length: dropped by the decoder
val waitUntil = platform.elapsedRealtimeMs() + 3000
while (events.pcmChunks.size < 2 && platform.elapsedRealtimeMs() < waitUntil) sleepMs(5)
session.stop()
assertTrue(events.stoppedLatch.await(3000))
val stats = session.audioStats()
assertEquals(4L, stats.queuedPackets)
assertEquals(1L, stats.wrongArmPackets)
assertEquals(1L, stats.latePackets)
assertEquals(150L, stats.maxInterPacketMs)
assertEquals(2, events.pcmChunks.size)
assertEquals(Lc3PacketFramer.SAMPLES_PER_PACKET * 2, events.pcmChunks[0].size)
assertEquals(listOf(10 to 5, 90 to 5, 0 to 0), events.frameMeta)
assertEquals(listOf(7), events.stopped)
assertTrue(host.g2Stops >= 1)
assertTrue(events.statuses.contains("Listening (cloud)..."))
assertTrue(events.transcripts.isEmpty())
assertTrue(logs.any { it.startsWith("I G2 mic packets=4 decoded=3") && it.contains("wrongArm=1") }, logs.toString())
}
@Test
fun startRefusesWithoutGlassesAndWhenAlreadyRunning() {
val host = FakeHost(testPlatform(), g2Ready = false)
val events = Events()
val session = session(host, testPlatform(), "voice-test-refuse")
session.setListener(events)
session.start("onboard", 3)
assertEquals<List<String?>>(listOf("Voice control needs an active G2 connection."), events.statuses)
assertEquals(listOf(3), events.stopped)
assertFalse(session.isCapturing())
}
@Test
fun onboardTranscriptCommitsSegmentsAndFinalizesWithReplaceSemantics() {
val platform = ShiftedPlatform(testPlatform())
// 170 chunks of 800 samples = 8.5 s: one 8 s segment commit plus a tail.
val mic = ScriptedMic(List(170) { 3000 }) { platform.offsetMs += 1000 }
val transcriber = FakeTranscriber { "x" }
val host = FakeHost(platform, mic = mic, transcriber = transcriber)
val events = Events()
val session = session(host, platform, "voice-test-onboard")
session.setListener(events)
session.setUsePhoneMic(true)
session.setSaveRecordings(true)
session.start("onboard", 1)
assertTrue(events.stoppedLatch.await(10000))
assertTrue(mic.closed)
assertTrue(transcriber.released)
assertEquals("Loading transcription model...", events.statuses[0])
assertEquals("Listening...", events.statuses[1])
val finals = events.transcripts.filter { it.second }
assertEquals(1, finals.size)
assertEquals("x x", finals.single().first)
assertEquals("x" to false, events.transcripts.first())
assertTrue(events.transcripts.any { it == ("x x" to false) })
// Every segment handed to the model is at most 8 s and was peak-normalized.
assertTrue(transcriber.calls.all { it in 1..VoiceCaptureSession.TRANSCRIPT_SEGMENT_MAX_SAMPLES })
assertTrue(logs.any { it.startsWith("I Moonshine decode final=true") }, logs.toString())
assertEquals(1, host.recordings.size)
assertEquals(170 * 800 * 2, host.recordings[0].size)
assertEquals(170, events.pcmChunks.size)
assertEquals("x x", VoiceCaptureSession.joinTranscript("x", "x"))
assertEquals("x, y", VoiceCaptureSession.joinTranscript("x", ", y"))
}
@Test
fun endpointingFiresOnceAfterSpeechThenSilence() {
val platform = ShiftedPlatform(testPlatform())
val script = List(8) { 0 } + List(10) { 3000 } + List(24) { 0 }
val host = FakeHost(platform, mic = ScriptedMic(script))
val events = Events()
val session = session(host, platform, "voice-test-endpoint")
session.setListener(events)
session.setUsePhoneMic(true)
session.setEndpointing(true)
session.start("cloud", 2)
assertTrue(events.stoppedLatch.await(10000))
assertEquals(1, events.speechEnds)
assertNull(events.verified)
}
@Test
fun speakerVerificationFailsOpenAndComparesEmbeddings() {
fun run(embedding: FloatArray?, chunks: Int): Pair<Boolean, Float>? {
val platform = ShiftedPlatform(testPlatform())
val host = FakeHost(platform, mic = ScriptedMic(List(chunks) { 1000 }), embedding = embedding)
val events = Events()
val session = session(host, platform, "voice-test-verify")
session.setListener(events)
session.setUsePhoneMic(true)
session.setSpeakerVerification("model", floatArrayOf(1f, 0f), 0.8f)
session.start("cloud", 4)
assertTrue(events.stoppedLatch.await(10000))
return events.verified
}
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(floatArrayOf(1f, 0f), 10)) // under 1 s: too short, fails open
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(null, 30)) // no embedding: fails open
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(floatArrayOf(1f), 30)) // dimension mismatch: fails open
assertEquals<Pair<Boolean, Float>?>(true to 1f, run(floatArrayOf(1f, 0f), 30))
assertEquals<Pair<Boolean, Float>?>(false to 0f, run(floatArrayOf(0f, 1f), 30))
}
@Test
fun missingModelReportsAndStops() {
val host = FakeHost(testPlatform(), mic = ScriptedMic(emptyList()), hasModel = false)
val events = Events()
val session = session(host, testPlatform(), "voice-test-nomodel")
session.setListener(events)
session.setUsePhoneMic(true)
session.start("onboard", 9)
assertTrue(events.stoppedLatch.await(5000))
assertEquals<List<String?>>(listOf("Voice model not downloaded (see Settings > Voice)."), events.statuses)
assertEquals(listOf(9), events.stopped)
assertEquals("1.50", formatFixed(1.5, 2))
assertEquals("-0.333", formatFixed(-1.0 / 3, 3))
assertEquals("0", formatFixed(0.4, 0))
}
}
@@ -0,0 +1,42 @@
package com.faceclaw.app
import kotlin.test.*
class VoiceEndpointDetectorTest {
@Test fun silenceEndsOnlyAfterSpeechAndFiresOnce() {
val detector = VoiceEndpointDetector()
repeat(6) { assertFalse(detector.acceptLevel(100.0, 800)) }
repeat(10) { assertFalse(detector.accept(ShortArray(800) { 2000 }, 800)) }
repeat(17) { assertFalse(detector.acceptLevel(100.0, 800)) }
assertTrue(detector.acceptLevel(100.0, 800))
assertFalse(detector.acceptLevel(100.0, 800))
detector.reset()
assertFalse(detector.acceptLevel(100.0, 800))
}
@Test fun pausesResetWhenSpeechResumesAndContinuousSpeechIsBounded() {
val detector = VoiceEndpointDetector()
repeat(6) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertFalse(detector.acceptLevel(2000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertFalse(detector.acceptLevel(2000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertTrue(detector.acceptLevel(0.0, 800))
detector.reset()
repeat(6) { assertFalse(detector.acceptLevel(0.0, 800)) }
repeat(593) { assertFalse(detector.acceptLevel(2000.0, 800)) }
assertTrue(detector.acceptLevel(2000.0, 800))
}
@Test fun quietRoomTimesOutOnSampleClockAndNoiseCalibrationIsRelative() {
val detector = VoiceEndpointDetector()
repeat(119) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertTrue(detector.acceptLevel(0.0, 800))
detector.reset()
repeat(6) { assertFalse(detector.acceptLevel(1000.0, 800)) }
repeat(20) { assertFalse(detector.acceptLevel(2000.0, 800)) }
assertFalse(detector.acceptLevel(4000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(1000.0, 800)) }
assertTrue(detector.acceptLevel(1000.0, 800))
}
}
@@ -0,0 +1,36 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertTrue
import platform.Foundation.NSDate
import platform.Foundation.NSDefaultRunLoopMode
import platform.Foundation.NSRunLoop
import platform.Foundation.NSThread
import platform.Foundation.dateWithTimeIntervalSinceNow
import platform.Foundation.runMode
class IosBleCentralTest {
/** Registering a state listener must create the central and report a state without any scan. */
@Test
fun scanListenerAloneReceivesABluetoothStateReport() {
val central = IosBleCentral(IosProtocolPlatform)
val states = ArrayList<Int>()
var offMain = 0
central.setScanListener(object : IosBleScanListener {
override fun onBluetoothState(state: Int, authorization: Int) {
if (!NSThread.isMainThread) offMain++
states.add(state)
}
override fun onAdvertisement(identifier: String, name: String, manufacturerDataHex: String, rssi: Int, connectable: Boolean) {}
})
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + 5_000
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline && states.none { it != 0 }) {
NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02))
}
// The simulator reports unsupported/powered-off; a real phone powered-on. Any non-unknown state proves the central exists.
assertTrue(states.any { it != 0 }, "no CBManagerState reported: $states")
assertTrue(offMain == 0, "state reports must arrive on the main queue")
central.close()
}
}
@@ -0,0 +1,46 @@
package com.faceclaw.app
import kotlin.test.*
class IosNativeApiTest {
@Test
fun binaryFacadeRoundTripsAndSlices() {
val bytes = byteArrayOf(0, -1, 2, -128)
assertContentEquals(bytes, bytes.data().byteArray())
assertTrue(byteArrayOf().data().byteArray().isEmpty())
val reader = IosByteReader(bytes.data())
assertEquals(0, reader.get().toInt())
val target = ByteArray(5)
reader.get(target, 1, 3)
assertContentEquals(byteArrayOf(0, -1, 2, -128, 0), target)
assertEquals(0, reader.remaining())
val protocol = IosProtocol()
val auth = protocol.authentication(101)
val frames = protocol.frame(auth, 128, 0, 64, 185)
val result = IosMessageReceiver().receive("L", frames.single(), 0).single()
assertEquals(101, result.magic)
assertContentEquals(auth.byteArray(), result.payload.byteArray())
}
@Test
fun compassFacadePreservesTheEndOfTheCrcFreePayload() {
val protocol = IosProtocol()
val payload = byteArrayOf(8, 15, 16, 0, 82, 3, 8, -25, 2).data()
assertEquals(359, protocol.compassInput(payload, 8, 1)?.headingDegrees)
assertNull(protocol.compassInput(payload, 8, 0))
}
@Test
fun nativeCompositorClipsPartialUpdatesBeforeCoalescing() {
val compositor = IosSurfaceCompositor(3, 2)
compositor.configure("app", 0, 0, 3, 2, 0, false)
compositor.submit("app", byteArrayOf(10, 20, 30, 40, 50, 60).data(), -1, 0, 3, 2)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 0), compositor.composite().byteArray())
compositor.submit("app", byteArrayOf(99).data(), 2, 1, 1, 1)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 99), compositor.composite().byteArray())
compositor.blank(true)
assertContentEquals(ByteArray(6), compositor.composite().byteArray())
compositor.blank(false)
assertEquals(99, compositor.composite().byteArray().last().toInt())
}
}
@@ -0,0 +1,314 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.allocPointerTo
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.value
import platform.Foundation.NSTemporaryDirectory
import platform.posix.AI_NUMERICHOST
import platform.posix.AI_NUMERICSERV
import platform.posix.SOCK_STREAM
import platform.posix.addrinfo
import platform.posix.close
import platform.posix.connect
import platform.posix.freeaddrinfo
import platform.posix.getaddrinfo
import platform.posix.recv
import platform.posix.send
import platform.posix.socket
private var nextPort = 43000 + (currentTimeMillis() % 9000).toInt()
/** Binds the next free loopback port; returns the listener and its port. */
private fun bindFreePort(): Pair<RemoteInputListener, Int> {
repeat(50) {
val port = nextPort++
val listener = runCatching { IosLocalServerPort.bind("127.0.0.1", port) }.getOrNull() ?: return@repeat
return listener to port
}
error("no free loopback port")
}
/** Blocking POSIX client: connects to loopback, sends [request], reads until the peer closes. */
private fun loopbackExchange(port: Int, request: ByteArray, readTimeoutMs: Int = 8000): ByteArray = memScoped {
val hints = alloc<addrinfo>()
hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV
hints.ai_socktype = SOCK_STREAM
val resolved = allocPointerTo<addrinfo>()
check(getaddrinfo("127.0.0.1", port.toString(), hints.ptr, resolved.ptr) == 0)
val info = resolved.value!!.pointed
val fd = socket(info.ai_family, SOCK_STREAM, 0)
check(fd >= 0)
try {
check(connect(fd, info.ai_addr, info.ai_addrlen) == 0) { "connect failed" }
request.usePinned { check(send(fd, it.addressOf(0), request.size.toULong(), 0) == request.size.toLong()) }
val out = ByteSink()
val buffer = ByteArray(4096)
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + readTimeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
val n = buffer.usePinned { recv(fd, it.addressOf(0), buffer.size.toULong(), 0) }
if (n <= 0L) break
out.write(buffer, 0, n.toInt())
if (out.toByteArray().last() == '\n'.code.toByte()) break
}
out.toByteArray()
} finally {
freeaddrinfo(resolved.value)
close(fd)
}
}
/** Minimal loopback HTTP/1.1 server for the NSURLSession facades; one request per connection. */
private class LoopbackHttpServer(private val handler: (path: String, headers: Map<String, String>) -> Reply) {
class Reply(val status: Int, val headers: List<Pair<String, String>>, val pieces: List<ByteArray>, val pieceDelayMs: Long = 0)
private val listener: RemoteInputListener
val port: Int
val requests = ArrayList<Map<String, String>>()
private val lock = IosProtocolPlatform.createLock()
init {
val bound = bindFreePort()
listener = bound.first
port = bound.second
startThread("loopback-http", true) {
while (!listener.isClosed) {
val connection = listener.accept() ?: continue
startThread("loopback-http-conn", true) { serve(connection) }
}
}
}
fun url(path: String) = "http://127.0.0.1:$port$path"
fun close() = listener.close()
fun requestsFor(path: String): List<Map<String, String>> = lock.withLock { requests.filter { it["path"] == path } }
private fun serve(connection: RemoteInputConnection) {
try {
val head = ByteSink()
while (true) {
val b = connection.readByte(5000)
if (b < 0) return
head.write(b)
val bytes = head.toByteArray()
val n = bytes.size
if (n >= 4 && bytes[n - 4] == '\r'.code.toByte() && bytes[n - 3] == '\n'.code.toByte() &&
bytes[n - 2] == '\r'.code.toByte() && bytes[n - 1] == '\n'.code.toByte()) break
}
val lines = head.toByteArray().decodeToString().split("\r\n").filter { it.isNotEmpty() }
val path = lines.first().split(' ')[1]
val headers = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val bodyLength = headers["content-length"]?.toIntOrNull() ?: 0
repeat(bodyLength) { connection.readByte(5000) }
lock.withLock { requests.add(headers + ("path" to path)) }
val reply = handler(path, headers)
val total = reply.pieces.sumOf { it.size }
val response = buildString {
append("HTTP/1.1 ${reply.status} X\r\n")
for ((name, value) in reply.headers) append("$name: $value\r\n")
append("Content-Length: $total\r\nConnection: close\r\n\r\n")
}
connection.write(response.encodeToByteArray())
for (piece in reply.pieces) {
connection.write(piece)
if (reply.pieceDelayMs > 0) sleepMs(reply.pieceDelayMs)
}
} catch (ignored: Exception) {
} finally {
connection.close()
}
}
}
private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(20)
}
return condition()
}
private class RecordingSseListener : FaceclawSseListener {
private val lock = IosProtocolPlatform.createLock()
val lines = ArrayList<String>()
var httpError: Pair<Int, String>? = null
var failure: String? = null
var completed = false
val finished: Boolean get() = lock.withLock { completed || httpError != null || failure != null }
override fun onLine(line: String?) { lock.withLock { lines.add(line ?: "") } }
override fun onHttpError(code: Int, body: String?) { lock.withLock { httpError = code to (body ?: "") } }
override fun onComplete() { lock.withLock { completed = true } }
override fun onFailure(message: String?) { lock.withLock { failure = message ?: "" } }
}
private class RecordingDownloadListener : FaceclawModelDownloaderListener {
private val lock = IosProtocolPlatform.createLock()
var progress = 0
var done: String? = null
var error: String? = null
val finished: Boolean get() = lock.withLock { done != null || error != null }
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { lock.withLock { progress++ } }
override fun onDone(path: String?) { lock.withLock { done = path } }
override fun onError(message: String?) { lock.withLock { error = message } }
}
class IosNetworkingTest {
private val immediate: (() -> Unit) -> Unit = { it() }
/** Like the main queue: never runs on the caller's thread, so the session's lock is not re-entered. */
private val hop: (() -> Unit) -> Unit = { action -> startThread("test-dispatch", true, action) }
@Test
fun remoteInputRoundTripsOverLoopbackAndTimesOut() {
val (probe, port) = bindFreePort()
probe.close()
val remote = IosRemoteInput(hop, requestTimeoutMs = 1200)
val ready = BlockingQueue<String>(IosProtocolPlatform)
remote.setRequestListener { ready.put("ready") }
assertEquals("Invalid local address.", remote.startAddress(port, "example.com"))
assertEquals("Address is not assigned to a local interface.", remote.startAddress(port, "0.0.0.0"))
assertEquals("", remote.startAddress(port, "127.0.0.1"))
try {
val replies = BlockingQueue<ByteArray>(IosProtocolPlatform)
startThread("remote-client", true) { replies.put(loopbackExchange(port, "hello world\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
val request = Json.parseObject(assertNotNull(remote.nextRequest()))
assertEquals("hello world", request["body"].asString())
assertNull(remote.nextRequest())
remote.complete(request["id"].asLong()!!, "{\"ok\":true}")
assertEquals("{\"ok\":true}\n", assertNotNull(replies.poll(5000)).decodeToString())
startThread("remote-client-2", true) { replies.put(loopbackExchange(port, "later\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
assertNotNull(remote.nextRequest())
assertEquals(RemoteInputSession.TIMEOUT_RESPONSE + "\n", assertNotNull(replies.poll(8000)).decodeToString())
assertEquals(64, remote.randomSecret().length)
assertEquals(RemoteInputSession.tokenHash("abc"), remote.tokenDigest("abc"))
val all = iosInterfaceAddresses()
assertTrue(all.any { it.loopback && it.address == "127.0.0.1" }, all.toString())
assertTrue(Json.parseArray(remote.interfaces()).none { it.asObject()!!["address"].asString() == "127.0.0.1" })
assertTrue(IosLocalServerPort.isLocalUnicastAddress("::1"))
assertFalse(IosLocalServerPort.isLocalUnicastAddress("224.0.0.1"))
} finally {
remote.stop()
}
}
@Test
fun sseStreamsLinesRefusesRedirectsAndReportsErrors() {
val body = "event: a\r\ndata: one\n\ndata: two\r\n".encodeToByteArray()
val server = LoopbackHttpServer { path, _ ->
when (path) {
"/sse" -> LoopbackHttpServer.Reply(200, listOf("Content-Type" to "text/event-stream"),
listOf(body.copyOfRange(0, 13), body.copyOfRange(13, body.size)), pieceDelayMs = 50)
"/limited" -> LoopbackHttpServer.Reply(429, listOf("Content-Type" to "text/plain"), listOf("slow down".encodeToByteArray()))
else -> LoopbackHttpServer.Reply(302, listOf("Location" to "http://127.0.0.1:1/never"), listOf(ByteArray(0)))
}
}
try {
val ok = RecordingSseListener()
IosSseRequest(server.url("/sse"), "{\"q\":1}", "{\"X-Test\":\"yes\"}", ok, immediate, false)
assertTrue(waitUntil(10_000) { ok.finished }, "sse did not finish: ${ok.failure}")
assertEquals(listOf("event: a", "data: one", "", "data: two"), ok.lines)
assertTrue(ok.completed)
val request = server.requestsFor("/sse").single()
assertEquals("yes", request["x-test"])
assertEquals("text/event-stream", request["accept"])
assertTrue(request["user-agent"]!!.isNotEmpty())
val limited = RecordingSseListener()
IosSseRequest(server.url("/limited"), "{}", null, limited, immediate, false)
assertTrue(waitUntil(10_000) { limited.finished })
assertEquals(429 to "slow down", limited.httpError)
val redirected = RecordingSseListener()
IosSseRequest(server.url("/moved"), "{}", "{}", redirected, immediate, false)
assertTrue(waitUntil(10_000) { redirected.finished })
assertEquals(302, redirected.httpError?.first)
assertTrue(server.requestsFor("/never").isEmpty())
} finally {
server.close()
}
}
@Test
fun downloaderFetchesAndResumesWithRange() {
val payload = ByteArray(200_000) { (it * 31 + it / 977).toByte() }
val sha = sha256Hex(payload)
val server = LoopbackHttpServer { _, headers ->
val range = headers["range"]
if (range != null && range.startsWith("bytes=")) {
val from = range.removePrefix("bytes=").removeSuffix("-").toInt()
LoopbackHttpServer.Reply(206, listOf("Content-Range" to "bytes $from-${payload.size - 1}/${payload.size}"),
listOf(payload.copyOfRange(from, payload.size)))
} else LoopbackHttpServer.Reply(200, emptyList(), listOf(payload.copyOfRange(0, 70_000), payload.copyOfRange(70_000, payload.size)), pieceDelayMs = 30)
}
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-dl-" + currentTimeMillis()
val dest = "$dir/model.bin"
try {
val first = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), first, immediate).start()
assertTrue(waitUntil(20_000) { first.finished }, "download did not finish: ${first.error}")
assertEquals(dest, first.done, first.error)
assertContentEquals(payload, readFileData(dest))
assertTrue(first.progress >= 1)
assertNull(server.requestsFor("/model.bin").single()["range"])
deleteFile(dest)
writeFileData("$dest.part", payload.copyOfRange(0, 50_000))
val second = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), second, immediate).start()
assertTrue(waitUntil(20_000) { second.finished }, "resume did not finish: ${second.error}")
assertEquals(dest, second.done, second.error)
assertContentEquals(payload, readFileData(dest))
assertEquals("bytes=50000-", server.requestsFor("/model.bin").last()["range"])
assertEquals(-1L, fileLength("$dest.part"))
} finally {
server.close()
deleteFile(dest)
deleteFile("$dest.part")
}
}
@Test
fun frameTimingsExportsToAFile() {
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-ft-" + currentTimeMillis()
platform.Foundation.NSFileManager.defaultManager.createDirectoryAtPath(dir, true, null, null)
val timings = IosFrameTimings(IosProtocolPlatform)
assertNull(timings.exportNow())
timings.startExport(dir)
val frame = timings.startFrame("test:frame")
timings.spanStart(frame, "work")
timings.log(frame, "hello")
timings.spanEnd(frame, "work")
timings.finishFrame(frame, "sent")
val path = assertNotNull(timings.exportNow())
assertEquals("$dir/${IosFrameTimings.EXPORT_FILE_NAME}", path)
val text = readFileData(path).decodeToString()
assertTrue(text.contains("test:frame"), text)
assertTrue(text.contains("hello"), text)
assertNull(timings.exportNow())
assertTrue(timings.statsSummary().isNotEmpty())
deleteFile(path)
}
}
@@ -0,0 +1,97 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.*
import kotlinx.cinterop.*
import platform.CoreBluetooth.*
import platform.posix.memset
import platform.zlib.*
internal actual fun testPlatform(): ProtocolPlatform = IosProtocolPlatform
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> = memScoped {
val stream = alloc<z_stream>()
memset(stream.ptr, 0, sizeOf<z_stream>().convert())
check(inflateInit(stream.ptr) == Z_OK)
try {
records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
check(inflateReset(stream.ptr) == Z_OK)
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
val output = mutableListOf<Byte>()
val buffer = ByteArray(4096)
body.usePinned { input ->
stream.next_in = input.addressOf(0).reinterpret()
stream.avail_in = body.size.toUInt()
buffer.usePinned { destination ->
do {
stream.next_out = destination.addressOf(0).reinterpret()
stream.avail_out = buffer.size.toUInt()
val status = inflate(stream.ptr, Z_SYNC_FLUSH)
check(status == Z_OK || status == Z_BUF_ERROR)
output.addAll(buffer.take(buffer.size - stream.avail_out.toInt()))
} while (stream.avail_in > 0u || stream.avail_out == 0u)
}
}
stream.next_in = null
stream.next_out = null
output.toByteArray()
}
}
} finally {
inflateEnd(stream.ptr)
}
}
class IosProtocolTest {
@Test
fun wakewordPacketsReachTheSharedEventDecoder() {
val api = IosProtocol()
val ctrl = BleProtocol.encodeVarintField(1, 1) // EVEN_AI_WAKE_UP
val payload = (BleProtocol.encodeVarintField(1, BleProtocol.EVEN_AI_CMD_CTRL) +
BleProtocol.encodeBytesField(3, ctrl)).data()
for (flag in listOf(1, 6)) {
val event = assertNotNull(api.glassesInput(payload, BleProtocol.SID_EVEN_AI, flag))
assertEquals("even-ai", event.kind)
assertEquals(1, event.eventType)
}
assertNull(api.glassesInput(payload, BleProtocol.SID_EVEN_AI, 2))
assertNull(api.glassesInput(payload, 0xff, 1))
assertNull(api.glassesInput(byteArrayOf().data(), BleProtocol.SID_EVEN_AI, 1))
}
@Test
fun platformClockAndWriteModes() {
val before = IosProtocolPlatform.elapsedRealtimeMs()
assertTrue(before > 0)
assertTrue(IosProtocolPlatform.elapsedRealtimeMs() >= before)
assertEquals(
CBCharacteristicWriteWithResponse,
IosProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
CBCharacteristicWriteWithoutResponse,
IosProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
}
internal actual fun digest(bytes: ByteArray): String {
val result = ByteArray(32)
result.usePinned { output ->
if (bytes.isEmpty())
platform.CoreCrypto.CC_SHA256(null, 0u, output.addressOf(0).reinterpret())
else
bytes.usePinned { input ->
platform.CoreCrypto.CC_SHA256(
input.addressOf(0),
bytes.size.toUInt(),
output.addressOf(0).reinterpret(),
)
}
}
return BinaryEncoding.bytesToHex(result)
}
@@ -0,0 +1,228 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import platform.Foundation.NSDate
import platform.Foundation.NSDefaultRunLoopMode
import platform.Foundation.NSRunLoop
import platform.Foundation.NSThread
import platform.Foundation.dateWithTimeIntervalSinceNow
import platform.Foundation.runMode
private const val RIGHT = "11111111-2222-3333-4444-555555555501"
private const val LEFT = "11111111-2222-3333-4444-555555555502"
/** Pump the main run loop (which drains the main dispatch queue) until [condition] or timeout. */
private fun pumpMainUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02))
}
return condition()
}
/** A GATT link that acks EvenHub/settings/auth requests and CFW stream messages like the firmware. */
private class FakeIosLink : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = IosProtocolPlatform.createLock()
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
@Volatile var writes = 0
private var seq = 0
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
return true
}
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
writes++
val sid = frames[0][6].toInt() and 255
val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq
val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } }
if (inFlight != null) {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray()
val pb = joined.copyOf(maxOf(0, joined.size - 2))
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return lock.withLock { BleProtocol.framePb(body, sid, 0x00, seq++)[0] }
}
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = 11
packet[4] = 1
packet[5] = 1
packet[6] = CfwTransport.SID.toByte()
packet[8] = 1
packet[9] = streamId.toByte()
packet[12] = lens.toByte()
packet[13] = size.toByte()
packet[14] = (size ushr 8).toByte()
packet[15] = checksum.toByte()
packet[16] = (checksum ushr 8).toByte()
val crc = CfwTransport.crc(packet.copyOfRange(8, 17))
packet[17] = crc.toByte()
packet[18] = (crc ushr 8).toByte()
return packet
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
}
override fun close() {
closed = true
}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class MainThreadListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
var offMainCallbacks = 0
private fun record(phase: String) {
if (!NSThread.isMainThread) offMainCallbacks++
phases.add(phase)
}
override fun onStateChange(phase: String?, status: String?) = record(phase ?: "")
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
if (!NSThread.isMainThread) offMainCallbacks++
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
}
class IosSessionFacadeTest {
@Test
fun facadeSessionConnectsOverAnInjectedLinkAndReportsOnTheMainQueue() {
assertTrue(NSThread.isMainThread, "tests drive the main run loop")
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
link.core = session.coreForTests()
val listener = MainThreadListener()
session.setListener(listener)
assertTrue(session.start())
assertFalse(session.start(), "already running")
assertTrue(pumpMainUntil(5_000) { listener.phases.contains("connected") }, "phases=${listener.phases}")
assertTrue(session.isSessionReady())
assertEquals(0, listener.offMainCallbacks, "listener callbacks must arrive on the main queue")
assertTrue(pumpMainUntil(5_000) { link.writes > 3 }, "auth, prelude, settings and layout writes (saw ${link.writes})")
session.disconnect()
assertTrue(pumpMainUntil(2_000) { listener.phases.lastOrNull() == "disconnected" }, "phases=${listener.phases}")
assertFalse(session.isSessionReady())
assertTrue(link.closed)
assertEquals(listOf(RIGHT, LEFT), link.disconnected.takeLast(2))
assertEquals(0, listener.offMainCallbacks)
}
@Test
fun relayFramesReachTheAncsListenerOnMainAndOtherFramesDoNot() {
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session-ancs")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
val core = session.coreForTests()
link.core = core
val relayed = ArrayList<ByteArray>()
var offMain = 0
session.setAncsListener(object : IosAncsListener {
override fun onAncsAuthorization(authorized: Boolean) {}
override fun onRelayFrame(data: platform.Foundation.NSData) {
if (!NSThread.isMainThread) offMain++
relayed.add(data.byteArray())
}
})
val relay = byteArrayOf(65, 78, 1, 0, 9, 9, 9, 9, 0, 0, 0)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, relay) // wrong arm: ignored by the tap
assertTrue(pumpMainUntil(2_000) { relayed.size == 1 })
assertEquals(relay.toList(), relayed[0].toList())
assertEquals(0, offMain)
session.setAncsListener(null)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
assertFalse(pumpMainUntil(200) { relayed.size > 1 })
}
@Test
fun hostDispatchesToTheCallingQueueAndRunsTheWorker() {
val host = IosSessionHost(threadName = "test-host")
var onMain = false
host.currentThreadDispatcher().post { onMain = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { onMain })
var workerThread = ""
host.startWorker { workerThread = NSThread.currentThread.name ?: "" }
host.joinWorker(2_000)
assertEquals("test-host", workerThread)
var posted = false
host.postToMain { posted = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { posted })
assertFalse(host.isEvenAppActive())
}
@Test
fun stockFlowFacadesConstructWithoutBluetooth() {
// No CoreBluetooth on the simulator; construction and cancel/close must still be safe.
val probe = IosDeviceInfoProbe(RIGHT, LEFT)
probe.setListener(null)
probe.close()
val prompt = IosFlashPrompt(RIGHT, LEFT, "warn", true)
prompt.close()
val flasher = IosFirmwareFlasher(RIGHT, LEFT, "/nonexistent.bin")
flasher.close()
assertNotNull(IosFrameTimings.shared.core.buildExport())
}
}
@@ -0,0 +1,90 @@
package com.faceclaw.app
import kotlin.test.*
class IosTextureApiTest {
private fun imageDraw(id: Int): ByteArray = byteArrayOf(
1, id.toByte(), (id shr 8).toByte(), (id shr 16).toByte(), (id shr 24).toByte(), 0, 0, 0, 0,
)
@Test
fun nativeSnapshotsPreserveDrawsAcrossCoalescingAndSessionResets() {
val atlas = IosTextureAtlas()
val white = ByteArray(4) { -1 }.data()
val id = atlas.imageId("ios-texture-api-white", 2, 2, white)
assertEquals(id, IosTextureAtlas().imageId("ios-texture-api-white", 2, 2, white))
val compositor = IosSurfaceCompositor(8, 4)
compositor.configure("app", 2, 0, 2, 2, 0, false)
compositor.submitDraws("app", white, 0, 0, 2, 2, imageDraw(id).data())
val frame = compositor.compositeFrame()
assertEquals(2, frame.composite.draws!!.single().x)
// A later update must not change the previously submitted snapshot.
compositor.submit("app", ByteArray(4).data(), 0, 0, 2, 2)
assertTrue(compositor.compositeFrame().composite.draws!!.isEmpty())
val next = IosProtocol().pack(frame.pixels, 8, 4)
val planner = IosTexturePlanner()
val cold = assertNotNull(planner.plan(null, next, frame, 1))
assertEquals(27, cold.resourceCommands.first().byteArray()[0].toInt())
assertTrue(cold.resourceCommands.any { it.byteArray()[0].toInt() == 21 })
assertEquals(28, cold.payload.byteArray()[0].toInt())
val warm = assertNotNull(planner.plan(null, next, frame, 1))
assertTrue(warm.resourceCommands.isEmpty())
assertContentEquals(cold.payload.byteArray(), warm.payload.byteArray())
planner.reset()
assertTrue(assertNotNull(planner.plan(null, next, frame, 1)).resourceCommands.isNotEmpty())
// A partial update clears identities even if the caller supplies stale draws.
compositor.submitDraws("app", byteArrayOf(-1).data(), 0, 0, 1, 1, imageDraw(id).data())
assertTrue(compositor.compositeFrame().composite.draws!!.isEmpty())
}
@Test
fun glyphRegistrationAndDrawingUseTheSharedAsciiTable() {
val atlas = IosTextureAtlas()
val key = "ios-aa-texture-test"
val bytes = key.encodeToByteArray()
atlas.registerAaGlyphs((byteArrayOf(bytes.size.toByte()) + bytes +
byteArrayOf(2, 1, 0, 65, 0, 0, 0, 0, 0, 2, 2, -1, -1)).data())
val font = atlas.fontId(key)
val draws = byteArrayOf(0, font.toByte(), (font shr 8).toByte(), 65, 0, 0, 0, 0, 0, 0, 0, -1)
val compositor = IosSurfaceCompositor(4, 2)
compositor.configure("text", 0, 0, 2, 2, 0, false)
compositor.submitDraws("text", ByteArray(4) { -1 }.data(), 0, 0, 2, 2, draws.data())
val frame = compositor.compositeFrame()
val plan = assertNotNull(IosTexturePlanner().plan(null, IosProtocol().pack(frame.pixels, 4, 2), frame, 1))
assertTrue(plan.usedBytes > 2048 + 192)
assertEquals(28, plan.payload.byteArray()[0].toInt())
assertTrue(plan.resourceCommands.any { command ->
val bytes = command.byteArray()
bytes[0].toInt() == 26 && bytes.last().toInt() == 65
})
}
@Test
fun oversizedPlanDiscardsUnsentResidencyBeforePixelFallback() {
val atlas = IosTextureAtlas()
val white = ByteArray(4) { -1 }.data()
val id = atlas.imageId("ios-oversized-plan", 2, 2, white)
var random = 12345
val gray = ByteArray(640 * 480) {
random = random xor (random shl 13)
random = random xor (random ushr 17)
random = random xor (random shl 5)
random.toByte()
}
gray[0] = -1; gray[1] = -1; gray[640] = -1; gray[641] = -1
val compositor = IosSurfaceCompositor(640, 480)
compositor.configure("noise", 0, 0, 640, 480, 0, false)
compositor.submitDraws("noise", gray.data(), 0, 0, 640, 480, imageDraw(id).data())
val frame = compositor.compositeFrame()
val planner = IosTexturePlanner()
val noisy = assertNotNull(planner.plan(null, IosProtocol().pack(frame.pixels, 640, 480), frame, 1))
assertTrue(noisy.resourceCommands.all { it.length <= 65535uL })
planner.reset()
val small = IosSurfaceCompositor(4, 2)
small.configure("icon", 0, 0, 2, 2, 0, false)
small.submitDraws("icon", white, 0, 0, 2, 2, imageDraw(id).data())
val next = small.compositeFrame()
val retry = assertNotNull(planner.plan(null, IosProtocol().pack(next.pixels, 4, 2), next, 1))
assertTrue(retry.resourceCommands.isNotEmpty(), "the rejected plan's image was never uploaded")
}
}