forked from aslanon/node-mac-recorder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiWindowRecorder.js
More file actions
546 lines (469 loc) · 21.2 KB
/
MultiWindowRecorder.js
File metadata and controls
546 lines (469 loc) · 21.2 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/**
* MultiWindowRecorder - Creavit Desktop Integration
* Manages multiple simultaneous window recordings
*/
const MacRecorder = require('./index-multiprocess');
const MacRecorderSync = require('./index'); // For cursor tracking
const path = require('path');
const { EventEmitter } = require('events');
class MultiWindowRecorder extends EventEmitter {
constructor(options = {}) {
super();
this.recorders = [];
this.windows = [];
this.isRecording = false;
this.outputFiles = [];
this.cursorFiles = [];
this.cameraFile = null; // Camera output file (from first recorder)
this.audioFile = null; // Audio output file (from first recorder)
this.cursorRecorder = null; // Separate recorder for cursor tracking
this.timeUpdateInterval = null; // Timer for timeUpdate events
this.metadata = {
startTime: null,
syncTimestamps: [],
windowCount: 0
};
this.options = {
frameRate: options.frameRate || 30,
captureCursor: false, // Don't show system cursor in window recording
preferScreenCaptureKit: options.preferScreenCaptureKit !== false,
// Audio options
enableMicrophone: options.enableMicrophone || false,
microphoneDeviceId: options.microphoneDeviceId || null,
captureSystemAudio: options.captureSystemAudio || false,
// Camera options
enableCamera: options.enableCamera || false,
cameraDeviceId: options.cameraDeviceId || null,
// Cursor tracking
trackCursor: options.trackCursor !== false, // Default: true
...options
};
}
/**
* Add a window to be recorded
* @param {Object} windowInfo - Window information from getWindows()
* @returns {number} Index of the added window
*/
async addWindow(windowInfo) {
const recorder = new MacRecorder();
const recorderInfo = {
recorder,
windowId: windowInfo.id,
windowInfo: {
id: windowInfo.id,
appName: windowInfo.appName,
title: windowInfo.title,
width: windowInfo.width,
height: windowInfo.height
},
outputPath: null,
cursorFilePath: null,
syncTimestamp: null,
index: this.recorders.length
};
this.recorders.push(recorderInfo);
this.windows.push(windowInfo);
// Wait for worker to be ready
await new Promise(r => setTimeout(r, 500));
console.log(`✅ Window added: ${windowInfo.appName} (index: ${recorderInfo.index})`);
return recorderInfo.index;
}
/**
* Remove a window by index
* @param {number} index - Window index
*/
removeWindow(index) {
if (index < 0 || index >= this.recorders.length) {
throw new Error(`Invalid window index: ${index}`);
}
const recorderInfo = this.recorders[index];
if (recorderInfo && recorderInfo.recorder) {
recorderInfo.recorder.destroy();
console.log(`🗑️ Window removed: ${recorderInfo.windowInfo.appName}`);
}
this.recorders.splice(index, 1);
this.windows.splice(index, 1);
// Update indices
this.recorders.forEach((rec, i) => {
rec.index = i;
});
}
/**
* Get current window count
*/
getWindowCount() {
return this.recorders.length;
}
/**
* Start recording all windows
* @param {string} outputDir - Output directory path
* @param {Object} options - Recording options
*/
async startRecording(outputDir, options = {}) {
if (this.isRecording) {
throw new Error('Recording already in progress');
}
if (this.recorders.length === 0) {
throw new Error('No windows added. Call addWindow() first.');
}
const timestamp = Date.now();
this.metadata.startTime = timestamp;
this.metadata.windowCount = this.recorders.length;
this.outputFiles = [];
console.log(`🎬 Starting ${this.recorders.length} window recordings...`);
console.log(`📁 Output directory: ${outputDir}`);
// Start all recorders sequentially with 1s delay between each
for (let i = 0; i < this.recorders.length; i++) {
const recInfo = this.recorders[i];
const appName = recInfo.windowInfo.appName.replace(/[^a-zA-Z0-9]/g, '_');
const outputPath = path.join(outputDir, `temp_window_${i}_${appName}_${timestamp}.mov`);
console.log(`\n▶️ Starting recorder ${i + 1}/${this.recorders.length}: ${recInfo.windowInfo.appName}`);
const recordingOptions = {
windowId: recInfo.windowId,
frameRate: this.options.frameRate,
captureCursor: this.options.captureCursor,
preferScreenCaptureKit: this.options.preferScreenCaptureKit,
// Use the MAIN timestamp for ALL files to keep them synchronized
sessionTimestamp: timestamp,
// Audio options - ONLY record audio on first window to avoid duplicates
includeMicrophone: (i === 0 && this.options.enableMicrophone) || false,
audioDeviceId: (i === 0 && this.options.microphoneDeviceId) || null,
includeSystemAudio: (i === 0 && this.options.captureSystemAudio) || false,
systemAudioDeviceId: null,
// Camera options - record on first window only
captureCamera: (i === 0 && this.options.enableCamera) || false,
cameraDeviceId: (i === 0 && this.options.cameraDeviceId) || null,
...options
};
try {
const startTimestamp = Date.now();
// For first recorder, pre-calculate camera and audio paths
// IMPORTANT: Use the MAIN timestamp, not startTimestamp, to match window files!
if (i === 0) {
if (this.options.enableCamera) {
this.cameraFile = path.join(outputDir, `temp_camera_${timestamp}.mov`);
console.log(` 📷 Camera will be saved to: ${path.basename(this.cameraFile)}`);
}
if (this.options.enableMicrophone || this.options.captureSystemAudio) {
this.audioFile = path.join(outputDir, `temp_audio_${timestamp}.mov`);
console.log(` 🎵 Audio will be saved to: ${path.basename(this.audioFile)}`);
}
}
await recInfo.recorder.startRecording(outputPath, recordingOptions);
recInfo.outputPath = outputPath;
recInfo.syncTimestamp = startTimestamp;
this.metadata.syncTimestamps.push(startTimestamp);
this.outputFiles.push(outputPath);
console.log(` ✅ Recorder ${i + 1} started`);
console.log(` 📄 Output: ${path.basename(outputPath)}`);
// Start cursor tracking if enabled (only once for all windows)
if (this.options.trackCursor && i === 0) {
const cursorPath = path.join(outputDir, `temp_cursor_${timestamp}.json`);
// Create cursor recorder on first use
if (!this.cursorRecorder) {
this.cursorRecorder = new MacRecorderSync();
}
// Get main display info for global cursor tracking
const displays = await this.cursorRecorder.getDisplays();
const mainDisplay = displays.find(d => d.isPrimary) || displays[0];
// Collect all window bounds for cursor location detection
const windowBounds = this.recorders.map(rec => ({
windowId: rec.windowId,
appName: rec.windowInfo.appName,
title: rec.windowInfo.title,
// Window bounds will be retrieved from native API
bounds: null // Will be filled by cursor tracker
}));
// Track cursor with global coordinates (for multi-window setup)
// Use main display as reference for coordinate system
const cursorOptions = {
videoRelative: false, // Global screen coordinates (not video-relative)
displayInfo: mainDisplay ? {
displayId: mainDisplay.id,
x: mainDisplay.x || 0,
y: mainDisplay.y || 0,
width: parseInt(mainDisplay.resolution.split('x')[0]),
height: parseInt(mainDisplay.resolution.split('x')[1]),
logicalWidth: parseInt(mainDisplay.resolution.split('x')[0]),
logicalHeight: parseInt(mainDisplay.resolution.split('x')[1])
} : null,
recordingType: 'multi-window', // Multi-window recording type
startTimestamp: startTimestamp, // Use same timestamp as video
// Pass window information for location detection
multiWindowBounds: windowBounds
};
await this.cursorRecorder.startCursorCapture(cursorPath, cursorOptions);
// Store cursor file path for all windows
this.recorders.forEach(rec => {
rec.cursorFilePath = cursorPath;
});
this.cursorFiles.push(cursorPath);
console.log(` 🖱️ Cursor tracking started (multi-window mode)`);
console.log(` 📄 Cursor file: ${path.basename(cursorPath)}`);
}
this.emit('recorderStarted', {
index: i,
windowInfo: recInfo.windowInfo,
outputPath: outputPath,
cursorFilePath: recInfo.cursorFilePath,
timestamp: startTimestamp
});
// Wait for ScreenCaptureKit initialization (except for last recorder)
if (i < this.recorders.length - 1) {
console.log(` ⏳ Waiting 1s for ScreenCaptureKit init...`);
await new Promise(r => setTimeout(r, 1000));
}
} catch (error) {
console.error(` ❌ Failed to start recorder ${i + 1}:`, error.message);
// Stop all previously started recorders and cursor tracking
for (let j = 0; j < i; j++) {
try {
await this.recorders[j].recorder.stopRecording();
} catch (stopError) {
console.error(`Failed to stop recorder ${j}:`, stopError.message);
}
}
// Stop cursor tracking if it was started
if (this.options.trackCursor && this.cursorRecorder) {
try {
await this.cursorRecorder.stopCursorCapture();
} catch (cursorError) {
console.error(`Failed to stop cursor tracking:`, cursorError.message);
}
}
throw new Error(`Failed to start recorder ${i + 1}: ${error.message}`);
}
}
this.isRecording = true;
// Start timeUpdate timer (emit every second)
this.timeUpdateInterval = setInterval(() => {
if (this.isRecording && this.metadata.startTime) {
const elapsed = Math.floor((Date.now() - this.metadata.startTime) / 1000);
this.emit('timeUpdate', elapsed);
}
}, 1000);
console.log(`\n✅ All ${this.recorders.length} recordings started successfully!`);
console.log(`🔴 Multi-window recording in progress...`);
this.emit('allStarted', {
windowCount: this.recorders.length,
outputFiles: this.outputFiles,
metadata: this.metadata
});
return {
windowCount: this.recorders.length,
outputFiles: this.outputFiles,
metadata: this.metadata
};
}
/**
* Stop all recordings
*/
async stopRecording() {
if (!this.isRecording) {
throw new Error('No recording in progress');
}
console.log(`\n🛑 Stopping ${this.recorders.length} recordings...`);
const stopTimestamp = Date.now();
// Stop timeUpdate timer
if (this.timeUpdateInterval) {
clearInterval(this.timeUpdateInterval);
this.timeUpdateInterval = null;
console.log(` ⏱️ Timer stopped`);
}
// Stop cursor tracking first (before stopping video recordings)
if (this.options.trackCursor && this.cursorRecorder) {
try {
console.log(` 🖱️ Stopping cursor tracking...`);
await this.cursorRecorder.stopCursorCapture();
console.log(` ✅ Cursor tracking stopped`);
} catch (error) {
console.error(` ❌ Failed to stop cursor tracking:`, error.message);
}
}
// Stop all recorders in parallel
const stopPromises = this.recorders.map(async (recInfo, index) => {
try {
console.log(` Stopping recorder ${index + 1}: ${recInfo.windowInfo.appName}...`);
await recInfo.recorder.stopRecording();
console.log(` ✅ Recorder ${index + 1} stopped`);
this.emit('recorderStopped', {
index,
windowInfo: recInfo.windowInfo,
outputPath: recInfo.outputPath,
cursorFilePath: recInfo.cursorFilePath
});
return {
index,
success: true,
outputPath: recInfo.outputPath,
cursorFilePath: recInfo.cursorFilePath
};
} catch (error) {
console.error(` ❌ Failed to stop recorder ${index + 1}:`, error.message);
this.emit('recorderError', {
index,
error: error.message
});
return {
index,
success: false,
error: error.message
};
}
});
const results = await Promise.all(stopPromises);
this.isRecording = false;
// Get camera and audio paths from first recorder's status
if (this.recorders.length > 0) {
try {
const firstRecorderStatus = this.recorders[0].recorder.getStatus();
if (firstRecorderStatus.cameraOutputPath) {
this.cameraFile = firstRecorderStatus.cameraOutputPath;
console.log(` 📷 Camera file from recorder: ${path.basename(this.cameraFile)}`);
}
if (firstRecorderStatus.audioOutputPath) {
this.audioFile = firstRecorderStatus.audioOutputPath;
console.log(` 🎵 Audio file from recorder: ${path.basename(this.audioFile)}`);
}
} catch (error) {
console.error(` ⚠️ Could not get camera/audio paths from first recorder:`, error.message);
}
}
// Calculate duration
const duration = stopTimestamp - this.metadata.startTime;
const result = {
success: results.every(r => r.success),
windowCount: this.recorders.length,
outputFiles: this.outputFiles,
cursorFiles: this.cursorFiles,
cameraFile: this.cameraFile, // Camera output path (from first recorder)
audioFile: this.audioFile, // Audio output path (from first recorder)
duration: duration,
metadata: {
...this.metadata,
stopTime: stopTimestamp,
duration: duration,
windows: this.recorders.map((recInfo, i) => ({
index: i,
windowInfo: recInfo.windowInfo,
outputPath: recInfo.outputPath,
cursorFilePath: recInfo.cursorFilePath,
syncTimestamp: recInfo.syncTimestamp,
syncOffset: recInfo.syncTimestamp - this.metadata.startTime
}))
}
};
console.log(`\n✅ All recordings stopped successfully!`);
console.log(`📊 Duration: ${(duration / 1000).toFixed(2)}s`);
console.log(`📁 Output files: ${this.outputFiles.length}`);
if (this.options.trackCursor) {
console.log(`🖱️ Cursor files: ${this.cursorFiles.length}`);
}
this.emit('allStopped', result);
return result;
}
/**
* Get recording status
*/
getStatus() {
return {
isRecording: this.isRecording,
windowCount: this.recorders.length,
outputFiles: this.outputFiles,
metadata: this.metadata,
windows: this.recorders.map(rec => ({
index: rec.index,
windowInfo: rec.windowInfo,
outputPath: rec.outputPath
}))
};
}
/**
* Get metadata for CRVT file creation
* @param {Object} options - Options for metadata generation
* @param {string} options.clipId - Clip ID for media paths (e.g., 'clip_1762961230017')
*/
getMetadataForCRVT(options = {}) {
const { clipId } = options;
// Helper function to convert full path to media path
const toMediaPath = (fullPath) => {
if (!fullPath || !clipId) return fullPath;
const filename = path.basename(fullPath);
return `media/${clipId}/${filename}`;
};
return {
version: '2.0',
timestamp: this.metadata.startTime,
duration: this.metadata.duration || 0,
multiWindow: {
enabled: true,
windowCount: this.recorders.length,
windows: this.recorders.map((recInfo, i) => ({
index: i,
windowInfo: {
id: recInfo.windowId,
appName: recInfo.windowInfo.appName,
title: recInfo.windowInfo.title,
width: recInfo.windowInfo.width,
height: recInfo.windowInfo.height
},
outputPath: toMediaPath(recInfo.outputPath), // media/clip_xxx/filename.mov
cursorFilePath: toMediaPath(recInfo.cursorFilePath), // media/clip_xxx/filename.json
syncTimestamp: recInfo.syncTimestamp,
syncOffset: recInfo.syncTimestamp - this.metadata.startTime
})),
syncTimestamps: this.metadata.syncTimestamps
},
// Recording options
options: {
enableCamera: this.options.enableCamera,
cameraDeviceId: this.options.cameraDeviceId,
enableMicrophone: this.options.enableMicrophone,
microphoneDeviceId: this.options.microphoneDeviceId,
captureSystemAudio: this.options.captureSystemAudio,
trackCursor: this.options.trackCursor
}
};
}
/**
* Destroy all recorders and cleanup
*/
destroy() {
console.log('🧹 Cleaning up multi-window recorder...');
// Stop timeUpdate timer
if (this.timeUpdateInterval) {
clearInterval(this.timeUpdateInterval);
this.timeUpdateInterval = null;
}
this.recorders.forEach((recInfo, index) => {
try {
recInfo.recorder.destroy();
console.log(` ✓ Recorder ${index + 1} destroyed`);
} catch (error) {
console.error(` ✗ Failed to destroy recorder ${index + 1}:`, error.message);
}
});
// Destroy cursor recorder if exists
if (this.cursorRecorder) {
try {
// MacRecorderSync uses cleanup() instead of destroy()
if (typeof this.cursorRecorder.cleanup === 'function') {
this.cursorRecorder.cleanup();
} else if (typeof this.cursorRecorder.destroy === 'function') {
this.cursorRecorder.destroy();
}
console.log(` ✓ Cursor recorder destroyed`);
} catch (error) {
console.error(` ✗ Failed to destroy cursor recorder:`, error.message);
}
this.cursorRecorder = null;
}
this.recorders = [];
this.windows = [];
this.outputFiles = [];
this.cursorFiles = [];
this.isRecording = false;
console.log('✅ Multi-window recorder cleaned up');
}
}
module.exports = MultiWindowRecorder;