-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
597 lines (518 loc) · 18.8 KB
/
main.js
File metadata and controls
597 lines (518 loc) · 18.8 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
// ─────────────────────────────────────────────────────────────────────────────
// main.js — Electron + FFmpeg two-pass encoding, reorganized for clarity
// ─────────────────────────────────────────────────────────────────────────────
const {
app,
BrowserWindow,
ipcMain,
dialog,
shell,
Notification,
} = require("electron");
const path = require("path");
const fs = require("fs");
const { execFile, spawn } = require("child_process");
const checkDiskSpace = require("check-disk-space").default;
// ─────────────────────────────────────────────────────────────────────────────
// Globals
// ─────────────────────────────────────────────────────────────────────────────
let mainWindow;
let activeProcess = null;
let totalDuration = null;
let currentEncoding = null;
let isCanceled = false;
let passLogBase = null;
let encodingDir = null;
// Holds the calculated settings from analyze-file → start-encoding
const encodingSettings = {};
// Path to FFprobe/FFmpeg shipped in your app bundle
const isDev = !app.isPackaged;
// use ffmpeg-static (exports the exe path) in dev,
// and your extraResources copy in prod
const ffmpegPath = isDev
? require("ffmpeg-static")
: path.join(process.resourcesPath, "ffmpeg", "ffmpeg.exe");
// ffprobe-static ships an object with a `.path` property
const ffprobePath = isDev
? require("ffprobe-static").path
: path.join(process.resourcesPath, "ffmpeg", "ffprobe.exe");
// ─────────────────────────────────────────────────────────────────────────────
// Utility Functions
// ─────────────────────────────────────────────────────────────────────────────
/**
* Kill a process tree (Windows or POSIX).
*/
function killProcessTree(pid) {
if (!pid) return Promise.resolve();
return new Promise((resolve) => {
if (process.platform === "win32") {
const killer = spawn("taskkill", ["/pid", pid, "/t", "/f"]);
killer.on("close", () => resolve());
// ensure kill if taskkill hangs
setTimeout(() => {
killer.kill("SIGKILL");
resolve();
}, 2000);
} else {
try {
process.kill(-pid, "SIGKILL");
} catch {}
resolve();
}
});
}
/**
* Called whenever we start a new encoding or cancel:
* stops any in-flight FFmpeg, rejects promise, resets flags.
*/
async function cleanupEncoding() {
console.log("[main] cleanupEncoding called");
isCanceled = true;
if (activeProcess?.pid) {
console.log("[main] Killing process tree:", activeProcess.pid);
await killProcessTree(activeProcess.pid);
}
if (currentEncoding) {
currentEncoding.reject(new Error("Encoding canceled"));
currentEncoding = null;
}
activeProcess = null;
totalDuration = null;
// small delay so processes wind down
await new Promise((r) => setTimeout(r, 500));
// Cleanup log files if paths are available
if (passLogBase && encodingDir) {
console.log("[main] Deleting temp files from:", encodingDir, passLogBase);
await deletePassLogFiles(encodingDir, passLogBase);
} else {
console.warn(
"[main] ⚠ Skipping log cleanup—missing encodingDir or passLogBase",
);
}
// Optional: clear them for safety
passLogBase = null;
encodingDir = null;
}
/**
* Remove all temporary two-pass log files.
*/
async function deletePassLogFiles(dir, statsBase) {
console.log("[main] Attempting to delete temp files for:", statsBase);
const tempFiles = [
`${statsBase}`,
`${statsBase}.log`,
`${statsBase}.log.temp`,
`${statsBase}.log.cutree`,
`${statsBase}.log.cutree.temp`,
`${statsBase}-0`,
`${statsBase}-0.log`,
`${statsBase}-0.log.mbtree`,
`${statsBase}-0.log.mbtree.temp`,
];
const deletionPromises = tempFiles.map((tempPath) => {
const fullPath = path.join(dir, tempPath);
return fs.promises.unlink(fullPath).catch((err) => {
if (err.code !== "ENOENT") {
console.warn(`[main] Could not delete temp file: ${fullPath}`, err);
}
});
});
await Promise.allSettled(deletionPromises);
}
/**
* Convert "HH:MM:SS.ss" to seconds (float).
*/
function parseTime(str) {
const [h, m, s] = str.split(":").map(parseFloat);
return h * 3600 + m * 60 + s;
}
/**
* Check if there's enough free space for the output file.
*/
async function ensureEnoughDisk(dir, requiredBytes) {
const { free } = await checkDiskSpace(dir);
if (free < requiredBytes) {
throw new Error(
`Insufficient disk space. Need ${Math.ceil(requiredBytes / 1024 / 1024)} MB free.`,
);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// FFprobe + Settings Calculation
// ─────────────────────────────────────────────────────────────────────────────
ipcMain.handle("open-file-dialog", async () => {
const res = await dialog.showOpenDialog({
properties: ["openFile"],
filters: [{ name: "Videos", extensions: ["mp4", "mkv", "mov", "avi"] }],
});
return res.canceled ? null : res.filePaths[0];
});
ipcMain.handle("analyze-file", async (_, inputPath) => {
try {
// 1) Get file size
const inputSizeBytes = fs.statSync(inputPath).size;
// 2) Build ffprobe arguments
const ffprobeArgs = [
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height:format=duration",
"-of",
"json",
inputPath,
];
// 3) DEBUG: log the exact ffprobe command
const debugLogPath = path.join(app.getPath("userData"), "drinkme-log.txt");
fs.appendFileSync(
debugLogPath,
`[DEBUG] spawning ffprobe: ${ffprobePath} ${ffprobeArgs.join(" ")}\n`,
);
// 4) Run ffprobe
const { stdout } = await new Promise((res, rej) =>
execFile(ffprobePath, ffprobeArgs, (err, so) =>
err ? rej(err) : res({ stdout: so }),
),
);
// 5) DEBUG: capture ffprobe stdout
fs.appendFileSync(
debugLogPath,
`[DEBUG] ffprobe stdout: ${stdout.slice(0, 200)}\n`,
);
// 6) Parse metadata
const probe = JSON.parse(stdout);
const durationSec = parseFloat(probe.format.duration);
const width = probe.streams[0].width;
const height = probe.streams[0].height;
// 7) Compute encoding settings
const settings = calculateTargetBitrate({
inputSizeBytes,
durationSec,
resolution: { width, height },
});
encodingSettings[inputPath] = settings;
// 8) Build user-facing estimates
const rawMB = settings.targetSizeBytes / (1024 * 1024);
const estimatedSizeMB = Math.ceil(rawMB);
const estimatedOutputBytes = estimatedSizeMB * 1024 * 1024;
// 9) Warn if savings < 10MB
const savedMB = (inputSizeBytes - estimatedOutputBytes) / (1024 * 1024);
const warning =
savedMB < 10
? `This video is already highly compressed. This will only reduce the file by ~${savedMB.toFixed(1)} MB.`
: null;
// 10) Determine output path
const baseName = path.basename(inputPath, path.extname(inputPath));
const outputFile = path.join(
path.dirname(inputPath),
`${baseName}_SMALL.mp4`,
);
if (fs.existsSync(outputFile)) {
return {
error: `A file named “${path.basename(outputFile)}” already exists in this folder.`,
};
}
// 11) Return the results to renderer
return { ...settings, estimatedSizeMB, warning, outputFile };
} catch (err) {
// DEBUG: log the actual error
const logPath = path.join(app.getPath("userData"), "drinkme-log.txt");
fs.appendFileSync(logPath, `[DEBUG] ANALYZE ERROR: ${err.stack || err}\n`);
console.error("[main] analyze-file error:", err);
return { error: "Failed to analyze video." };
}
});
// ─────────────────────────────────────────────────────────────────────────────
// Two-Pass Encoding Workflow
// ─────────────────────────────────────────────────────────────────────────────
ipcMain.on("start-encoding", async (event, inputPath) => {
// 1) Make sure we have settings
if (!encodingSettings[inputPath]) {
return event.sender.send("encoding-error", "Missing encoding parameters");
}
// 2) Build file names & paths
const settings = encodingSettings[inputPath];
const dir = path.dirname(inputPath);
const baseName = path.basename(inputPath, path.extname(inputPath));
const safeBase = baseName.replace(/[^a-zA-Z0-9_-]/g, "_");
const statsBase = `${safeBase}_ffmpeg2pass`;
const nullSink = process.platform === "win32" ? "NUL" : "/dev/null";
// 3) Kill any prior runs _first_
await cleanupEncoding();
isCanceled = false;
// 4) Now assign the globals so they stick around until we cancel
passLogBase = statsBase;
encodingDir = dir;
// 5) Disk‐space check
try {
await ensureEnoughDisk(dir, settings.targetSizeBytes * 1.1);
} catch (err) {
return event.sender.send("encoding-error", err.message);
}
// 6) Launch the two‐pass encode
try {
const result = await twoPassEncode(
inputPath,
dir,
baseName,
statsBase,
nullSink,
settings,
);
// Show notification if unfocused
if (!mainWindow.isFocused()) {
const notification = new Notification({
title: "Encoding Complete",
body: `Your file "${baseName}_SMALL.mp4" is ready.`,
});
notification.on("click", () => {
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
mainWindow.focus();
});
notification.show();
}
currentEncoding = null;
console.log("[main] Encoding complete:", result);
mainWindow.webContents.send("encoding-complete", result);
} catch (err) {
console.error("[main] Encoding error:", err);
currentEncoding = null;
const channel = err.message.includes("canceled")
? "encoding-cancelled"
: "encoding-error";
mainWindow.webContents.send(channel, err.message);
}
});
/**
* Encapsulates the two-pass cycle as a Promise.
*/
function twoPassEncode(
inputPath,
dir,
baseName,
statsBase,
nullSink,
settings,
) {
const { videoKbps, audioBitrate, scaleFilter } = settings;
// build args for pass 1 or 2
const makeArgs = (pass) => {
const bannerFlags = ["-hide_banner", "-loglevel", "info"];
const common = [
...bannerFlags,
"-y",
"-i",
inputPath,
"-fflags",
"+genpts",
"-avoid_negative_ts",
"make_zero",
"-vf",
scaleFilter,
"-map",
"0:v:0",
"-c:v",
"libx265",
"-preset",
"ultrafast",
"-b:v",
`${videoKbps}k`,
"-pass",
`${pass}`,
"-passlogfile",
statsBase,
"-x265-params",
"pools=6:no-sao=1:log-level=error",
];
if (pass === 1) {
return [...common, "-an", "-f", "null", nullSink];
} else {
return [
...common,
"-map",
"0:a:0",
"-c:a",
"aac",
"-b:a",
`${audioBitrate}k`,
"-ar",
"48000",
"-ac",
"2",
path.join(dir, `${baseName}_SMALL.mp4`),
];
}
};
return new Promise((resolve, reject) => {
currentEncoding = { resolve, reject };
totalDuration = null;
function runPass(pass) {
if (isCanceled) {
deletePassLogFiles(dir, statsBase);
return reject(new Error("Encoding canceled"));
}
let args;
try {
args = makeArgs(pass);
} catch (err) {
deletePassLogFiles(dir, statsBase);
return reject(err);
}
console.log(`[main] Starting pass ${pass}`, args.join(" "));
activeProcess = spawn(ffmpegPath, args, {
cwd: dir,
detached: process.platform !== "win32",
});
const thisProc = activeProcess;
activeProcess.stdout.on("data", () => {});
// track progress from stderr
activeProcess.stderr.on("data", (data) => {
if (isCanceled || thisProc !== activeProcess) return;
const line = data.toString();
console.log(`[FFmpeg P${pass}]`, line.trim());
if (!totalDuration) {
const m = line.match(/Duration:\s*([\d:.]+)/);
if (m) totalDuration = parseTime(m[1]);
}
if (totalDuration) {
const tm = line.match(/time=([\d:.]+)/);
if (tm) {
const elapsed = parseTime(tm[1]);
const pct = Math.min(
100,
Math.round((elapsed / totalDuration) * 100),
);
mainWindow.webContents.send("encoding-progress", {
percent: pct,
pass,
});
}
}
});
activeProcess.on("close", (code) => {
if (thisProc !== activeProcess) return;
activeProcess = null;
// error or cancel → cleanup & reject
if (isCanceled || code !== 0) {
deletePassLogFiles(dir, statsBase);
const msg = isCanceled
? "Encoding canceled"
: `FFmpeg pass ${pass} failed: ${code}`;
return reject(new Error(msg));
}
// success path
if (pass === 1) {
runPass(2);
} else {
deletePassLogFiles(dir, statsBase);
resolve({
success: true,
outputFile: path.join(dir, `${baseName}_SMALL.mp4`),
});
}
});
activeProcess.on("error", (err) => {
if (thisProc !== activeProcess) return;
activeProcess = null;
if (!isCanceled) reject(err);
});
}
runPass(1);
});
}
// ─────────────────────────────────────────────────────────────────────────────
// Cancel & Show-In-Folder Handlers
// ─────────────────────────────────────────────────────────────────────────────
ipcMain.on("cancel-encoding", async () => {
console.log("[main] Cancel requested");
await cleanupEncoding();
mainWindow.webContents.send("encoding-cancelled");
});
ipcMain.on("show-in-folder", (_, filePath) => {
if (filePath) shell.showItemInFolder(filePath);
});
// ─────────────────────────────────────────────────────────────────────────────
// Bitrate Calculator (unchanged)
// ─────────────────────────────────────────────────────────────────────────────
function calculateTargetBitrate({
inputSizeBytes,
durationSec,
resolution = { width: 1920, height: 1080 },
}) {
// 1) Base ratio by file size
const sizeThresholds = [
{ bytes: 1_073_741_824, ratio: 0.1 },
{ bytes: 536_870_912, ratio: 0.12 },
];
let baseRatio = 0.15;
for (const t of sizeThresholds) {
if (inputSizeBytes > t.bytes) {
baseRatio = t.ratio;
break;
}
}
// 2) Duration boost
const mins = durationSec / 60;
let boost = mins > 45 ? 0.05 : mins < 20 ? 0.02 + (1 - mins / 20) * 0.03 : 0;
const retentionRatio = Math.min(0.2, baseRatio + boost);
// 3) Total kbps
const totalKbps = Math.round(
(inputSizeBytes * retentionRatio * 8) / durationSec / 1000,
);
// 4) Audio/video split
const audioBitrate = durationSec < 1800 ? 96 : 64;
const minVideoKbps = 850;
const videoKbps = Math.max(minVideoKbps, totalKbps - audioBitrate);
// 5) Scale filter
const pixels = resolution.width * resolution.height;
const scaleFilter = pixels > 1280 * 720 ? "scale=1080:720,fps=25" : "fps=25";
// 6) Final size estimate
const targetSizeBytes = Math.round(
((videoKbps + audioBitrate) * durationSec * 1000) / 8,
);
return { videoKbps, audioBitrate, totalKbps, targetSizeBytes, scaleFilter };
}
// ─────────────────────────────────────────────────────────────────────────────
// App Lifecycle
// ─────────────────────────────────────────────────────────────────────────────
function createWindow() {
mainWindow = new BrowserWindow({
width: 620,
height: 520,
icon: path.join(__dirname, "assets", "icon.ico"),
webPreferences: {
preload: path.join(__dirname, "src", "preload.js"),
contextIsolation: true,
nodeIntegration: false,
},
});
mainWindow.loadFile(path.join("src", "index.html"));
mainWindow.setTitle("DrinkMe");
if (!isDev) {
mainWindow.setMenu(null); // hide menu in production
}
mainWindow.webContents.on("before-input-event", (event, input) => {
if (input.control && input.shift && input.key.toLowerCase() === "i") {
event.preventDefault();
}
});
}
app.whenReady().then(() => {
// —————— DEBUG LOGGING ——————
const logPath = path.join(app.getPath("userData"), "drinkme-log.txt");
try {
fs.appendFileSync(
logPath,
`Resources path: ${process.resourcesPath}\n` +
`Resolved ffprobe path: ${ffprobePath}\n\n`,
);
} catch (err) {
console.error("💥 failed to write drinkme-log.txt", err);
}
// ——————————————————————
createWindow();
});