-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cjs
480 lines (401 loc) · 14.9 KB
/
main.cjs
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
///////
// requires ffmpeg to be installed on the system
// requires ...sudo apt-get install gstreamer1.0-tools gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly
// v4l2loopback-dkms v4l2loopback-utils, wmctrl,
/////////
const { app, BrowserWindow, ipcMain, desktopCapturer, dialog } = require("electron");
const os = require("os");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const sudo = require("sudo-prompt");
const sudoExecAsync = promisify(sudo.exec);
const systemEndianness = os.endianness();
const { streamMaskcamToDevice, stopMaskcamStream } = require("./main-fns/maskcam.cjs");
const { myWriteFileSync, showDialog, systemX11orWayland, systemPulseaudioOrPipewire, installDependencies, createGif } = require("./main-fns/main-utilities.cjs");
const {
getSinksAndSourcesList,
startAudioRecording,
pauseAudioRecording,
resumeAudioRecording,
cancelAudioRecording,
stopAudioRecording,
recordingsCompleted,
} = require("./main-fns/audio-utilities.cjs");
const { audioEffectsStart, audioEffectsStop, cleanupAudioDevices } = require("./main-fns/audio-effects.cjs");
const packageJson = require("./package.json");
const appName = packageJson.name;
let TARGET_DIR = path.join(__dirname, "..", appName + "Files");
// Enable hot-reloading for development
//TODO: set this in the package.json build scripts
process.env.NODE_ENV = "development"; //"production"
console.log(`process.env.NODE_ENV = ${process.env.NODE_ENV}`);
if (process.env.NODE_ENV !== "production") {
require("electron-reload")(__dirname, {
electron: path.join(__dirname, "node_modules", ".bin", "electron"),
});
} else {
TARGET_DIR = path.join(__dirname, "..", "..", "..", appName + "Files");
//For tfjs and Human
const depsPath = path.join(__dirname, "..", "deps", "lib");
process.env.LD_LIBRARY_PATH = depsPath + ":" + (process.env.LD_LIBRARY_PATH || "");
console.log("LD_LIBRARY_PATH:", process.env.LD_LIBRARY_PATH);
}
let X11orWayland; // = systemX11orWayland();
systemX11orWayland().then((value) => {
X11orWayland = value;
console.log(`top, X11orWayland = ${X11orWayland}`);
});
let pulseaudioOrPipeWire; // = systemPulseaudioOrPipewire();
systemPulseaudioOrPipewire().then((value) => {
pulseaudioOrPipeWire = value;
console.log(`top, pulseaudioOrPipeWire = ${pulseaudioOrPipeWire}`);
});
let modprobLoaded = false;
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
title: appName,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, "preload.cjs"),
},
});
mainWindow.setMenu(null);
mainWindow.loadFile("main.html");
if (process.env.NODE_ENV === "development") {
// Keep the default menu in development mode
mainWindow.webContents.openDevTools();
} else {
mainWindow.setMenu(null); // remove the menu bar and deactivates devTools
}
mainWindow.on("closed", function () {
mainWindow = null;
if (maskcam_window) {
maskcam_window.close();
}
});
}
app.on("ready", createWindow);
app.on("before-quit", async (event) => {
// Prevent the default behavior first if needed
// event.preventDefault();
console.log("before before quit");
await audioEffectsStop();
await cleanupAudioDevices();
// app.quit();
console.log("Cleanup completed. before quit");
});
// app.on("window-all-closed", async function () {
// //await audioEffectsStop();
// //app.quit();
// });
app.on("will-quit", async (event) => {
console.log("before will quit");
await audioEffectsStop();
await cleanupAudioDevices();
console.log("Cleanup completed. will quit");
app.quit();
});
app.on("activate", function () {
if (mainWindow === null) {
createWindow();
}
});
//make folders
let main_folder_exists = fs.existsSync(TARGET_DIR);
if (!main_folder_exists) fs.mkdirSync(TARGET_DIR);
//due to nodeIntegration being false these node libraries come from here
ipcMain.handle("getDirname", () => {
return __dirname;
});
ipcMain.handle("joinPath", (event, strArray) => {
return path.join(...strArray);
});
ipcMain.handle("getTargetDir", () => {
return TARGET_DIR;
});
ipcMain.handle("writeFileSync", (event, arg_obj) => {
myWriteFileSync(event, arg_obj);
});
ipcMain.handle("existsSync", (event, path) => {
return fs.existsSync(path);
});
//ge the list of ids of screens or windows to record with the electron mediaRecorder (audio on linux no go)
ipcMain.handle("getCaptureID", async (event) => {
try {
const sources = await desktopCapturer.getSources({
types: ["window", "screen"],
});
if (!sources || sources.length === 0) {
throw new Error("No sources available");
}
// If specific thumbnail scaling is needed, maintain that feature from cuttleTron
return sources.map((source) => ({
id: source.id,
name: source.name,
thumbnail: source.thumbnail.toDataURL({ scaleFactor: 0.25 }), // Adjust scaleFactor as needed
}));
} catch (error) {
console.error("Error getting capture sources:", error);
return null; // Ensures upstream code can handle the error gracefully
}
});
ipcMain.handle("system-X11-or-wayland", async (event) => {
return X11orWayland;
});
ipcMain.handle("pulseaudio-or-pipewire", async (event) => {
return pulseaudioOrPipeWire; // await systemPulseaudioOrPipewire();
});
////////////////////////////////////
//dialog handler
////////////////////////////////////
ipcMain.handle("show-dialog", async (event, options) => {
const response = await showDialog(options);
return response.response; // Return the index of the clicked button
});
////////////////////////////////////
//install dependencies
////////////////////////////////////
ipcMain.handle("install-dependencies", async () => {
try {
return await installDependencies();
} catch (error) {
console.error(`Installation error: ${error}`);
return { success: false, error: error.message };
}
});
///////////////////////////////////////////
// *handler for creating a GIF
///////////////////////////////////////////
ipcMain.handle("create-gif", async (event, baseFilename, numDigits, startNumber, endNumber, FPS) => {
console.log({
baseFilename,
numDigits,
startNumber,
endNumber,
FPS,
TARGET_DIR,
});
try {
const result = await createGif(baseFilename, numDigits, startNumber, endNumber, FPS, TARGET_DIR);
return result;
} catch (error) {
throw new Error(`Error creating GIF: ${error.message}`);
}
});
//*trying to use any npm package to get the audio or even repos for pulse audio specifically like
// https://github.com/mscdex/paclient worked within nodejs itself but totally failed in electronjs
ipcMain.handle("get-sinks-sources", async (event) => {
try {
const audioSystem = await systemPulseaudioOrPipewire();
const sinksAndSources = await getSinksAndSourcesList(audioSystem);
return sinksAndSources;
} catch (error) {
console.error("Error in get-sinks-sources IPC handler:", error);
// Optionally send a meaningful error message back to the renderer
return { error: "Failed to retrieve sinks and sources." };
}
});
//record audio from sink monitor provided
ipcMain.handle("startAudioRecording", (event, sink_monitor, filepath) => {
startAudioRecording(sink_monitor, filepath);
});
// Pause recording
ipcMain.handle("pauseAudioRecording", (event) => {
pauseAudioRecording();
});
// Resume recording
ipcMain.handle("resumeAudioRecording", (event, sink_monitor, audio_path) => {
// Append a timestamp to the filepath to ensure uniqueness
resumeAudioRecording(sink_monitor, audio_path);
});
// Cancel recording and reset the audioSegments array and ffmpegProcess
ipcMain.handle("cancelAudioRecording", (event) => {
cancelAudioRecording();
});
// Stop recording
ipcMain.handle("stopAudioRecording", (event, recording_bool) => {
stopAudioRecording(recording_bool);
});
ipcMain.on("recordings-completed", async (event, args) => {
recordingsCompleted(args);
});
// AUDIO EFFECTS
ipcMain.handle("audioeffects-start", async (event, effects_params) => {
try {
const status = await audioEffectsStart(effects_params);
return status;
} catch (error) {
// Handle any errors
console.error("Error in trying to engage audioEffectsStart:", error);
return { success: false, message: error.message };
}
});
ipcMain.handle("audioeffects-stop", async (event) => {
await audioEffectsStop();
});
ipcMain.handle("audioeffects-cleanup", async (event) => {
await cleanupAudioDevices();
});
//////////////////////////////////////////////////////////////////////////
//* for maskcam
//////////////////////////////////////////////////////////////////////////
const maskcamWindowTitle = "cuttleTronMaskcam";
let maskcam_window;
let maskcamWinIdInt;
let maskcamWinIdHex;
let webcamAspectRatio;
let webcamWidth;
let webcamHeight;
let maskcamWidth;
let maskcamHeight;
let isCleanupInitiated = false;
function resetMaskCam() {
if (maskcam_window) {
maskcam_window.close();
maskcam_window = null;
}
maskcamWinIdInt = maskcamWinIdHex = null;
webcamAspectRatio = null;
webcamWidth = webcamHeight = null;
maskcamWidth = maskcamHeight = null;
}
ipcMain.handle("mask-opened", () => {
return maskcam_window && !maskcam_window.isDestroyed() && maskcam_window.isVisible();
});
ipcMain.on("stop-maskcam", async (event) => {
maskcam_window.webContents.send("stop-maskcam"); //calls renderer handler
if (!isCleanupInitiated && maskcam_window) {
isCleanupInitiated = await stopMaskcamStream(isCleanupInitiated);
resetMaskCam();
}
});
ipcMain.on("update-maskcam", (event, mask_settings) => {
if (!maskcam_window) {
console.error("MaskCam window is not available.");
return;
}
maskcam_window.webContents.send("toggle-mask-view", mask_settings);
});
ipcMain.handle("stream-maskcam", async (event, mask_settings) => {
if (maskcam_window && !maskcam_window.isDestroyed()) {
const standardResolutions = [
{ width: 640, height: 480 }, // 4:3
{ width: 1280, height: 720 }, // 16:9
{ width: 1920, height: 1080 }, // 16:9
// Add more resolutions if necessary
];
let bestMatch = standardResolutions[0];
for (const res of standardResolutions) {
if (Math.abs(res.width / res.height - webcamAspectRatio) < Math.abs(bestMatch.width / bestMatch.height - webcamAspectRatio)) {
bestMatch = res;
}
}
// Update the window size to the best matching standard resolution
maskcamWidth = bestMatch.width;
maskcamHeight = bestMatch.height;
await maskcam_window.setSize(maskcamWidth, maskcamHeight);
await maskcam_window.setResizable(false);
maskcam_window.setAlwaysOnTop(true);
maskcam_window.webContents.send("toggle-mask-view", mask_settings);
}
await maskcam_window.webContents.send("anchor-mask-view");
streamMaskcamToDevice(maskcamWindowTitle, maskcamWinIdHex, X11orWayland);
return maskcamWindowTitle;
});
const preloadMaskcamPath = path.join(__dirname, "preloadMaskcam.cjs");
console.log(`Loading maskcam preload script from: ${preloadMaskcamPath}`);
ipcMain.handle("init-maskcam", async (event, mask_settings) => {
console.log(`in init-maskcam, X11orWayland = ${X11orWayland}`);
if (!(X11orWayland == "x11" || X11orWayland == "Wayland")) {
X11orWayland = await systemX11orWayland();
console.log(`now, X11orWayland = ${X11orWayland}`);
}
if (maskcam_window) {
maskcam_window.focus(); // Focus the already opened window instead of creating a new one
return;
}
if (!modprobLoaded) {
const command = `modprobe v4l2loopback`;
try {
await sudoExecAsync(command, { name: "CuttleTron load modprobe" });
modprobLoaded = true;
console.log("modprobe v4l2loopback loaded successfully.");
} catch (e) {
console.error(`error trying to load the modprob of v4l2, ${e}`);
dialog
.showMessageBox({
type: "error",
title: "Error loading modprobe",
message: `Attempted: ${command},\n Error: ${e.message}`,
buttons: ["OK"],
})
.then(() => {
throw new Error("Failed to load v4l2loopback module. Cannot continue.");
});
}
}
isCleanupInitiated = false;
maskcam_window = new BrowserWindow({
title: maskcamWindowTitle,
autoHideMenuBar: true,
width: 640,
height: 480, //640x480 is the 4:3 aspect ratio init, changed later
minimizable: false,
maximizable: false,
resizable: true,
frame: false, // Remove window frame
transparent: false, // transparent background
backgroundColor: "blue",
webPreferences: {
nodeIntegration: true, //needed for tensorflow in the renderer window...
nodeIntegrationInWorker: true, // Enable Node.js integration in Web Workers
contextIsolation: false,
preload: path.join(__dirname, "preloadMaskcam.cjs"),
webviewTag: false,
},
}); //offscreen boolean (optional) - Whether to enable offscreen rendering for the browser window
//win.setAspectRatio(aspectRatio[, extraSize]) //win.setSize(width, height[, animate]) win.getSize() //win.getMediaSourceId()
await maskcam_window.setMenu(null); // remove the menu bar and deactivates devTools
await maskcam_window.removeMenu(); //new
await maskcam_window.show(); // Show the window after loading //win.destroy() //win.isDestroyed() //win.isVisible()
await maskcam_window.loadFile("maskcam-view.html");
// *do if NOT WAYLAND
if (X11orWayland == "x11") {
let buffer = maskcam_window.getNativeWindowHandle(); // The buffer contains the window ID in a platform-specific format For X11 on Linux, the ID is an unsigned long (32-bit) integer in the buffer
// Read the window ID based on the system's endianness
if (systemEndianness === "LE") {
maskcamWinIdInt = buffer.readUInt32LE(0);
} else {
maskcamWinIdInt = buffer.readUInt32BE(0);
}
maskcamWinIdHex = `0x${maskcamWinIdInt.toString(16).padStart(8, "0")}`;
console.log(`--------Window ID int: ${maskcamWinIdInt}, maskcamWinIdHex: ${maskcamWinIdHex}`);
}
await maskcam_window.webContents.send("toggle-mask-view", mask_settings);
if (process.env.NODE_ENV !== "production") {
maskcam_window.webContents.openDevTools();
}
maskcam_window.on("closed", async function () {
if (!isCleanupInitiated) {
isCleanupInitiated = await stopMaskcamStream(isCleanupInitiated); // This is async, so it might still be running when resetMaskCam() executes
resetMaskCam();
}
});
return "move window, then stream";
});
//called from maskcam-view
ipcMain.on("webcam-size", (event, webcam_specs) => {
if (maskcam_window && !maskcam_window.isDestroyed()) {
const { width, height } = webcam_specs;
// Update global variables
webcamWidth = width;
webcamHeight = height;
webcamAspectRatio = width / height; // Calculate the aspect ratio
console.log(`Webcam Aspect Ratio: ${webcamAspectRatio}, webcamWidth=${webcamWidth}, webcamHeight=${webcamHeight}`);
}
});