Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 220 additions & 0 deletions docs/experiments/remote-web-public-network-confinement.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/command-surface/src/recording/index.ts

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions packages/contracts/src/screen-recording-runtime-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,18 @@ export type ApplePhysicalDeviceRecorder = 'runner' | 'usb-capture';
* records instead, and the recording result names the reason.
*/
export const IOS_USB_CAPTURE_FALLBACK_REASONS = {
// No USB screen-capture source with the device name appeared on the host.
// Neither the USB screen-capture source learned for the device nor another source with the device name appeared on the host.
deviceNotFound: { reason: 'ios_usb_capture_device_not_found' },
// The capture source opened but sent no frame before the first-frame timeout.
noFrames: { reason: 'ios_usb_capture_no_frames' },
// macOS camera access is not authorized for the app that launched the daemon. Nothing prompts for it.
cameraAccessNotAuthorized: { reason: 'ios_usb_capture_camera_access_not_authorized' },
// Another USB capture recording on this Mac, of any user, held the start lock for the whole lock timeout.
startBusy: { reason: 'ios_usb_capture_start_busy' },
// Another Apple device in the daemon's inventory, cabled or wireless, has the device name.
// No capture source is learned for the device, and the device name is not unique among the unlearned: another Apple device in the daemon's inventory, cabled or wireless, with no learned source, or another USB capture source on this Mac not learned for another device, has it, or the inventory could not be read.
deviceNameShared: { reason: 'ios_usb_capture_device_name_shared' },
// Another Apple device learned the capture source that matched the device name while this start ran.
sourceOfAnotherDevice: { reason: 'ios_usb_capture_source_of_another_device' },
} as const satisfies ReasonTable<'record'>;

export type IosUsbCaptureFallbackReason =
Expand Down
2 changes: 1 addition & 1 deletion packages/host-swift/src/recording-swift-sources.ts

Large diffs are not rendered by default.

