-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
707 lines (598 loc) · 27.6 KB
/
main.js
File metadata and controls
707 lines (598 loc) · 27.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
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
// main.js
console.log("------------------- Main.js VERSION 5.1 LOADING -------------------");
const { ipcMain, app, BrowserWindow, dialog, Notification, protocol } = require('electron');
const { watchKeypoints } = require('./backend/poseDataWatcher');
const { loadBounceConfig } = require('./backend/helpers/bounceTagger');
const { exportMotionData } = require('./backend/exporters/exporter');
const { getVideoMetadata, processVideoForOpenPose } = require('./backend/videoService');
const ffmpegHelper = require('./backend/helpers/ffmpegHelper');
const { OpenPoseWrapper } = require('./backend/openposeWrapper');
const fs = require('fs/promises');
const path = require('path');
const os = require('os');
const { exec } = require('child_process');
// --- Helper Functions ---
function getUserDataPath() {
return app.getPath('userData');
}
async function fileExists(filePath) {
try {
await fs.access(filePath, fs.constants.F_OK);
return true;
} catch {
return false;
}
}
// --- END Helper Functions ---
// Path for general settings (msfw_settings.json)
const settingsPath = path.join(getUserDataPath(), 'msfw_settings.json');
// Settings helpers
async function getSettings() {
try {
const data = await fs.readFile(settingsPath, 'utf-8');
return JSON.parse(data);
} catch (e) {
if (e.code === 'ENOENT') {
return {}; // File not found, return empty settings
}
console.error("Error loading settings:", e.message, `(Code: ${e.code})`);
return {};
}
}
async function setSettings(newSettings) {
try {
await fs.writeFile(settingsPath, JSON.stringify(newSettings, null, 2), 'utf-8');
} catch (e) {
console.error("Error saving settings:", e.message, `(Code: ${e.code})`);
}
}
// NEW: Define tempVideoDir for transcoded playback files
const tempVideoDir = path.join(os.tmpdir(), 'msfw_temp_playback');
// ADDED: Declare mainWindow and openPoseWrapper globally
let mainWindow; // <--- ADDED
let openPoseWrapper; // <--- ADDED
let currentJob = { provider: null, jobId: null };
function setCurrentJob(p, id) { currentJob = { provider: p, jobId: id }; }
function createWindow() {
// CHANGED: Assign to global mainWindow instead of local 'win'
mainWindow = new BrowserWindow({ // <--- CHANGED
width: 1200,
height: 800,
minWidth: 800, // <--- ADDED: Good practice for responsive UI
minHeight: 600, // <--- ADDED: Good practice for responsive UI
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
// CHANGED: Corrected security settings for webPreferences
nodeIntegration: false, // <--- CHANGED: Set to false for security with contextIsolation
contextIsolation: true, // <--- CHANGED: Should be true for security
webSecurity: false // <--- ADDED: May be needed for local file access, consider hardening for production
},
title: "MSFW Engine" // <--- ADDED: Add a title to the window
});
// DETERMINE OPENPOSE PATH BASED ON ENVIRONMENT
let openposeBasePath;
if (app.isPackaged) {
openposeBasePath = path.join(process.resourcesPath, 'app.asar.unpacked', 'openpose');
} else {
openposeBasePath = path.join(__dirname, 'openpose');
}
console.log(`[Main Process] OpenPose base path: ${openposeBasePath}`);
console.log(path.join(getUserDataPath(), 'openpose_output_keypoints'))
openPoseWrapper = new OpenPoseWrapper({
openposeBasePath: openposeBasePath, // ✅ was openposePath
userDataPath: getUserDataPath(),
outputDir: path.join(getUserDataPath(), 'openpose_output_keypoints'),
});
// ADDED: Set up listeners for OpenPoseWrapper events once and forward them to the renderer
openPoseWrapper.on('progress', (data) => {
if (mainWindow) mainWindow.webContents.send('openpose-status', { type: 'progress', data: data });
}); // <--- ADDED
openPoseWrapper.on('start', (message) => {
if (mainWindow) mainWindow.webContents.send('openpose-status', { type: 'start', data: message });
}); // <--- ADDED
openPoseWrapper.on('complete', (data) => {
if (mainWindow) mainWindow.webContents.send('openpose-status', { type: 'complete', data: data });
}); // <--- ADDED
openPoseWrapper.on('error', (error) => {
if (mainWindow) mainWindow.webContents.send('openpose-status', { type: 'error', data: error.message });
}); // <--- ADDED
openPoseWrapper.on('cancelled', (message) => {
if (mainWindow) mainWindow.webContents.send('openpose-status', { type: 'cancelled', data: message });
}); // <--- ADDED
// ADDED: Initialize OpenPoseWrapper to detect GPU etc. This should run once at startup.
openPoseWrapper.initialize().catch(err => {
console.error('[Main Process] OpenPoseWrapper initialization failed:', err.message);
if (mainWindow) {
mainWindow.webContents.send('app-notification', {
title: 'OpenPose Setup Error',
body: `OpenPose initialization failed: ${err.message}. Please check your OpenPose installation and ensure models are present.`,
severity: 'error'
});
}
});
const isDev = !app.isPackaged;
if (isDev) {
mainWindow.loadURL('http://localhost:3000'); // <--- CHANGED: Use mainWindow
mainWindow.webContents.openDevTools(); // <--- CHANGED: Use mainWindow
} else {
mainWindow.loadFile(path.join(__dirname, 'build', 'index.html')); // <--- CHANGED: Use mainWindow
}
}
app.whenReady().then(async () => { // Made this async to await directory creation
createWindow();
// Ensure the temporary directory for playback transcoding exists
await fs.mkdir(tempVideoDir, { recursive: true });
console.log(`[Main Process] Playback temp directory created at: ${tempVideoDir}`);
watchKeypoints(async (keypoints, filename) => {
const win = BrowserWindow.getAllWindows()[0];
if (win) {
win.webContents.send('pose-data', { keypoints, filename });
}
const playbackPath = path.join(getUserDataPath(), 'playback.json');
try {
await fs.writeFile(playbackPath, JSON.stringify(keypoints, null, 2), 'utf-8');
console.log(`[MSFW] Auto-saved ${keypoints.length} frames to playback.json`);
} catch (err) {
console.error("[MSFW] Failed to write playback.json:", err.message);
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});
// --- Capture Provider Loader (main.js) ---
const providers = new Map(); // 'openpose' | 'easymocap' -> provider instance
function registerOpenPoseProvider() {
// We will call your existing OpenPose path directly (no wrapper object required),
// but we still register a shim so the dispatcher is uniform.
providers.set('openpose', {
kind: 'openpose',
async processVideo({ filePath, startTime, endTime, webContents }) {
// call your existing handler code path directly (see section D below)
return runOpenPoseFlow({ filePath, startTime, endTime, webContents });
}
});
}
function registerEasyMocapProvider() {
const pluginRoot = app.isPackaged
? path.join(process.resourcesPath, 'app.asar.unpacked', 'plugins', 'easymocap')
: path.join(__dirname, 'plugins', 'easymocap');
const { EasyMocapProvider } = require(path.join(pluginRoot, 'easymocapProvider.js'));
const em = new EasyMocapProvider(pluginRoot);
em.on('log', (l) => {
const msg = `[EM] ${l.level || 'info'}: ${l.msg || ''}`;
BrowserWindow.getAllWindows()[0]?.webContents.send('video-processing-status', { type: 'log', message: msg });
});
em.on('result', async ({ jobId, manifest }) => {
try {
const outFile = path.join(manifest.output, 'manifest_easymocap.json');
await fs.writeFile(outFile, JSON.stringify(manifest, null, 2), 'utf-8');
} catch (err) {
BrowserWindow.getAllWindows()[0]?.webContents.send('video-processing-status', { type: 'error', message: `Failed to write EM manifest: ${err.message}` });
}
BrowserWindow.getAllWindows()[0]?.webContents.send('video-processing-status', { type: 'complete', message: 'EasyMocap complete', manifest });
});
// ✅ forward provider errors to UI
em.on('error', (e) => {
BrowserWindow.getAllWindows()[0]?.webContents.send('video-processing-status', {
type: 'error',
message: `EasyMocap failed: ${e?.payload?.error || e?.message || 'Unknown error'}`,
error: e
});
});
providers.set('easymocap', { kind: 'easymocap', instance: em, processVideo: (opts) => em.processVideo(opts) });
}
// call both at startup (after app.whenReady)
registerOpenPoseProvider();
registerEasyMocapProvider();
async function runOpenPoseFlow({ filePath, startTime, endTime, webContents, preClippedPath }) {
try {
webContents.send('video-processing-status', { type: 'start', message: 'Starting video processing...' });
// ✅ reuse pre-clipped video if provided
let clippedVideoOutputPath = preClippedPath;
if (!clippedVideoOutputPath) {
webContents.send('video-processing-status', { type: 'clipping', message: 'Clipping video...' });
const clip = await processVideoForOpenPose({ filePath, startTime, endTime }, (progress) => {
webContents.send('video-processing-status', { type: 'clipping-progress', message: `Clipping: ${progress.percent.toFixed(1)}%`, progress });
});
clippedVideoOutputPath = clip.outputPath;
}
webContents.send('video-processing-status', { type: 'openpose-start', message: 'Starting OpenPose...' });
await openPoseWrapper.runOpenPose(clippedVideoOutputPath, { display: 0, renderPose: 0 });
setCurrentJob('openpose', 'openpose');
try { if (await fileExists(clippedVideoOutputPath)) await fs.unlink(clippedVideoOutputPath); } catch {}
webContents.send('video-processing-status', { type: 'complete', message: 'Video processing and OpenPose complete!' });
return { success: true, message: 'Video processed and OpenPose run.' };
} catch (error) {
const errorMessage = `Video processing failed: ${error.message}`;
webContents.send('video-processing-status', { type: 'error', message: errorMessage, error: error.message });
throw new Error(errorMessage);
}
}
// --- IPC Handlers ---
// NEW: IPC handlers for path operations
ipcMain.handle('get-path-basename', async (event, filePath) => {
return path.basename(filePath);
});
ipcMain.handle('get-path-dirname', async (event, filePath) => {
return path.dirname(filePath);
});
ipcMain.handle('get-path-join', async (event, ...args) => {
return path.join(...args);
});
ipcMain.handle('export-motion', async (event, config) => {
const exportDir = path.join(getUserDataPath(), 'output', 'exports');
await fs.mkdir(exportDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const outputPath = path.join(exportDir, `${config.filename}_${timestamp}.${config.format}`);
let frameData = config.frames;
if (!Array.isArray(frameData) || frameData.length === 0) {
try {
const fallbackPath = path.join(getUserDataPath(), 'playback.json');
frameData = JSON.parse(await fs.readFile(fallbackPath, 'utf-8'));
console.warn("[MSFW] Using fallback playback.json for export.");
} catch (err) {
console.error("[MSFW] No valid frame data found for export:", err.message);
return false;
}
}
exportMotionData(frameData, outputPath, config.format);
if (process.platform === 'win32') {
exec(`start "" "${exportDir}"`);
} else if (process.platform === 'darwin') {
exec(`open "${exportDir}"`);
} else { // Linux
exec(`xdg-open "${exportDir}"`);
}
return true;
});
ipcMain.handle('load-plugins', async () => {
// CHANGED: Corrected path for packaged app to explicitly unpack plugins
const pluginDir = app.isPackaged ? path.join(process.resourcesPath, 'app.asar.unpacked', 'plugins') : './plugins'; // <--- CHANGED
const results = [];
await fs.mkdir(pluginDir, { recursive: true });
const pluginFiles = (await fs.readdir(pluginDir)).filter(f => f.endsWith('.js'));
for (const file of pluginFiles) {
const pluginPath = path.join(pluginDir, file);
try {
const plugin = require(path.resolve(pluginPath));
if (typeof plugin.onLoad === 'function') plugin.onLoad();
results.push({ name: plugin.name || file, status: 'Loaded' });
} catch (e) {
results.push({ name: file, status: 'Error: ' + e.message });
}
}
return results;
});
ipcMain.handle('load-bounce-config', async () => {
return loadBounceConfig();
});
ipcMain.handle('start-openpose', async (event, mode) => {
// This handler is typically for starting OpenPose in webcam mode or similar,
// which has different setup from video processing.
console.warn("[Main Process] 'start-openpose' handler invoked. Implement specific webcam/live processing logic here.");
// Example: (needs a dedicated OpenPoseWrapper instance for live feed if different from video processing)
// const webcamOpenPose = new OpenPoseWrapper({ /* webcam config */ });
// await webcamOpenPose.initialize();
// webcamOpenPose.runOpenPose(0); // 0 often represents default webcam
return false; // Or return true once implemented
});
ipcMain.handle('save-playback', async (event, data) => {
const filePath = path.join(getUserDataPath(), 'playback.json');
try {
await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');
console.log('[MSFW] Playback saved manually.');
return true;
} catch (err) {
console.error('[MSFW] Error saving playback:', err);
return false;
}
});
ipcMain.handle('check-file', async (event, filePath) => {
console.log(`[Main Process - check-file] Checking existence for: ${filePath}`);
if (!filePath) {
console.warn('[Main Process - check-file] Warning: filePath is null or empty.');
return false;
}
return await fileExists(filePath);
});
ipcMain.handle('load-pose-sequence', async () => {
const playbackPath = path.join(getUserDataPath(), 'playback.json');
try {
const data = await fs.readFile(playbackPath, 'utf-8');
return JSON.parse(data);
} catch (e) {
console.error("[MSFW] Error loading pose sequence:", e.message);
return [];
}
});
ipcMain.handle('choose-model-file', async () => {
const result = await dialog.showOpenDialog({
title: "Select DAZ Model (FBX)",
filters: [{ name: 'FBX Files', extensions: ['fbx'] }],
properties: ['openFile']
});
if (result.canceled || result.filePaths.length === 0) return null;
return result.filePaths[0];
});
ipcMain.handle('save-model-path', async (event, modelPath) => {
try {
const configPath = path.join(getUserDataPath(), 'config.json');
let config = {};
if (await fileExists(configPath)) {
const data = await fs.readFile(configPath, 'utf-8');
config = JSON.parse(data);
}
config.savedModelPath = modelPath;
await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');
console.log('Model path saved asynchronously:', modelPath);
return { success: true };
} catch (error) {
console.error('Failed to save model path:', error);
throw new Error(`Failed to save model path: ${error.message}`);
}
});
ipcMain.handle('load-saved-model-path', async (event) => {
try {
const configPath = path.join(getUserDataPath(), 'config.json');
if (await fileExists(configPath)) {
const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
return config.savedModelPath || null;
}
return null;
} catch (error) {
console.error('Failed to load saved model path:', error);
return null;
}
});
ipcMain.handle('read-model-file', async (event, filePath) => {
console.log(`[Main Process - read-model-file] Attempting to read model file: ${filePath}`);
if (!filePath) {
console.warn('[Main Process - read-model-file] Warning: filePath is null or empty.');
return null;
}
try {
const buffer = await fs.readFile(filePath);
const base64Data = buffer.toString('base64');
console.log(`[Main Process - read-model-file] Successfully read file: ${filePath}, Base64 length: ${base64Data.length}`);
return base64Data;
} catch (error) {
console.error(`[Main Process - read-model-file] Error reading model file "${filePath}":`, error.message, `(Code: ${error.code})`);
return null;
}
});
// Handler to open a native file dialog for video selection
ipcMain.handle('select-video-file-dialog', async () => {
const result = await dialog.showOpenDialog({
title: "Select Video File",
filters: [
{ name: 'All Video Files', extensions: ['mp4', 'mov', 'webm', 'avi', 'mkv', 'flv', 'wmv', 'm4v', '3gp', 'mpg', 'mpeg'] },
{ name: 'MPEG-4 Video', extensions: ['mp4', 'm4v'] },
{ name: 'QuickTime Movie', extensions: ['mov'] },
{ name: 'WebM Video', extensions: ['webm'] },
{ name: 'AVI Video', extensions: ['avi'] },
{ name: 'Matroska Video', extensions: ['mkv'] },
{ name: 'Flash Video', extensions: ['flv'] },
{ name: 'Windows Media Video', extensions: ['wmv'] },
{ name: 'MPEG Video', extensions: ['mpg', 'mpeg'] },
{ name: 'All Files', extensions: ['*'] }
],
properties: ['openFile']
});
if (result.canceled || result.filePaths.length === 0) {
return null;
}
return result.filePaths[0];
});
// Handler to get video metadata (duration)
ipcMain.handle('get-video-metadata', async (event, videoPath) => {
try {
const metadata = await getVideoMetadata(videoPath);
const formatName = metadata.format?.format_name;
const videoCodecName = metadata.streams?.[0]?.codec_name;
let playbackMimeType = 'application/octet-stream';
if (formatName === 'mov,mp4,m4a,3gp,3g2,mj2') {
playbackMimeType = 'video/mp4';
} else if (formatName === 'mpegts') {
if (videoCodecName === 'h264' || videoCodecName === 'avc1') {
playbackMimeType = 'video/mp2t; codecs="avc1"';
} else if (videoCodecName === 'mpeg2video') {
playbackMimeType = 'video/mp2t; codecs="mpeg-2 video"';
} else {
playbackMimeType = 'video/mp2t';
}
} else if (formatName === 'webm') {
playbackMimeType = 'video/webm';
} else if (formatName === 'ogg') {
playbackMimeType = 'video/ogg';
}
return {
success: true,
metadata: {
...metadata,
playbackMimeType: playbackMimeType
}
};
} catch (error) {
console.error('Error in main.js get-video-metadata handler:', error);
return { success: false, error: error.message };
}
});
ipcMain.handle('transcode-for-playback', async (event, filePath) => {
const webContents = event.sender;
try {
const tempDir = path.join(os.tmpdir(), 'msfw_temp_playback');
await fs.mkdir(tempDir, { recursive: true });
const tempFilePath = path.join(tempDir, `playback_temp_${Date.now()}.mp4`);
let lastProgress = 0;
await ffmpegHelper.transcodeVideo(filePath, tempFilePath, (progress) => {
const currentPercent = progress.percent || 0;
if (currentPercent - lastProgress >= 1 || currentPercent === 100) { // Update roughly every 1% or at 100%
webContents.send('transcode-playback-progress', { percent: currentPercent });
lastProgress = currentPercent;
}
});
// NEW CHECK: Verify file size after transcoding
const stats = await fs.stat(tempFilePath);
if (stats.size === 0) {
console.error(`[Main Process] Transcoded file ${tempFilePath} is empty!`);
// Clean up the empty file
await fs.unlink(tempFilePath);
throw new Error('Transcoding completed, but the output file is empty.');
}
webContents.send('transcode-playback-progress', { percent: 100 }); // Ensure 100% is sent
console.log(`[Main Process] Transcoding for playback successfully created: ${tempFilePath} (${stats.size} bytes)`);
return { success: true, tempFilePath };
} catch (error) {
console.error('[Main Process] Error during transcode-for-playback:', error);
webContents.send('transcode-playback-progress', { percent: 0 }); // Reset progress on error
return { success: false, error: error.message };
}
});
// Modified process-video handler (with EM robustness)
ipcMain.handle('process-video', async (event, { filePath, startTime, endTime, emOptions }) => {
const webContents = event.sender;
const settings = await getSettings();
const providerKey = settings.captureProvider || 'openpose';
// If EasyMocap *might* need multiview folder, we’ll clip only if needed.
let clippedPath = null;
if (providerKey === 'easymocap') {
// Merge persisted options + UI overrides
const emOpts = Object.assign({}, settings.easymocap || {}, emOptions || {});
const emPlugin = providers.get('easymocap')?.instance;
if (!emPlugin) {
const msg = 'EasyMocap plugin not available (not detected or failed to load).';
webContents.send('video-processing-status', { type: 'error', message: msg });
throw new Error(msg);
}
if (!emOpts.easymocapRoot) {
webContents.send('video-processing-status', { type: 'error', message: 'Set EASYMOCAP_ROOT in EasyMocap options.' });
throw new Error('Missing EASYMOCAP_ROOT');
}
if (emOpts.exportBVH !== false && !emOpts.blenderPath) {
webContents.send('video-processing-status', { type: 'error', message: 'Blender path is required to export BVH.' });
throw new Error('Missing Blender path');
}
const isMultiview = (emOpts.mode || 'monocular') === 'multiview';
// For monocular, keep UX the same: clip first.
let dataRoot;
if (isMultiview) {
// Expect a prepared dataset folder with intri/extri.yml
dataRoot = emOpts.dataRoot || path.dirname(filePath);
} else {
webContents.send('video-processing-status', { type: 'clipping', message: 'Clipping video...' });
const { outputPath } = await processVideoForOpenPose({ filePath, startTime, endTime }, (progress) => {
webContents.send('video-processing-status', { type: 'clipping-progress', message: `Clipping: ${progress.percent?.toFixed?.(1) ?? 0}%`, progress });
});
clippedPath = outputPath;
dataRoot = path.dirname(outputPath);
}
const outputDir = path.join(dataRoot, 'output');
await fs.mkdir(outputDir, { recursive: true });
webContents.send('video-processing-status', { type: 'start', message: 'Starting EasyMocap...' });
const jobId = emPlugin.processVideo({
jobId: `em_${Date.now()}`,
mode: emOpts.mode || 'monocular',
dataRoot,
output: outputDir,
emcCmd: emOpts.emcCmd || 'emc',
emcArgs: emOpts.emcArgs || '--data config/datasets/svimage.yml --exp config/1v1p/hrnet_pare_finetune.yml --root {data_root}',
exportBVH: emOpts.exportBVH !== false,
profile: emOpts.profile || 'genesis8',
blender: emOpts.blenderPath || '',
extraEnv: Object.assign({ EASYMOCAP_ROOT: emOpts.easymocapRoot || '' }, emOpts.extraEnv || {}),
pythonPath: emOpts.pythonPath || '' // provider will honor this
});
setCurrentJob('easymocap', jobId);
return { success: true, message: `EasyMocap job started: ${jobId}` };
}
// ---- OpenPose path (no double clipping): clip once then reuse
webContents.send('video-processing-status', { type: 'clipping', message: 'Clipping video...' });
const { outputPath } = await processVideoForOpenPose({ filePath, startTime, endTime }, (progress) => {
webContents.send('video-processing-status', { type: 'clipping-progress', message: `Clipping: ${progress.percent?.toFixed?.(1) ?? 0}%`, progress });
});
clippedPath = outputPath;
return await runOpenPoseFlow({ filePath, startTime, endTime, webContents, preClippedPath: clippedPath });
});
ipcMain.on('show-notification', (event, options) => {
if (Notification.isSupported()) {
const notification = new Notification(options);
notification.show();
} else {
console.warn('Electron Notification API is not supported on this system.');
event.sender.send('app-notification', { title: options.title, body: options.body });
}
});
ipcMain.handle('read-local-file', async (event, filePath) => {
try {
const data = await fs.readFile(filePath);
// Using slice to get a detached ArrayBuffer, which is safer for renderer process
const arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
console.log(`[Main Process - read-local-file] Read ${arrayBuffer.byteLength} bytes from ${filePath}`);
if (arrayBuffer.byteLength === 0) {
console.warn(`[Main Process - read-local-file] Warning: File ${filePath} returned an empty buffer.`);
}
return arrayBuffer; // Return ArrayBuffer for Blob creation in renderer
} catch (error) {
console.error(`[Main Process - read-local-file] Failed to read local file ${filePath}:`, error);
throw new Error(`Failed to read local file: ${error.message}`);
}
});
ipcMain.handle('get-capture-provider', async () => {
const s = await getSettings();
return s.captureProvider || 'openpose';
});
ipcMain.handle('set-capture-provider', async (event, provider) => {
const s = await getSettings();
s.captureProvider = provider; // 'openpose' | 'easymocap'
await setSettings(s);
return true;
});
ipcMain.handle('list-capture-providers', async () => {
const arr = [];
if (providers.has('openpose')) arr.push({ key: 'openpose', name: 'OpenPose' });
if (providers.has('easymocap')) {
// verify the EM bridge exists
const ok = await providers.get('easymocap').instance.detect();
if (ok) arr.push({ key: 'easymocap', name: 'EasyMocap' });
}
return arr;
});
ipcMain.handle('get-easymocap-options', async () => {
const s = await getSettings();
return s.easymocap || {
mode: 'monocular',
easymocapRoot: '',
blenderPath: '',
profile: 'genesis8',
emcCmd: 'emc',
emcArgs: '--data config/datasets/svimage.yml --exp config/1v1p/hrnet_pare_finetune.yml --root {data_root}',
pythonPath: '',
exportBVH: true
};
});
ipcMain.handle('set-easymocap-options', async (_e, opts) => {
const s = await getSettings();
s.easymocap = Object.assign({}, s.easymocap || {}, opts);
await setSettings(s);
return true;
});
ipcMain.handle('cancel-processing', async () => {
if (!currentJob.provider) return false;
if (currentJob.provider === 'openpose') {
try { await openPoseWrapper.stop(); } catch {}
currentJob = { provider: null, jobId: null };
return true;
}
if (currentJob.provider === 'easymocap') {
const inst = providers.get('easymocap')?.instance;
if (inst) inst.cancel(currentJob.jobId);
currentJob = { provider: null, jobId: null };
return true;
}
return false;
});
// --- END IPC Handlers ---