-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
271 lines (238 loc) · 9.44 KB
/
main.js
File metadata and controls
271 lines (238 loc) · 9.44 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
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const os = require('os');
const fs = require('fs');
const { spawn, execFile } = require('child_process');
const isDev = !app.isPackaged;
const BIN_DIR = isDev
? path.join(__dirname, 'bin')
: path.join(process.resourcesPath, 'bin');
const FFMPEG_BIN = path.join(BIN_DIR, 'ffmpeg.exe');
const FFPROBE_BIN = path.join(BIN_DIR, 'ffprobe.exe');
const FFPLAY_BIN = path.join(BIN_DIR, 'ffplay.exe');
const TRIM_EXE = isDev
? path.join(__dirname, 'trim.exe')
: path.join(process.resourcesPath, 'trim.exe');
// Fallback to trim.py when trim.exe not built (dev)
const TRIM_SCRIPT = path.join(__dirname, 'trim.py');
let mainWindow;
let currentProcess = null; // Store the active process (compress.exe or trim.exe / python trim.py)
let cancellationRequested = false; // true when user cancelled — avoid sending "exited with code" after "cancelled"
let currentOutputPath = null; // output file being written
function createWindow() {
// Increased height slightly to accommodate the logs
mainWindow = new BrowserWindow({
width: 600,
height: 900,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.loadFile('index.html');
}
app.whenReady().then(createWindow);
// --- 1. Handle Folder Selection Dialog (Restored from Old Code) ---
ipcMain.on('open-directory-dialog', async (event) => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (!result.canceled) {
// Send the selected path back to the renderer (index.html)
event.sender.send('selected-directory', result.filePaths[0]);
}
});
// --- 1a. Open a folder in the OS file explorer ---
ipcMain.on('open-folder', (event, folderPath) => {
if (!folderPath) return;
shell.openPath(folderPath);
});
// --- 1b. Video Info for Estimation (duration, etc.) ---
ipcMain.handle('get-video-info', async (event, inputPath) => {
return new Promise((resolve) => {
if (!inputPath || !FFPROBE_BIN) {
return resolve({ error: 'No input path or ffprobe missing' });
}
execFile(
FFPROBE_BIN,
['-v', 'error', '-show_entries', 'format=duration', '-of', 'json', inputPath],
(err, stdout) => {
if (err) {
return resolve({ error: err.message });
}
try {
const data = JSON.parse(stdout);
const duration = parseFloat(data.format?.duration || '0');
if (!duration || Number.isNaN(duration)) {
return resolve({ error: 'Could not read duration' });
}
resolve({ duration });
} catch (e) {
resolve({ error: 'Failed to parse ffprobe output' });
}
}
);
});
});
// --- 1c. Generate Thumbnail via ffmpeg (temporary file) ---
ipcMain.handle('generate-thumbnail', async (event, inputPath) => {
return new Promise((resolve) => {
if (!inputPath || !FFMPEG_BIN) {
return resolve({ error: 'No input path or ffmpeg missing' });
}
const tmpDir = os.tmpdir();
const thumbPath = path.join(
tmpDir,
`vc_thumb_${Date.now()}_${Math.random().toString(36).slice(2)}.jpg`
);
// Grab a frame at 10% into the video (or 1s for very short clips)
const args = ['-y', '-ss', '1', '-i', inputPath, '-frames:v', '1', '-qscale:v', '2', thumbPath];
execFile(FFMPEG_BIN, args, (err) => {
if (err) {
return resolve({ error: err.message });
}
resolve({ path: thumbPath });
});
});
});
// --- 2. Start Compression ---
ipcMain.on('start-compression', (event, data) => {
// We now accept inputPath AND outputPath (for batch or single file flexibility)
const { inputPath, outputPath, sizeLimit, qualityLevel, fps } = data;
const compressorExe = isDev
? path.join(__dirname, 'compress.exe')
: path.join(process.resourcesPath, 'compress.exe');
cancellationRequested = false;
currentOutputPath = outputPath;
if (currentProcess) {
try { currentProcess.kill(); } catch(e) {}
}
console.log(`Starting: ${inputPath} -> ${outputPath}`);
const args = [inputPath, outputPath, sizeLimit, qualityLevel, fps === 60 ? '60' : '30'];
currentProcess = spawn(compressorExe, args);
currentProcess.stdout.on('data', (data) => {
const str = data.toString();
const lines = str.split('\n');
lines.forEach(line => {
// Robust JSON parsing from the new code
if (line.includes("JSON:")) {
try {
const jsonStr = line.split("JSON:")[1].trim();
const json = JSON.parse(jsonStr);
event.sender.send('log', json);
} catch (e) {
console.error("JSON Parse Error:", e);
}
}
});
});
currentProcess.stderr.on('data', (data) => {
const errStr = data.toString();
// Ignore FFmpeg frame progress info, only show real errors
if (errStr.toLowerCase().includes("error") && !errStr.includes("frame=")) {
event.sender.send('log', { status: 'stderr', msg: errStr });
}
});
currentProcess.on('close', (code) => {
if (code === 0) {
event.sender.send('log', { status: 'done', path: outputPath });
} else if (code !== null && !cancellationRequested) {
event.sender.send('log', { status: 'error', msg: `Process exited with code ${code}` });
}
if (cancellationRequested) cancellationRequested = false;
currentOutputPath = null;
currentProcess = null;
});
});
// --- 2b. Start Trim (trim.exe or fallback: python trim.py) ---
ipcMain.on('start-trim', (event, data) => {
const { inputPath, outputPath, startSec, endSec } = data;
cancellationRequested = false;
currentOutputPath = outputPath;
if (currentProcess) {
try { currentProcess.kill(); } catch (e) {}
}
const args = [inputPath, outputPath, String(startSec), String(endSec)];
const useExe = fs.existsSync(TRIM_EXE);
const cmd = useExe ? TRIM_EXE : (process.platform === 'win32' ? 'py' : 'python3');
const cmdArgs = useExe ? args : [TRIM_SCRIPT, ...args];
console.log(`Trim: ${cmd} ${cmdArgs.join(' ')}`);
currentProcess = spawn(cmd, cmdArgs, useExe ? {} : { cwd: __dirname });
currentProcess.stdout.on('data', (data) => {
const str = data.toString();
str.split('\n').forEach(line => {
if (line.includes('JSON:')) {
try {
const jsonStr = line.split('JSON:')[1].trim();
const json = JSON.parse(jsonStr);
event.sender.send('log', json);
} catch (e) {
console.error('Trim JSON parse error:', e);
}
}
});
});
currentProcess.stderr.on('data', (data) => {
const errStr = data.toString();
if (errStr.trim()) {
event.sender.send('log', { status: 'stderr', msg: errStr });
}
});
currentProcess.on('close', (code) => {
if (code === 0) {
event.sender.send('log', { status: 'done', path: outputPath });
} else if (code !== null && !cancellationRequested) {
event.sender.send('log', { status: 'error', msg: `Trim process exited with code ${code}` });
}
if (cancellationRequested) cancellationRequested = false;
currentOutputPath = null;
currentProcess = null;
});
currentProcess.on('error', (err) => {
event.sender.send('log', { status: 'error', msg: `Failed to start trim: ${err.message}. Build trim.exe (npm run build-trim) or install Python and run: pip install smartcut` });
currentProcess = null;
});
});
// --- 3. Cancel Compression ---
ipcMain.on('cancel-compression', (event) => {
if (currentProcess) {
cancellationRequested = true;
const pid = currentProcess.pid;
if (process.platform === 'win32') {
require('child_process').exec(`taskkill /pid ${pid} /T /F`);
} else {
currentProcess.kill();
}
currentOutputPath = null;
currentProcess = null;
event.sender.send('log', { status: 'cancelled' });
}
});
// --- 3b. Cancel Trim ---
ipcMain.on('cancel-trim', (event) => {
if (currentProcess) {
cancellationRequested = true;
const pid = currentProcess.pid;
if (process.platform === 'win32') {
require('child_process').exec(`taskkill /pid ${pid} /T /F`);
} else {
currentProcess.kill();
}
currentOutputPath = null;
currentProcess = null;
event.sender.send('log', { status: 'cancelled' });
}
});
// --- 4. Playback via ffplay (original / compressed) ---
ipcMain.on('play-video', (event, filePath) => {
if (!filePath) {
event.sender.send('log', { status: 'error', msg: 'No file to play.' });
return;
}
const player = spawn(FFPLAY_BIN, ['-autoexit', filePath], {
windowsHide: false
});
player.on('error', (err) => {
event.sender.send('log', { status: 'error', msg: `ffplay error: ${err.message}` });
});
});