Skip to content
Merged
23 changes: 21 additions & 2 deletions e2e/slow-ios-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,34 @@ describe.skipIf(process.platform !== "darwin")(
);
// why: nothing touches the simulator here, so its screen is still; the stream must stay
// open well past the 30 s silence bound on the capture's own idle repaints.
const stillUntil = Date.now() + 35_000;
const stillFrom = Date.now();
const stillUntil = stillFrom + 35_000;
// why: the stream is endless, so a key frame's arrival is stamped as the read that
// brought it ends; `enough` runs after every read.
const keyArrivals = [stillFrom];
let keysSeen = 0;
const held = await within(
readFrames(second.reader, () => Date.now() > stillUntil),
readFrames(second.reader, (read) => {
const keys = read.filter((frame) => frame.tag === TAG.keyframe).length;
if (keys > keysSeen) keyArrivals.push(Date.now());
keysSeen = keys;
return Date.now() > stillUntil;
}),
KEY_FRAME_BOUND,
"the still stream's frames",
);
expect(held.length, "a still simulator's stream sent nothing for 35 s").toBeGreaterThan(
0,
);
expect(
keysSeen,
"a still simulator's stream sent too few key frames",
).toBeGreaterThanOrEqual(3);
const gaps = [...keyArrivals, Date.now()].slice(1).map((at, i) => at - keyArrivals[i]!);
expect(
Math.max(...gaps.slice(0, -1)),
"a still simulator's stream went over 5.5 s without a key frame",
).toBeLessThanOrEqual(5_500);
expect(
[...opening, ...held].filter((frame) => frame.tag === TAG.meta).length,
"a one-panel device's stream sent more than one meta frame",
Expand Down
4 changes: 2 additions & 2 deletions src/drivers/ios/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Resolve and boot:
- The overrides folder lives outside the device set (`launchdOverridesRoot`), so `destroy` removes it itself after `simctl delete`.
- After every boot and before the readback, `runAfterBoot` (`boot-courtesies.ts`) runs the volume step, then the window step. Each only reports its failure (`onSilenceFailed`, `onWindowFailed`), and the device stays in use.
- Volume (`ios.simulator.audio: false`): Apps keep playing at volume 0. A baseline source is not silenced.
- Window (`ios.simulator.headless: false`): DeviceHub is opened in the background, so the front app stays in front, and is told not to shut down started devices when it quits. Only a non-zero exit of that open means DeviceHub is missing: Simulator.app is then opened instead, detached, so quitting it leaves the simulator running. Any other failure opens nothing.
- Window (`ios.simulator.headless: false`): DeviceHub is opened in the background, so the front app stays in front, and is told not to shut down started devices when it quits. Only a non-zero exit of that open means DeviceHub is missing: Simulator.app is then opened instead, detached, so quitting it leaves the simulator running.

Seeds (ADR 0061):

Expand All @@ -38,7 +38,7 @@ Seeds (ADR 0061):
Physical, passthrough, screen:

- `devicectl` over `device.exec` is an allow-list (`devicectlExecCommand`): what is not on the reviewed list is refused, and so is every option that names a host path.
- Screen (`screen-capture.ts`): stdout is the frames, stdin the program's liveness, and closing stdin is the stop. The daemon's own `SIMLOCK_IOS_DEVICE_SET` and `SIMLOCK_COREDEVICE_INFO_PLIST` reach neither program; the driver sets the first for a simulator under `simlock` only.
- Screen (`screen-capture.ts`): stdout is the frames, stdin the program's liveness, and closing stdin is the stop. Key frames keep coming on a still screen. The daemon's own `SIMLOCK_IOS_DEVICE_SET` and `SIMLOCK_COREDEVICE_INFO_PLIST` reach neither program; the driver sets the first for a simulator under `simlock` only.
- An iPhone below iOS 27 is `ScreenUnavailableError`; an unreadable version goes on. The iPhone program enforces its CoreDevice pin itself: another major exits 69 with the reason, a 503 for the viewer.

Tunnels (`device-tcp.ts`):
Expand Down
13 changes: 10 additions & 3 deletions vendor/screen-capture/Sources/SimlockCapture/Lifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -203,24 +203,30 @@ func prepareForEncode(

// MARK: - The encode loop

/// The longest a stream goes without a key frame, in arrival time.
let maxKeyframeGapNanos: UInt64 = 5_000_000_000

/// Runs the encode loop until the viewer goes away. `newest(1)` on the stream means a slow encoder or
/// a relay that stops draining drops old frames instead of queueing them without bound, which is the
/// behaviour a live view needs.
///
/// The first frame forces an IDR so the viewer that just asked for the stream can start decoding
/// immediately rather than waiting for the encoder's own keyframe interval; after that VideoToolbox
/// spaces IDRs itself (`MaxKeyFrameInterval = fps * 5`, from serve-sim's encoder).
/// immediately rather than waiting for the encoder's own keyframe interval. After that the loop forces
/// one whenever 5 s of arrival time have passed since the last key frame, whatever its cause, so a
/// still screen (a few frames a second) still gives a new decoder a picture within 5 s; the encoder's
/// own `MaxKeyFrameInterval` counts frames and would stretch to half a minute at the idle floor.
func encodeLoop(_ frames: AsyncStream<Pending>, options: Options, session: Session) async {
let intervalNanos = UInt64(1_000_000_000 / Double(options.fps))
var lastSent: UInt64 = 0
var started = false
var metaSize: Dimensions?
var lastKeyframe: UInt64 = 0
let encoder = H264Encoder(fps: options.fps, bitrate: options.bitrate)
let jpegEncoder = VideoEncoder(quality: 0.7)
for await frame in frames {
if started, frame.atNanos &- lastSent < intervalNanos { continue }
lastSent = frame.atNanos
let forceKeyframe = !started
let forceKeyframe = !started || frame.atNanos &- lastKeyframe >= maxKeyframeGapNanos
started = true

guard let prepared = prepareForEncode(frame.buffer, options: options, session: session) else {
Expand Down Expand Up @@ -261,6 +267,7 @@ func encodeLoop(_ frames: AsyncStream<Pending>, options: Options, session: Sessi
if let description = encoded.description {
Wire.emit(.description, description, countedBy: session)
}
if encoded.kind == .keyframe { lastKeyframe = frame.atNanos }
Wire.emit(
encoded.kind == .keyframe ? .keyframe : .delta,
encoded.avcc,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,53 @@ final class EncodeLoopTests: XCTestCase {
XCTAssertEqual(tags.filter { $0 == .keyframe }.count, 3)
XCTAssertEqual(tags.filter { $0 == .delta }.count, 2)
}

func testACaptureWritesAKeyframeAtLeastEvery5SecondsOfFrameTime() async throws {
struct Case {
let name: String
let step: UInt64
let count: Int
/// The frame index at which the picture changes size, if it does.
let resizeAt: Int?
/// The exact key-frame times when the encoder's own spacing cannot move them.
let keyTimes: [Double]?
}
let second: UInt64 = 1_000_000_000
let cases = [
Case(name: "idle-floor frames for 12 s", step: second / 5, count: 60, resizeAt: nil, keyTimes: [0, 5, 10]),
Case(name: "30 frames a second for 12 s", step: second / 30, count: 360, resizeAt: nil, keyTimes: nil),
Case(name: "a size change at 3 s", step: second / 5, count: 60, resizeAt: 15, keyTimes: [0, 3, 8]),
]
for testCase in cases {
let (frames, input) = AsyncStream.makeStream(of: Pending.self)
for index in 0..<testCase.count {
let resized = testCase.resizeAt.map { index >= $0 } ?? false
input.yield(Pending(
buffer: picture(resized ? 1398 : 1179, resized ? 2034 : 2556),
atNanos: UInt64(index) * testCase.step
))
}
input.finish()

nonisolated(unsafe) var written: [Tag] = []
Wire.sink = { tag, _ in written.append(tag) }
defer { Wire.sink = nil }
await encodeLoop(frames, options: Options(), session: Session())

let pictures = written.filter { $0 == .keyframe || $0 == .delta }
XCTAssertEqual(pictures.count, testCase.count, "\(testCase.name): every frame is written")
let keyTimes = pictures.enumerated().filter { $0.element == .keyframe }
.map { Double($0.offset) * Double(testCase.step) / Double(second) }
let end = Double(testCase.count) * Double(testCase.step) / Double(second)
let gaps = zip(keyTimes, keyTimes.dropFirst().map { $0 } + [end]).map { $1 - $0 }
XCTAssertLessThanOrEqual(gaps.max() ?? .infinity, 5.2, "\(testCase.name): key frames at \(keyTimes)")
if let expected = testCase.keyTimes {
XCTAssertEqual(keyTimes, expected, testCase.name)
}
if testCase.resizeAt != nil {
XCTAssertEqual(written.filter { $0 == .meta }.count, 2, "\(testCase.name): meta")
XCTAssertEqual(written.filter { $0 == .description }.count, 2, "\(testCase.name): parameter sets")
}
}
}
}
Loading