65 changes: 48 additions & 17 deletions packages/host-swift/swift/ios-usb-capture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@ import Foundation
/// Records the screen of an iPhone or iPad connected by USB cable to an H.264 MP4, through the
/// CoreMediaIO screen-capture device macOS exposes for it (the source QuickTime Player records).
///
/// Usage: `ios-usb-capture --device-name <name> --output <path> --start-lock-path <path>
/// Usage: `ios-usb-capture --device-name <name> [--device-uid <uniqueID>]
/// [--exclude-device-uid <uniqueID>]... --output <path> --start-lock-path <path>
/// [--device-timeout-ms <n>] [--first-frame-timeout-ms <n>] [--start-lock-timeout-ms <n>]`.
///
/// The writer creates the output file when the first frame arrives and appends that frame at once. A
/// writer that refuses the first frame exits 8, so a file and a live helper are the readiness signal.
/// A capture device names only the device name, never its UDID, so the caller passes the name it
/// resolved and a name two connected devices share is refused rather than guessed.
/// A capture device names only the device name, never its UDID. A name match opens the one capture
/// device with the device name that no `--exclude-device-uid` names, and refuses a name that two such
/// devices share rather than guess. The caller excludes the sources it knows belong to other devices.
/// With `--device-uid`, the helper waits for the capture device with that `uniqueID` and opens it
/// only while it has the device name. When that device has another name, or does not appear within
/// the device timeout, the helper tries a name match instead. Before the capture session starts, so
/// before the first frame, the helper prints `capture-source-uid <uniqueID>` on stdout for the
/// capture device that it opened.
///
/// Two helpers that discover and open capture devices at the same time can each receive the other
/// device's frames. With two iPhones connected, 4 of 6 simultaneous starts recorded the wrong phone
Expand All @@ -23,8 +30,9 @@ import Foundation
/// SIGINT or SIGTERM ends the helper by that signal. Exit codes:
/// - 0: SIGINT or SIGTERM arrived after recording began; the file is finished.
/// - 2: invalid arguments.
/// - 3: no capture device with that name appeared within the device timeout.
/// - 4: more than one capture device has that name.
/// - 3: no capture device with that `uniqueID` and name, and none that a name match finds, appeared
/// within the device timeout.
/// - 4: a name match found more than one capture device that is not excluded with that name.
/// - 5: no frame was written within the first-frame timeout or before SIGINT or SIGTERM; no file is usable.
/// - 6: macOS camera access is not authorized for the process that launched the recorder. The helper
/// checks before anything else and never asks for access.
Expand Down Expand Up @@ -57,6 +65,8 @@ enum FinishOutcome {

struct CaptureOptions {
let deviceName: String
let deviceUid: String?
let excludedUids: Set<String>
let outputURL: URL
let startLockPath: String
let deviceTimeout: TimeInterval
Expand All @@ -77,13 +87,18 @@ func fail(_ code: CaptureExit, _ message: String) -> Never {

func parseOptions(_ arguments: [String]) -> CaptureOptions {
var values: [String: String] = [:]
var excludedUids: Set<String> = []
var index = 1
while index < arguments.count {
let key = arguments[index]
guard key.hasPrefix("--"), index + 1 < arguments.count else {
fail(.invalidArguments, "invalid argument: \(key)")
}
values[key] = arguments[index + 1]
if key == "--exclude-device-uid" {
excludedUids.insert(arguments[index + 1])
} else {
values[key] = arguments[index + 1]
}
index += 2
}
guard let name = values["--device-name"], !name.isEmpty,
Expand All @@ -92,13 +107,17 @@ func parseOptions(_ arguments: [String]) -> CaptureOptions {
else {
fail(.invalidArguments, "--device-name, --output and an absolute --start-lock-path are required")
}
let uid = values["--device-uid"]
if let uid, uid.isEmpty { fail(.invalidArguments, "invalid --device-uid") }
func milliseconds(_ key: String, _ fallback: Double) -> TimeInterval {
guard let text = values[key] else { return fallback / 1000 }
guard let value = Double(text), value > 0 else { fail(.invalidArguments, "invalid \(key)") }
return value / 1000
}
return CaptureOptions(
deviceName: name,
deviceUid: uid,
excludedUids: excludedUids,
outputURL: URL(fileURLWithPath: output),
startLockPath: lockPath,
deviceTimeout: milliseconds("--device-timeout-ms", 10_000),
Expand Down Expand Up @@ -199,18 +218,30 @@ func ensureCameraAccess() {
}
}

func findCaptureDevice(named name: String, within timeout: TimeInterval) -> AVCaptureDevice {
let deadline = Date().addingTimeInterval(timeout)
func findCaptureDevice(_ options: CaptureOptions) -> AVCaptureDevice {
let deadline = Date().addingTimeInterval(options.deviceTimeout)
var learnedUid = options.deviceUid
while true {
let matches = AVCaptureDevice.DiscoverySession(
let devices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.external], mediaType: .muxed, position: .unspecified
).devices.filter { $0.localizedName == name }
if matches.count > 1 {
fail(.deviceAmbiguous, "\(matches.count) USB capture devices are named \(name)")
).devices
if let uid = learnedUid, let learned = devices.first(where: { $0.uniqueID == uid }) {
if learned.localizedName == options.deviceName { return learned }
report("the USB capture device \(uid) is named \(learned.localizedName); matching by name")
learnedUid = nil
}
let timedOut = Date() >= deadline
if learnedUid == nil || timedOut {
let matches = devices.filter {
$0.localizedName == options.deviceName && !options.excludedUids.contains($0.uniqueID)
}
if matches.count > 1 {
fail(.deviceAmbiguous, "\(matches.count) USB capture devices are named \(options.deviceName)")
}
if let device = matches.first { return device }
}
if let device = matches.first { return device }
if Date() >= deadline {
fail(.deviceNotFound, "no USB capture device named \(name) appeared")
if timedOut {
fail(.deviceNotFound, "no USB capture device for \(options.deviceName) appeared")
}
RunLoop.current.run(until: Date().addingTimeInterval(0.25))
}
Expand Down Expand Up @@ -320,7 +351,7 @@ ensureCameraAccess()
let startLock = StartLock()
startLock.acquire(at: options.startLockPath, within: options.startLockTimeout)
allowScreenCaptureDevices()
let device = findCaptureDevice(named: options.deviceName, within: options.deviceTimeout)
let device = findCaptureDevice(options)

let session = AVCaptureSession()
let deviceInput: AVCaptureDeviceInput
Expand Down Expand Up @@ -371,12 +402,12 @@ let interruptions = [
}
}

print("capture-source-uid \(device.uniqueID)")
session.startRunning()
DispatchQueue.main.asyncAfter(deadline: .now() + options.firstFrameTimeout) {
if !captureWriter.queue.sync(execute: { captureWriter.hasRecorded }) {
session.stopRunning()
fail(.noFrames, "no frame from the USB capture device was written; wake and unlock the device")
}
}
print("capturing \(options.deviceName)")
withExtendedLifetime((stopSources, interruptions)) { dispatchMain() }
2 changes: 1 addition & 1 deletion scripts/capability-matrix/annotations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [
label: 'Screen recording',
commands: ['record'],
link: docs('commands', 'media-and-logs'),
note: 'A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and no other Apple device has its name, and falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks.',
note: 'A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and its capture source appears. agent-device learns the source of a device on a recording when every other Apple device and capture source with the device name is learned for another device; later recordings of that device open the learned source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. It falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks.',
},
{
id: 'logs',
Expand Down
1 change: 1 addition & 0 deletions scripts/layering/root-module-zones.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const ROOT_MODULE_ZONES: Readonly<Record<string, readonly string[]>> = {
'src/platform-runtime-screen-recording-apple-simulator-host.ts',
'src/platform-runtime-screen-recording-apple-transport.ts',
'src/platform-runtime-screen-recording-apple-usb-capture-host.ts',
'src/platform-runtime-screen-recording-apple-usb-capture-sources.ts',
'src/platform-runtime-screen-recording-finalizer-host.ts',
'src/platform-runtime-screen-recording-harmony-host.ts',
'src/platform-runtime-screen-recording-host.ts',
Expand Down
3 changes: 2 additions & 1 deletion src/commands/schema/cli-help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,8 @@ iOS runner transport:

iOS physical-device recording:
A CoreDevice iPhone or iPad on a USB cable of this Mac records its USB screen-capture source (the source QuickTime Player records) at native resolution near 60 fps, video only, when the recording transports are this host's own. Otherwise it records runner screenshots at a low frame rate. record start and record stop --json name the recorder in recordingBackend.
When USB capture cannot record, the runner records instead, and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized, ios_usb_capture_device_name_shared (another Apple device in the daemon's inventory, cabled or wireless, or another USB capture source on this Mac has the name; give each device a unique name in Settings > General > About > Name), ios_usb_capture_device_not_found, ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy. This happens only before the first frame. After it the recorder never changes.
A capture source carries the device name, not its UDID. A device that has no learned source matches its source by name, among the capture sources not learned for another device. When every other Apple device in the daemon's inventory with that name has a learned source, the match is exact: the recording learns the uniqueID of the source and records it in ~/.agent-device/ios-usb-capture-sources. The record is a hint: when that directory cannot be written, nothing is learned and later recordings match by name again. Later recordings of a learned device open its source by uniqueID while that source has the device name, whatever other devices are named, and do not read the device inventory. When the learned source does not appear or has another name, the recording matches by name instead, and only a newer exact match replaces the record. So devices that share a name all keep USB capture when you connect and record them one at a time. Two devices that share a name and have no learned source cannot be told apart: give one of them a unique name for one recording.
When USB capture cannot record, the runner records instead, and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized, ios_usb_capture_device_name_shared (no capture source is learned for the device, and another Apple device in the daemon's inventory, cabled or wireless, that has no learned source, or another USB capture source on this Mac that is not learned for another device, has the name, so give the device a unique name in Settings > General > About > Name for one recording; or the daemon could not read its device inventory, so check agent-device devices and retry), ios_usb_capture_source_of_another_device (no capture source is learned for the device, and another device learned the capture source that matched its name while it started; retry record start), ios_usb_capture_device_not_found (when a source is learned for the device, neither it nor another source with the device name appeared, and the record is kept for the next start), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy. This happens only before the first frame. After it the recorder never changes.
agent-device never asks for camera access. Allow it for the app that runs agent-device in System Settings > Privacy & Security > Camera, then restart the daemon. The first frame can take several seconds, and up to about 10 s after the previous USB capture recording of the device stopped.
USB capture recordings start one at a time on this Mac, for every daemon and every user, through the start lock /private/tmp/agent-device-ios-usb-capture-start.lock. Another user's recording holds it until its first frame. A lock file that another account owns and does not let this user read fails with ios_usb_capture_start_lock_unusable; ask that account or an administrator to remove the file.

Expand Down
Loading
Loading