-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
228 lines (198 loc) · 7.77 KB
/
Copy pathmain.js
File metadata and controls
228 lines (198 loc) · 7.77 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
const { app, BrowserWindow, ipcMain, shell } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
const fs = require('fs');
let ffmpegPath;
try {
ffmpegPath = require('ffmpeg-static');
// electron-builder extracts asarUnpack files to app.asar.unpacked/,
// but require() still returns the path inside app.asar (not executable).
// Replace so the binary can actually be spawned in the packaged app.
if (app.isPackaged) {
ffmpegPath = ffmpegPath.replace('app.asar', 'app.asar.unpacked');
}
} catch {
ffmpegPath = 'ffmpeg';
}
// Binary confirmed to have h264_nvenc — set during detection
let nvencFfmpegPath = null;
// Track active ffmpeg processes so we can cancel them
const activeProcesses = new Map();
// ─── Helpers ───────────────────────────────────────────────────────────────
// Ask Windows 'where' for every ffmpeg on PATH (handles winget, choco, scoop, manual)
function findFfmpegOnPath() {
return new Promise((resolve) => {
const proc = spawn('where', ['ffmpeg'], { shell: true, windowsHide: true });
let out = '';
proc.stdout?.on('data', (d) => { out += d.toString(); });
proc.on('close', () => {
const found = out.trim().split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
resolve(found);
});
proc.on('error', () => resolve([]));
});
}
// Returns true if the given binary lists h264_nvenc in its encoder table
function hasNvencEncoder(binary) {
return new Promise((resolve) => {
const proc = spawn(binary, ['-hide_banner', '-encoders'], { windowsHide: true });
let out = '';
proc.stdout?.on('data', (d) => { out += d.toString(); });
proc.stderr?.on('data', (d) => { out += d.toString(); });
proc.on('close', () => resolve(out.includes('h264_nvenc')));
proc.on('error', () => resolve(false));
});
}
// ─── Window ────────────────────────────────────────────────────────────────
function createWindow() {
const win = new BrowserWindow({
width: 860,
height: 720,
minWidth: 640,
minHeight: 500,
backgroundColor: '#0d1117',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
},
show: false,
});
win.loadFile('index.html');
win.once('ready-to-show', () => win.show());
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
for (const proc of activeProcesses.values()) {
try { proc.kill(); } catch {}
}
if (process.platform !== 'darwin') app.quit();
});
// ─── Detect NVENC ──────────────────────────────────────────────────────────
ipcMain.handle('detect-nvenc', async () => {
// 1. Find every ffmpeg on PATH (catches winget, chocolatey, scoop, manual PATH adds)
const pathBinaries = await findFfmpegOnPath();
// 2. Hardcoded fallback locations for common Windows installs
const hardcoded = [
ffmpegPath,
'C:\\ProgramData\\chocolatey\\bin\\ffmpeg.exe',
path.join(process.env.USERPROFILE || '', 'scoop', 'apps', 'ffmpeg', 'current', 'bin', 'ffmpeg.exe'),
'C:\\ffmpeg\\bin\\ffmpeg.exe',
'C:\\tools\\ffmpeg\\bin\\ffmpeg.exe',
path.join(process.env.ProgramFiles || '', 'ffmpeg', 'bin', 'ffmpeg.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Programs', 'ffmpeg', 'bin', 'ffmpeg.exe'),
];
// PATH-found binaries take priority; deduplicate falsy/duplicates
const candidates = [...pathBinaries, ...hardcoded]
.filter((v, i, a) => v && a.indexOf(v) === i);
for (const binary of candidates) {
const ok = await hasNvencEncoder(binary);
if (ok) {
nvencFfmpegPath = binary;
return true;
}
}
nvencFfmpegPath = null;
return false;
});
// ─── Compress a single video ───────────────────────────────────────────────
ipcMain.handle('compress-video', async (event, { id, filePath, crf, preset, useGpu, cq, nvencPreset, copyMetadata }) => {
const ext = path.extname(filePath);
const dir = path.dirname(filePath);
const basename = path.basename(filePath, ext);
const outputPath = path.join(dir, `${basename}_cpd.mp4`);
function runCompress(withGpu) {
return new Promise((resolve, reject) => {
const metaFlags = copyMetadata
? ['-map_metadata', '0']
: ['-map_metadata', '-1'];
const args = withGpu
? [
'-i', filePath,
...metaFlags,
'-c:v', 'h264_nvenc',
'-preset', nvencPreset,
'-rc', 'vbr',
'-cq', String(cq),
'-b:v', '0',
'-maxrate', '8M',
'-bufsize', '16M',
'-c:a', 'aac',
'-b:a', '128k',
'-movflags', '+faststart',
'-y',
outputPath,
]
: [
'-i', filePath,
...metaFlags,
'-c:v', 'libx264',
'-crf', String(crf),
'-preset', preset,
'-c:a', 'aac',
'-b:a', '128k',
'-movflags', '+faststart',
'-y',
outputPath,
];
const binary = withGpu && nvencFfmpegPath ? nvencFfmpegPath : ffmpegPath;
const proc = spawn(binary, args, { windowsHide: true });
activeProcesses.set(id, proc);
let duration = 0;
let stderrBuf = '';
proc.stderr.on('data', (chunk) => {
const str = chunk.toString();
stderrBuf += str;
if (!duration) {
const m = str.match(/Duration:\s*(\d+):(\d+):(\d+\.?\d*)/);
if (m) {
duration = parseInt(m[1]) * 3600 + parseInt(m[2]) * 60 + parseFloat(m[3]);
}
}
const t = str.match(/time=(\d+):(\d+):(\d+\.?\d*)/);
if (t && duration > 0) {
const current = parseInt(t[1]) * 3600 + parseInt(t[2]) * 60 + parseFloat(t[3]);
const pct = Math.min(Math.round((current / duration) * 100), 99);
event.sender.send('compression-progress', { id, progress: pct });
}
});
proc.on('close', (code) => {
activeProcesses.delete(id);
if (code === 0) {
const originalSize = fs.statSync(filePath).size;
let compressedSize = 0;
try { compressedSize = fs.statSync(outputPath).size; } catch {}
resolve({ success: true, outputPath, originalSize, compressedSize });
} else {
reject(new Error(`FFmpeg exited with code ${code}`));
}
});
proc.on('error', (err) => {
activeProcesses.delete(id);
reject(new Error(`Could not start FFmpeg: ${err.message}`));
});
});
}
// GPU mode: try NVENC first, auto-fall back to CPU on any failure
if (useGpu) {
try {
return await runCompress(true);
} catch {
event.sender.send('nvenc-fallback', { id });
return runCompress(false);
}
}
return runCompress(false);
});
// ─── Cancel a compression ──────────────────────────────────────────────────
ipcMain.on('cancel-compression', (_event, { id }) => {
const proc = activeProcesses.get(id);
if (proc) {
try { proc.kill(); } catch {}
activeProcesses.delete(id);
}
});
// ─── Reveal output file in Explorer / Finder ──────────────────────────────
ipcMain.on('reveal-file', (_event, { filePath }) => {
shell.showItemInFolder(filePath);
});