forked from getsentry/XcodeBuildMCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_capture.ts
More file actions
246 lines (212 loc) · 6.38 KB
/
video_capture.ts
File metadata and controls
246 lines (212 loc) · 6.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
* Video capture utility for simulator recordings using AXe.
*
* Manages long-running AXe "record-video" processes keyed by simulator UUID.
* It aggregates stdout/stderr to parse the generated MP4 path on stop.
*/
import type { ChildProcess } from 'child_process';
import { log } from './logging/index.ts';
import { getAxePath, getBundledAxeEnvironment } from './axe-helpers.ts';
import type { CommandExecutor } from './execution/index.ts';
type Session = {
process: unknown;
sessionId: string;
startedAt: number;
buffer: string;
ended: boolean;
};
const sessions = new Map<string, Session>();
let signalHandlersAttached = false;
export interface AxeHelpers {
getAxePath: () => string | null;
getBundledAxeEnvironment: () => Record<string, string>;
}
function ensureSignalHandlersAttached(): void {
if (signalHandlersAttached) return;
signalHandlersAttached = true;
const stopAll = (): void => {
for (const [simulatorUuid, sess] of sessions) {
try {
const child = sess.process as ChildProcess | undefined;
child?.kill?.('SIGINT');
} catch {
// ignore
} finally {
sessions.delete(simulatorUuid);
}
}
};
try {
process.on('SIGINT', stopAll);
process.on('SIGTERM', stopAll);
process.on('exit', stopAll);
} catch {
// Non-Node environments may not support process signals; ignore
}
}
function parseLastAbsoluteMp4Path(buffer: string | undefined): string | null {
if (!buffer) return null;
const matches = [...buffer.matchAll(/(\s|^)(\/[^\s'"]+\.mp4)\b/gi)];
if (matches.length === 0) return null;
const last = matches[matches.length - 1];
return last?.[2] ?? null;
}
function createSessionId(simulatorUuid: string): string {
return `${simulatorUuid}:${Date.now()}`;
}
/**
* Start recording video for a simulator using AXe.
*/
export async function startSimulatorVideoCapture(
params: { simulatorUuid: string; fps?: number },
executor: CommandExecutor,
axeHelpers?: AxeHelpers,
): Promise<{ started: boolean; sessionId?: string; warning?: string; error?: string }> {
const simulatorUuid = params.simulatorUuid;
if (!simulatorUuid) {
return { started: false, error: 'simulatorUuid is required' };
}
if (sessions.has(simulatorUuid)) {
return {
started: false,
error: 'A video recording session is already active for this simulator. Stop it first.',
};
}
const helpers = axeHelpers ?? {
getAxePath,
getBundledAxeEnvironment,
};
const axeBinary = helpers.getAxePath();
if (!axeBinary) {
return { started: false, error: 'Bundled AXe binary not found' };
}
const fps = Number.isFinite(params.fps as number) ? Number(params.fps) : 30;
const command = [axeBinary, 'record-video', '--udid', simulatorUuid, '--fps', String(fps)];
const env = helpers.getBundledAxeEnvironment?.() ?? {};
log('info', `Starting AXe video recording for simulator ${simulatorUuid} at ${fps} fps`);
const result = await executor(command, 'Start Simulator Video Capture', true, { env }, true);
if (!result.success || !result.process) {
return {
started: false,
error: result.error ?? 'Failed to start video capture process',
};
}
const child = result.process as ChildProcess;
const session: Session = {
process: child,
sessionId: createSessionId(simulatorUuid),
startedAt: Date.now(),
buffer: '',
ended: false,
};
try {
child.stdout?.on('data', (d: unknown) => {
try {
session.buffer += String(d ?? '');
} catch {
// ignore
}
});
child.stderr?.on('data', (d: unknown) => {
try {
session.buffer += String(d ?? '');
} catch {
// ignore
}
});
} catch {
// ignore stream listener setup failures
}
// Track when the child process naturally ends, so stop can short-circuit
try {
child.once?.('exit', () => {
session.ended = true;
});
child.once?.('close', () => {
session.ended = true;
});
} catch {
// ignore
}
sessions.set(simulatorUuid, session);
ensureSignalHandlersAttached();
return {
started: true,
sessionId: session.sessionId,
warning: fps !== (params.fps ?? 30) ? `FPS coerced to ${fps}` : undefined,
};
}
/**
* Stop recording video for a simulator. Returns aggregated output and parsed MP4 path if found.
*/
export async function stopSimulatorVideoCapture(
params: { simulatorUuid: string },
executor: CommandExecutor,
): Promise<{
stopped: boolean;
sessionId?: string;
stdout?: string;
parsedPath?: string;
error?: string;
}> {
// Mark executor as used to satisfy lint rule
void executor;
const simulatorUuid = params.simulatorUuid;
if (!simulatorUuid) {
return { stopped: false, error: 'simulatorUuid is required' };
}
const session = sessions.get(simulatorUuid);
if (!session) {
return { stopped: false, error: 'No active video recording session for this simulator' };
}
const child = session.process as ChildProcess | undefined;
// Attempt graceful shutdown
try {
child?.kill?.('SIGINT');
} catch {
try {
child?.kill?.();
} catch {
// ignore
}
}
// Wait for process to close (avoid hanging if it already exited)
await new Promise<void>((resolve): void => {
if (!child) return resolve();
// If process has already ended, resolve immediately
const alreadyEnded = (session as Session).ended === true;
const hasExitCode = (child as ChildProcess).exitCode !== null;
const hasSignal = (child as unknown as { signalCode?: string | null }).signalCode != null;
if (alreadyEnded || hasExitCode || hasSignal) {
return resolve();
}
let resolved = false;
const finish = (): void => {
if (!resolved) {
resolved = true;
resolve();
}
};
try {
child.once('close', finish);
child.once('exit', finish);
} catch {
return finish();
}
// Safety timeout to prevent indefinite hangs
setTimeout(finish, 5000);
});
const combinedOutput = session.buffer;
const parsedPath = parseLastAbsoluteMp4Path(combinedOutput) ?? undefined;
sessions.delete(simulatorUuid);
log(
'info',
`Stopped AXe video recording for simulator ${simulatorUuid}. ${parsedPath ? `Detected file: ${parsedPath}` : 'No file detected in output.'}`,
);
return {
stopped: true,
sessionId: session.sessionId,
stdout: combinedOutput,
parsedPath,
};
}