-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstartRecording.js
More file actions
336 lines (308 loc) · 10.6 KB
/
startRecording.js
File metadata and controls
336 lines (308 loc) · 10.6 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
const { validate } = require("doc-detective-common");
const { log } = require("../utils");
const { instantiateCursor } = require("./moveTo");
const path = require("path");
const fs = require("fs");
const os = require("os");
const { spawn } = require("child_process");
const ffmpegPath = require("@ffmpeg-installer/ffmpeg").path;
exports.startRecording = startRecording;
async function startRecording({ config, context, step, driver }) {
let result = {
status: "PASS",
description: "Started recording.",
};
// Validate step payload
const isValidStep = validate({ schemaKey: "step_v3", object: step });
if (!isValidStep.valid) {
result.status = "FAIL";
result.description = `Invalid step definition: ${isValidStep.errors}`;
return result;
}
// Accept coerced and defaulted values
step = isValidStep.object;
// Convert boolean to string
if (typeof step.record === "boolean") {
step.record = { path: `${step.stepId}.mp4` };
}
// Convert string to object
if (typeof step.record === "string") {
step.record = { path: step.record };
}
// Compute path if unset
if (typeof step.record.path === "undefined") {
step.record.path = `${step.stepId}.mp4`;
// If `directory` is set, prepend it to the path
if (step.record.directory) {
step.record.path = path.resolve(step.record.directory, step.record.path);
}
}
// Set default values
step.record = {
...step.record,
overwrite: step.record.overwrite || "false",
};
// If headless is true, skip recording
if (context.browser?.headless) {
result.status = "SKIPPED";
result.description = `Recording isn't supported in headless mode.`;
return result;
}
// Set file name
if (!step.record.path) {
step.record.path = `${step.record.id}.mp4`;
if (step.record.directory) {
step.record.path = path.join(step.record.directory, step.record.path);
}
}
let filePath = step.record.path;
const baseName = path.basename(filePath, path.extname(filePath));
// Set path directory
const dir = path.dirname(step.record.path);
// If `dir` doesn't exist, create it
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Check if file already exists
if (fs.existsSync(filePath) && step.record.overwrite == "false") {
// File already exists
result.status = "SKIPPED";
result.description = `File already exists: ${filePath}`;
return result;
}
if (
context?.browser?.name === "chrome" &&
context?.browser?.headless === false
) {
config.recording = {};
// Chrome and Chromium
// Get document title
const documentTitle = await driver.getTitle();
const originalTab = await driver.getWindowHandle();
// Set document title to "RECORD_ME"
await driver.execute(() => (document.title = "RECORD_ME"));
// Instantiate cursor
await instantiateCursor(driver, { position: "center" });
// Create new tab
const recorderTab = await driver.createWindow("tab");
// Switch to new tab
await driver.switchToWindow(recorderTab.handle);
await driver.url("chrome://new-tab-page");
await driver.execute(() => (document.title = "RECORDER"));
config.recording.tab = await driver.getWindowHandle();
// Start recording using executeAsync so we properly wait for
// getDisplayMedia() to resolve before switching tabs.
const recorderStarted = await driver.executeAsync((baseName, done) => {
let stream;
let recorder;
const displayMediaOptions = {
video: {
displaySurface: "browser",
},
audio: {
suppressLocalAudioPlayback: false,
},
preferCurrentTab: false,
selfBrowserSurface: "exclude",
systemAudio: "include",
surfaceSwitching: "include",
monitorTypeSurfaces: "include",
};
async function startCapture(displayMediaOptions) {
try {
const captureStream = await navigator.mediaDevices.getDisplayMedia(
displayMediaOptions
);
return captureStream;
} catch (err) {
console.error(`Error: ${err}`);
return null;
}
}
async function captureAndDownload() {
stream = await startCapture(displayMediaOptions);
if (stream) {
await recordStream(stream);
} else {
done(false);
}
return stream;
}
async function recordStream(stream) {
window.recorder = new MediaRecorder(stream, { mimeType: "video/webm" }); // or 'video/mp4'
let data = [];
window.recorder.ondataavailable = (event) => data.push(event.data);
window.recorder.start();
// Signal that recording has started successfully.
// executeAsync resolves here; the rest continues in the browser.
done(true);
let stopped = new Promise((resolve, reject) => {
window.recorder.onstop = resolve;
window.recorder.onerror = (event) => reject(event.name);
});
await stopped;
let blob = new Blob(data, { type: "video/webm" });
let url = URL.createObjectURL(blob);
let a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = `${baseName}.webm`;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
captureAndDownload();
}, baseName);
if (!recorderStarted) {
config.recording = null;
result.status = "FAIL";
result.description =
"Failed to start recording. getDisplayMedia may have been rejected. " +
"On macOS, ensure Chrome has screen recording permission in " +
"System Preferences > Privacy & Security > Screen Recording.";
log(config, "error", result.description);
// Clean up: close the recorder tab and switch back
await driver.closeWindow();
await driver.switchToWindow(originalTab);
await driver.execute((documentTitle) => {
document.title = documentTitle;
}, documentTitle);
return result;
}
// Switch to original tab
await driver.switchToWindow(originalTab);
// Set document title back to original
await driver.execute((documentTitle) => {
document.title = documentTitle;
}, documentTitle);
// Set recorder
result.recording = {
type: "MediaRecorder",
tab: recorderTab.handle,
downloadPath: path.join(os.tmpdir(), `${baseName}.webm`), // Where the recording will be downloaded.
targetPath: filePath, // Where the recording will be saved.
};
} else {
// Other context
result.status = "SKIPPED";
result.description = `Recording is not supported for this context.`;
return result;
const dimensions = await driver.execute(() => {
return {
outerHeight: window.outerHeight,
outerWidth: window.outerWidth,
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
screenX: window.screenX,
screenY: window.screenY,
devicePixelRatio: window.devicePixelRatio,
mozInnerScreenX: window.mozInnerScreenX,
mozInnerScreenY: window.mozInnerScreenY,
};
});
// compute width of borders
dimensions.borderWidthX =
(dimensions.outerWidth - dimensions.innerWidth) / 2;
// compute absolute page position
dimensions.innerScreenX =
dimensions.mozInnerScreenX ||
dimensions.screenX + dimensions.borderWidthX;
dimensions.innerScreenY =
dimensions.mozInnerScreenY ||
dimensions.screenY +
(dimensions.outerHeight - dimensions.innerHeight) -
dimensions.borderWidthX;
const recordingSettings = {
scale: dimensions.devicePixelRatio,
width: dimensions.mozInnerScreenX
? dimensions.innerWidth
: dimensions.innerWidth - dimensions.borderWidthX, //dimensions.innerWidth,
height: dimensions.mozInnerScreenY
? dimensions.innerHeight
: dimensions.innerHeight - 2, //dimensions.innerHeight,
x: dimensions.innerScreenX, //innerScreenX,
y: dimensions.innerScreenY, //innerScreenY,
fps: step.record.fps,
};
try {
// Build args
const args = [
"-y",
"-f",
"gdigrab",
"-i",
"desktop",
"-framerate",
recordingSettings.fps,
"-vf",
`scale=w=iw/${recordingSettings.scale}:h=-1,crop=out_w=${recordingSettings.width}:out_h=${recordingSettings.height}:x=${recordingSettings.x}:y=${recordingSettings.y},format=yuv420p`,
step.record.path,
];
// const args = {
// windows: [
// "-y",
// "-f",
// "gdigrab",
// "-i",
// "desktop",
// "-framerate",
// recordingSettings.fps,
// "-vf",
// `crop=out_w=${recordingSettings.width}:out_h=${recordingSettings.height}:x=${recordingSettings.x}:y=${recordingSettings.y}`,
// // `crop=${recordingSettings.width}:${recordingSettings.height}:${recordingSettings.x}:${recordingSettings.y}`,
// step.path,
// ],
// mac: [
// "-y",
// "-f",
// "avfoundation",
// "-framerate",
// recordingSettings.fps,
// "-i",
// "1",
// "-vf",
// `crop=${recordingSettings.width}:${recordingSettings.height}:${recordingSettings.x}:${recordingSettings.y}`,
// step.path,
// ],
// linux: [
// "-y",
// "-f",
// "x11grab",
// "-framerate",
// recordingSettings.fps,
// "-video_size",
// `${recordingSettings.width}x${recordingSettings.height}`,
// "-i",
// `:0.0+${recordingSettings.x},${recordingSettings.y}`,
// step.path,
// ],
// };
// Instantiate cursor
await instantiateCursor(driver);
// Start recording
const ffmpegProcess = spawn(ffmpegPath, args);
ffmpegProcess.stdin.setEncoding("utf8");
// // Output stdout, stderr, and exit code
// ffmpegProcess.stdout.on("data", (data) => {
// console.log(`stdout: ${data}`);
// });
// ffmpegProcess.stderr.on("data", (data) => {
// console.log(`stderr: ${data}`);
// });
// ffmpegProcess.on("close", (code) => {
// console.log(`child process exited with code ${code}`);
// });
result.recording = ffmpegProcess;
} catch (error) {
// Couldn't save screenshot
result.status = "FAIL";
result.description = `Couldn't start recording. ${error}`;
return result;
}
}
// PASS
return result;
}