forked from aslanon/node-mac-recorder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1922 lines (1723 loc) · 60.1 KB
/
index.js
File metadata and controls
1922 lines (1723 loc) · 60.1 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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { EventEmitter } = require("events");
const path = require("path");
const fs = require("fs");
// Auto-switch to Electron-safe implementation when running under Electron and binary exists
let USE_ELECTRON_SAFE = false;
let ElectronSafeMacRecorder = null;
try {
const isElectron = !!(process && process.versions && process.versions.electron);
const preferElectronSafe = process.env.PREFER_ELECTRON_SAFE === "1" || process.env.USE_ELECTRON_SAFE === "1";
if (isElectron || preferElectronSafe) {
const rel = path.join(__dirname, "build", "Release", "mac_recorder_electron.node");
const dbg = path.join(__dirname, "build", "Debug", "mac_recorder_electron.node");
if (fs.existsSync(rel) || fs.existsSync(dbg) || preferElectronSafe) {
// Defer requiring native .node; use JS wrapper which loads it
ElectronSafeMacRecorder = require("./electron-safe-index");
USE_ELECTRON_SAFE = true;
console.log("✅ Auto-enabled Electron-safe MacRecorder");
}
}
} catch (_) {
// Ignore auto-switch errors; fall back to standard binding
}
// Native modülü yükle
let nativeBinding;
if (!USE_ELECTRON_SAFE) {
try {
nativeBinding = require("./build/Release/mac_recorder.node");
} catch (error) {
try {
nativeBinding = require("./build/Debug/mac_recorder.node");
} catch (debugError) {
throw new Error(
'Native module not found. Please run "npm run build" to compile the native module.\n' +
"Original error: " +
error.message
);
}
}
}
class MacRecorder extends EventEmitter {
constructor() {
super();
this.isRecording = false;
this.outputPath = null;
this.recordingTimer = null;
this.recordingStartTime = null;
// MULTI-SESSION: Unique session ID for this recorder instance
this.nativeSessionId = null; // Will be generated when recording starts
// Cursor capture variables
this.cursorCaptureInterval = null;
this.cursorCaptureFile = null;
this.cursorCaptureStartTime = null;
this.cursorCaptureFirstWrite = true;
this.lastCapturedData = null;
this.cursorDisplayInfo = null;
this.recordingDisplayInfo = null;
this.cameraCaptureFile = null;
this.cameraCaptureActive = false;
this.sessionTimestamp = null;
this.syncTimestamp = null;
this.audioCaptureFile = null;
this.audioCaptureActive = false;
this.options = {
includeMicrophone: false, // Default olarak mikrofon kapalı
includeSystemAudio: false, // Default olarak sistem sesi kapalı - kullanıcı explicit olarak açmalı
quality: "high",
frameRate: 60,
captureArea: null, // { x, y, width, height }
captureCursor: false, // Default olarak cursor gizli
showClicks: false,
displayId: null, // Hangi ekranı kaydedeceği (null = ana ekran)
windowId: null, // Hangi pencereyi kaydedeceği (null = tam ekran)
captureCamera: false,
cameraDeviceId: null,
systemAudioDeviceId: null,
};
// Display cache için async initialization
this.cachedDisplays = null;
this.refreshDisplayCache();
// Native cursor warm-up (cold start delay'ini önlemek için)
this.warmUpCursor();
}
/**
* macOS ses cihazlarını listeler
*/
async getAudioDevices() {
return new Promise((resolve, reject) => {
try {
const devices = nativeBinding.getAudioDevices();
const formattedDevices = devices.map((device) => ({
name: device?.name || "Unknown Audio Device",
id: device?.id || "",
manufacturer: device?.manufacturer || null,
isDefault: device?.isDefault === true,
transportType: device?.transportType ?? null,
}));
resolve(formattedDevices);
} catch (error) {
reject(error);
}
});
}
/**
* macOS kamera cihazlarını listeler
*/
async getCameraDevices() {
return new Promise((resolve, reject) => {
try {
const devices = nativeBinding.getCameraDevices();
if (!Array.isArray(devices)) {
return resolve([]);
}
const formatted = devices.map((device) => ({
id: device?.id ?? "",
name: device?.name ?? "Unknown Camera",
model: device?.model ?? null,
manufacturer: device?.manufacturer ?? null,
position: device?.position ?? "unspecified",
transportType: device?.transportType ?? null,
isConnected: device?.isConnected ?? false,
isDefault: device?.isDefault === true,
hasFlash: device?.hasFlash ?? false,
supportsDepth: device?.supportsDepth ?? false,
deviceType: device?.deviceType ?? null,
requiresContinuityCameraPermission: device?.requiresContinuityCameraPermission ?? false,
maxResolution: device?.maxResolution ?? null,
}));
resolve(formatted);
} catch (error) {
reject(error);
}
});
}
/**
* macOS ekranlarını listeler
*/
async getDisplays() {
const displays = nativeBinding.getDisplays();
return displays.map((display, index) => ({
id: display.id, // Use the actual display ID from native code
name: display.name,
width: display.width,
height: display.height,
x: display.x,
y: display.y,
isPrimary: display.isPrimary,
resolution: `${display.width}x${display.height}`,
}));
}
/**
* macOS açık pencerelerini listeler
*/
async getWindows() {
return new Promise((resolve, reject) => {
try {
const windows = nativeBinding.getWindows();
resolve(windows);
} catch (error) {
reject(error);
}
});
}
/**
* Kayıt seçeneklerini ayarlar
*/
setOptions(options = {}) {
// Merge options instead of replacing to preserve previously set values
if (options.sessionTimestamp !== undefined) {
this.options.sessionTimestamp = options.sessionTimestamp;
}
if (options.includeMicrophone !== undefined) {
this.options.includeMicrophone = options.includeMicrophone === true;
}
if (options.includeSystemAudio !== undefined) {
this.options.includeSystemAudio = options.includeSystemAudio === true;
}
if (options.captureCursor !== undefined) {
this.options.captureCursor = options.captureCursor || false;
}
if (options.displayId !== undefined) {
this.options.displayId = options.displayId || null;
}
if (options.windowId !== undefined) {
this.options.windowId = options.windowId || null;
}
if (options.audioDeviceId !== undefined) {
this.options.audioDeviceId = options.audioDeviceId || null;
}
if (options.systemAudioDeviceId !== undefined) {
this.options.systemAudioDeviceId = options.systemAudioDeviceId || null;
}
if (options.captureArea !== undefined) {
this.options.captureArea = options.captureArea || null;
}
if (options.captureCamera !== undefined) {
this.options.captureCamera = options.captureCamera === true;
}
if (options.frameRate !== undefined) {
const fps = parseInt(options.frameRate, 10);
if (!Number.isNaN(fps) && fps > 0) {
// Clamp reasonable range 1-120
this.options.frameRate = Math.min(Math.max(fps, 1), 120);
}
}
// Prefer ScreenCaptureKit (macOS 15+) toggle
if (options.preferScreenCaptureKit !== undefined) {
this.options.preferScreenCaptureKit = options.preferScreenCaptureKit === true;
}
if (options.cameraDeviceId !== undefined) {
this.options.cameraDeviceId =
typeof options.cameraDeviceId === "string" && options.cameraDeviceId.length > 0
? options.cameraDeviceId
: null;
}
}
/**
* Mikrofon kaydını açar/kapatır
*/
setMicrophoneEnabled(enabled) {
this.options.includeMicrophone = enabled === true;
return this.options.includeMicrophone;
}
setAudioDevice(deviceId) {
if (typeof deviceId === "string" && deviceId.length > 0) {
this.options.audioDeviceId = deviceId;
} else {
this.options.audioDeviceId = null;
}
return this.options.audioDeviceId;
}
/**
* Sistem sesi kaydını açar/kapatır
*/
setSystemAudioEnabled(enabled) {
this.options.includeSystemAudio = enabled === true;
return this.options.includeSystemAudio;
}
setSystemAudioDevice(deviceId) {
if (typeof deviceId === "string" && deviceId.length > 0) {
this.options.systemAudioDeviceId = deviceId;
} else {
this.options.systemAudioDeviceId = null;
}
return this.options.systemAudioDeviceId;
}
/**
* Kamera kaydını açar/kapatır
*/
setCameraEnabled(enabled) {
this.options.captureCamera = enabled === true;
if (!this.options.captureCamera) {
this.cameraCaptureActive = false;
}
return this.options.captureCamera;
}
/**
* Kamera cihazını seçer
*/
setCameraDevice(deviceId) {
if (typeof deviceId === "string" && deviceId.length > 0) {
this.options.cameraDeviceId = deviceId;
} else {
this.options.cameraDeviceId = null;
}
return this.options.cameraDeviceId;
}
/**
* Mikrofon durumunu döndürür
*/
isMicrophoneEnabled() {
return this.options.includeMicrophone === true;
}
/**
* Sistem sesi durumunu döndürür
*/
isSystemAudioEnabled() {
return this.options.includeSystemAudio === true;
}
/**
* Kamera durumunu döndürür
*/
isCameraEnabled() {
return this.options.captureCamera === true;
}
/**
* Audio ayarlarını toplu olarak değiştirir
*/
setAudioSettings(settings = {}) {
if (typeof settings.microphone === 'boolean') {
this.setMicrophoneEnabled(settings.microphone);
}
if (typeof settings.systemAudio === 'boolean') {
this.setSystemAudioEnabled(settings.systemAudio);
}
return {
microphone: this.isMicrophoneEnabled(),
systemAudio: this.isSystemAudioEnabled()
};
}
/**
* Ekran kaydını başlatır (macOS native AVFoundation kullanarak)
*/
async startRecording(outputPath, options = {}) {
if (this.isRecording) {
throw new Error("Recording is already in progress");
}
if (!outputPath) {
throw new Error("Output path is required");
}
// Seçenekleri güncelle
this.setOptions(options);
// Cache display list so we don't fetch multiple times during preparation
let cachedDisplays = null;
const getCachedDisplays = async () => {
if (cachedDisplays) {
return cachedDisplays;
}
try {
cachedDisplays = await this.getDisplays();
} catch (error) {
console.warn("Display bilgisi alınamadı:", error.message);
cachedDisplays = [];
}
return cachedDisplays;
};
/**
* Normalize capture area coordinates:
* - Pick correct display based on user-provided area/displayId info
* - Convert global coordinates to display-relative when needed
* - Clamp to valid bounds to avoid ScreenCaptureKit skipping crops
*/
const normalizeCaptureArea = async () => {
if (!this.options.captureArea) {
return;
}
const displays = await getCachedDisplays();
if (!Array.isArray(displays) || displays.length === 0) {
return;
}
const rawArea = this.options.captureArea;
const parsedArea = {
x: Number(rawArea.x),
y: Number(rawArea.y),
width: Number(rawArea.width),
height: Number(rawArea.height),
};
if (
!Number.isFinite(parsedArea.x) ||
!Number.isFinite(parsedArea.y) ||
!Number.isFinite(parsedArea.width) ||
!Number.isFinite(parsedArea.height) ||
parsedArea.width <= 0 ||
parsedArea.height <= 0
) {
return;
}
const areaRect = {
left: parsedArea.x,
top: parsedArea.y,
right: parsedArea.x + parsedArea.width,
bottom: parsedArea.y + parsedArea.height,
};
const getDisplayRect = (display) => {
const dx = Number(display.x) || 0;
const dy = Number(display.y) || 0;
const dw = Number(display.width) || 0;
const dh = Number(display.height) || 0;
return {
left: dx,
top: dy,
right: dx + dw,
bottom: dy + dh,
width: dw,
height: dh,
};
};
const requestedDisplayId =
this.options.displayId === null || this.options.displayId === undefined
? null
: Number(this.options.displayId);
let targetDisplay = null;
if (requestedDisplayId !== null && Number.isFinite(requestedDisplayId)) {
targetDisplay =
displays.find(
(display) => Number(display.id) === requestedDisplayId
) || null;
}
if (!targetDisplay) {
targetDisplay =
displays.find((display) => {
const rect = getDisplayRect(display);
return (
areaRect.left >= rect.left &&
areaRect.right <= rect.right &&
areaRect.top >= rect.top &&
areaRect.bottom <= rect.bottom
);
}) || null;
}
if (!targetDisplay) {
let bestDisplay = null;
let bestOverlap = 0;
displays.forEach((display) => {
const rect = getDisplayRect(display);
const overlapWidth =
Math.min(areaRect.right, rect.right) -
Math.max(areaRect.left, rect.left);
const overlapHeight =
Math.min(areaRect.bottom, rect.bottom) -
Math.max(areaRect.top, rect.top);
if (overlapWidth > 0 && overlapHeight > 0) {
const overlapArea = overlapWidth * overlapHeight;
if (overlapArea > bestOverlap) {
bestOverlap = overlapArea;
bestDisplay = display;
}
}
});
targetDisplay = bestDisplay;
}
if (!targetDisplay) {
targetDisplay =
displays.find((display) => display.isPrimary) || displays[0];
}
if (!targetDisplay) {
return;
}
const targetRect = getDisplayRect(targetDisplay);
if (targetRect.width <= 0 || targetRect.height <= 0) {
return;
}
const tolerance = 1; // allow sub-pixel offsets
const isRelativeToDisplay = () => {
const endX = parsedArea.x + parsedArea.width;
const endY = parsedArea.y + parsedArea.height;
return (
parsedArea.x >= -tolerance &&
parsedArea.y >= -tolerance &&
endX <= targetRect.width + tolerance &&
endY <= targetRect.height + tolerance
);
};
let relativeX = parsedArea.x;
let relativeY = parsedArea.y;
if (!isRelativeToDisplay()) {
relativeX = parsedArea.x - targetRect.left;
relativeY = parsedArea.y - targetRect.top;
}
let relativeWidth = parsedArea.width;
let relativeHeight = parsedArea.height;
// Discard if area sits completely outside the display
if (
relativeX >= targetRect.width ||
relativeY >= targetRect.height ||
relativeWidth <= 0 ||
relativeHeight <= 0
) {
return;
}
if (relativeX < 0) {
relativeWidth += relativeX;
relativeX = 0;
}
if (relativeY < 0) {
relativeHeight += relativeY;
relativeY = 0;
}
const maxWidth = targetRect.width - relativeX;
const maxHeight = targetRect.height - relativeY;
if (maxWidth <= 0 || maxHeight <= 0) {
return;
}
relativeWidth = Math.min(relativeWidth, maxWidth);
relativeHeight = Math.min(relativeHeight, maxHeight);
if (relativeWidth <= 0 || relativeHeight <= 0) {
return;
}
const normalizeValue = (value, minValue) =>
Math.max(minValue, Math.round(value));
const normalizedArea = {
x: Math.max(0, Math.round(relativeX)),
y: Math.max(0, Math.round(relativeY)),
width: normalizeValue(relativeWidth, 1),
height: normalizeValue(relativeHeight, 1),
};
const originalRounded = {
x: Math.round(parsedArea.x),
y: Math.round(parsedArea.y),
width: normalizeValue(parsedArea.width, 1),
height: normalizeValue(parsedArea.height, 1),
};
const displayChanged =
!Number.isFinite(requestedDisplayId) ||
Number(targetDisplay.id) !== requestedDisplayId;
const areaChanged =
normalizedArea.x !== originalRounded.x ||
normalizedArea.y !== originalRounded.y ||
normalizedArea.width !== originalRounded.width ||
normalizedArea.height !== originalRounded.height;
if (displayChanged || areaChanged) {
console.log(
`🎯 Capture area normalize: display=${targetDisplay.id} -> (${rawArea.x},${rawArea.y},${rawArea.width}x${rawArea.height}) ➜ (${normalizedArea.x},${normalizedArea.y},${normalizedArea.width}x${normalizedArea.height})`
);
}
this.options.captureArea = normalizedArea;
this.options.displayId = Number(targetDisplay.id);
this.recordingDisplayInfo = {
displayId: Number(targetDisplay.id),
x: Number(targetDisplay.x) || 0,
y: Number(targetDisplay.y) || 0,
width: Number(targetDisplay.width) || 0,
height: Number(targetDisplay.height) || 0,
logicalWidth: Number(targetDisplay.width) || 0,
logicalHeight: Number(targetDisplay.height) || 0,
};
};
// WindowId varsa captureArea'yı otomatik ayarla
if (this.options.windowId && !this.options.captureArea) {
try {
const windows = await this.getWindows();
const displays = await getCachedDisplays();
const targetWindow = windows.find(
(w) => w.id === this.options.windowId
);
if (targetWindow) {
// Pencere hangi display'de olduğunu bul
let targetDisplayId = null;
let adjustedX = targetWindow.x;
let adjustedY = targetWindow.y;
// Pencere hangi display'de?
for (let i = 0; i < displays.length; i++) {
const display = displays[i];
const displayWidth = parseInt(display.resolution.split("x")[0]);
const displayHeight = parseInt(display.resolution.split("x")[1]);
// Pencere bu display sınırları içinde mi?
if (
targetWindow.x >= display.x &&
targetWindow.x < display.x + displayWidth &&
targetWindow.y >= display.y &&
targetWindow.y < display.y + displayHeight
) {
targetDisplayId = display.id; // Use actual display ID, not array index
// CRITICAL FIX: Convert global coordinates to display-relative coordinates
// AVFoundation expects simple display-relative top-left coordinates (no flipping)
adjustedX = targetWindow.x - display.x;
adjustedY = targetWindow.y - display.y;
// console.log(`🔧 macOS 14/13 coordinate fix: Global (${targetWindow.x},${targetWindow.y}) -> Display-relative (${adjustedX},${adjustedY})`);
break;
}
}
// Eğer display bulunamadıysa ana display kullan
if (targetDisplayId === null) {
const mainDisplay = displays.find((d) => d.x === 0 && d.y === 0);
if (mainDisplay) {
targetDisplayId = mainDisplay.id; // Use actual display ID, not array index
adjustedX = Math.max(
0,
Math.min(
targetWindow.x,
parseInt(mainDisplay.resolution.split("x")[0]) -
targetWindow.width
)
);
adjustedY = Math.max(
0,
Math.min(
targetWindow.y,
parseInt(mainDisplay.resolution.split("x")[1]) -
targetWindow.height
)
);
}
}
// DisplayId'yi ayarla
if (targetDisplayId !== null) {
this.options.displayId = targetDisplayId;
// Recording için display bilgisini sakla (cursor capture için)
const targetDisplay = displays.find(d => d.id === targetDisplayId);
this.recordingDisplayInfo = {
displayId: targetDisplayId,
x: targetDisplay.x,
y: targetDisplay.y,
width: parseInt(targetDisplay.resolution.split("x")[0]),
height: parseInt(targetDisplay.resolution.split("x")[1]),
// Add scaling information for cursor coordinate transformation
logicalWidth: parseInt(targetDisplay.resolution.split("x")[0]),
logicalHeight: parseInt(targetDisplay.resolution.split("x")[1]),
};
}
this.options.captureArea = {
x: Math.max(0, adjustedX),
y: Math.max(0, adjustedY),
width: targetWindow.width,
height: targetWindow.height,
};
// console.log(
// `Window ${targetWindow.appName}: display=${targetDisplayId}, coords=${targetWindow.x},${targetWindow.y} -> ${adjustedX},${adjustedY}`
// );
}
} catch (error) {
console.warn(
"Pencere bilgisi alınamadı, tam ekran kaydedilecek:",
error.message
);
}
}
// Ensure recordingDisplayInfo is always set for cursor tracking
if (!this.recordingDisplayInfo) {
try {
const displays = await getCachedDisplays();
let targetDisplay;
if (this.options.displayId !== null) {
// Manual displayId specified
targetDisplay = displays.find(d => d.id === this.options.displayId);
} else {
// Default to main display
targetDisplay = displays.find(d => d.isPrimary) || displays[0];
}
if (targetDisplay) {
this.recordingDisplayInfo = {
displayId: targetDisplay.id,
x: targetDisplay.x || 0,
y: targetDisplay.y || 0,
width: parseInt(targetDisplay.resolution.split("x")[0]),
height: parseInt(targetDisplay.resolution.split("x")[1]),
// Add scaling information for cursor coordinate transformation
logicalWidth: parseInt(targetDisplay.resolution.split("x")[0]),
logicalHeight: parseInt(targetDisplay.resolution.split("x")[1]),
};
}
} catch (error) {
console.warn("Display bilgisi alınamadı:", error.message);
}
}
// Normalize capture area AFTER automatic window capture logic
if (this.options.captureArea) {
await normalizeCaptureArea();
}
// Çıkış dizinini oluştur
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
this.outputPath = outputPath;
return new Promise(async (resolve, reject) => {
try {
// MULTI-SESSION: Generate unique session ID for this recording
// Use provided sessionTimestamp from options, or generate new one
const sessionTimestamp = this.options.sessionTimestamp || Date.now();
this.sessionTimestamp = sessionTimestamp;
this.nativeSessionId = `rec_${sessionTimestamp}_${Math.random().toString(36).substr(2, 9)}`;
console.log(`🎬 Starting recording with session ID: ${this.nativeSessionId}`);
if (this.options.sessionTimestamp) {
console.log(` ⏰ Using provided sessionTimestamp: ${this.options.sessionTimestamp}`);
} else {
console.log(` ⏰ Generated new sessionTimestamp: ${sessionTimestamp}`);
}
// CRITICAL FIX: Ensure main video file also uses sessionTimestamp
// This guarantees ALL files have the exact same timestamp
const outputDir = path.dirname(outputPath);
const originalBaseName = path.basename(outputPath, path.extname(outputPath));
const extension = path.extname(outputPath);
// Remove any existing timestamp from filename (pattern: -1234567890 or _1234567890)
const cleanBaseName = originalBaseName.replace(/[-_]\d{13}$/, '');
// Reconstruct path with sessionTimestamp
outputPath = path.join(outputDir, `${cleanBaseName}-${sessionTimestamp}${extension}`);
this.outputPath = outputPath;
const cursorFilePath = path.join(outputDir, `temp_cursor_${sessionTimestamp}.json`);
// CRITICAL FIX: Use .mov extension for camera (native recorder uses .mov, not .webm)
let cameraFilePath =
this.options.captureCamera === true
? path.join(outputDir, `temp_camera_${sessionTimestamp}.mov`)
: null;
const captureAudio = this.options.includeMicrophone === true || this.options.includeSystemAudio === true;
// CRITICAL FIX: Use .mov extension for audio (consistent with native recorder)
let audioFilePath = captureAudio
? path.join(outputDir, `temp_audio_${sessionTimestamp}.mov`)
: null;
if (this.options.captureCamera === true) {
this.cameraCaptureFile = cameraFilePath;
this.cameraCaptureActive = false;
} else {
this.cameraCaptureFile = null;
this.cameraCaptureActive = false;
}
if (captureAudio) {
this.audioCaptureFile = audioFilePath;
this.audioCaptureActive = false;
} else {
this.audioCaptureFile = null;
this.audioCaptureActive = false;
}
// Native kayıt başlat
let recordingOptions = {
includeMicrophone: this.options.includeMicrophone === true, // Only if explicitly enabled
includeSystemAudio: this.options.includeSystemAudio === true, // Only if explicitly enabled
captureCursor: this.options.captureCursor || false,
displayId: this.options.displayId || null, // null = ana ekran
windowId: this.options.windowId || null, // null = tam ekran
audioDeviceId: this.options.audioDeviceId || null, // null = default device
systemAudioDeviceId: this.options.systemAudioDeviceId || null, // null = auto-detect system audio device
captureCamera: this.options.captureCamera === true,
cameraDeviceId: this.options.cameraDeviceId || null,
sessionTimestamp,
// MULTI-SESSION: Pass unique session ID to native code
nativeSessionId: this.nativeSessionId,
frameRate: this.options.frameRate || 60,
quality: this.options.quality || "high",
// Hint native side to use ScreenCaptureKit on macOS 15+
preferScreenCaptureKit: this.options.preferScreenCaptureKit === true,
};
if (cameraFilePath) {
recordingOptions = {
...recordingOptions,
cameraOutputPath: cameraFilePath,
};
}
if (audioFilePath) {
recordingOptions = {
...recordingOptions,
audioOutputPath: audioFilePath,
};
}
// Manuel captureArea varsa onu kullan
if (this.options.captureArea) {
recordingOptions.captureArea = {
x: this.options.captureArea.x,
y: this.options.captureArea.y,
width: this.options.captureArea.width,
height: this.options.captureArea.height,
};
}
// CRITICAL SYNC FIX: Start native recording FIRST (video/audio/camera)
// Then IMMEDIATELY start cursor tracking with the SAME timestamp
// This ensures ALL components capture their first frame at the same time
let success;
try {
console.log('🎯 SYNC: Starting native recording (screen/audio/camera) at timestamp:', sessionTimestamp);
success = nativeBinding.startRecording(
outputPath,
recordingOptions
);
if (success) {
console.log('✅ SYNC: Native recording started successfully');
}
} catch (error) {
success = false;
console.warn('❌ Native recording failed to start:', error.message);
}
// Only start cursor if native recording started successfully
if (success) {
// For ScreenCaptureKit (async startup), wait briefly until native fully initialized
// ScreenCaptureKit needs ~150-300ms to start + ~150ms for first 10 frames
const waitStart = Date.now();
try {
while (Date.now() - waitStart < 600) {
try {
const nativeStatus = nativeBinding && nativeBinding.getRecordingStatus ? nativeBinding.getRecordingStatus() : true;
if (nativeStatus) {
console.log(`✅ SYNC: Native recording fully ready after ${Date.now() - waitStart}ms`);
break;
}
} catch (_) {}
await new Promise(r => setTimeout(r, 30));
}
} catch (_) {}
this.sessionTimestamp = sessionTimestamp;
// CURSOR SYNC FIX: Wait additional 300ms for first frames to start
// This ensures cursor tracking aligns with actual video timeline
// ScreenCaptureKit needs ~200-350ms to actually start capturing frames
// We wait 300ms to ensure cursor starts AFTER first video frame
console.log('⏳ CURSOR SYNC: Waiting 300ms for first video frames...');
await new Promise(r => setTimeout(r, 300));
const syncTimestamp = Date.now();
this.syncTimestamp = syncTimestamp;
this.recordingStartTime = syncTimestamp;
console.log(`🎯 CURSOR SYNC: Cursor tracking will use timestamp: ${syncTimestamp}`);
const standardCursorOptions = {
videoRelative: true,
displayInfo: this.recordingDisplayInfo,
recordingType: this.options.windowId ? 'window' :
this.options.captureArea ? 'area' : 'display',
captureArea: this.options.captureArea,
windowId: this.options.windowId,
startTimestamp: syncTimestamp // Align cursor timeline to actual start
};
try {
console.log('🎯 SYNC: Starting cursor tracking at timestamp:', syncTimestamp);
await this.startCursorCapture(cursorFilePath, standardCursorOptions);
console.log('✅ SYNC: Cursor tracking started successfully');
} catch (cursorError) {
console.warn('⚠️ Cursor tracking failed to start:', cursorError.message);
// Continue with recording even if cursor fails - don't stop native recording
}
}
if (success) {
const timelineTimestamp = this.syncTimestamp || sessionTimestamp;
const fileTimestamp = this.sessionTimestamp || sessionTimestamp;
if (this.options.captureCamera === true) {
try {
const nativeCameraPath = nativeBinding.getCameraRecordingPath
? nativeBinding.getCameraRecordingPath()
: null;
if (typeof nativeCameraPath === "string" && nativeCameraPath.length > 0) {
this.cameraCaptureFile = nativeCameraPath;
cameraFilePath = nativeCameraPath;
}
} catch (pathError) {
console.warn("Camera output path sync failed:", pathError.message);
}
}
if (captureAudio) {
try {
const nativeAudioPath = nativeBinding.getAudioRecordingPath
? nativeBinding.getAudioRecordingPath()
: null;
if (typeof nativeAudioPath === "string" && nativeAudioPath.length > 0) {
this.audioCaptureFile = nativeAudioPath;
audioFilePath = nativeAudioPath;
}
} catch (pathError) {
console.warn("Audio output path sync failed:", pathError.message);
}
}
this.isRecording = true;
if (this.options.captureCamera === true && cameraFilePath) {
this.cameraCaptureActive = true;
console.log('📹 SYNC: Camera recording started at timestamp:', timelineTimestamp);
this.emit("cameraCaptureStarted", {
outputPath: cameraFilePath,
deviceId: this.options.cameraDeviceId || null,
timestamp: timelineTimestamp,
sessionTimestamp: fileTimestamp,
syncTimestamp: timelineTimestamp,
fileTimestamp,
});
}
if (captureAudio && audioFilePath) {
this.audioCaptureActive = true;
console.log('🎙️ SYNC: Audio recording started at timestamp:', timelineTimestamp);
this.emit("audioCaptureStarted", {
outputPath: audioFilePath,
deviceIds: {
microphone: this.options.audioDeviceId || null,
system: this.options.systemAudioDeviceId || null,
},
timestamp: timelineTimestamp,
sessionTimestamp: fileTimestamp,
syncTimestamp: timelineTimestamp,
fileTimestamp,
});
}
// SYNC FIX: Cursor tracking already started BEFORE recording for perfect sync
// (Removed duplicate cursor start code)
// Log synchronized recording summary
const activeComponents = [];
activeComponents.push('Screen');
if (this.cursorCaptureInterval) activeComponents.push('Cursor');
if (this.cameraCaptureActive) activeComponents.push('Camera');
if (this.audioCaptureActive) activeComponents.push('Audio');
console.log(`✅ SYNC COMPLETE: All components synchronized at timestamp ${timelineTimestamp}`);
console.log(` Active components: ${activeComponents.join(', ')}`);
// Timer başlat (progress tracking için)
this.recordingTimer = setInterval(() => {
const elapsed = Math.floor(
(Date.now() - this.recordingStartTime) / 1000
);
this.emit("timeUpdate", elapsed);
}, 1000);
// Native kayıt gerçekten başladığını kontrol etmek için polling başlat
let recordingStartedEmitted = false;
const checkRecordingStatus = setInterval(() => {
try {
const nativeStatus = nativeBinding.getRecordingStatus();
if (nativeStatus && !recordingStartedEmitted) {
recordingStartedEmitted = true;
clearInterval(checkRecordingStatus);
// Kayıt gerçekten başladığı anda event emit et
const startTimestampPayload = this.syncTimestamp || this.recordingStartTime || Date.now();
const fileTimestampPayload = this.sessionTimestamp;
this.emit("recordingStarted", {
outputPath: this.outputPath,
timestamp: startTimestampPayload,
options: this.options,
nativeConfirmed: true,
cameraOutputPath: this.cameraCaptureFile || null,
audioOutputPath: this.audioCaptureFile || null,
cursorOutputPath: cursorFilePath,
sessionTimestamp: fileTimestampPayload,
syncTimestamp: startTimestampPayload,
fileTimestamp: fileTimestampPayload,
});
}
} catch (error) {
// Native status check error - fallback
if (!recordingStartedEmitted) {
recordingStartedEmitted = true;