-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
259 lines (212 loc) · 5.81 KB
/
index.js
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
import os from 'node:os';
import {debuglog} from 'node:util';
import path from 'node:path';
import url from 'node:url';
import {execa} from 'execa';
import {temporaryFile} from 'tempy';
import {assertMacOSVersionGreaterThanOrEqualTo} from 'macos-version';
import fileUrl from 'file-url';
import {fixPathForAsarUnpack} from 'electron-util/node';
import delay from 'delay';
const log = debuglog('aperture');
const getRandomId = () => Math.random().toString(36).slice(2, 15);
const dirname_ = path.dirname(url.fileURLToPath(import.meta.url));
// Workaround for https://github.com/electron/electron/issues/9459
const BINARY = path.join(fixPathForAsarUnpack(dirname_), 'aperture');
const supportsHevcHardwareEncoding = (() => {
const cpuModel = os.cpus()[0].model;
// All Apple silicon Macs support HEVC hardware encoding.
if (cpuModel.startsWith('Apple ')) {
// Source string example: `'Apple M1'`
return true;
}
// Get the Intel Core generation, the `4` in `Intel(R) Core(TM) i7-4850HQ CPU @ 2.30GHz`
// More info: https://www.intel.com/content/www/us/en/processors/processor-numbers.html
// Example strings:
// - `Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz`
// - `Intel(R) Core(TM) i7-4850HQ CPU @ 2.30GHz`
const result = /Intel.*Core.*i\d+-(\d)/.exec(cpuModel);
// Intel Core generation 6 or higher supports HEVC hardware encoding
return result && Number.parseInt(result[1], 10) >= 6;
})();
class Recorder {
constructor() {
assertMacOSVersionGreaterThanOrEqualTo('10.13');
}
startRecording({
fps = 30,
cropArea = undefined,
showCursor = true,
highlightClicks = false,
screenId = 0,
audioDeviceId = undefined,
videoCodec = 'h264',
} = {}) {
this.processId = getRandomId();
return new Promise((resolve, reject) => {
if (this.recorder !== undefined) {
reject(new Error('Call `.stopRecording()` first'));
return;
}
this.tmpPath = temporaryFile({extension: 'mp4'});
if (highlightClicks === true) {
showCursor = true;
}
if (
typeof cropArea === 'object'
&& (typeof cropArea.x !== 'number'
|| typeof cropArea.y !== 'number'
|| typeof cropArea.width !== 'number'
|| typeof cropArea.height !== 'number')
) {
reject(new Error('Invalid `cropArea` option object'));
return;
}
const recorderOptions = {
destination: fileUrl(this.tmpPath),
framesPerSecond: fps,
showCursor,
highlightClicks,
screenId,
audioDeviceId,
};
if (cropArea) {
recorderOptions.cropRect = [
[cropArea.x, cropArea.y],
[cropArea.width, cropArea.height],
];
}
if (videoCodec) {
const codecMap = new Map([
['h264', 'avc1'],
['hevc', 'hvc1'],
['proRes422', 'apcn'],
['proRes4444', 'ap4h'],
]);
if (!supportsHevcHardwareEncoding) {
codecMap.delete('hevc');
}
if (!codecMap.has(videoCodec)) {
throw new Error(`Unsupported video codec specified: ${videoCodec}`);
}
recorderOptions.videoCodec = codecMap.get(videoCodec);
}
const timeout = setTimeout(() => {
// `.stopRecording()` was called already
if (this.recorder === undefined) {
return;
}
const error = new Error('Could not start recording within 5 seconds');
error.code = 'RECORDER_TIMEOUT';
this.recorder.kill();
delete this.recorder;
reject(error);
}, 5000);
(async () => {
try {
await this.waitForEvent('onStart');
clearTimeout(timeout);
setTimeout(resolve, 1000);
} catch (error) {
reject(error);
}
})();
this.isFileReady = (async () => {
await this.waitForEvent('onFileReady');
return this.tmpPath;
})();
this.recorder = execa(BINARY, [
'record',
'--process-id',
this.processId,
JSON.stringify(recorderOptions),
]);
this.recorder.catch(error => {
clearTimeout(timeout);
delete this.recorder;
reject(error);
});
this.recorder.stdout.setEncoding('utf8');
this.recorder.stdout.on('data', log);
});
}
async waitForEvent(name, parse) {
const {stdout} = await execa(BINARY, [
'events',
'listen',
'--process-id',
this.processId,
'--exit',
name,
]);
if (parse) {
return parse(stdout.trim());
}
}
async sendEvent(name, parse) {
const {stdout} = await execa(BINARY, [
'events',
'send',
'--process-id',
this.processId,
name,
]);
if (parse) {
return parse(stdout.trim());
}
}
throwIfNotStarted() {
if (this.recorder === undefined) {
throw new Error('Call `.startRecording()` first');
}
}
async pause() {
this.throwIfNotStarted();
await this.sendEvent('pause');
}
async resume() {
this.throwIfNotStarted();
await this.sendEvent('resume');
// It takes about 1s after the promise resolves for the recording to actually start
await delay(1000);
}
async isPaused() {
this.throwIfNotStarted();
return this.sendEvent('isPaused', value => value === 'true');
}
async stopRecording() {
this.throwIfNotStarted();
this.recorder.kill();
await this.recorder;
delete this.recorder;
delete this.isFileReady;
return this.tmpPath;
}
}
export const recorder = new Recorder();
const removeWarnings = string => string.split('\n').filter(line => !line.includes('] WARNING:')).join('\n');
export const screens = async () => {
const {stderr} = await execa(BINARY, ['list', 'screens']);
try {
return JSON.parse(removeWarnings(stderr));
} catch (error) {
throw new Error(stderr, {cause: error});
}
};
export const audioDevices = async () => {
const {stderr} = await execa(BINARY, ['list', 'audio-devices']);
try {
return JSON.parse(removeWarnings(stderr));
} catch (error) {
throw new Error(stderr, {cause: error});
}
};
export const videoCodecs = new Map([
['h264', 'H264'],
['hevc', 'HEVC'],
['proRes422', 'Apple ProRes 422'],
['proRes4444', 'Apple ProRes 4444'],
]);
if (!supportsHevcHardwareEncoding) {
videoCodecs.delete('hevc');
}