@ponderdev/justfits 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.cjs ADDED
@@ -0,0 +1,270 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Driving ffmpeg.
5
+ *
6
+ * Knows nothing about Electron, so the whole compression path can be run and
7
+ * tested from a plain node script. main.cjs supplies the binary paths and
8
+ * turns the callbacks into IPC.
9
+ *
10
+ * The original file is only ever read. Everything is written to a new path.
11
+ */
12
+
13
+ const { spawn } = require('node:child_process');
14
+ const fs = require('node:fs');
15
+ const os = require('node:os');
16
+ const path = require('node:path');
17
+
18
+ const plan = require('./plan.js');
19
+
20
+ const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
21
+
22
+ // The first go is the plan; the rest correct for what x264 actually produced,
23
+ // which varies with how hard the footage is to compress.
24
+ const MAX_ATTEMPTS = 3;
25
+
26
+ /** A handle the caller can cancel through. */
27
+ function control() {
28
+ return { child: null, cancelled: false, cancel() {
29
+ this.cancelled = true;
30
+ if (this.child) this.child.kill();
31
+ } };
32
+ }
33
+
34
+ function run(bin, args, { onProgress, durationSec, ctl } = {}) {
35
+ return new Promise((resolve, reject) => {
36
+ const child = spawn(bin, args, { windowsHide: true });
37
+ if (ctl) ctl.child = child;
38
+ let stderr = '';
39
+
40
+ child.stdout.on('data', (chunk) => {
41
+ if (!onProgress || !durationSec) return;
42
+ // -progress emits key=value lines, which beats scraping the banner.
43
+ for (const line of String(chunk).split('\n')) {
44
+ const m = /^out_time_us=(\d+)/.exec(line.trim());
45
+ if (m) onProgress(Math.max(0, Math.min(1, Number(m[1]) / 1e6 / durationSec)));
46
+ }
47
+ });
48
+
49
+ // Keep the tail only. A failing ffmpeg says why in the last few lines and
50
+ // a working one can produce megabytes we would otherwise hold in memory.
51
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000); });
52
+
53
+ child.on('error', reject);
54
+ child.on('close', (code) => {
55
+ if (ctl) ctl.child = null;
56
+ if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
57
+ if (code !== 0) {
58
+ const why = stderr.trim().split('\n').filter(Boolean).slice(-3).join('\n');
59
+ return reject(new Error(why || `ffmpeg exited with ${code}`));
60
+ }
61
+ resolve();
62
+ });
63
+ });
64
+ }
65
+
66
+ function ffprobeOut(ffprobe, args) {
67
+ return new Promise((resolve, reject) => {
68
+ const child = spawn(ffprobe, args, { windowsHide: true });
69
+ let out = '';
70
+ let err = '';
71
+ child.stdout.on('data', (c) => { out += c; });
72
+ child.stderr.on('data', (c) => { err += c; });
73
+ child.on('error', reject);
74
+ // ffprobe's own lines carry a demuxer tag and a memory address
75
+ // ("[mov,mp4,... @ 0x1234] moov atom not found"), which changes every run
76
+ // and means nothing to a person or a script; the line after it says why.
77
+ const reason = () => err.split('\n').map((l) => l.trim())
78
+ .filter((l) => l && !/^\[[^\]]* @ 0x[0-9a-f]+\]/i.test(l)).pop();
79
+ child.on('close', (code) => (code === 0 ? resolve(out) : reject(new Error(reason() || 'Could not read that file'))));
80
+ });
81
+ }
82
+
83
+ // "00:01:02.500000000", as Matroska writes its DURATION tag.
84
+ function clockSeconds(value) {
85
+ const m = /^(\d+):(\d+):(\d+(?:\.\d+)?)$/.exec(String(value || '').trim());
86
+ return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : 0;
87
+ }
88
+
89
+ // The last packet's timestamp. Only reached for files whose header carries no
90
+ // duration at all (a webm recorded live by a browser), so the cost of reading
91
+ // every packet header is paid only when there is no other way to know.
92
+ async function scanDuration(ffprobe, file) {
93
+ try {
94
+ const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', 'v:0',
95
+ '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file]);
96
+ let last = 0;
97
+ for (const line of packets.split('\n')) {
98
+ const t = Number(line.split(',')[0]);
99
+ if (Number.isFinite(t) && t > last) last = t;
100
+ }
101
+ return last;
102
+ } catch {
103
+ return 0;
104
+ }
105
+ }
106
+
107
+ async function probe(ffprobe, file) {
108
+ const json = await ffprobeOut(ffprobe, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', file]);
109
+
110
+ const info = JSON.parse(json);
111
+ const streams = info.streams || [];
112
+ // Cover art in an mp3 or m4a is a video stream too, but it is not the
113
+ // picture anyone means to send, so it never counts as one.
114
+ const video = streams.find((s) => s.codec_type === 'video' && !(s.disposition && s.disposition.attached_pic));
115
+ const audio = streams.find((s) => s.codec_type === 'audio');
116
+ if (!video) throw new Error('There is no picture in that file');
117
+
118
+ const imageFormat = /^(image2|png_pipe|jpeg_pipe|webp_pipe)/.test((info.format && info.format.format_name) || '');
119
+ let durationSec = Number(info.format && info.format.duration) ||
120
+ Number(video.duration) ||
121
+ clockSeconds(video.tags && (video.tags.DURATION || video.tags.duration)) || 0;
122
+ // No duration in the header does not make a video a still: a live-recorded
123
+ // webm has none, and treating it as an image turned it into one JPEG frame.
124
+ if (!durationSec && !imageFormat && video.nb_frames !== '1') {
125
+ durationSec = await scanDuration(ffprobe, file);
126
+ }
127
+ // A still is a video stream with no duration and a single frame.
128
+ const still = !durationSec || video.nb_frames === '1' || imageFormat;
129
+
130
+ // Phones store portrait video landscape with a rotation flag, and ffmpeg
131
+ // rotates before the scale filter runs, so plan in the shape that is shown
132
+ // or a portrait clip gets squashed into a landscape frame.
133
+ const sideRotation = (video.side_data_list || []).find((d) => d.rotation !== undefined);
134
+ const rotation = Number(sideRotation ? sideRotation.rotation : (video.tags && video.tags.rotate)) || 0;
135
+ const sideways = Math.abs(Math.round(rotation)) % 180 === 90;
136
+
137
+ const [num, den] = String(video.r_frame_rate || '30/1').split('/').map(Number);
138
+ const fps = den ? num / den : 30;
139
+
140
+ return {
141
+ kind: still ? 'image' : 'video',
142
+ durationSec,
143
+ width: Number(sideways ? video.height : video.width) || 0,
144
+ height: Number(sideways ? video.width : video.height) || 0,
145
+ fps: Number.isFinite(fps) && fps > 0 ? fps : 30,
146
+ hasAudio: Boolean(audio),
147
+ bytes: fs.statSync(file).size,
148
+ };
149
+ }
150
+
151
+ /*
152
+ * Beside the original, never over it. The source is the one file here that
153
+ * cannot be recreated, so it is never a candidate for the output path.
154
+ */
155
+ function outputPath(source, ext, exists = fs.existsSync) {
156
+ const dir = path.dirname(source);
157
+ const base = path.basename(source, path.extname(source));
158
+ let candidate = path.join(dir, `${base}-fits${ext}`);
159
+ for (let n = 2; exists(candidate) && n < 1000; n++) {
160
+ candidate = path.join(dir, `${base}-fits ${n}${ext}`);
161
+ }
162
+ return candidate;
163
+ }
164
+
165
+ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress = () => {}, ctl = control() }) {
166
+ const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.mp4');
167
+ const logFile = path.join(os.tmpdir(), `justfits-${process.pid}-${Date.now()}`);
168
+ let correction = 1;
169
+ let result = null;
170
+ let lastPlan = null;
171
+
172
+ try {
173
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
174
+ const p = plan.planVideo({ ...info, targetBytes, correction });
175
+ // At the floors a smaller correction changes nothing, and encoding the
176
+ // same plan again only repeats a slow two-pass for the same result.
177
+ const key = [p.width, p.height, p.fps, p.videoKbps, p.audioKbps, p.audioChannels].join(',');
178
+ if (key === lastPlan) break;
179
+ lastPlan = key;
180
+
181
+ const filters = [];
182
+ if (p.width !== info.width || p.height !== info.height) {
183
+ filters.push(`scale=${p.width}:${p.height}:flags=lanczos`);
184
+ }
185
+ if (Math.abs(p.fps - info.fps) > 0.01) filters.push(`fps=${p.fps}`);
186
+
187
+ const common = [
188
+ '-hide_banner', '-nostats', '-progress', 'pipe:1', '-y',
189
+ '-i', file,
190
+ '-c:v', 'libx264', '-b:v', `${p.videoKbps}k`,
191
+ '-preset', 'slow', '-pix_fmt', 'yuv420p',
192
+ ...(filters.length ? ['-vf', filters.join(',')] : []),
193
+ // Scoped to the video stream. Unscoped, -pass also reaches the audio
194
+ // encoder in pass 2, and the Windows ffmpeg build then looks for a
195
+ // two-pass log for the audio, finds none, and fails the encode.
196
+ '-passlogfile:v', logFile,
197
+ ];
198
+
199
+ // Two passes, because hitting a size is precisely what two-pass is for.
200
+ // The first sees the whole clip so the second can spend the budget
201
+ // where the picture actually needs it.
202
+ await run(ffmpeg, [...common, '-pass:v', '1', '-an', '-f', 'mp4', NULL_DEVICE], {
203
+ durationSec: info.durationSec, ctl,
204
+ onProgress: (v) => onProgress({ stage: 'Looking at the video', progress: v * 0.35, attempt }),
205
+ });
206
+
207
+ const audioArgs = p.audioKbps
208
+ ? ['-c:a', 'aac', '-b:a', `${p.audioKbps}k`, '-ac', String(p.audioChannels)]
209
+ : ['-an'];
210
+
211
+ await run(ffmpeg, [...common, '-pass:v', '2', ...audioArgs, '-movflags', '+faststart', out], {
212
+ durationSec: info.durationSec, ctl,
213
+ onProgress: (v) => onProgress({ stage: 'Compressing', progress: 0.35 + v * 0.65, attempt }),
214
+ });
215
+
216
+ const bytes = fs.statSync(out).size;
217
+ result = { path: out, bytes, plan: p, attempts: attempt + 1 };
218
+ if (bytes <= targetBytes) return result;
219
+
220
+ // Overshot. Measure by how much and aim lower rather than guess again.
221
+ correction = plan.correctionFor(bytes, targetBytes, correction);
222
+ }
223
+ } catch (err) {
224
+ // A cancelled or failed encode leaves a half-written file under a name
225
+ // that says it fits. Nothing should be left that looks sendable.
226
+ try { fs.unlinkSync(out); } catch {}
227
+ // Fedora's default ffmpeg and other LGPL builds have no x264, and ffmpeg's
228
+ // own wording for that does not say what to do about it.
229
+ if (/Unknown encoder 'libx264'/.test(err.message) && !err.cancelled) {
230
+ throw new Error(`This ffmpeg has no H.264 encoder (libx264), which video needs. Install a full ffmpeg build.\n${err.message}`);
231
+ }
232
+ throw err;
233
+ } finally {
234
+ for (const suffix of ['-0.log', '-0.log.mbtree', '.log', '.log.mbtree']) {
235
+ try { fs.unlinkSync(logFile + suffix); } catch {}
236
+ }
237
+ }
238
+
239
+ return { ...result, over: true };
240
+ }
241
+
242
+ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, onProgress = () => {}, ctl = control() }) {
243
+ const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.jpg');
244
+ let result = null;
245
+
246
+ for (let attempt = 0; attempt < 5; attempt++) {
247
+ const p = plan.planImage({ targetBytes, width: info.width, height: info.height, attempt });
248
+ onProgress({ stage: attempt ? 'Trying harder' : 'Compressing', progress: attempt / 5, attempt });
249
+
250
+ try {
251
+ await run(ffmpeg, [
252
+ '-hide_banner', '-nostats', '-y', '-i', file,
253
+ '-vf', `scale=${p.width}:${p.height}:flags=lanczos`,
254
+ '-q:v', String(p.quality), out,
255
+ ], { ctl });
256
+ } catch (err) {
257
+ // Same as video: no half-written file left behind under a "fits" name.
258
+ try { fs.unlinkSync(out); } catch {}
259
+ throw err;
260
+ }
261
+
262
+ const bytes = fs.statSync(out).size;
263
+ result = { path: out, bytes, plan: p, attempts: attempt + 1 };
264
+ if (bytes <= targetBytes) return result;
265
+ }
266
+
267
+ return { ...result, over: true };
268
+ }
269
+
270
+ module.exports = { control, probe, outputPath, fitVideo, fitImage, MAX_ATTEMPTS };
package/src/main.cjs ADDED
@@ -0,0 +1,189 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Just Fits: makes a file small enough to send.
5
+ *
6
+ * This file is only wiring. The arithmetic is in plan.js and the ffmpeg work
7
+ * is in engine.cjs, both of which run without Electron so they can be tested
8
+ * directly.
9
+ *
10
+ * Two rules hold throughout: the original file is only ever read, and the app
11
+ * never touches the network.
12
+ */
13
+
14
+ const { app, BrowserWindow, screen, ipcMain, dialog, shell } = require('electron');
15
+ const path = require('node:path');
16
+ const fs = require('node:fs');
17
+
18
+ const engine = require('./engine.cjs');
19
+ const plan = require('./plan.js');
20
+ const binaries = require('./binaries.cjs');
21
+
22
+ let win = null;
23
+ let ctl = null;
24
+ let licenceWindow = null;
25
+
26
+ // Windows starts an Open window in Downloads, which is usually empty and,
27
+ // filtered to video and images, shows nothing at all. So it starts where the
28
+ // last file came from instead, by dialog or by drop, else in Documents.
29
+ let lastOpenDir = null;
30
+
31
+ /* --- the bundled binaries --------------------------------------------- */
32
+
33
+ function vendorDir() {
34
+ return app.isPackaged
35
+ ? path.join(process.resourcesPath, 'ffmpeg')
36
+ : path.join(__dirname, '..', 'vendor', 'ffmpeg');
37
+ }
38
+
39
+ // The app must never fall back to a system ffmpeg: someone who downloaded a
40
+ // finished app should not discover it needs a video encoder installing. The
41
+ // command line is the opposite and does fall back, which is why the two share
42
+ // a resolver with a flag rather than each having their own.
43
+ function binary(name) {
44
+ return binaries.resolve(name, [vendorDir()], false);
45
+ }
46
+
47
+ /* --- wiring ------------------------------------------------------------ */
48
+
49
+ /*
50
+ * Exported so test/window.test.cjs can register the same handlers against its
51
+ * own window. Without that the test would be checking a renderer that has
52
+ * nothing to talk to, and would miss a handler going missing here.
53
+ */
54
+ function registerHandlers() {
55
+ ipcMain.handle('targets', () => plan.TARGETS);
56
+
57
+ ipcMain.handle('probe', async (_e, file) => {
58
+ let ffprobe;
59
+ try {
60
+ ffprobe = binary('ffprobe');
61
+ } catch (err) {
62
+ return { ok: false, message: String(err.message || err) };
63
+ }
64
+ try {
65
+ const info = await engine.probe(ffprobe, file);
66
+ lastOpenDir = path.dirname(file);
67
+ return { ok: true, info };
68
+ } catch (err) {
69
+ return { ok: false, message: probeMessage(file, String(err.message || err)) };
70
+ }
71
+ });
72
+
73
+ ipcMain.handle('fit', async (_e, { file, targetBytes }) => {
74
+ ctl = engine.control();
75
+ const onProgress = (p) => {
76
+ if (win && !win.isDestroyed()) win.webContents.send('progress', p);
77
+ };
78
+ try {
79
+ const info = await engine.probe(binary('ffprobe'), file);
80
+ const args = { ffmpeg: binary('ffmpeg'), file, info, targetBytes, onProgress, ctl };
81
+ const result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
82
+ return { ok: true, ...result, before: info.bytes, kind: info.kind };
83
+ } catch (err) {
84
+ if (err && err.cancelled) return { ok: false, cancelled: true };
85
+ return { ok: false, message: String(err.message || err) };
86
+ } finally {
87
+ ctl = null;
88
+ }
89
+ });
90
+
91
+ ipcMain.handle('cancel', () => {
92
+ if (!ctl) return false;
93
+ ctl.cancel();
94
+ return true;
95
+ });
96
+
97
+ ipcMain.handle('reveal', (_e, file) => shell.showItemInFolder(file));
98
+
99
+ // Opens in the real browser, never in an app window.
100
+ ipcMain.handle('open-site', () => shell.openExternal('https://ponderdev.com'));
101
+
102
+ // The GPL wants its notices readable by whoever has the app, not just by
103
+ // whoever finds the repo, so they open in a window of their own.
104
+ ipcMain.handle('open-licences', () => {
105
+ if (licenceWindow && !licenceWindow.isDestroyed()) return licenceWindow.focus();
106
+ licenceWindow = new BrowserWindow({
107
+ width: 720,
108
+ height: 680,
109
+ title: 'Licences and credits',
110
+ backgroundColor: '#12131a',
111
+ webPreferences: { contextIsolation: true, nodeIntegration: false },
112
+ });
113
+ licenceWindow.setMenuBarVisibility(false);
114
+ licenceWindow.loadFile(path.join(__dirname, 'renderer', 'licenses.html'));
115
+ });
116
+
117
+ ipcMain.handle('pick-file', async () => {
118
+ const r = await dialog.showOpenDialog(win, {
119
+ defaultPath: lastOpenDir || app.getPath('documents'),
120
+ properties: ['openFile'],
121
+ filters: [{
122
+ name: 'Video and images',
123
+ extensions: ['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'jpg', 'jpeg', 'png', 'heic', 'webp', 'gif'],
124
+ }],
125
+ });
126
+ if (r.canceled) return null;
127
+ lastOpenDir = path.dirname(r.filePaths[0]);
128
+ return r.filePaths[0];
129
+ });
130
+ }
131
+
132
+ // ffprobe's reason starts with the whole path ("C:\Users\...\clip.mp4:
133
+ // Invalid data found when processing input"), which in the window is long,
134
+ // technical and wraps across the error box. The window says it as a sentence
135
+ // that names the file. The command line keeps ffprobe's words, for scripts.
136
+ function probeMessage(file, reason) {
137
+ const name = path.basename(String(file || ''));
138
+ if (/no such file/i.test(reason)) return `Could not find ${name}. It may have been moved or deleted.`;
139
+ if (/permission denied|operation not permitted/i.test(reason)) return `Just Fits is not allowed to open ${name}.`;
140
+ return `${name} is not a video or picture that Just Fits can read.`;
141
+ }
142
+
143
+
144
+ // A laptop at 1366x768 has about 728 pixels of height left for a window once
145
+ // the taskbar (or the menu bar and Dock) is taken off, and a window opened
146
+ // taller than that put the bottom of the screen, the main button included,
147
+ // out of reach under the taskbar. So the window, and its minimum, are fitted
148
+ // to the work area of the screen it opens on.
149
+ function fitToScreen(opts) {
150
+ const area = screen.getPrimaryDisplay().workAreaSize;
151
+ const fit = { ...opts };
152
+ for (const [key, side] of [['width', 'width'], ['height', 'height'], ['minWidth', 'width'], ['minHeight', 'height']]) {
153
+ if (typeof fit[key] === 'number') fit[key] = Math.min(fit[key], area[side]);
154
+ }
155
+ return fit;
156
+ }
157
+
158
+ function createWindow() {
159
+ win = new BrowserWindow(fitToScreen({
160
+ width: 720,
161
+ height: 780,
162
+ minWidth: 560,
163
+ minHeight: 640,
164
+ backgroundColor: '#12131a',
165
+ titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
166
+ webPreferences: {
167
+ preload: path.join(__dirname, 'preload.cjs'),
168
+ contextIsolation: true,
169
+ nodeIntegration: false,
170
+ },
171
+ }));
172
+ win.setMenuBarVisibility(false);
173
+ win.loadFile(path.join(__dirname, 'renderer', 'index.html'));
174
+ }
175
+
176
+ // Guarded so requiring this file from a test registers the handlers without
177
+ // also opening a window. An env var rather than require.main, because under
178
+ // `electron .` from source Electron does not make this file require.main, so
179
+ // that check opened nothing.
180
+ if (process.env.JUST_TEST_NO_WINDOW !== '1') {
181
+ registerHandlers();
182
+ app.whenReady().then(createWindow);
183
+ app.on('window-all-closed', () => app.quit());
184
+ app.on('activate', () => {
185
+ if (BrowserWindow.getAllWindows().length === 0) createWindow();
186
+ });
187
+ }
188
+
189
+ module.exports = { registerHandlers, binary, probeMessage };