diff --git a/.fallowrc.json b/.fallowrc.json index 147c7777c..649a285db 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -82,6 +82,11 @@ "maxCrap": 80, "reason": "The supervisor's test arranges a process table, a clock, a filesystem and a scripted runner in one helper so each of its cases reads as one claim; the helper is branching setup, not logic under test." }, + { + "files": ["src/drivers/android/screen/session.test.ts"], + "maxCrap": 45, + "reason": "The capture's `setup` builds both devices' worlds — two targets, a scripted runner, an adb server, a clock, a filesystem, an optional scripted screen answer — in one helper so each case reads as one claim; the branches are optional arrangement, not logic under test." + }, { "files": ["e2e/fake-driver/fake-driver.ts"], "maxCrap": 45, diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3e33a58c7..34deb0148 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -607,10 +607,13 @@ sends almost nothing. `capabilities.stream.fps` is a ceiling rather than a rate reason. On a Mac an iOS capture costs about 50-80 MB of memory per device being watched. -An iOS simulator's screen and an Android emulator's screen can be streamed. A -lease on a physical iPhone or Android phone is refused with -`STREAM_NOT_SUPPORTED`, naming that as the reason rather than failing for one -the reader has to guess. +An iOS simulator's screen, an Android emulator's screen and a physical +Android phone's screen can be streamed. A lease on a physical iPhone is +refused with `STREAM_NOT_SUPPORTED`, naming that as the reason rather than +failing for one the reader has to guess. A phone whose screen is off is +woken first; one that does not wake is refused with `STREAM_UNAVAILABLE` saying +to turn it on. While a phone streams, its stay-awake setting is raised so the +screen stays on as long as it charges, and put back when the stream ends. - **iOS** needs the capture program `pnpm build` builds on a Mac with Xcode selected. Without it an iOS stream is refused with diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 1aa849a08..3c7acf10a 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -263,12 +263,15 @@ The panel is on every lease's page, and streams wherever the worker the lease runs on has screen streaming turned on (see [`capabilities.stream.enabled`](CONFIGURATION.md)). Where it is off, the panel says so before you press anything, and the button cannot be pressed; where the lease is on a device a screen cannot be -captured from — a physical iPhone or Android phone — it says that a live screen -comes only from a simulator or an emulator. Either way it starts nothing. - -The first picture can take a while on a slow emulator. The panel waits up to 90 -seconds for it, longer than a worker takes to give up, so a capture that cannot -start shows the worker's reason rather than a timeout. +captured from — a physical iPhone — it says that a live screen comes only from a +simulator, an emulator or a physical Android phone. Either way it starts nothing. + +The first picture can take a while — on a slow emulator, or on a physical +Android phone, whose screen state and shared adb server are read before the +capture starts. The panel waits up to 200 seconds for it, longer than a worker +takes to give up, so a capture that cannot start shows the worker's reason +rather than a timeout. A phone whose screen is off is woken first; one that does +not wake is refused with a message that says so. ### Who holds a lease diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index f25ff98e9..1abbd7b69 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -942,8 +942,10 @@ worth asking for twice rather than holding open in advance. Authorization is the same as every other lease route: a token sees its own leases, an operator sees any, and anything else is a `404`. `STREAM_NOT_SUPPORTED` (415) means the device behind the lease can never produce a picture here — a -physical phone. `STREAM_UNAVAILABLE` (503) means it could but cannot now: a -capture program that is not installed, or a device that painted nothing within +physical iPhone. `STREAM_UNAVAILABLE` (503) means it could but cannot now: a +capture program that is not installed, a physical Android phone whose screen is +off and did not turn on when woken (a phone whose screen is off is woken first), +or a device that painted nothing within 30 seconds; asking again is the right move. A stream that stops receiving frames for 30 seconds ends with an error rather than freezing on its last picture. `WORKER_UNREACHABLE` on a gateway means the worker that holds the lease is gone. diff --git a/e2e/slow-android-physical.test.ts b/e2e/slow-android-physical.test.ts index ee1709442..142d8e642 100644 --- a/e2e/slow-android-physical.test.ts +++ b/e2e/slow-android-physical.test.ts @@ -12,7 +12,10 @@ const APK = process.env["SIMLOCK_PHYSICAL_ANDROID_APK"]; const PROBE_INTERVAL_MS = 2_000; const EXEC_TIMEOUT_MS = 5_000; const MINUTE = 60_000; +const STREAM_OPEN_BOUND = 4 * MINUTE; +const KEY_FRAME_BOUND = 2 * MINUTE; const AGENT = "phone-lane-android"; +const TAG = { alive: 0x06, description: 0x01, keyframe: 0x02, delta: 0x03, meta: 0x05 } as const; const missing = SERIAL === undefined || SERIAL === "" @@ -21,6 +24,11 @@ const missing = ? "SIMLOCK_PHYSICAL_ANDROID_APK" : undefined; +interface Frame { + readonly tag: number; + readonly payload: Uint8Array; +} + interface Grant { readonly device: { readonly driverDeviceId: string }; readonly environment: Record; @@ -69,12 +77,17 @@ async function serverPid(): Promise { return stdout.trim().split("\n")[0] ?? ""; } -async function rig(execTimeoutMs?: number): Promise { +async function rig(options: { readonly execTimeoutMs?: number } = {}): Promise { const { env, port } = await withHttpDaemon((port) => ({ configOverrides: { - ...(execTimeoutMs === undefined ? {} : { exec: { timeoutMs: execTimeoutMs } }), + ...(options.execTimeoutMs === undefined + ? {} + : { exec: { timeoutMs: options.execTimeoutMs } }), health: { probeIntervalMs: PROBE_INTERVAL_MS, stableObservations: 2 }, http: { enabled: true, host: "127.0.0.1", port }, + capabilities: { + stream: { bitrateKbps: 1500, enabled: true, fps: 30, maxDimension: 720 }, + }, }, driver: "real", })); @@ -125,6 +138,66 @@ async function exec(daemon: Rig, leaseId: string, args: readonly string[]): Prom return response.text(); } +async function within(work: Promise, bound: number, what: string): Promise { + let timer: NodeJS.Timeout | undefined; + const stalled = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`timed out after ${bound} ms waiting for ${what}`)), + bound, + ); + }); + try { + return await Promise.race([work, stalled]); + } finally { + clearTimeout(timer); + } +} + +// why: the body is an endless stream, so this reads frames until it has what it came for and then +// lets go, rather than reading to an end that never comes. +async function readFrames( + body: ReadableStream, + enough: (frames: readonly Frame[]) => boolean, + whileOpen?: () => Promise, +): Promise { + const reader = body.getReader(); + const frames: Frame[] = []; + let buffer = new Uint8Array(0); + try { + while (!enough(frames)) { + const step = await within(reader.read(), KEY_FRAME_BOUND, "the stream's frames"); + if (step.done) break; + const joined = new Uint8Array(buffer.length + step.value.length); + joined.set(buffer); + joined.set(step.value, buffer.length); + buffer = joined; + while (buffer.length >= 5) { + const length = new DataView(buffer.buffer, buffer.byteOffset).getUint32(0); + if (buffer.length < 4 + length) break; + frames.push({ payload: buffer.slice(5, 4 + length), tag: buffer[4]! }); + buffer = buffer.slice(4 + length); + } + } + // why: runs once the frames are in and before the stream is let go, so it sees the stream open. + await whileOpen?.(); + } finally { + await reader.cancel().catch(() => undefined); + } + return frames; +} + +async function streamOf(daemon: Rig, leaseId: string): Promise { + const response = await fetch(`${daemon.base}/v1/stream/leases/${encodeURIComponent(leaseId)}`, { + headers: daemon.auth, + // why: covers the ~185 s worst case of opening the stream, so a stall fails here naming its step. + signal: AbortSignal.timeout(STREAM_OPEN_BOUND), + }); + // why: a 200 body is an endless stream, so its text is read only for a failure, never as an argument evaluated up front. + const detail = response.status === 200 ? "" : await response.text().catch(() => ""); + expect(response.status, detail).toBe(200); + return response; +} + describe.skipIf(missing !== undefined)( missing === undefined ? "Android physical phone (real adb)" @@ -223,11 +296,131 @@ describe.skipIf(missing !== undefined)( }, ); + it( + "a lease on the phone streams a meta frame and a key frame over GET /v1/stream/leases/{leaseId}, and after the lease ends the phone holds no simlock-scrcpy jar and no scrcpy server process and the host keeps no capture shell, with the phone's screen off when the stream asks and its stay-awake setting put back within 10 s of the lease's end", + { timeout: 10 * MINUTE }, + async () => { + const stayOn = ( + await adbOut(serial, ["shell", "settings", "get", "global", "stay_on_while_plugged_in"]) + ).trim(); + const screenIsOff = async (): Promise => { + const power = await adbOut(serial, ["shell", "dumpsys", "power"]); + const word = /^\s*mWakefulness=(\S+)\s*$/m.exec(power)?.[1]; + return word === "Asleep" || word === "Dozing"; + }; + // why: the setting is put back whatever the case does, so a failure leaves the phone as it was found. + try { + // why: 2 is not scrcpy's 7, so a restore of the recorded value shows in the setting. + await adbOut(serial, [ + "shell", + "settings", + "put", + "global", + "stay_on_while_plugged_in", + "2", + ]); + await adbOut(serial, ["shell", "input", "keyevent", "KEYCODE_SLEEP"]); + await waitFor(screenIsOff, { + interval: 500, + label: "the phone's screen off before the stream asks", + timeout: 15_000, + }); + + const daemon = await rig(); + await enroll(daemon.env, serial); + const grant = await leasePhysical(daemon.env); + + const response = await streamOf(daemon, grant.lease.id); + if (response.body === null) throw new Error("the stream answered without a body"); + const frames = await readFrames( + response.body, + (read) => read.some((frame) => frame.tag === TAG.keyframe), + async () => { + // why: 7 is scrcpy's stay_awake value; read while the stream body is still open, so the viewer's cancel cannot have put it back. + expect( + ( + await adbOut(serial, [ + "shell", + "settings", + "get", + "global", + "stay_on_while_plugged_in", + ]) + ).trim(), + "stay_on_while_plugged_in while the stream is open", + ).toBe("7"); + // why: the lease ends with the stream still open, so the wait below cannot be met by the viewer's own cancel. + expect(await daemon.env.cli(["release", grant.lease.id])).toMatchObject({ code: 0 }); + }, + ); + + const tags = frames.map((frame) => frame.tag); + expect(tags).toContain(TAG.meta); + expect(tags).toContain(TAG.keyframe); + const meta = JSON.parse(new TextDecoder().decode(frames[0]!.payload)) as { + codec: string; + width: number; + height: number; + }; + expect(meta.codec).toBe("h264"); + expect(Math.max(meta.width, meta.height)).toBeGreaterThan(0); + + await waitFor( + async () => + ( + await adbOut(serial, [ + "shell", + "settings", + "get", + "global", + "stay_on_while_plugged_in", + ]) + ).trim() === "2", + { + interval: 500, + label: "stay_on_while_plugged_in back at 2 after the lease ended", + timeout: 10_000, + }, + ); + + await waitFor( + async () => { + const processes = await adbOut(serial, ["shell", "ps", "-A", "-o", "ARGS"]); + const files = await adbOut(serial, ["shell", "ls", "/data/local/tmp"]); + return ( + !processes.includes("com.genymobile.scrcpy.Server") && + !files.includes("simlock-scrcpy-") + ); + }, + { + interval: 500, + label: "no scrcpy server process and no pushed jar left on the phone", + timeout: 30_000, + }, + ); + + const hostShells = await new Promise((resolve) => { + execFile("pgrep", ["-fl", "[s]imlock-scrcpy-"], (_error, stdout) => resolve(stdout)); + }); + expect(hostShells, "a host adb shell for the capture outlived the lease").toBe(""); + } finally { + await adbOut(serial, [ + "shell", + "settings", + "put", + "global", + "stay_on_while_plugged_in", + stayOn, + ]); + } + }, + ); + it( "with a short exec.timeoutMs, a device.exec adb shell sleep 60 on the leased phone ends EXEC_TIMEOUT, and the adb server listening on 5037 still runs with the pid it had before the command", { timeout: 5 * MINUTE }, async () => { - const daemon = await rig(EXEC_TIMEOUT_MS); + const daemon = await rig({ execTimeoutMs: EXEC_TIMEOUT_MS }); await enroll(daemon.env, serial); const grant = await leasePhysical(daemon.env); const pidBefore = await serverPid(); diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 5e0232047..26ec6f547 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -3038,8 +3038,192 @@ describe("AndroidDriver screen capture", () => { ).rejects.toThrow(/not running/); expect(runner.calls).toEqual([]); }); + + it("routes each device's capture to its own adb server: a phone's commands run adb -P 5037 and its socket connects to 5037, an emulator's use Simlock's port", async () => { + const filesystem = await androidFilesystem(); + await filesystem.mkdirp("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/simlock/vendor"); + await filesystem.writeFileAtomic(serverPath, "jar"); + const phone = { + address: "R58M123ABC", + deviceId: "R58M123ABC", + driverData: {}, + enrolledApps: [], + physical: true, + } as const; + const clock = new FakeClock(1_000); + // why: the shared server answers the version check with Simlock's own protocol, so the phone's + // target is open and its commands are expected to go out. + const probe = new FakeTcpProbe([5038, 5037]); + probe.replyWith("OKAY00040029"); + const runner = new CaptureRoutingRunner(); + const tcp = new FakeTcpStreamConnector(); + const driver = await createDriver(filesystem, runner, { + clock, + scrcpyServerPath: serverPath, + tcpProbe: probe, + tcpStreamConnector: tcp, + }); + + // why: each open is stopped while it waits on its socket's first reply — which is exactly the + // moment this test owns: every command has gone out through the device's own server, the socket + // has been aimed at the device, and a stop runs nothing further. + const phoneStop = new AbortController(); + const phoneOpening = driver.screenCapture?.open(phone, settings, phoneStop.signal); + if (phoneOpening === undefined) throw new Error("the driver offers no screen capture"); + // why: the rejection is asserted below; marking it handled here keeps a rejection that arrives + // while this test is still reading the socket from being reported as unhandled. + phoneOpening.catch(() => undefined); + await waitForSocket(clock, tcp, 1); + expect(tcp.connections[0]?.port).toBe(5037); + expect(tcp.connections[0]?.peer.writtenText()).toContain("host:transport:R58M123ABC"); + phoneStop.abort(); + await expect(driveOpen(clock, phoneOpening)).rejects.toThrow(/closed the connection/); + + const emulatorStop = new AbortController(); + const emulatorOpening = driver.screenCapture?.open(running, settings, emulatorStop.signal); + if (emulatorOpening === undefined) throw new Error("the driver offers no screen capture"); + emulatorOpening.catch(() => undefined); + await waitForSocket(clock, tcp, 2); + expect(tcp.connections[1]?.port).toBe(adbServerPort); + expect(tcp.connections[1]?.peer.writtenText()).toContain("host:transport:emulator-5586"); + emulatorStop.abort(); + await expect(driveOpen(clock, emulatorOpening)).rejects.toThrow(/closed the connection/); + + // why: every command the phone's session ran aims at the shared server — `adb -P 5037` with + // that server's env, Simlock's port in it and the three keys that could aim adb elsewhere + // removed — and every command the emulator's session ran carries this driver's scoped env, + // which points at Simlock's own port. Which commands a phone's session runs (its screen read + // included) is the capture's and the handler's own claim, proved in their own files. + const commands = runner.calls.filter((call) => call.args[0] !== "version"); + const phoneCommands = commands.filter((call) => call.args[0] === "-P"); + const emulatorCommands = commands.filter((call) => call.args[0] === "-s"); + expect(phoneCommands.length).toBeGreaterThanOrEqual(3); + for (const call of phoneCommands) { + expect(call.args.slice(0, 3)).toEqual(["-P", "5037", "-s"]); + expect(call.args[3]).toBe("R58M123ABC"); + expect(call.options.env).toEqual({ + ANDROID_ADB_SERVER_PORT: "5037", + ANDROID_HOME: sdk, + }); + } + expect( + phoneCommands.map((call) => + call.args[4] === "push" + ? "push" + : call.args[5] === "rm" + ? "rm" + : call.args[5]?.startsWith("CLASSPATH=") + ? "server" + : String(call.args[4]), + ), + ).toEqual(expect.arrayContaining(["push", "server", "rm"])); + expect(emulatorCommands.map((call) => call.args.slice(0, 3))).toEqual([ + ["-s", "emulator-5586", "push"], + ["-s", "emulator-5586", "shell"], + ["-s", "emulator-5586", "shell"], + ]); + for (const call of emulatorCommands) { + expect(call.options.env).toEqual(scopedEnv); + } + }); }); +// why: flushes work until the n-th raw connection has been made, advancing the fake clock so the +// capture's own bounds cannot strand it; an open that died first fails on a named assertion. +async function waitForSocket( + clock: FakeClock, + tcp: FakeTcpStreamConnector, + count: number, +): Promise { + for (let spent = 0; spent < 60_000 && tcp.connections.length < count; spent += 50) { + for (let flush = 0; flush < 10; flush += 1) + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(50); + } + expect(tcp.connections.length, "the capture reached its socket").toBe(count); +} + +// why: awaits an open with the fake clock turning, so its own 15 s bound can fire while the test waits. +async function driveOpen(clock: FakeClock, opening: Promise): Promise { + let done = false; + void opening.then( + () => (done = true), + () => (done = true), + ); + for (let spent = 0; spent < 60_000 && !done; spent += 50) { + for (let flush = 0; flush < 10; flush += 1) + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(50); + } + return await opening; +} + +/** + * why: answers every adb call a capture makes by what it is rather than by its place in a queue, so + * the routing this test reads is proven the same way whether or not the capture reads the phone's + * screen state first -- the server's shell hangs until the capture's own close kills it, as a live + * scrcpy server does. + */ +class CaptureRoutingRunner implements ProcessRunner { + readonly calls: { readonly args: readonly string[]; readonly options: ProcessRunOptions }[] = []; + #nextPid = 1; + + run( + command: string, + args: readonly string[], + options: ProcessRunOptions = {}, + ): Promise { + return this.spawn(command, args, options).wait(); + } + + spawn(_command: string, args: readonly string[], options: ProcessRunOptions = {}): ProcessHandle { + this.calls.push({ args, options }); + const rest = args[0] === "-P" ? args.slice(2) : [...args]; + const line = rest.join(" "); + if (line === "version") { + return endedHandle(this.#nextPid++, "Android Debug Bridge version 1.0.41\nVersion 35.0.2\n"); + } + if (line.includes("dumpsys power")) { + return endedHandle(this.#nextPid++, " mWakefulness=Awake\n"); + } + if (/shell CLASSPATH=\S*app_process/.test(line)) { + return hangingHandle(this.#nextPid++); + } + return endedHandle(this.#nextPid++, ""); + } + + spawnStreaming(..._args: Parameters): never { + throw new Error("a screen capture spawns no streaming process"); + } +} + +function endedHandle(pid: number, stdout: string): ProcessHandle { + return { + kill: () => undefined, + pid, + stderr: emptyLines(), + stdout: emptyLines(), + unref: () => undefined, + wait: async () => ({ code: 0, stderr: "", stdout }), + }; +} + +function hangingHandle(pid: number): ProcessHandle { + let settle: (() => void) | undefined; + const ended = new Promise((resolve) => (settle = resolve)); + return { + kill: () => settle?.(), + pid, + stderr: emptyLines(), + stdout: emptyLines(), + unref: () => undefined, + wait: async () => { + await ended; + return { code: null, stderr: "", stdout: "" }; + }, + }; +} + describe("AndroidDriver.create", () => { it("creates and marks its own AVD home under SIMLOCK_HOME when none exists yet", async () => { const filesystem = await androidFilesystem({ withDeviceRoot: false }); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index f28da9f4c..0269f4c82 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -40,6 +40,7 @@ import { type ReclaimResult, removeListedComponent, type ScreenCapture, + ScreenUnavailableError, RuntimeMissingError, sameReceipt, } from "../../core/index.js"; @@ -74,7 +75,7 @@ import { } from "./device-profile-source.js"; import { fits, isPlayStoreImage, misfitReason } from "./image-fit.js"; import { LibraryDeviceProfileSource } from "./profiles/index.js"; -import { createAndroidScreenCapture } from "./screen/index.js"; +import { createAndroidScreenCapture, type ScreenTarget } from "./screen/index.js"; import { type AndroidSdkPaths, locateSdk } from "./sdk-paths.js"; export { AdbServerUnavailableError } from "./adb-server.js"; @@ -524,19 +525,28 @@ export class AndroidDriver implements Driver { adb: string, adbServerPort: number, ): ScreenCapture | undefined { - if (options.scrcpyServerPath === undefined || options.tcpStreamConnector === undefined) { + const tcp = options.tcpStreamConnector; + if (options.scrcpyServerPath === undefined || tcp === undefined) { return undefined; } + const runner = options.processRunner; + const serverPort = adbServerPort; return createAndroidScreenCapture({ - adb, - adbServerPort, clock: options.clock, - env: () => this.#env(), filesystem: options.filesystem, - processRunner: options.processRunner, - serialOf: (device) => this.#dataFor(device).serial, serverPath: options.scrcpyServerPath, - tcp: options.tcpStreamConnector, + targetFor: async (device) => + isPhysicalDriverDevice(device) + ? this.#physical.screenTargetFor(device, tcp) + : emulatorScreenTarget( + runner, + adb, + tcp, + serverPort, + () => this.#env(), + this.#dataFor(device).serial, + device, + ), }); } @@ -2537,6 +2547,33 @@ function defaultDeviceProfileSources( }; } +// why: an emulator's capture target -- the same `adb -s …` with this driver's scoped env +// that every other emulator call carries, and raw connections to Simlock's own adb server. A phone +// gets its target from the physical handler, behind that server's version check; the capture itself +// names neither a port nor a check. +function emulatorScreenTarget( + processRunner: ProcessRunner, + adb: string, + tcp: TcpStreamConnector, + serverPort: number, + env: () => NodeJS.ProcessEnv, + serial: string, + device: VirtualDriverDevice, +): ScreenTarget { + if (serial === "") { + throw new ScreenUnavailableError( + `${device.deviceId} is not running, so it has no screen to stream`, + ); + } + return { + connect: async (timeoutMs) => await tcp.connect(serverPort, timeoutMs), + serial, + spawn: async (args) => processRunner.spawn(adb, ["-s", serial, ...args], { env: env() }), + run: async (args, timeoutMs) => + await processRunner.run(adb, ["-s", serial, ...args], { env: env(), timeoutMs }), + }; +} + function portAllocatorFor(processRunner: ProcessRunner, adb: string): PortAllocator { const existing = allocationsByRunner.get(processRunner); if (existing !== undefined) { diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 1f0549eb4..4904e8c10 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -1,10 +1,15 @@ import { describe, expect, it } from "vitest"; -import { OWNED_ROOT_MARKER_FILE, PassthroughRefusedError } from "../../core/index.js"; +import { + OWNED_ROOT_MARKER_FILE, + PassthroughRefusedError, + ScreenUnavailableError, +} from "../../core/index.js"; import { FakeClock, FakeProcessSupervisor, FakeTcpProbe, + FakeTcpStreamConnector, type Filesystem, MemoryFilesystem, type ProcessHandle, @@ -17,6 +22,8 @@ import { type StreamingProcessHandle, } from "../../ports/index.js"; import { AndroidDriver } from "./index.js"; +import { AndroidPhysicalHandler } from "./physical-handler.js"; +import type { ScreenTarget } from "./screen/index.js"; const sdk = "/android-sdk"; const home = "/home/simlock"; @@ -1496,6 +1503,94 @@ describe("Android physical handler: passthrough", () => { }); }); +describe("Android physical handler: the screen target", () => { + // why: the target a phone's scrcpy session runs on, built straight from the handler: the capture + // reaches it only through the driver, and what it must never see is the port or the check. + async function screenWorld(options: { readonly reply?: string } = {}): Promise<{ + readonly runner: PhoneAdb; + readonly target: ScreenTarget; + readonly tcp: FakeTcpStreamConnector; + }> { + const runner = new PhoneAdb([]); + const probe = new FakeTcpProbe([]); + probe.replyWith(options.reply ?? VERSION_REPLY_41); + const handler = new AndroidPhysicalHandler({ + adb, + // why: an env that aims adb elsewhere on purpose — a target that leaked these to a child + // would reach a server other than the one it just checked. + baseEnv: { + ADB_SERVER_SOCKET: "tcp:10.0.0.5:5037", + ANDROID_ADB_SERVER_ADDRESS: "10.0.0.5", + ANDROID_HOME: sdk, + ANDROID_SERIAL: "SOMEONE-ELSES-PHONE", + }, + filesystem: await androidFilesystem(), + isBareShell: () => false, + processRunner: runner, + tcpProbe: probe, + }); + const tcp = new FakeTcpStreamConnector(); + return { runner, target: handler.screenTargetFor(PHYSICAL, tcp), tcp }; + } + + it("sends nothing and refuses with the check's own message when the check is closed, for run, spawn and connect, at a mismatch and an unreadable server", async () => { + const closed = [ + { message: /speaks protocol 40/, name: "another protocol", reply: VERSION_REPLY_40 }, + { message: /unreadable/, name: "a server it cannot read", reply: "gibberish" }, + ] as const; + const verbs = [ + { + call: (target: ScreenTarget) => target.run(["shell", "dumpsys", "power"], 10_000), + name: "run", + }, + { + call: (target: ScreenTarget) => target.spawn(["shell", "app_process"]), + name: "spawn", + }, + { + call: (target: ScreenTarget) => target.connect(5_000), + name: "connect", + }, + ] as const; + for (const refusal of closed) { + for (const verb of verbs) { + const world = await screenWorld({ reply: refusal.reply }); + + const error = await rejectionOf(verb.call(world.target)); + + expect(error, `${refusal.name} via ${verb.name}`).toBeInstanceOf(ScreenUnavailableError); + expect((error as Error).message, `${refusal.name} via ${verb.name}`).toMatch( + refusal.message, + ); + expect(world.runner.commands, `${refusal.name} via ${verb.name}`).toEqual([]); + expect(world.tcp.connections, `${refusal.name} via ${verb.name}`).toEqual([]); + } + } + }); + + it("runs adb -P 5037 with the shared server's env for run and spawn, and connects to 5037, when the check is open", async () => { + const world = await screenWorld(); + + await world.target.run(["shell", "dumpsys", "power"], 10_000); + await world.target.spawn(["shell", "app_process"]); + await world.target.connect(4_000); + + expect(world.runner.calls.map((call) => [...call.args])).toEqual([ + ["version"], + ["-P", "5037", "-s", PHONE, "shell", "dumpsys", "power"], + ["-P", "5037", "-s", PHONE, "shell", "app_process"], + ]); + for (const call of world.runner.commands) { + expect(call.options.env).toEqual({ + ANDROID_ADB_SERVER_PORT: "5037", + ANDROID_HOME: sdk, + }); + } + expect(world.runner.commands[0]?.options.timeoutMs).toBe(10_000); + expect(world.tcp.connections.map((connection) => connection.port)).toEqual([5037]); + }); +}); + describe("Android physical handler: estimate", () => { it("is 90 000 ms for a reclaim of a physical spec at both clean levels, and unchanged for an emulator spec", async () => { const { driver } = await world(); diff --git a/src/drivers/android/physical-handler.ts b/src/drivers/android/physical-handler.ts index ed993f3d0..f68dcd748 100644 --- a/src/drivers/android/physical-handler.ts +++ b/src/drivers/android/physical-handler.ts @@ -7,9 +7,11 @@ import { type PhysicalInspection, type PresentPhysical, type ReclaimResult, + ScreenUnavailableError, uninstallPlan, } from "../../core/index.js"; -import type { ProcessRunner } from "../../ports/index.js"; +import type { ProcessRunner, TcpStreamConnector } from "../../ports/index.js"; +import type { ScreenTarget } from "./screen/index.js"; import { type AdbGateAnswer, DEFAULT_ADB_PORT, @@ -87,6 +89,39 @@ export class AndroidPhysicalHandler { this.#gate = new DefaultAdbServerGate({ ...options, env }); } + /** + * why: where one phone's scrcpy session runs. Every step passes the same version check every other + * phone command passes, and only then runs `adb -P 5037` with this handler's environment or opens a + * raw connection to port 5037, so the capture never names a port or a check. + */ + screenTargetFor(device: PhysicalDriverDevice, tcp: TcpStreamConnector): ScreenTarget { + const serial = device.deviceId; + const checked = async (): Promise => { + const answer = await this.#gate.check(); + if (!answer.open) throw new ScreenUnavailableError(answer.message); + }; + return { + connect: async (timeoutMs) => { + await checked(); + return await tcp.connect(DEFAULT_ADB_PORT, timeoutMs); + }, + serial, + spawn: async (args) => { + await checked(); + return this.#processRunner.spawn(this.#adb, ["-P", PORT, "-s", serial, ...args], { + env: this.#env, + }); + }, + run: async (args, timeoutMs) => { + await checked(); + return await this.#processRunner.run(this.#adb, ["-P", PORT, "-s", serial, ...args], { + env: this.#env, + timeoutMs, + }); + }, + }; + } + async advisories(): Promise { const answer = await this.#gate.check(); if (answer.open) return []; diff --git a/src/drivers/android/screen/AGENTS.md b/src/drivers/android/screen/AGENTS.md index 202119307..6f8082f73 100644 --- a/src/drivers/android/screen/AGENTS.md +++ b/src/drivers/android/screen/AGENTS.md @@ -1,9 +1,10 @@ # Android screen capture -Does: an Android emulator's screen as core's screen frames, through the vendored scrcpy server and our own client. +Does: an Android emulator's or a leased physical phone's screen as core's screen frames, through the vendored scrcpy +server and our own client. Entry: `index.ts` → `createAndroidScreenCapture(options)`, built by `AndroidDriver` as its `screenCapture` when `create` gets `scrcpyServerPath` and `tcpStreamConnector` (`daemon/main.ts` passes the jar `pnpm build` copies to dist/vendor/scrcpy). -Uses: core (`ScreenCapture`, frame encoder), ports (`ProcessRunner`, `TcpStreamConnector`, `Clock`), `../adb-host-protocol.ts`. +Uses: core (`ScreenCapture`, frame encoder), ports (`Clock`, `Filesystem`), the device's `ScreenTarget` (below). Parent: [Android driver](../AGENTS.md). Consumer: [stream](../../../stream/AGENTS.md). ## Files @@ -11,49 +12,83 @@ Parent: [Android driver](../AGENTS.md). Consumer: [stream](../../../stream/AGENT | File | Role | | ----------------- | ------------------------------------------------------------------------------ | | `index.ts` | `createAndroidScreenCapture`: the driver's `ScreenCapture`, entered only here | -| `session.ts` | One stream: push, server, socket, body, close | -| `adb-socket.ts` | `openDeviceSocket`: `host:transport` + `localabstract` on Simlock's adb server | +| `session.ts` | One stream: screen read, push, server, socket, body, close; the `ScreenTarget` | +| `adb-socket.ts` | `openDeviceSocket`: `host:transport` + `localabstract` on the target's server | | `scrcpy-video.ts` | `ScrcpyVideoParser`: scrcpy's video socket (codec id, session, media packets) | | `h264.ts` | Annex-B split, AVCC, the `avcC` record | | `envelope.ts` | `EnvelopeMapper`: scrcpy events → core's screen frames | +## Where a session runs: the target + +The driver hands the capture one `ScreenTarget` per device: `serial`, `run(args, timeoutMs)`, `spawn(args)` and +`connect(timeoutMs)`. `args` start at the adb subcommand — the target aims them at its device and picks its adb server. + +- **Emulator** (`index.ts` of the driver): `adb -s …` with the driver's scoped env, connections to Simlock's + own adb server. +- **Physical phone** (`../physical-handler.ts`): each of `run`, `spawn` and `connect` first passes the 5037 protocol + check every other phone command passes; a closed check sends nothing and throws `ScreenUnavailableError` with its + message. An open one runs `adb -P 5037 -s …` with that server's env (Simlock's port in it, + `ANDROID_ADB_SERVER_ADDRESS`, `ADB_SERVER_SOCKET` and `ANDROID_SERIAL` removed), or connects to port 5037. + +**This capture never names port 5037 and never runs that check** — the physical handler is the one place that knows +both (architecture rule 10, safety rule: the check before every physical command). A physical iPhone stays refused by +the iOS driver, not here. + ## How it works -1. Physical → `ScreenNotSupportedError`. Jar missing at `scrcpyServerPath` → `ScreenUnavailableError` - (`unavailable()` gives the same reason). No serial (not running) → `ScreenUnavailableError`. -2. `scid`: random 31-bit, written `%08x`. `adb -s push /data/local/tmp/simlock-scrcpy-.jar`. -3. `adb -s shell CLASSPATH= app_process / com.genymobile.scrcpy.Server 5.0.1 scid= +1. Jar missing at `scrcpyServerPath` → `ScreenUnavailableError` (`unavailable()` gives the same reason). Then the + device's target. **A phone's screen state is read before anything is pushed**: + `run(["shell", "dumpsys", "power"], 10_000)`, the line + `^\s*mWakefulness=(\S+)\s*$` after a trailing `\r` is stripped — what follows the word, if anything, + is blanks, so a printed `Dozing ` (a trailing blank) is the word `Dozing` — compared exactly. `Asleep` or + `Dozing` → wake it: `run(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], 10_000)` (its exit is not looked at; a + closed check at the wake still refuses), then the same read again. A second read of `Asleep` or `Dozing` → + `ScreenUnavailableError("The phone's screen is off and did not turn on. …")`, and nothing is pushed. Anything + else — `Awake`, `Dreaming`, a word that is not one, no line, a non-zero exit, a timed-out read — goes on, with no + wake after a first read of those. Emulators skip the read and the wake. The wake is the only key sent. +2. `scid`: random 31-bit, written `%08x`. ` push /data/local/tmp/simlock-scrcpy-.jar` (40 s: the + phone's own check plus the 30 s push). +3. ` shell CLASSPATH= app_process / com.genymobile.scrcpy.Server 5.0.1 scid= log_level=info tunnel_forward=true video=true audio=false control=false video_codec=h264 send_device_meta=false send_dummy_byte=true send_stream_meta=true send_frame_meta=true cleanup=true -max_size= max_fps= video_bit_rate=`. No option that changes a - device setting (`show_touches`, `stay_awake`, `screen_off_timeout`, `power_off_on_close`); with - `control=false` the server never powers the screen on. -4. No `adb forward`: a TCP connection to Simlock's adb server sends `host:transport:`, then +[stay_awake=true for a phone] max_size= max_fps= video_bit_rate=`. Only a + phone's gets `stay_awake=true`: scrcpy sets `stay_on_while_plugged_in` to 7 and its clean-up process puts + the old value back when the server ends. No other option changes a device setting (`show_touches`, + `screen_off_timeout`, `power_off_on_close`); with `control=false` the server never powers the screen on, so the + wake above is simlock's. +4. No `adb forward`: `target.connect` reaches the device socket and the session sends `host:transport:`, then `localabstract:scrcpy_`. `FAIL` on the second (nothing listening yet), a refused connect, or a socket that closes before the server's zero byte → retry every 100 ms. `FAIL` on the first → refuse. 5. Then the codec id (must be `h264`) and the first session packet (width, height) → `open` resolves. - One 15 s budget from the push's return to here. Past it, or when the shell exits first → - `ScreenUnavailableError` with the server's last 20 output lines. + One 15 s budget from the moment `spawn`'s process started (a phone's check before it is outside the + budget; each attempt's own check is inside it, and one still running past the deadline is waited for, + ≤ 5 s) to here. Past it, or when the shell exits first → `ScreenUnavailableError` with the server's last + 20 output lines. Each step keeps its own limit; there is no overall budget. A phone's worst case is + about 185 s (checks 45 s the first time and 5 s before each later step, three screen steps 20 s each, the push + 40 s, the server 15 s and a last check 5 s), which is why the console waits 200 s for a stream's headers. 6. Body: meta (session size, configured fps) on every session packet; the `avcC` description before the first picture after config packets; key/delta frames as 4-byte-length AVCC. Pull-based (`highWaterMark: 0`): the socket is read only when the body's reader pulls; nothing is dropped. A body whose socket ends errors with the server's last output and closes the feed. scrcpy sends nothing for a still screen, so after 5 s of quiet the body sends an empty `alive` frame. 7. `close` (idempotent, ≤ 5 s): close the socket, wait 1 s for the shell, then SIGKILL it, - `adb shell rm -f `. The body's end, error or cancel calls it. + ` shell rm -f ` — through the target, so a check still closed then sends nothing and `close` + resolves. The body's end, error or cancel calls it. A rotation starts a new scrcpy session: a new meta frame, then a new description before the next picture; the browser decoder re-reads both mid-stream. -Stop: `open` takes an `AbortSignal`. A stop before the push runs nothing; one during the push (it -cannot be interrupted) starts no server after it; one while connecting ends the retries. A stopped -open cleans up (shell killed, jar removed) before it throws. `alive` frames begin only after the +Stop: `open` takes an `AbortSignal`. A stop before the screen read runs nothing; one during the first read, the +wake, the second read or the push (none can be interrupted) waits for it and runs nothing after it; one while connecting ends the retries. +A stopped open cleans up (shell killed, jar removed) before it throws. `alive` frames begin only after the first key frame, so an encoder that never paints meets the stream's silence bound. ## State and timers | What | Default | Key | | -------------------- | ------------------------------- | ----------------------------------------------------------- | +| Phone's screen read | 10 s | `SCREEN_READ_TIMEOUT_MS` | +| Phone's wake | 10 s | `WAKE_TIMEOUT_MS` | | Push / start / close | 30 s / 15 s, retry 100 ms / 5 s | `PUSH_TIMEOUT_MS`, `START_DEADLINE_MS`, `CLOSE_DEADLINE_MS` | | Quiet before `alive` | 5 s | `ALIVE_AFTER_MS` | @@ -63,7 +98,10 @@ process at its start and by `rm -f` on close. ## Rules - A screen stream touches only its own `scid`: its jar path and socket name; never another stream's. -- A screen stream changes no device setting and drops no frame. +- A screen stream changes no device setting and drops no frame. One exception: a phone's stream sets stay + awake (`stay_on_while_plugged_in` to 7) while it runs, and scrcpy puts the old value back. +- Every adb command and connection of a session goes through its target. The capture names no adb server port and + runs no version check of its own. ## Known gaps @@ -72,4 +110,15 @@ process at its start and by `rm -f` on close. `adb shell` died no scrcpy process and no jar were left on the device. - **Key frames every 10 s** (scrcpy's default): a viewer that resets its decoder waits up to 10 s. - **The `avcC` record omits the High-profile extension** (chroma format, bit depths); browsers accept it. -- **Physical Android devices have no screen stream**, and the jar's digest is not checked at push. +- **A phone that is not charging is woken but not held awake**: stay awake does nothing without power. When its + screen turns off mid-stream it shows its last picture, still marked live by `alive` frames, until the screen is on + again or the lease ends. Nothing ends the stream for it. +- **A phone woken to its lock screen streams the lock screen.** simlock does not unlock it. +- **Two viewers of one lease**: the second's server finds the setting at 7 already and remembers nothing; when the + first viewer's stream ends, the old value comes back while the second still streams. +- **The setting stays at 7** if the phone loses power or reboots before the clean-up process writes the old value back. +- **A holder's own stay-awake change is overwritten**: a holder that changes `stay_on_while_plugged_in` over + passthrough `adb` while a stream is open has it replaced when the stream ends, since scrcpy writes back the value it found. +- **A pushed jar can survive on a phone** when the version check closes after the push and stays closed through the + close and the server never started: the `rm -f` goes through that check and is not sent. A server that started + deletes its own jar (`cleanup=true`). The jar's digest is not checked at push either. diff --git a/src/drivers/android/screen/adb-socket.ts b/src/drivers/android/screen/adb-socket.ts index 56491b2cc..26886401b 100644 --- a/src/drivers/android/screen/adb-socket.ts +++ b/src/drivers/android/screen/adb-socket.ts @@ -1,4 +1,4 @@ -import type { TcpStream, TcpStreamConnector } from "../../../ports/index.js"; +import type { TcpStream } from "../../../ports/index.js"; import { ADB_FAIL, ADB_LENGTH_BYTES, @@ -51,21 +51,22 @@ type DeviceSocketOutcome = | { readonly kind: "no-transport"; readonly reason: string }; interface DeviceSocketRequest { - readonly tcp: TcpStreamConnector; - readonly adbServerPort: number; + // why: the raw connection is made by the device's target, which owns the choice of adb server: + // Simlock's own for an emulator, port 5037 for a physical phone. + readonly connect: (timeoutMs: number) => Promise; readonly serial: string; readonly socketName: string; readonly timeoutMs: number; readonly signal: AbortSignal; } -// why: speaking adb's host protocol directly reaches the device socket through Simlock's own server -// without an `adb forward`, so a daemon that dies mid-stream leaves no listening port on the host. -// adb answers `localabstract:` with OKAY only once adbd's connect to that socket succeeded, and with -// FAIL "closed" while nothing listens there yet: +// why: speaking adb's host protocol directly reaches the device socket through the target's adb +// server without an `adb forward`, so a daemon that dies mid-stream leaves no listening port on the +// host. adb answers `localabstract:` with OKAY only once adbd's connect to that socket succeeded, and +// with FAIL "closed" while nothing listens there yet: // https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/sockets.cpp export async function openDeviceSocket(request: DeviceSocketRequest): Promise { - const stream = await request.tcp.connect(request.adbServerPort, request.timeoutMs); + const stream = await request.connect(request.timeoutMs); const onAbort = () => { stream.close(); }; diff --git a/src/drivers/android/screen/index.ts b/src/drivers/android/screen/index.ts index 408559af3..79cf0f3a3 100644 --- a/src/drivers/android/screen/index.ts +++ b/src/drivers/android/screen/index.ts @@ -1 +1,2 @@ export { createAndroidScreenCapture } from "./session.js"; +export type { ScreenTarget } from "./session.js"; diff --git a/src/drivers/android/screen/session.test.ts b/src/drivers/android/screen/session.test.ts index 1961dde59..27683e623 100644 --- a/src/drivers/android/screen/session.test.ts +++ b/src/drivers/android/screen/session.test.ts @@ -3,23 +3,23 @@ import { describe, expect, it } from "vitest"; import { type PhysicalDriverDevice, SCREEN_FRAME_TAG, - ScreenNotSupportedError, ScreenUnavailableError, type VirtualDriverDevice, } from "../../../core/index.js"; import { FakeClock, MemoryFilesystem, + type ProcessResult, ScriptedProcessRunner, type ScriptedProcessExpectation, type TcpStream, - type TcpStreamConnector, } from "../../../ports/index.js"; import { ALIVE_AFTER_MS, CLOSE_DEADLINE_MS, CONNECT_RETRY_MS, createAndroidScreenCapture, + type ScreenTarget, START_DEADLINE_MS, } from "./session.js"; import { codecId, concatBytes, mediaPacket, SAMPLE, sessionPacket } from "./test-scrcpy.js"; @@ -27,17 +27,34 @@ import { codecId, concatBytes, mediaPacket, SAMPLE, sessionPacket } from "./test const ADB = "/sdk/platform-tools/adb"; const SERVER = "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/simlock/scrcpy-server-v5.0.1"; const SERIAL = "emulator-5586"; -const PORT = 5038; +const PHONE_SERIAL = "R58M123ABC"; const SCID = 0x1234abcd; const DEVICE_JAR = "/data/local/tmp/simlock-scrcpy-1234abcd.jar"; const SETTINGS = { bitrateKbps: 1500, fps: 30, maxDimension: 720 }; +const SCREEN_READ_MS = 10_000; +const WAKE_MS = 10_000; const DEVICE: VirtualDriverDevice = { address: SERIAL, deviceId: "simlock_1", driverData: {}, physical: false, }; -const ENV = { ANDROID_ADB_SERVER_PORT: String(PORT), ANDROID_AVD_HOME: "/root", PATH: "/bin" }; +const PHONE: PhysicalDriverDevice = { + address: PHONE_SERIAL, + deviceId: PHONE_SERIAL, + driverData: {}, + enrolledApps: [], + physical: true, +}; + +// why: the reason a phone's target gives when the shared adb server's version check is closed. The +// capture is expected to pass it through as its own, unchanged, and to run nothing after it. +const GATE_REFUSAL = + "the adb server on port 5037 speaks protocol 40 and Simlock's adb speaks 41. " + + "No command goes to physical Android devices until they match, and Simlock will not restart that server."; +const SCREEN_OFF = + "The phone's screen is off and did not turn on. Turn it on and ask for the stream again."; +const WAKE_ARGS = "shell input keyevent KEYCODE_WAKEUP"; type Behaviour = "accept" | "refuse" | "no-transport" | "connection-refused" | "silent"; @@ -93,28 +110,34 @@ class Peer { } } -class AdbServer implements TcpStreamConnector { +// why: the adb server on the far side of a target's `connect`; what it answers is scripted per attempt. +class AdbServer { readonly peers: Peer[] = []; - readonly ports: number[] = []; readonly #behaviours: Behaviour[]; constructor( behaviours: Behaviour[] = [], readonly otherwise: Behaviour = "accept", + // why: a peer that stays silent and open until this moment of the fake clock, then refuses. + private readonly acceptFromMs: number | undefined = undefined, ) { this.#behaviours = behaviours; } - async connect(port: number): Promise { - this.ports.push(port); + newPeer(clock: FakeClock): Peer | undefined { + if (this.acceptFromMs !== undefined && clock.now() < this.acceptFromMs) { + const waiting = new Peer(); + waiting.send("OKAY", "FAIL0006closed"); + return waiting; + } const behaviour = this.#behaviours.shift() ?? this.otherwise; if (behaviour === "connection-refused") throw new Error("connect ECONNREFUSED 127.0.0.1"); const peer = new Peer(); this.peers.push(peer); - if (behaviour === "no-transport") peer.send("FAIL0020device 'emulator-5586' not found"); + if (behaviour === "no-transport") peer.send(`FAIL0020device '${SERIAL}' not found`); if (behaviour === "refuse") peer.send("OKAY", "FAIL0006closed"); if (behaviour === "accept") peer.send("OKAY", "OKAY", new Uint8Array([0])); - return peer.stream; + return peer; } get last(): Peer { @@ -124,21 +147,131 @@ class AdbServer implements TcpStreamConnector { } } +interface PowerAnswer { + readonly code: number | null; + readonly stdout: string; +} + +// why: the device's capture target as the driver builds it. `args` start at the adb subcommand, so +// the serial and the adb server are the target's and not the capture's: this fake records what it +// was asked to run, and the commands themselves are the scripted runner's, so a push can fail, a +// server can hang and a kill can be escalated exactly as before the target existed. +class FakeTarget implements ScreenTarget { + readonly log: string[] = []; + readonly powerReads: number[] = []; + readonly wakes: number[] = []; + // why: the order of the screen steps, so "reads again after the wake" can fail. + readonly screenSteps: string[] = []; + readonly connects: number[] = []; + readonly runner: ScriptedProcessRunner; + readonly server: AdbServer; + // why: `"refuse"` is the version check refusing the read, `"slow"` a read that ends later. + // why: a list answers the reads in turn, the last one for every read after it. + power: PowerAnswer | "refuse" | "slow" | readonly (PowerAnswer | "refuse" | "slow")[] = { + code: 0, + stdout: " mWakefulness=Awake\n", + }; + // why: what the wake does: exits 0, exits non-zero, hangs to its limit, or is refused by the check. + wake: "ok" | "fail" | "slow" | "refuse" = "ok"; + // why: holds each screen read the check lets through in flight for the read limit before it answers as scripted (a refused read throws before the hold), so a stop can arrive while a read that will say Asleep is still running. + holdReads = false; + // why: stands in for a check that closes mid-session: a command whose args this picks out is refused as a closed check refuses it. + refuses: (args: readonly string[]) => boolean = () => false; + // why: stand-ins for the check a target runs before its own command or connection, so a bound can be measured against it. + spawnDelayMs = 0; + connectDelayMs = 0; + #clock: FakeClock; + + constructor( + readonly serial: string, + clock: FakeClock, + expectations: ScriptedProcessExpectation[], + server: AdbServer | undefined, + ) { + this.#clock = clock; + this.runner = new ScriptedProcessRunner(expectations); + this.server = server ?? new AdbServer(); + } + + get steps(): string[] { + return this.log.map((entry) => (entry.includes("app_process") ? "server" : entry)); + } + + async run(args: readonly string[], timeoutMs: number): Promise { + if (isScreenRead(args)) return await this.#readScreen(timeoutMs); + if (args.join(" ") === WAKE_ARGS) { + this.wakes.push(timeoutMs); + this.screenSteps.push("wake"); + if (this.wake === "refuse") throw new ScreenUnavailableError(GATE_REFUSAL); + if (this.wake === "slow") { + await this.#sleep(WAKE_MS); + return { code: null, stderr: "", stdout: "" }; + } + return { code: this.wake === "fail" ? 1 : 0, stderr: "", stdout: "" }; + } + if (this.refuses(args)) throw new ScreenUnavailableError(GATE_REFUSAL); + this.log.push(args.join(" ")); + return await this.runner.run(ADB, args); + } + + async spawn(args: readonly string[]): Promise { + if (this.spawnDelayMs > 0) await this.#sleep(this.spawnDelayMs); + if (this.refuses(args)) throw new ScreenUnavailableError(GATE_REFUSAL); + this.log.push(args.join(" ")); + return await this.runner.spawn(ADB, args); + } + + async connect(timeoutMs: number): Promise { + this.connects.push(timeoutMs); + if (this.refuses(["connect"])) throw new ScreenUnavailableError(GATE_REFUSAL); + if (this.connectDelayMs > 0) await this.#sleep(this.connectDelayMs); + const peer = this.server.newPeer(this.#clock); + if (peer === undefined) throw new Error("connect ECONNREFUSED 127.0.0.1"); + return peer.stream; + } + + async #readScreen(timeoutMs: number): Promise { + const answer = Array.isArray(this.power) + ? (this.power[Math.min(this.powerReads.length, this.power.length - 1)] as PowerAnswer) + : (this.power as PowerAnswer | "refuse" | "slow"); + this.powerReads.push(timeoutMs); + this.screenSteps.push("read"); + if (answer === "refuse") throw new ScreenUnavailableError(GATE_REFUSAL); + if (this.holdReads || answer === "slow") await this.#sleep(SCREEN_READ_MS); + if (answer === "slow") return { code: null, stderr: "", stdout: "" }; + return { code: answer.code, stderr: "", stdout: answer.stdout }; + } + + #sleep(ms: number): Promise { + return new Promise((resolve) => { + this.#clock.setTimer(ms, resolve); + }); + } +} + +function isScreenRead(args: readonly string[]): boolean { + return args.join(" ") === "shell dumpsys power"; +} + function push(result: Partial<{ code: number; stderr: string }> = {}): ScriptedProcessExpectation { return { match: { - args: ["-s", SERIAL, "push", SERVER, /^\/data\/local\/tmp\/simlock-scrcpy-[0-9a-f]{8}\.jar$/], + args: ["push", SERVER, /^\/data\/local\/tmp\/simlock-scrcpy-[0-9a-f]{8}\.jar$/], command: ADB, }, result: { code: result.code ?? 0, stderr: result.stderr ?? "", stdout: "" }, }; } -function shell(extra: Partial = {}): ScriptedProcessExpectation { +// why: a phone's server command carries one more option (stay_awake) than an emulator's 20 arguments. +function shell( + extra: Partial = {}, + options = 20, +): ScriptedProcessExpectation { return { hangs: true, match: { - args: ["-s", SERIAL, "shell", ...Array.from({ length: 20 }, () => /.*/)], + args: ["shell", ...Array.from({ length: options }, () => /.*/)], command: ADB, }, ...extra, @@ -148,25 +281,25 @@ function shell(extra: Partial = {}): ScriptedProcess function remove(): ScriptedProcessExpectation { return { match: { - args: [ - "-s", - SERIAL, - "shell", - "rm", - "-f", - /^\/data\/local\/tmp\/simlock-scrcpy-[0-9a-f]{8}\.jar$/, - ], + args: ["shell", "rm", "-f", /^\/data\/local\/tmp\/simlock-scrcpy-[0-9a-f]{8}\.jar$/], command: ADB, }, }; } +// why: both devices' worlds — the other device's target is here so "it went through this device's +// target" can fail; a capture that aimed at the wrong device would show up in the other's lists. async function setup( options: { + readonly acceptFromMs?: number; + readonly device?: VirtualDriverDevice | PhysicalDriverDevice; readonly expectations?: ScriptedProcessExpectation[]; - readonly server?: AdbServer; readonly jar?: boolean; + readonly power?: FakeTarget["power"]; + readonly wake?: FakeTarget["wake"]; + readonly refuses?: (args: readonly string[]) => boolean; readonly scid?: (() => number) | null; + readonly server?: AdbServer; } = {}, ) { const clock = new FakeClock(1_000); @@ -175,21 +308,35 @@ async function setup( await filesystem.mkdirp("/simlock"); await filesystem.writeFileAtomic(SERVER, "jar"); } - const runner = new ScriptedProcessRunner(options.expectations ?? [push(), shell(), remove()]); - const server = options.server ?? new AdbServer(); + const device = options.device ?? DEVICE; + const phone = device.physical === true; + const server = + options.server ?? + new AdbServer( + [], + "accept", + options.acceptFromMs === undefined ? undefined : 1_000 + options.acceptFromMs, + ); + const target = new FakeTarget( + phone ? PHONE_SERIAL : SERIAL, + clock, + options.expectations ?? [push(), shell({}, phone ? 21 : 20), remove()], + server, + ); + const scripted = { power: options.power, refuses: options.refuses, wake: options.wake }; + Object.assign( + target, + Object.fromEntries(Object.entries(scripted).filter(([, value]) => value !== undefined)), + ); + const other = new FakeTarget(phone ? SERIAL : PHONE_SERIAL, clock, [], new AdbServer()); const capture = createAndroidScreenCapture({ - adb: ADB, - adbServerPort: PORT, clock, - env: () => ({ ...ENV }), filesystem, - processRunner: runner, - serialOf: () => SERIAL, - serverPath: SERVER, - tcp: server, ...(options.scid === null ? {} : { scid: options.scid ?? (() => SCID) }), + serverPath: SERVER, + targetFor: async (asked) => (asked === device ? target : other), }); - return { capture, clock, runner, server }; + return { capture, clock, other, target }; } async function drive(clock: FakeClock, promise: Promise, stepMs = 50): Promise { @@ -222,66 +369,105 @@ function frameTag(frame: Uint8Array | undefined): number | undefined { return frame?.[4]; } -async function opened(setupResult: Awaited>) { - const { capture, clock, server } = setupResult; - const opening = capture.open(DEVICE, SETTINGS, new AbortController().signal); - const feed = await drive(clock, waitThenStart(server, opening)); - return feed; -} - -async function waitThenStart(server: AdbServer, opening: Promise): Promise { - for (let tries = 0; tries < 100 && server.peers.length === 0; tries += 1) { +async function waitThenStart(target: FakeTarget, opening: Promise): Promise { + for (let tries = 0; tries < 100 && target.server.peers.length === 0; tries += 1) { await new Promise((resolve) => setImmediate(resolve)); } - server.last.send(streamStart()); + target.server.last.send(streamStart()); return await opening; } +async function opened(setupResult: Awaited>) { + const { capture, clock, target } = setupResult; + const opening = capture.open(DEVICE, SETTINGS, new AbortController().signal); + return await drive(clock, waitThenStart(target, opening)); +} + describe("Android screen capture: open", () => { it("pushes the server to a per-session path and starts it with that session's id and the settings", async () => { const world = await setup(); await opened(world); - expect(world.runner.calls[0]).toMatchObject({ - args: ["-s", SERIAL, "push", SERVER, DEVICE_JAR], - command: ADB, - options: { env: ENV }, - }); - expect(world.runner.calls[1]).toMatchObject({ command: ADB, options: { env: ENV } }); - expect(world.runner.calls[1]!.args).toEqual([ - "-s", - SERIAL, - "shell", - `CLASSPATH=${DEVICE_JAR}`, - "app_process", - "/", - "com.genymobile.scrcpy.Server", - "5.0.1", - "scid=1234abcd", - "log_level=info", - "tunnel_forward=true", - "video=true", - "audio=false", - "control=false", - "video_codec=h264", - "send_device_meta=false", - "send_dummy_byte=true", - "send_stream_meta=true", - "send_frame_meta=true", - "cleanup=true", - "max_size=720", - "max_fps=30", - "video_bit_rate=1500000", + expect(world.target.log[0]).toBe(`push ${SERVER} ${DEVICE_JAR}`); + expect(world.target.log[1]).toBe( + [ + "shell", + `CLASSPATH=${DEVICE_JAR}`, + "app_process", + "/", + "com.genymobile.scrcpy.Server", + "5.0.1", + "scid=1234abcd", + "log_level=info", + "tunnel_forward=true", + "video=true", + "audio=false", + "control=false", + "video_codec=h264", + "send_device_meta=false", + "send_dummy_byte=true", + "send_stream_meta=true", + "send_frame_meta=true", + "cleanup=true", + "max_size=720", + "max_fps=30", + "video_bit_rate=1500000", + ].join(" "), + ); + }); + + it("streams a physical phone through its target: the screen read, the push, the server start and the close's removal go through its run and spawn with the phone's serial, and its socket through its connect", async () => { + const world = await setup({ device: PHONE }); + const opening = world.capture.open(PHONE, SETTINGS, new AbortController().signal); + const feed = await drive(world.clock, waitThenStart(world.target, opening)); + + expect(frameTag((await feed.body.getReader().read()).value)).toBe(SCREEN_FRAME_TAG.meta); + await drive(world.clock, feed.close()); + // why: the phone's screen is read before the jar is pushed, and the push, the server start and the + // close's removal all run on the target that carries the phone's serial. + expect(world.target.steps).toEqual([ + `push ${SERVER} ${DEVICE_JAR}`, + "server", + `shell rm -f ${DEVICE_JAR}`, ]); + expect(world.target.powerReads).toEqual([SCREEN_READ_MS]); + expect(world.target.connects.length).toBeGreaterThan(0); + expect(world.other.steps).toEqual([]); + expect(world.other.powerReads).toEqual([]); + expect(world.other.connects).toEqual([]); + }); + + it("adds stay_awake=true to a phone's server options and to nothing of an emulator's", async () => { + const emulator = await setup(); + await opened(emulator); + const phone = await setup({ device: PHONE }); + const opening = phone.capture.open(PHONE, SETTINGS, new AbortController().signal); + await drive(phone.clock, waitThenStart(phone.target, opening)); + const serverOf = (log: readonly string[]) => log.find((l) => l.includes("app_process"))!; + const emulatorOptions = serverOf(emulator.target.log).split(" "); + expect(emulatorOptions).not.toContain("stay_awake=true"); + expect(emulatorOptions).toContain("control=false"); + const phoneOptions = serverOf(phone.target.log).split(" "); + expect(phoneOptions).toContain("stay_awake=true"); + expect(phoneOptions).toContain("control=false"); + expect(phoneOptions.filter((o) => o !== "stay_awake=true")).toEqual(emulatorOptions); }); - it("reaches the server's abstract socket through Simlock's adb server, named by the session id", async () => { + it("reads no screen state for an emulator", async () => { const world = await setup(); await opened(world); - expect(world.server.ports).toEqual([PORT]); - expect(world.server.last.written).toEqual([ + expect(world.target.powerReads).toEqual([]); + expect(world.target.log).not.toContainEqual(expect.stringContaining("dumpsys")); + }); + + it("reaches the server's abstract socket through the device's target, named by the session id", async () => { + const world = await setup(); + await opened(world); + expect(world.target.server.peers).toHaveLength(1); + expect(world.target.server.last.written).toEqual([ "001chost:transport:emulator-5586", "001dlocalabstract:scrcpy_1234abcd", ]); + expect(world.other.connects).toEqual([]); }); it("hands out a body that starts with the session's meta frame", async () => { @@ -303,12 +489,13 @@ describe("Android screen capture: open", () => { const opening = world.capture.open(DEVICE, SETTINGS, new AbortController().signal); const started = world.clock.now(); const watcher = (async () => { - while (world.server.peers.length < 3) await new Promise((resolve) => setImmediate(resolve)); - world.server.last.send(streamStart()); + while (world.target.server.peers.length < 3) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.last.send(streamStart()); })(); const feed = await drive(world.clock, opening, 10); await watcher; - expect(world.server.ports).toHaveLength(4); + expect(world.target.connects).toHaveLength(4); expect(world.clock.now() - started).toBeGreaterThanOrEqual(3 * CONNECT_RETRY_MS); expect(frameTag((await feed.body.getReader().read()).value)).toBe(SCREEN_FRAME_TAG.meta); }); @@ -317,15 +504,17 @@ describe("Android screen capture: open", () => { const world = await setup({ server: new AdbServer(["silent"]) }); const opening = world.capture.open(DEVICE, SETTINGS, new AbortController().signal); const watcher = (async () => { - while (world.server.peers.length < 1) await new Promise((resolve) => setImmediate(resolve)); - world.server.peers[0]!.send("OKAY", "OKAY"); - world.server.peers[0]!.close(); - while (world.server.peers.length < 2) await new Promise((resolve) => setImmediate(resolve)); - world.server.last.send(streamStart()); + while (world.target.server.peers.length < 1) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.peers[0]!.send("OKAY", "OKAY"); + world.target.server.peers[0]!.close(); + while (world.target.server.peers.length < 2) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.last.send(streamStart()); })(); await drive(world.clock, opening, 10); await watcher; - expect(world.server.peers).toHaveLength(2); + expect(world.target.server.peers).toHaveLength(2); }); it("gives up at the start deadline, reporting the server's last output, and cleans up", async () => { @@ -343,12 +532,12 @@ describe("Android screen capture: open", () => { const failedAt = world.clock.now() - started; expect(failedAt).toBeGreaterThanOrEqual(START_DEADLINE_MS); expect(failedAt).toBeLessThan(START_DEADLINE_MS + CLOSE_DEADLINE_MS); - expect(world.runner.calls.map((call) => call.args.slice(2, 4))).toEqual([ - ["push", SERVER], - ["shell", `CLASSPATH=${DEVICE_JAR}`], - ["shell", "rm"], + expect(world.target.steps).toEqual([ + `push ${SERVER} ${DEVICE_JAR}`, + "server", + `shell rm -f ${DEVICE_JAR}`, ]); - expect(world.server.peers.every((peer) => peer.closed)).toBe(true); + expect(world.target.server.peers.every((peer) => peer.closed)).toBe(true); }); it("fails at once when the server's shell exits before it listens", async () => { @@ -382,15 +571,16 @@ describe("Android screen capture: open", () => { ).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(ScreenUnavailableError); expect((error as Error).message).toMatch(/not found/); - expect(world.server.peers).toHaveLength(1); + expect(world.target.server.peers).toHaveLength(1); }); it("refuses with the server's reason when it cannot configure its encoder", async () => { const world = await setup(); const opening = world.capture.open(DEVICE, SETTINGS, new AbortController().signal); const watcher = (async () => { - while (world.server.peers.length < 1) await new Promise((resolve) => setImmediate(resolve)); - world.server.last.send(codecId(1)); + while (world.target.server.peers.length < 1) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.last.send(codecId(1)); })(); const error = await drive(world.clock, opening).catch((caught: unknown) => caught); await watcher; @@ -407,20 +597,10 @@ describe("Android screen capture: open", () => { world.capture.open(DEVICE, SETTINGS, new AbortController().signal), ).catch((caught: unknown) => caught); expect((error as Error).message).toMatch(/device offline/); - expect(world.runner.calls.map((call) => call.args[2])).toEqual(["push", "shell"]); - expect(world.runner.calls[1]!.args.slice(3)).toEqual(["rm", "-f", DEVICE_JAR]); - }); - - it("refuses a physical device as not supported, before running anything", async () => { - const world = await setup({ expectations: [] }); - await expect( - world.capture.open( - { ...DEVICE, enrolledApps: [], physical: true } as PhysicalDriverDevice, - SETTINGS, - new AbortController().signal, - ), - ).rejects.toBeInstanceOf(ScreenNotSupportedError); - expect(world.runner.calls).toEqual([]); + expect(world.target.steps).toEqual([ + `push ${SERVER} ${DEVICE_JAR}`, + `shell rm -f ${DEVICE_JAR}`, + ]); }); it("starts no server when it is stopped while the jar is being copied, and removes the jar", async () => { @@ -430,10 +610,8 @@ describe("Android screen capture: open", () => { }); const opening = world.capture.open(DEVICE, SETTINGS, stop.signal); await expect(drive(world.clock, opening)).rejects.toBeInstanceOf(ScreenUnavailableError); - expect(world.runner.calls.map((call) => call.args.join(" "))).not.toContainEqual( - expect.stringContaining("app_process"), - ); - expect(world.runner.calls.at(-1)?.args.join(" ")).toContain("rm -f"); + expect(world.target.log).not.toContainEqual(expect.stringContaining("app_process")); + expect(world.target.steps.at(-1)).toContain("rm -f"); }); it("refuses an open that was stopped before it began, running nothing", async () => { @@ -443,7 +621,8 @@ describe("Android screen capture: open", () => { await expect(world.capture.open(DEVICE, SETTINGS, stop.signal)).rejects.toBeInstanceOf( ScreenUnavailableError, ); - expect(world.runner.calls).toEqual([]); + expect(world.target.log).toEqual([]); + expect(world.target.connects).toEqual([]); }); it("is unavailable, with the reason, while the server jar is missing", async () => { @@ -455,7 +634,7 @@ describe("Android screen capture: open", () => { await expect( world.capture.open(DEVICE, SETTINGS, new AbortController().signal), ).rejects.toBeInstanceOf(ScreenUnavailableError); - expect(world.runner.calls).toEqual([]); + expect(world.target.log).toEqual([]); }); it("gives two concurrent opens two session ids, two sockets and two jar paths", async () => { @@ -466,16 +645,17 @@ describe("Android screen capture: open", () => { const first = world.capture.open(DEVICE, SETTINGS, new AbortController().signal); const second = world.capture.open(DEVICE, SETTINGS, new AbortController().signal); const watcher = (async () => { - while (world.server.peers.length < 2) await new Promise((resolve) => setImmediate(resolve)); - for (const peer of world.server.peers) peer.send(streamStart()); + while (world.target.server.peers.length < 2) + await new Promise((resolve) => setImmediate(resolve)); + for (const peer of world.target.server.peers) peer.send(streamStart()); })(); await drive(world.clock, Promise.all([first, second])); await watcher; - const sockets = world.server.peers.map((peer) => peer.written[1]); + const sockets = world.target.server.peers.map((peer) => peer.written[1]); expect(new Set(sockets).size).toBe(2); - const jars = world.runner.calls - .filter((call) => call.args[2] === "push") - .map((call) => call.args[4]); + const jars = world.target.log + .filter((entry) => entry.startsWith("push ")) + .map((entry) => entry.split(" ")[2]); expect(new Set(jars).size).toBe(2); for (const socket of sockets) { const hex = /scrcpy_([0-9a-f]{8})$/.exec(socket ?? "")?.[1]; @@ -485,11 +665,294 @@ describe("Android screen capture: open", () => { }); }); +describe("Android screen capture: a phone's screen state", () => { + it("wakes a phone whose screen is off through its target with a 10 s limit, reads again, and pushes once the second read says it is on, for each wakefulness that means off", async () => { + for (const printed of ["Asleep", "Dozing", "Asleep\r", "Dozing "]) { + const world = await setup({ + device: PHONE, + power: [ + { code: 0, stdout: ` mWakefulness=${printed}\n` }, + { code: 0, stdout: " mWakefulness=Awake\n" }, + ], + }); + const opening = world.capture.open(PHONE, SETTINGS, new AbortController().signal); + const feed = await drive(world.clock, waitThenStart(world.target, opening)); + expect(await feed.body.getReader().read(), printed).toBeDefined(); + + expect(world.target.screenSteps, printed).toEqual(["read", "wake", "read"]); + expect(world.target.wakes, printed).toEqual([WAKE_MS]); + expect(world.target.powerReads, printed).toEqual([SCREEN_READ_MS, SCREEN_READ_MS]); + expect(world.target.log[0], printed).toBe(`push ${SERVER} ${DEVICE_JAR}`); + } + }); + + it("refuses a phone whose second read still says the screen is off, with its own reason, and pushes nothing, whatever the wake did", async () => { + for (const second of ["Asleep", "Dozing"]) { + for (const wake of ["ok", "fail", "slow"] as const) { + const world = await setup({ + device: PHONE, + wake, + power: [ + { code: 0, stdout: " mWakefulness=Asleep\n" }, + { code: 0, stdout: ` mWakefulness=${second}\n` }, + ], + }); + const error = await drive( + world.clock, + world.capture.open(PHONE, SETTINGS, new AbortController().signal), + ).catch((caught: unknown) => caught); + + const name = `${second} after a wake that is ${wake}`; + expect(error, name).toBeInstanceOf(ScreenUnavailableError); + expect((error as Error).message, name).toBe(SCREEN_OFF); + // why: a wake that exited non-zero or timed out is not looked at; the second read decides. + expect(world.target.screenSteps, name).toEqual(["read", "wake", "read"]); + expect(world.target.steps, name).toEqual([]); + expect(world.target.connects, name).toEqual([]); + } + } + }); + + it("sends no wake to a phone whose screen is on, and none to an emulator", async () => { + const world = await setup({ device: PHONE }); + await drive( + world.clock, + waitThenStart( + world.target, + world.capture.open(PHONE, SETTINGS, new AbortController().signal), + ), + ); + expect(world.target.wakes).toEqual([]); + const emulator = await setup({ power: { code: 0, stdout: " mWakefulness=Asleep\n" } }); + await opened(emulator); + expect(emulator.target.wakes).toEqual([]); + }); + + it("goes on to the push for every other wakefulness, including a word that is not one and no line at all", async () => { + for (const printed of ["Awake", "Dreaming", "Awaken", "asleep"]) { + const world = await setup({ + device: PHONE, + power: { code: 0, stdout: ` mWakefulness=${printed}\n` }, + }); + const opening = world.capture.open(PHONE, SETTINGS, new AbortController().signal); + const feed = await drive(world.clock, waitThenStart(world.target, opening)); + expect(await feed.body.getReader().read(), printed).toBeDefined(); + + expect(world.target.log[0], printed).toBe(`push ${SERVER} ${DEVICE_JAR}`); + expect(world.target.powerReads, printed).toEqual([SCREEN_READ_MS]); + expect(world.target.wakes, printed).toEqual([]); + } + }); + + it("goes on to the push when the screen read has no matching line, exits non-zero, or times out, and asks for it with a 10 s limit", async () => { + for (const answer of [ + { code: 0, stdout: " mPolicyBoost=0\n" }, + { code: 1, stdout: " mWakefulness=Asleep\n" }, + "slow", + ] as const) { + const world = await setup({ device: PHONE, power: answer }); + const opening = world.capture.open(PHONE, SETTINGS, new AbortController().signal); + // why: a timed-out read ends 10 s of fake clock after the open, and waitThenStart's capped + // flush-wait cannot span it; the file's uncapped watcher pattern waits for the peer whenever + // it appears, and drive still ends the run if the open never reaches it. + const watcher = (async () => { + while (world.target.server.peers.length === 0) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.last.send(streamStart()); + })(); + const feed = await drive(world.clock, opening); + await watcher; + expect(await feed.body.getReader().read(), String(answer)).toBeDefined(); + + expect(world.target.powerReads, String(answer)).toEqual([SCREEN_READ_MS]); + expect(world.target.wakes, String(answer)).toEqual([]); + expect(world.target.log[0], String(answer)).toBe(`push ${SERVER} ${DEVICE_JAR}`); + } + }); + + it("checks for a stop after each of the first read, the wake and the second read, and does nothing after the step it was stopped in", async () => { + const asleep = { code: 0, stdout: " mWakefulness=Asleep\n" }; + const awake = { code: 0, stdout: " mWakefulness=Awake\n" }; + const cases = [ + { name: "the first read", power: [asleep], wake: "ok", wakes: 0, reads: 1, hold: true }, + { name: "the wake", power: [asleep, awake], wake: "slow", wakes: 1, reads: 1, hold: false }, + { + name: "the second read", + power: [asleep, "slow"], + wake: "ok", + wakes: 1, + reads: 2, + hold: false, + }, + ] as const; + for (const stage of cases) { + const stop = new AbortController(); + const world = await setup({ + device: PHONE, + power: stage.power as unknown as FakeTarget["power"], + wake: stage.wake, + }); + world.target.holdReads = stage.hold; + const opening = world.capture.open(PHONE, SETTINGS, stop.signal); + // why: stops at the step itself: the step is in flight once its entry is recorded. + while ( + stage.name === "the first read" + ? world.target.powerReads.length < 1 + : stage.name === "the wake" + ? world.target.wakes.length < 1 + : world.target.powerReads.length < 2 + ) + await new Promise((resolve) => setImmediate(resolve)); + stop.abort(); + const failed = await drive(world.clock, opening).catch((caught: unknown) => caught); + + expect(failed, stage.name).toBeInstanceOf(ScreenUnavailableError); + expect(world.target.wakes.length, stage.name).toBe(stage.wakes); + expect(world.target.powerReads.length, stage.name).toBe(stage.reads); + expect(world.target.log, stage.name).toEqual([]); + expect(world.target.connects, stage.name).toEqual([]); + } + }); + + it("fails the open with a target's own reason and runs nothing after it, for the first screen read, the wake, the second screen read, the push, the server start and a connection attempt", async () => { + const stages: readonly { + readonly name: string; + readonly power?: FakeTarget["power"]; + readonly wake?: FakeTarget["wake"]; + readonly refuses: (args: readonly string[]) => boolean; + readonly screenBefore: string[]; + readonly stepsBefore: string[]; + }[] = [ + { + name: "the first screen read", + power: "refuse", + refuses: () => false, + screenBefore: ["read"], + stepsBefore: [], + }, + { + // why: the wake's exit is ignored, but a closed check at the wake still refuses the open. + name: "the wake", + power: { code: 0, stdout: " mWakefulness=Asleep\n" }, + wake: "refuse", + refuses: () => false, + screenBefore: ["read", "wake"], + stepsBefore: [], + }, + { + name: "the second screen read", + power: [{ code: 0, stdout: " mWakefulness=Asleep\n" }, "refuse"], + refuses: () => false, + screenBefore: ["read", "wake", "read"], + stepsBefore: [], + }, + { + name: "the push", + refuses: (args) => args[0] === "push", + screenBefore: ["read"], + stepsBefore: [], + }, + { + name: "the server start", + refuses: (args) => args.includes("app_process"), + screenBefore: ["read"], + stepsBefore: [`push ${SERVER} ${DEVICE_JAR}`, `shell rm -f ${DEVICE_JAR}`], + }, + { + // why: the server's spawn sits between the push and the connection attempt, so it is in the + // log by the time the attempt's check refuses; only the `rm -f` follows it. + name: "a connection attempt", + refuses: (args) => args[0] === "connect", + screenBefore: ["read"], + stepsBefore: [`push ${SERVER} ${DEVICE_JAR}`, "server", `shell rm -f ${DEVICE_JAR}`], + }, + ]; + for (const stage of stages) { + const world = await setup({ + device: PHONE, + ...(stage.power === undefined ? {} : { power: stage.power }), + ...(stage.wake === undefined ? {} : { wake: stage.wake }), + refuses: stage.refuses, + }); + const started = world.clock.now(); + const error = await drive( + world.clock, + world.capture.open(PHONE, SETTINGS, new AbortController().signal), + ).catch((caught: unknown) => caught); + + expect(error, stage.name).toBeInstanceOf(ScreenUnavailableError); + expect((error as Error).message, stage.name).toBe(GATE_REFUSAL); + // why: a refusal that was retried instead of propagated would have spent the start deadline on + // it, and the viewer would get a start timeout instead of the check's reason. + expect(world.clock.now() - started, stage.name).toBeLessThan(START_DEADLINE_MS); + expect(world.target.steps, stage.name).toEqual(stage.stepsBefore); + expect(world.target.screenSteps, stage.name).toEqual(stage.screenBefore); + } + }); + + it("sends nothing and settles when the version check is still closed at the jar's removal", async () => { + const world = await setup({ + device: PHONE, + refuses: (args) => args.includes("app_process") || args[0] === "shell", + }); + const error = await drive( + world.clock, + world.capture.open(PHONE, SETTINGS, new AbortController().signal), + ).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ScreenUnavailableError); + expect(world.target.steps).toEqual([`push ${SERVER} ${DEVICE_JAR}`]); + }); +}); + +describe("Android screen capture: the start bound", () => { + it("does not spend the 15 s start bound on the target's check that runs before the server is spawned", async () => { + // why: the check runs inside the target, before its process exists. The bound is measured from the + // moment that process started, so a slow first check costs a stream nothing. + const world = await setup({ acceptFromMs: 20_000, device: PHONE }); + world.target.spawnDelayMs = 8_000; + const started = world.clock.now(); + const opening = world.capture.open(PHONE, SETTINGS, new AbortController().signal); + const watcher = (async () => { + while (world.target.server.peers.length === 0) + await new Promise((resolve) => setImmediate(resolve)); + world.target.server.last.send(streamStart()); + })(); + + const feed = await drive(world.clock, opening, 500); + await watcher; + const took = world.clock.now() - started; + + // why: straddled on both sides -- 20 s from the open's start is past the 15 s budget a budget + // measured from the push would have allowed, and the stream is proof it was not spent. + expect(took).toBeGreaterThanOrEqual(20_000); + expect(took).toBeLessThan(20_000 + CLOSE_DEADLINE_MS); + expect(frameTag((await feed.body.getReader().read()).value)).toBe(SCREEN_FRAME_TAG.meta); + }); + + it("counts a connection attempt's own check inside the 15 s, waits for one still running at the deadline, and then fails as a start timeout", async () => { + const world = await setup({ server: new AdbServer([], "refuse") }); + world.target.connectDelayMs = START_DEADLINE_MS + 2_000; + const started = world.clock.now(); + const error = await drive( + world.clock, + world.capture.open(DEVICE, SETTINGS, new AbortController().signal), + 500, + ).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ScreenUnavailableError); + expect((error as Error).message).toMatch(/within 15 s/); + const failedAt = world.clock.now() - started; + expect(failedAt).toBeGreaterThanOrEqual(START_DEADLINE_MS); + expect(failedAt).toBeLessThanOrEqual(START_DEADLINE_MS + 5_000 + CLOSE_DEADLINE_MS); + }); +}); + describe("Android screen capture: the body", () => { it("reads the socket only when its reader asks for a frame", async () => { const world = await setup(); const feed = await opened(world); - const peer = world.server.last; + const peer = world.target.server.last; peer.send(mediaPacket({ config: true }, SAMPLE.config), mediaPacket({ key: true }, SAMPLE.idr)); const before = peer.pulls; for (let flush = 0; flush < 10; flush += 1) @@ -506,7 +969,7 @@ describe("Android screen capture: the body", () => { it("delivers every delta, in order, however slowly it is read", async () => { const world = await setup(); const feed = await opened(world); - const peer = world.server.last; + const peer = world.target.server.last; peer.send(mediaPacket({ config: true }, SAMPLE.config), mediaPacket({ key: true }, SAMPLE.idr)); for (let index = 0; index < 50; index += 1) peer.send(mediaPacket({ pts: index }, SAMPLE.p1)); const reader = feed.body.getReader(); @@ -522,7 +985,7 @@ describe("Android screen capture: the body", () => { it("says a still screen is alive every few seconds, and keeps the frames that follow in order", async () => { const world = await setup(); const feed = await opened(world); - const peer = world.server.last; + const peer = world.target.server.last; peer.send(mediaPacket({ config: true }, SAMPLE.config), mediaPacket({ key: true }, SAMPLE.idr)); const reader = feed.body.getReader(); for (let index = 0; index < 3; index += 1) await reader.read(); @@ -538,22 +1001,25 @@ describe("Android screen capture: the body", () => { expect(frameTag((await next).value)).toBe(SCREEN_FRAME_TAG.delta); }); - it("says nothing is alive while the encoder has not painted a first picture", async () => { - const world = await setup(); - const feed = await opened(world); - const peer = world.server.last; - peer.send(mediaPacket({ config: true }, SAMPLE.config)); - const reader = feed.body.getReader(); - expect(frameTag((await reader.read()).value)).toBe(SCREEN_FRAME_TAG.meta); - const quiet = reader.read(); - let settled = false; - void quiet.then(() => (settled = true)); - for (let flush = 0; flush < 10; flush += 1) - await new Promise((resolve) => setImmediate(resolve)); - world.clock.advance(ALIVE_AFTER_MS * 3); - for (let flush = 0; flush < 10; flush += 1) - await new Promise((resolve) => setImmediate(resolve)); - expect(settled).toBe(false); + it("says nothing is alive while the encoder has not painted a first picture, on an emulator and on a phone", async () => { + for (const device of [DEVICE, PHONE]) { + const world = await setup({ device }); + const opening = world.capture.open(device, SETTINGS, new AbortController().signal); + const feed = await drive(world.clock, waitThenStart(world.target, opening)); + const peer = world.target.server.last; + peer.send(mediaPacket({ config: true }, SAMPLE.config)); + const reader = feed.body.getReader(); + expect(frameTag((await reader.read()).value), device.deviceId).toBe(SCREEN_FRAME_TAG.meta); + const quiet = reader.read(); + let settled = false; + void quiet.then(() => (settled = true)); + for (let flush = 0; flush < 10; flush += 1) + await new Promise((resolve) => setImmediate(resolve)); + world.clock.advance(ALIVE_AFTER_MS * 3); + for (let flush = 0; flush < 10; flush += 1) + await new Promise((resolve) => setImmediate(resolve)); + expect(settled, device.deviceId).toBe(false); + } }); it("errors with the server's reason when the device side ends, and cleans up", async () => { @@ -563,12 +1029,12 @@ describe("Android screen capture: the body", () => { const feed = await opened(world); const reader = feed.body.getReader(); await reader.read(); - world.server.last.close(); + world.target.server.last.close(); const error = await drive(world.clock, reader.read()).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(ScreenUnavailableError); expect((error as Error).message).toMatch(/Encoding error/); await drive(world.clock, feed.close()); - expect(world.runner.calls.at(-1)?.args.slice(2)).toEqual(["shell", "rm", "-f", DEVICE_JAR]); + expect(world.target.steps.at(-1)).toBe(`shell rm -f ${DEVICE_JAR}`); }); }); @@ -579,9 +1045,9 @@ describe("Android screen capture: close", () => { const closes = Promise.all([feed.close(), feed.close()]); await drive(world.clock, closes); await drive(world.clock, feed.close()); - expect(world.server.last.closed).toBe(true); - expect(await hasEnded(world.runner.handles[1]!)).toBe(true); - expect(world.runner.calls.filter((call) => call.args.includes("rm"))).toHaveLength(1); + expect(world.target.server.last.closed).toBe(true); + expect(await hasEnded(world.target.runner.handles[1]!)).toBe(true); + expect(world.target.log.filter((entry) => entry.includes("rm"))).toHaveLength(1); }); it("kills a server still running a second after its socket closed, with SIGKILL", async () => { @@ -590,7 +1056,7 @@ describe("Android screen capture: close", () => { }); const feed = await opened(world); const closing = feed.close(); - const server = world.runner.handles[1]!; + const server = world.target.runner.handles[1]!; await hasEnded(server); world.clock.advance(999); expect(await hasEnded(server)).toBe(false); @@ -612,7 +1078,7 @@ describe("Android screen capture: close", () => { const world = await setup(); const feed = await opened(world); await drive(world.clock, feed.body.cancel()); - expect(world.server.last.closed).toBe(true); - expect(world.runner.calls.filter((call) => call.args.includes("rm"))).toHaveLength(1); + expect(world.target.server.last.closed).toBe(true); + expect(world.target.log.filter((entry) => entry.includes("rm"))).toHaveLength(1); }); }); diff --git a/src/drivers/android/screen/session.ts b/src/drivers/android/screen/session.ts index 5a6115f40..3915b9e3f 100644 --- a/src/drivers/android/screen/session.ts +++ b/src/drivers/android/screen/session.ts @@ -6,7 +6,6 @@ import { type PhysicalDriverDevice, type ScreenCapture, type ScreenFeed, - ScreenNotSupportedError, type ScreenSettings, ScreenUnavailableError, SCREEN_FRAME_TAG, @@ -16,9 +15,8 @@ import type { Clock, Filesystem, ProcessHandle, - ProcessRunner, + ProcessResult, TcpStream, - TcpStreamConnector, } from "../../../ports/index.js"; import { ChunkReader, openDeviceSocket } from "./adb-socket.js"; import { EnvelopeMapper } from "./envelope.js"; @@ -29,6 +27,13 @@ import { ScrcpyVideoParser } from "./scrcpy-video.js"; const SCRCPY_SERVER_VERSION = "5.0.1"; const DEVICE_DIRECTORY = "/data/local/tmp"; const PUSH_TIMEOUT_MS = 30_000; +// why: a phone's screen state is read before anything is pushed, and read again only after a wake; a read that outlives this +// goes on to the push rather than refusing, because only a read that says off is a fact about the screen. +const SCREEN_READ_TIMEOUT_MS = 10_000; +const WAKEFULNESS_LINE = /^\s*mWakefulness=(\S+)\s*$/; +const WAKE_TIMEOUT_MS = 10_000; +const SCREEN_OFF_MESSAGE = + "The phone's screen is off and did not turn on. Turn it on and ask for the stream again."; // why: measured from the moment the push returned, through every connect retry, to the first session // packet; the budget never restarts, so a server that keeps refusing cannot hold a viewer longer. export const START_DEADLINE_MS = 15_000; @@ -48,17 +53,28 @@ const QUIET = Symbol("quiet"); const LOG_TAIL_LINES = 20; const SCID_LIMIT = 2 ** 31; +// why: where one device's scrcpy session runs, as the driver builds it. An emulator's target runs +// `adb -s …` with Simlock's scoped env and connects to Simlock's own adb server; a physical +// phone's runs `adb -P 5037 …` with the shared server's env, behind that server's version check. The +// capture never names a port and never runs that check: the target is the one place that knows both. +export interface ScreenTarget { + readonly serial: string; + // why: `args` start at the adb subcommand; the target aims them at its device. A promise so a + // phone's version check can run before the process starts; an emulator's resolves at once. + spawn(args: readonly string[]): Promise; + run(args: readonly string[], timeoutMs: number): Promise; + // why: a raw connection to the adb server this target's device is reached through. + connect(timeoutMs: number): Promise; +} + export interface AndroidScreenCaptureOptions { - readonly adb: string; - readonly adbServerPort: number; readonly clock: Clock; - readonly env: () => NodeJS.ProcessEnv; readonly filesystem: Filesystem; - readonly processRunner: ProcessRunner; - readonly serialOf: (device: VirtualDriverDevice) => string; readonly serverPath: string; - readonly tcp: TcpStreamConnector; readonly scid?: () => number; + // why: where this device's session runs, built by the driver: an emulator's `adb` with Simlock's + // own env and server, a physical phone's `adb -P 5037` behind the shared server's version check. + targetFor(device: VirtualDriverDevice | PhysicalDriverDevice): Promise; } export function createAndroidScreenCapture(options: AndroidScreenCaptureOptions): ScreenCapture { @@ -72,51 +88,55 @@ export function createAndroidScreenCapture(options: AndroidScreenCaptureOptions) settings: ScreenSettings, signal: AbortSignal, ): Promise => { - if (isPhysicalDriverDevice(device)) { - throw new ScreenNotSupportedError( - "Screen streams are offered for Android emulators only, not for physical Android devices", - ); - } const reason = await unavailable(); if (reason !== undefined) throw new ScreenUnavailableError(reason); - const serial = options.serialOf(device); - if (serial === "") { - throw new ScreenUnavailableError( - `${device.deviceId} is not running, so it has no screen to stream`, - ); - } + const target = await options.targetFor(device); const scid = options.scid?.() ?? randomInt(0, SCID_LIMIT); - return await new ScrcpySession(options, serial, scid, settings).start(signal); + return await new ScrcpySession( + options.clock, + options.serverPath, + target, + scid, + settings, + isPhysicalDriverDevice(device), + ).start(signal); }, unavailable, }; } class ScrcpySession { - readonly #options: AndroidScreenCaptureOptions; - readonly #serial: string; + readonly #clock: Clock; + readonly #serverPath: string; + readonly #target: ScreenTarget; readonly #scidHex: string; readonly #devicePath: string; readonly #settings: ScreenSettings; + readonly #isPhone: boolean; readonly #tail: string[] = []; readonly #abort = new AbortController(); #pushed = false; #shell: ProcessHandle | undefined; #shellExited = false; + #collected: Promise | undefined; #stream: TcpStream | undefined; #closing: Promise | undefined; constructor( - options: AndroidScreenCaptureOptions, - serial: string, + clock: Clock, + serverPath: string, + target: ScreenTarget, scid: number, settings: ScreenSettings, + isPhone: boolean, ) { if (!Number.isInteger(scid) || scid < 0 || scid >= SCID_LIMIT) { throw new RangeError(`A scrcpy session id is a 31-bit number, not ${String(scid)}`); } - this.#options = options; - this.#serial = serial; + this.#isPhone = isPhone; + this.#clock = clock; + this.#serverPath = serverPath; + this.#target = target; // why: the server parses `scid` as hex and names its socket `scrcpy_%08x`, exactly as scrcpy's // own client formats it, so one formatting serves the argument, the socket and the file name. this.#scidHex = scid.toString(16).padStart(8, "0"); @@ -130,14 +150,15 @@ class ScrcpySession { stopped.addEventListener("abort", stop, { once: true }); try { if (stopped.aborted) throw this.#startFailure("was stopped before it started"); + if (this.#isPhone) await this.#wakeIfOff(); await this.#push(); // why: the push is the one step that cannot be interrupted; a stop that arrived during it // starts no server on a device that is being handed back. if (this.#abort.signal.aborted) throw this.#startFailure("was stopped while it was being copied"); - this.#spawnServer(); - const deadlineAt = this.#options.clock.now() + START_DEADLINE_MS; - timer = this.#options.clock.setTimer(START_DEADLINE_MS, () => { + const startedAt = await this.#spawnServer(); + const deadlineAt = startedAt + START_DEADLINE_MS; + timer = this.#clock.setTimer(START_DEADLINE_MS, () => { this.#abort.abort(); }); const reader = await this.#connect(deadlineAt); @@ -152,7 +173,7 @@ class ScrcpySession { : new ScreenUnavailableError(this.#withTail(errorMessage(error))); } finally { stopped.removeEventListener("abort", stop); - if (timer !== undefined) this.#options.clock.cancel(timer); + if (timer !== undefined) this.#clock.cancel(timer); } } @@ -179,64 +200,101 @@ class ScrcpySession { return this.#closing; } + // why: each of the three steps cannot be cut short from outside; a stop that arrived during one + // waits for it to end and runs nothing after it, so a device being handed back gets no more keys. + async #wakeIfOff(): Promise { + const wasOff = await this.#screenIsOff(); + this.#throwIfStopped("the phone's screen was being read"); + if (!wasOff) return; + // why: the wake's exit is not looked at; the second read decides. A closed check still throws. + await this.#target.run(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], WAKE_TIMEOUT_MS); + this.#throwIfStopped("the phone was being woken"); + const stillOff = await this.#screenIsOff(); + this.#throwIfStopped("the phone's screen was being read"); + if (stillOff) throw new ScreenUnavailableError(SCREEN_OFF_MESSAGE); + } + + #throwIfStopped(during: string): void { + if (this.#abort.signal.aborted) throw this.#startFailure(`was stopped while ${during}`); + } + + // why: only a read that names Asleep or Dozing is a fact about the screen; every other answer — + // another word, no line, a non-zero exit, a timed-out read — reads as unknown and goes on. + async #screenIsOff(): Promise { + const read = await this.#target.run(["shell", "dumpsys", "power"], SCREEN_READ_TIMEOUT_MS); + if (read.code !== 0) return false; + for (const line of read.stdout.split("\n")) { + const word = WAKEFULNESS_LINE.exec(line.endsWith("\r") ? line.slice(0, -1) : line)?.[1]; + if (word === undefined) continue; + return word === "Asleep" || word === "Dozing"; + } + return false; + } + async #push(): Promise { - const result = await this.#options.processRunner.run( - this.#options.adb, - ["-s", this.#serial, "push", this.#options.serverPath, this.#devicePath], - { env: this.#options.env(), timeoutMs: PUSH_TIMEOUT_MS }, + const result = await this.#target.run( + ["push", this.#serverPath, this.#devicePath], + PUSH_TIMEOUT_MS, ); // why: a push that timed out may still have written part of the file, so cleanup removes it too. this.#pushed = true; if (result.code !== 0) { throw new ScreenUnavailableError( - `adb could not copy the screen server to ${this.#serial}: ${(result.stderr || result.stdout).trim()}`, + `adb could not copy the screen server to ${this.#target.serial}: ${(result.stderr || result.stdout).trim()}`, ); } } - #spawnServer(): void { + // why: resolves with the moment the server's process started -- the 15 s budget begins there, so a + // phone's version check before the spawn does not spend it. + async #spawnServer(): Promise { const { fps, maxDimension, bitrateKbps } = this.#settings; - const shell = this.#options.processRunner.spawn( - this.#options.adb, - [ - "-s", - this.#serial, - "shell", - `CLASSPATH=${this.#devicePath}`, - "app_process", - "/", - "com.genymobile.scrcpy.Server", - SCRCPY_SERVER_VERSION, - `scid=${this.#scidHex}`, - "log_level=info", - "tunnel_forward=true", - "video=true", - "audio=false", - "control=false", - "video_codec=h264", - "send_device_meta=false", - "send_dummy_byte=true", - "send_stream_meta=true", - "send_frame_meta=true", - "cleanup=true", - `max_size=${String(maxDimension)}`, - `max_fps=${String(fps)}`, - `video_bit_rate=${String(bitrateKbps * 1000)}`, - ], - { env: this.#options.env() }, - ); + const shell = await this.#target.spawn([ + "shell", + `CLASSPATH=${this.#devicePath}`, + "app_process", + "/", + "com.genymobile.scrcpy.Server", + SCRCPY_SERVER_VERSION, + `scid=${this.#scidHex}`, + "log_level=info", + "tunnel_forward=true", + "video=true", + "audio=false", + "control=false", + "video_codec=h264", + "send_device_meta=false", + "send_dummy_byte=true", + "send_stream_meta=true", + "send_frame_meta=true", + "cleanup=true", + // why: scrcpy puts the phone's stay-awake setting back when the server ends (its clean-up + // process), and needs no controller for it; an emulator's screen is not held. + ...(this.#isPhone ? ["stay_awake=true"] : []), + `max_size=${String(maxDimension)}`, + `max_fps=${String(fps)}`, + `video_bit_rate=${String(bitrateKbps * 1000)}`, + ]); this.#shell = shell; - void this.#collect(shell.stdout); - void this.#collect(shell.stderr); + // why: the drain is kept, not fired away: a failure is reported with the server's last output, and + // a message built while that output is still in flight would say "exited" with nothing from it. + this.#collected = Promise.all([this.#collect(shell.stdout), this.#collect(shell.stderr)]).then( + () => undefined, + ); void shell.wait().then( () => this.#onShellExit(), () => this.#onShellExit(), ); + return this.#clock.now(); } #onShellExit(): void { this.#shellExited = true; - this.#abort.abort(); + // why: the abort is delayed until the server's output has been collected, so the failure it + // triggers names that output instead of racing it to the last line. + void (this.#collected ?? Promise.resolve()).then(() => { + this.#abort.abort(); + }); } async #collect(lines: AsyncIterable): Promise { @@ -266,15 +324,16 @@ class ScrcpySession { async #attempt(deadlineAt: number, signal: AbortSignal): Promise { try { const outcome = await openDeviceSocket({ - adbServerPort: this.#options.adbServerPort, - serial: this.#serial, + connect: (timeoutMs) => this.#target.connect(timeoutMs), + serial: this.#target.serial, signal, socketName: `scrcpy_${this.#scidHex}`, - tcp: this.#options.tcp, - timeoutMs: Math.max(1, deadlineAt - this.#options.clock.now()), + timeoutMs: Math.max(1, deadlineAt - this.#clock.now()), }); if (outcome.kind === "no-transport") { - throw new ScreenUnavailableError(`adb cannot reach ${this.#serial}: ${outcome.reason}`); + throw new ScreenUnavailableError( + `adb cannot reach ${this.#target.serial}: ${outcome.reason}`, + ); } if (outcome.kind !== "open") return outcome.reason; this.#stream = outcome.stream; @@ -300,12 +359,12 @@ class ScrcpySession { resolve(); return; } - const timer = this.#options.clock.setTimer(delayMs, () => { + const timer = this.#clock.setTimer(delayMs, () => { signal.removeEventListener("abort", wake); resolve(); }); const wake = () => { - this.#options.clock.cancel(timer); + this.#clock.cancel(timer); resolve(); }; signal.addEventListener("abort", wake, { once: true }); @@ -313,7 +372,7 @@ class ScrcpySession { } #startFailure(what: string): ScreenUnavailableError { - const server = `The screen server on ${this.#serial}`; + const server = `The screen server on ${this.#target.serial}`; const reason = this.#shellExited ? `${server} exited before it streamed` : this.#abort.signal.aborted @@ -389,14 +448,14 @@ class ScrcpySession { read: Promise, ): Promise { return new Promise((resolve, reject) => { - const timer = this.#options.clock.setTimer(ALIVE_AFTER_MS, () => resolve(QUIET)); + const timer = this.#clock.setTimer(ALIVE_AFTER_MS, () => resolve(QUIET)); read.then( (chunk) => { - this.#options.clock.cancel(timer); + this.#clock.cancel(timer); resolve(chunk); }, (error: unknown) => { - this.#options.clock.cancel(timer); + this.#clock.cancel(timer); reject(error instanceof Error ? error : new Error(String(error))); }, ); @@ -406,12 +465,12 @@ class ScrcpySession { async #close(): Promise { let timer: ReturnType | undefined; const bound = new Promise((resolve) => { - timer = this.#options.clock.setTimer(CLOSE_DEADLINE_MS, resolve); + timer = this.#clock.setTimer(CLOSE_DEADLINE_MS, resolve); }); try { await Promise.race([this.#teardown(), bound]); } finally { - if (timer !== undefined) this.#options.clock.cancel(timer); + if (timer !== undefined) this.#clock.cancel(timer); } } @@ -428,11 +487,8 @@ class ScrcpySession { if (this.#pushed) { // why: with cleanup=true the server unlinks its own jar as it starts, so this only matters for // a server that never got that far; it runs anyway because that case is not visible from here. - await this.#options.processRunner - .run(this.#options.adb, ["-s", this.#serial, "shell", "rm", "-f", this.#devicePath], { - env: this.#options.env(), - timeoutMs: REMOVE_TIMEOUT_MS, - }) + await this.#target + .run(["shell", "rm", "-f", this.#devicePath], REMOVE_TIMEOUT_MS) .catch(() => undefined); } } @@ -447,11 +503,11 @@ class ScrcpySession { () => true, ), new Promise((resolve) => { - timer = this.#options.clock.setTimer(delayMs, () => resolve(false)); + timer = this.#clock.setTimer(delayMs, () => resolve(false)); }), ]); } finally { - if (timer !== undefined) this.#options.clock.cancel(timer); + if (timer !== undefined) this.#clock.cancel(timer); } } } diff --git a/ui/src/state/screen.test.ts b/ui/src/state/screen.test.ts index 79ef4e2a1..5f2679bdc 100644 --- a/ui/src/state/screen.test.ts +++ b/ui/src/state/screen.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { ApiError } from "../data/api"; -import { refusalOf } from "./screen"; +import { refusalOf, STREAM_HEAD_TIMEOUT_MS } from "./screen"; describe("what a refused stream says", () => { it("says which devices can be streamed when the daemon answers that this one cannot", () => { @@ -12,10 +12,18 @@ describe("what a refused stream says", () => { ); expect(refusalOf(refused)).toBe( - "This device cannot be streamed. A live screen is captured from a simulator or an emulator, not from a physical phone.", + "This device cannot be streamed. A live screen is captured from a simulator, an emulator or a physical Android phone, not from a physical iPhone.", ); }); + it("waits for a stream's headers past the longest open a physical Android phone's capture can take", () => { + // why: a phone's open may spend about 185 s: the shared adb server's version check up to 45 s + // the first time and 5 s before each later step, the screen read, the wake and the second read + // 20 s each, the push 40 s, the server 15 s and a last check past it. + // A console that gave up sooner would show its own timeout instead of the worker's reason. + expect(STREAM_HEAD_TIMEOUT_MS).toBe(200_000); + }); + it("keeps the daemon's own reason when it named one, and says what else to check", () => { const refused = new ApiError(404, undefined, "Unknown lease: lse_1"); diff --git a/ui/src/state/screen.ts b/ui/src/state/screen.ts index e6aecc5f2..b45712923 100644 --- a/ui/src/state/screen.ts +++ b/ui/src/state/screen.ts @@ -25,10 +25,12 @@ const EMPTY: StreamStats = { }; // why: a worker answers a stream's headers only once its capture wrote its first frame, and it may -// take up to 75 s to give up (an emulator's push 30 s, its server 15 s, the first frame 30 s); a -// console that gave up at the API's usual 10 s would show its own timeout instead of the worker's -// reason. -const STREAM_HEAD_TIMEOUT_MS = 90_000; +// take about 185 s on a physical Android phone (the shared adb server's version check up to 45 s +// the first time and 5 s before each later step, the screen read 20 s, the wake 20 s, the second +// read 20 s, the push 40 s, the server 15 s and a last check of up to 5 s past it); an emulator's +// worst case is 75 s (its push 30 s, its server 15 s, the first frame 30 s). A console that gave up +// sooner would show its own timeout instead of the worker's reason. +export const STREAM_HEAD_TIMEOUT_MS = 200_000; export interface Screen { readonly canvas: RefObject; @@ -100,7 +102,7 @@ export function refusalOf(error: unknown): string { return `${error.message} A stream is only offered where capabilities.stream.enabled is on, and only for a lease that is still held.`; } if (error.status === 415) { - return "This device cannot be streamed. A live screen is captured from a simulator or an emulator, not from a physical phone."; + return "This device cannot be streamed. A live screen is captured from a simulator, an emulator or a physical Android phone, not from a physical iPhone."; } return error.message; }