@swmansion/argent 0.34.1-next.8 → 0.34.1-next.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -0
- package/README.md +1 -1
- package/assets/argent.tracecfg.pbtxt +7 -1
- package/assets/ios-screen-stream/Info.plist +12 -0
- package/assets/ios-screen-stream/ios-screen-stream.swift +321 -0
- package/assets/trace-processor/engine_bundle.node.js +2074 -11121
- package/assets/trace-processor/trace_processor.wasm +0 -0
- package/bin/argent-android-devtools-0.4.0.apk +0 -0
- package/bin/darwin/argent-macos-helper +0 -0
- package/bin/darwin/ax-service +0 -0
- package/bin/darwin/simulator-server +0 -0
- package/bin/darwin/tvos-ax-service +0 -0
- package/bin/darwin/tvos-hid-daemon +0 -0
- package/bin/linux/simulator-server +0 -0
- package/bin/linux-arm64/simulator-server +0 -0
- package/bin/network-inspector/network-inspector.jar +0 -0
- package/bin/tcp/ax-service +0 -0
- package/bin/win32/simulator-server.exe +0 -0
- package/dist/cli-cmds.mjs +1259 -616
- package/dist/cli.js +0 -0
- package/dist/client.js +381 -180
- package/dist/flow-script-runner.mjs +1 -0
- package/dist/installer-help.js +4 -0
- package/dist/installer-help.js.map +1 -1
- package/dist/installer.mjs +1161 -893
- package/dist/ios-device-runner/ArgentRunner/ArgentRunner.xcodeproj/xcshareddata/xcschemes/ArgentRunner.xcscheme +1 -0
- package/dist/ios-device-runner/ArgentRunner/ArgentRunnerUITests/ArgentLaunchPerformanceTests.swift +21 -0
- package/dist/ios-device-runner/ArgentRunner/ArgentRunnerUITests/ArgentRunnerSession+Commands.swift +9 -3
- package/dist/ios-device-runner/ArgentRunner/ArgentRunnerUITests/ArgentRunnerSession.swift +3 -0
- package/dist/ios-device-runner/ArgentRunner/ArgentRunnerUITests/RunnerHTTPServer.swift +21 -9
- package/dist/mcp-server.mjs +15613 -7957
- package/dist/preview-ui/index.html +28 -2
- package/dist/tool-args.generated.d.ts +101 -33
- package/dist/tool-server.cjs +20640 -38765
- package/dylibs/libArgentAudio.dylib +0 -0
- package/dylibs/libArgentInjectionBootstrap.dylib +0 -0
- package/dylibs/libKeyboardPatch.dylib +0 -0
- package/dylibs/libNativeDevtoolsIos.dylib +0 -0
- package/dylibs/macos/libArgentInjectionBootstrap.dylib +0 -0
- package/dylibs/macos/libNativeDevtoolsMacos.dylib +0 -0
- package/dylibs/tcp/libArgentInjectionBootstrap.dylib +0 -0
- package/dylibs/tcp/libKeyboardPatch.dylib +0 -0
- package/dylibs/tcp/libNativeDevtoolsIos.dylib +0 -0
- package/dylibs/tvos/libArgentInjectionBootstrap.dylib +0 -0
- package/dylibs/tvos/libKeyboardPatch.dylib +0 -0
- package/dylibs/tvos/libNativeDevtoolsIos.dylib +0 -0
- package/package.json +5 -4
- package/skills/argent-android-emulator-setup/SKILL.md +4 -4
- package/skills/argent-create-e2e/SKILL.md +3 -0
- package/skills/argent-create-e2e/references/e2e-yaml.md +20 -2
- package/skills/argent-create-e2e/references/live-authoring.md +12 -1
- package/skills/argent-device-interact/SKILL.md +22 -21
- package/skills/argent-device-interact/references/foldables.md +22 -0
- package/skills/argent-ios-device-interact/SKILL.md +3 -3
- package/skills/argent-ios-device-setup/SKILL.md +4 -2
- package/skills/argent-macos-app-interact/SKILL.md +15 -5
- package/skills/argent-macos-app-interact/references/e2e.md +1 -1
- package/skills/argent-metro-debugger/SKILL.md +25 -5
- package/skills/argent-native-profiler/SKILL.md +14 -2
- package/skills/argent-qa-e2e/SKILL.md +1 -1
- package/skills/argent-react-native-app-workflow/SKILL.md +2 -2
- package/skills/argent-react-native-optimization/SKILL.md +10 -1
- package/skills/argent-react-native-optimization/references/fix-reference.md +10 -10
- package/skills/argent-react-native-profiler/SKILL.md +4 -3
- package/skills/argent-screen-recording/SKILL.md +6 -4
- package/skills/argent-screenshot-diff/SKILL.md +1 -1
- package/skills/argent-test-ui-flow/SKILL.md +1 -1
- package/skills/argent-tv-interact/SKILL.md +3 -3
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
[](https://swm-delivery.com/www/delivery/ck-slug.php?zoneid=zone-gh-argent-2&n=1)
|
|
8
8
|
[](https://swm-delivery.com/www/delivery/ck-slug.php?zoneid=zone-gh-argent-3&n=1)
|
|
9
9
|
|
|
10
|
-
**[Argent](https://argent.swmansion.com)**
|
|
10
|
+
**[Argent](https://argent.swmansion.com)** is an MCP server, CLI and agent skills that let AI coding agents (Claude Code, Codex, Cursor and others) control iOS simulators, Android emulators and devices, TVs (Apple TV, Android TV, Fire TV), Electron/Chromium apps and native Mac apps. Tap a button, profile a screen, reproduce a bug - without leaving the CLI.
|
|
11
11
|
|
|
12
12
|
```bash
|
|
13
13
|
npx @swmansion/argent@latest init # pnpm: pnpm dlx @swmansion/argent@latest init
|
|
@@ -15,9 +15,15 @@
|
|
|
15
15
|
# If you want a hard cap, set duration_ms here AND keep the stop signal as a
|
|
16
16
|
# safety net (the perfetto daemon will exit either way).
|
|
17
17
|
|
|
18
|
+
# DISCARD is load-bearing: with write_into_file, a DISCARD buffer stops taking
|
|
19
|
+
# data once it has filled, even though its contents were already written to the
|
|
20
|
+
# file. That caps the trace (about 130 MB for a busy app). RING_BUFFER, which
|
|
21
|
+
# Perfetto recommends with write_into_file, lets the file grow for the whole
|
|
22
|
+
# recording, past the 2 GiB the analyze path can read within a few minutes.
|
|
23
|
+
# The config_write_into_file_discard health stat Perfetto reports is expected.
|
|
18
24
|
buffers: {
|
|
19
25
|
size_kb: 65536 # 64 MB — CPU samples + atrace slices
|
|
20
|
-
fill_policy: DISCARD #
|
|
26
|
+
fill_policy: DISCARD # stop once full: keeps the start of the recording
|
|
21
27
|
}
|
|
22
28
|
buffers: {
|
|
23
29
|
size_kb: 16384 # 16 MB — frame timeline + ANRs (sparser, smaller buffer)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
|
+
<plist version="1.0">
|
|
4
|
+
<dict>
|
|
5
|
+
<key>CFBundleIdentifier</key>
|
|
6
|
+
<string>com.swmansion.argent.ios-screen-stream</string>
|
|
7
|
+
<key>CFBundleName</key>
|
|
8
|
+
<string>Argent iPhone screen capture</string>
|
|
9
|
+
<key>NSCameraUsageDescription</key>
|
|
10
|
+
<string>Argent records the screen of an iPhone connected to this Mac by cable.</string>
|
|
11
|
+
</dict>
|
|
12
|
+
</plist>
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Serves a cabled iPhone's screen as an MJPEG stream on 127.0.0.1.
|
|
2
|
+
//
|
|
3
|
+
// Usage: ios-screen-stream [--name <device name>] [--fps <n>] [--quality <0-1>]
|
|
4
|
+
//
|
|
5
|
+
// macOS exposes a cabled iPhone's screen (what QuickTime's "New Movie
|
|
6
|
+
// Recording" shows) as an AVFoundation capture device once the process opts in
|
|
7
|
+
// to screen-capture devices through CoreMediaIO. Nothing runs on the phone.
|
|
8
|
+
//
|
|
9
|
+
// Protocol, one JSON object per stdout line:
|
|
10
|
+
// {"event":"awaiting_permission"} macOS is asking the user for camera access
|
|
11
|
+
// {"event":"ready","port":N,"device":…} GET http://127.0.0.1:N/ streams frames
|
|
12
|
+
// {"event":"error","code":…,"message":…} then exit 1
|
|
13
|
+
// The stream is multipart/x-mixed-replace;boundary=NextFrame, the same shape
|
|
14
|
+
// simulator-server serves. The process exits when stdin closes, so it never
|
|
15
|
+
// outlives the tool-server that spawned it.
|
|
16
|
+
//
|
|
17
|
+
// The tool-server compiles this file with `xcrun swiftc` on first use and
|
|
18
|
+
// embeds Info.plist (see ios-screen-stream.ts).
|
|
19
|
+
|
|
20
|
+
import AVFoundation
|
|
21
|
+
import CoreImage
|
|
22
|
+
import CoreMediaIO
|
|
23
|
+
import Foundation
|
|
24
|
+
import Network
|
|
25
|
+
|
|
26
|
+
setvbuf(stdout, nil, _IOLBF, 0)
|
|
27
|
+
|
|
28
|
+
func emit(_ obj: [String: Any]) {
|
|
29
|
+
guard let data = try? JSONSerialization.data(withJSONObject: obj) else { return }
|
|
30
|
+
FileHandle.standardOutput.write(data + Data([0x0A]))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
func fail(_ code: String, _ message: String) -> Never {
|
|
34
|
+
emit(["event": "error", "code": code, "message": message])
|
|
35
|
+
exit(1)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// MARK: Responsibility
|
|
39
|
+
|
|
40
|
+
// Capture needs camera (TCC) access, which macOS checks against the
|
|
41
|
+
// *responsible* process: the app that launched the tool-server (an editor, a
|
|
42
|
+
// terminal, an agent app). An app without a camera usage string gets a
|
|
43
|
+
// promptless denial. Re-spawning with responsibility disclaimed, as terminals
|
|
44
|
+
// do for their shells, makes this binary, with its embedded Info.plist, the one
|
|
45
|
+
// macOS asks about and remembers.
|
|
46
|
+
@_silgen_name("responsibility_spawnattrs_setdisclaim")
|
|
47
|
+
func responsibility_spawnattrs_setdisclaim(
|
|
48
|
+
_ attrs: UnsafeMutablePointer<posix_spawnattr_t?>, _ disclaim: Int32) -> Int32
|
|
49
|
+
|
|
50
|
+
let disclaimedEnv = "ARGENT_SCREEN_STREAM_DISCLAIMED"
|
|
51
|
+
if getenv(disclaimedEnv) == nil {
|
|
52
|
+
var attr: posix_spawnattr_t?
|
|
53
|
+
posix_spawnattr_init(&attr)
|
|
54
|
+
_ = responsibility_spawnattrs_setdisclaim(&attr, 1)
|
|
55
|
+
setenv(disclaimedEnv, "1", 1)
|
|
56
|
+
var child: pid_t = 0
|
|
57
|
+
let rc = posix_spawn(&child, CommandLine.unsafeArgv[0], nil, &attr, CommandLine.unsafeArgv, environ)
|
|
58
|
+
if rc != 0 { fail("spawn_failed", "Could not re-spawn the capture helper (errno \(rc)).") }
|
|
59
|
+
// Pass termination on. The child shares our stdin, so it also exits on EOF.
|
|
60
|
+
var sources: [DispatchSourceSignal] = []
|
|
61
|
+
for sig in [SIGTERM, SIGINT, SIGHUP] {
|
|
62
|
+
signal(sig, SIG_IGN)
|
|
63
|
+
let source = DispatchSource.makeSignalSource(signal: sig)
|
|
64
|
+
source.setEventHandler { kill(child, sig) }
|
|
65
|
+
source.resume()
|
|
66
|
+
sources.append(source)
|
|
67
|
+
}
|
|
68
|
+
DispatchQueue.global().async {
|
|
69
|
+
var status: Int32 = 0
|
|
70
|
+
while waitpid(child, &status, 0) == -1 && errno == EINTR {}
|
|
71
|
+
exit((status & 0x7f) == 0 ? (status >> 8) & 0xff : 1)
|
|
72
|
+
}
|
|
73
|
+
withExtendedLifetime(sources) { dispatchMain() }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// MARK: Arguments
|
|
77
|
+
|
|
78
|
+
var wantedName: String?
|
|
79
|
+
var fps = 30.0
|
|
80
|
+
var quality = 0.8
|
|
81
|
+
do {
|
|
82
|
+
var args = CommandLine.arguments.dropFirst().makeIterator()
|
|
83
|
+
while let arg = args.next() {
|
|
84
|
+
switch arg {
|
|
85
|
+
case "--name": wantedName = args.next()
|
|
86
|
+
case "--fps": fps = Double(args.next() ?? "") ?? fps
|
|
87
|
+
case "--quality": quality = Double(args.next() ?? "") ?? quality
|
|
88
|
+
default: fail("bad_arguments", "Unknown argument \(arg).")
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Exit with the parent: stdin EOF means the tool-server let go of us.
|
|
94
|
+
DispatchQueue.global().async {
|
|
95
|
+
while FileHandle.standardInput.availableData.count > 0 {}
|
|
96
|
+
exit(0)
|
|
97
|
+
}
|
|
98
|
+
signal(SIGTERM) { _ in exit(0) }
|
|
99
|
+
signal(SIGINT) { _ in exit(0) }
|
|
100
|
+
|
|
101
|
+
// MARK: Camera permission
|
|
102
|
+
|
|
103
|
+
let permissionAdvice =
|
|
104
|
+
"Allow \"ios-screen-stream\" in System Settings > Privacy & Security > Camera, then retry."
|
|
105
|
+
switch AVCaptureDevice.authorizationStatus(for: .video) {
|
|
106
|
+
case .authorized: break
|
|
107
|
+
case .notDetermined:
|
|
108
|
+
emit(["event": "awaiting_permission"])
|
|
109
|
+
let answered = DispatchSemaphore(value: 0)
|
|
110
|
+
var granted = false
|
|
111
|
+
AVCaptureDevice.requestAccess(for: .video) { ok in
|
|
112
|
+
granted = ok
|
|
113
|
+
answered.signal()
|
|
114
|
+
}
|
|
115
|
+
if answered.wait(timeout: .now() + 120) == .timedOut || !granted {
|
|
116
|
+
fail("camera_permission_denied",
|
|
117
|
+
"macOS did not grant the camera access it requires to capture an iPhone screen. \(permissionAdvice)")
|
|
118
|
+
}
|
|
119
|
+
default:
|
|
120
|
+
fail("camera_permission_denied",
|
|
121
|
+
"Camera access, which macOS requires to capture an iPhone screen, is denied. \(permissionAdvice)")
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// MARK: Device discovery
|
|
125
|
+
|
|
126
|
+
var allowProperty = CMIOObjectPropertyAddress(
|
|
127
|
+
mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),
|
|
128
|
+
mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),
|
|
129
|
+
mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMain))
|
|
130
|
+
var allow: UInt32 = 1
|
|
131
|
+
let allowStatus = CMIOObjectSetPropertyData(
|
|
132
|
+
CMIOObjectID(kCMIOObjectSystemObject), &allowProperty, 0, nil,
|
|
133
|
+
UInt32(MemoryLayout<UInt32>.size), &allow)
|
|
134
|
+
if allowStatus != 0 {
|
|
135
|
+
fail("helper_failed", "CoreMediaIO refused to expose screen-capture devices (status \(allowStatus)).")
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// An iPhone screen is an external, muxed device with model "iOS Device". The
|
|
139
|
+
/// phone's Continuity Camera is external too, but carries video media.
|
|
140
|
+
func screenDevices() -> [AVCaptureDevice] {
|
|
141
|
+
AVCaptureDevice.DiscoverySession(
|
|
142
|
+
deviceTypes: [.external], mediaType: nil, position: .unspecified
|
|
143
|
+
).devices.filter { $0.hasMediaType(.muxed) && $0.modelID == "iOS Device" }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// devicectl and AVFoundation may spell the apostrophe in "Name's iPhone" differently.
|
|
147
|
+
func normalize(_ s: String) -> String {
|
|
148
|
+
s.replacingOccurrences(of: "\u{2019}", with: "'").lowercased()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// The screen of the named iPhone, or the only one when the name matches none
|
|
152
|
+
/// (a renamed phone can keep its old name on one side for a while).
|
|
153
|
+
func pickDevice() -> AVCaptureDevice? {
|
|
154
|
+
let all = screenDevices()
|
|
155
|
+
if let wantedName {
|
|
156
|
+
let matches = all.filter { normalize($0.localizedName) == normalize(wantedName) }
|
|
157
|
+
if matches.count > 1 {
|
|
158
|
+
fail("ambiguous_device",
|
|
159
|
+
"\(matches.count) cabled iPhones are named \"\(wantedName)\", so argent cannot tell which screen to record. Rename one in Settings > General > About, or unplug the others.")
|
|
160
|
+
}
|
|
161
|
+
if let match = matches.first { return match }
|
|
162
|
+
}
|
|
163
|
+
if all.count > 1 {
|
|
164
|
+
let names = all.map(\.localizedName).joined(separator: ", ")
|
|
165
|
+
fail("ambiguous_device",
|
|
166
|
+
"\(all.count) cabled iPhones are connected (\(names)) and none is named \"\(wantedName ?? "")\".")
|
|
167
|
+
}
|
|
168
|
+
return all.first
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The device appears asynchronously after the opt-in, usually within 0.5s.
|
|
172
|
+
var device: AVCaptureDevice?
|
|
173
|
+
let discoveryDeadline = Date().addingTimeInterval(5)
|
|
174
|
+
while device == nil && Date() < discoveryDeadline {
|
|
175
|
+
device = pickDevice()
|
|
176
|
+
if device == nil { RunLoop.current.run(until: Date().addingTimeInterval(0.1)) }
|
|
177
|
+
}
|
|
178
|
+
guard let device else {
|
|
179
|
+
fail("device_not_found",
|
|
180
|
+
"macOS exposes no iPhone screen for capture. Connect the iPhone with a USB cable (not Wi-Fi), unlock it, and trust this Mac.")
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// MARK: Frames
|
|
184
|
+
|
|
185
|
+
final class FrameSink: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
|
|
186
|
+
private let context = CIContext(options: [.useSoftwareRenderer: false])
|
|
187
|
+
private let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
|
|
188
|
+
private let minInterval: CFTimeInterval
|
|
189
|
+
private let quality: Double
|
|
190
|
+
private var lastEmit: CFTimeInterval = 0
|
|
191
|
+
private let lock = NSLock()
|
|
192
|
+
private var clients: [ObjectIdentifier: NWConnection] = [:]
|
|
193
|
+
private var latest: Data?
|
|
194
|
+
|
|
195
|
+
init(fps: Double, quality: Double) {
|
|
196
|
+
minInterval = 1 / max(fps, 1)
|
|
197
|
+
self.quality = quality
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
func add(_ connection: NWConnection) {
|
|
201
|
+
lock.lock()
|
|
202
|
+
clients[ObjectIdentifier(connection)] = connection
|
|
203
|
+
let frame = latest
|
|
204
|
+
lock.unlock()
|
|
205
|
+
let head =
|
|
206
|
+
"HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace;boundary=NextFrame\r\n"
|
|
207
|
+
+ "Cache-Control: no-cache\r\nConnection: close\r\n\r\n--NextFrame"
|
|
208
|
+
send(Data(head.utf8), to: connection)
|
|
209
|
+
// The phone sends nothing while its screen is still; replay the last frame
|
|
210
|
+
// so a new client does not wait for the next change.
|
|
211
|
+
if let frame { send(part(frame), to: connection) }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
func remove(_ connection: NWConnection) {
|
|
215
|
+
lock.lock()
|
|
216
|
+
clients[ObjectIdentifier(connection)] = nil
|
|
217
|
+
lock.unlock()
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/// Each part ends with the next boundary, so a reader that splits on the
|
|
221
|
+
/// boundary has the frame the moment it is written.
|
|
222
|
+
private func part(_ jpeg: Data) -> Data {
|
|
223
|
+
Data("\r\nContent-Type: image/jpeg\r\nContent-Length: \(jpeg.count)\r\n\r\n".utf8)
|
|
224
|
+
+ jpeg + Data("\r\n--NextFrame".utf8)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private func send(_ data: Data, to connection: NWConnection) {
|
|
228
|
+
connection.send(content: data, completion: .contentProcessed { [weak self] error in
|
|
229
|
+
if error != nil {
|
|
230
|
+
self?.remove(connection)
|
|
231
|
+
connection.cancel()
|
|
232
|
+
}
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
func captureOutput(
|
|
237
|
+
_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
|
|
238
|
+
from connection: AVCaptureConnection
|
|
239
|
+
) {
|
|
240
|
+
let now = CACurrentMediaTime()
|
|
241
|
+
if now - lastEmit < minInterval { return }
|
|
242
|
+
guard let pixels = CMSampleBufferGetImageBuffer(sampleBuffer),
|
|
243
|
+
let jpeg = context.jpegRepresentation(
|
|
244
|
+
of: CIImage(cvPixelBuffer: pixels), colorSpace: colorSpace,
|
|
245
|
+
options: [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: quality])
|
|
246
|
+
else { return }
|
|
247
|
+
lastEmit = now
|
|
248
|
+
lock.lock()
|
|
249
|
+
latest = jpeg
|
|
250
|
+
let targets = Array(clients.values)
|
|
251
|
+
lock.unlock()
|
|
252
|
+
let payload = part(jpeg)
|
|
253
|
+
for client in targets { send(payload, to: client) }
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let session = AVCaptureSession()
|
|
258
|
+
let input: AVCaptureDeviceInput
|
|
259
|
+
do {
|
|
260
|
+
input = try AVCaptureDeviceInput(device: device)
|
|
261
|
+
} catch {
|
|
262
|
+
fail("helper_failed", "Could not open \(device.localizedName)'s screen: \(error.localizedDescription)")
|
|
263
|
+
}
|
|
264
|
+
guard session.canAddInput(input) else {
|
|
265
|
+
fail("helper_failed", "\(device.localizedName)'s screen cannot join a capture session.")
|
|
266
|
+
}
|
|
267
|
+
session.addInput(input)
|
|
268
|
+
|
|
269
|
+
let output = AVCaptureVideoDataOutput()
|
|
270
|
+
output.alwaysDiscardsLateVideoFrames = true
|
|
271
|
+
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
|
|
272
|
+
let sink = FrameSink(fps: fps, quality: quality)
|
|
273
|
+
output.setSampleBufferDelegate(sink, queue: DispatchQueue(label: "ios-screen-stream.capture"))
|
|
274
|
+
guard session.canAddOutput(output) else {
|
|
275
|
+
fail("helper_failed", "Could not attach a video output to \(device.localizedName)'s screen.")
|
|
276
|
+
}
|
|
277
|
+
session.addOutput(output)
|
|
278
|
+
|
|
279
|
+
// MARK: HTTP
|
|
280
|
+
|
|
281
|
+
let listener: NWListener
|
|
282
|
+
do {
|
|
283
|
+
let params = NWParameters.tcp
|
|
284
|
+
params.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: 0)
|
|
285
|
+
listener = try NWListener(using: params)
|
|
286
|
+
} catch {
|
|
287
|
+
fail("helper_failed", "Could not open a local port: \(error.localizedDescription)")
|
|
288
|
+
}
|
|
289
|
+
let serverQueue = DispatchQueue(label: "ios-screen-stream.server")
|
|
290
|
+
listener.newConnectionHandler = { connection in
|
|
291
|
+
connection.stateUpdateHandler = { state in
|
|
292
|
+
switch state {
|
|
293
|
+
case .failed, .cancelled: sink.remove(connection)
|
|
294
|
+
default: break
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
connection.start(queue: serverQueue)
|
|
298
|
+
// Any request gets the stream; read the head only to know one arrived.
|
|
299
|
+
connection.receive(minimumIncompleteLength: 1, maximumLength: 8192) { _, _, _, error in
|
|
300
|
+
if error != nil {
|
|
301
|
+
connection.cancel()
|
|
302
|
+
return
|
|
303
|
+
}
|
|
304
|
+
sink.add(connection)
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
listener.stateUpdateHandler = { state in
|
|
308
|
+
switch state {
|
|
309
|
+
case .ready:
|
|
310
|
+
session.startRunning()
|
|
311
|
+
emit(["event": "ready", "port": Int(listener.port?.rawValue ?? 0), "device": device.localizedName])
|
|
312
|
+
case .failed(let error):
|
|
313
|
+
fail("helper_failed", "The local stream server failed: \(error.localizedDescription)")
|
|
314
|
+
default: break
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
listener.start(queue: serverQueue)
|
|
318
|
+
|
|
319
|
+
// CoreMediaIO delivers device frames through the main run loop; dispatchMain()
|
|
320
|
+
// would leave the session running with no samples.
|
|
321
|
+
RunLoop.main.run()
|