@ponderdev/justfits 0.0.0-stage → 1.3.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/LICENSE +674 -0
- package/README.md +240 -2
- package/THIRD-PARTY-NOTICES.md +120 -0
- package/agents/skills/justfits/SKILL.md +102 -0
- package/licenses/ffmpeg-license.txt +127 -0
- package/licenses/gpl-2.0.txt +338 -0
- package/licenses/gpl-3.0.txt +674 -0
- package/package.json +51 -4
- package/scripts/link-skill.cjs +99 -0
- package/src/binaries.cjs +106 -0
- package/src/cli.cjs +603 -0
- package/src/engine.cjs +358 -0
- package/src/heif.cjs +156 -0
- package/src/kit/scan.cjs +105 -0
- package/src/kit/window.cjs +93 -0
- package/src/main.cjs +265 -0
- package/src/plan.js +257 -0
- package/src/preload.cjs +35 -0
- package/src/renderer/app.js +635 -0
- package/src/renderer/index.html +57 -0
- package/src/renderer/kit/kit.css +767 -0
- package/src/renderer/kit/kit.js +740 -0
- package/src/renderer/licenses.html +1204 -0
- package/src/renderer/styles.css +9 -0
- package/src/scan.cjs +43 -0
package/src/engine.cjs
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
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
|
+
const { heifOrientation, orientationFilters } = require('./heif.cjs');
|
|
20
|
+
|
|
21
|
+
const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
|
|
22
|
+
|
|
23
|
+
// The first go is the plan; the rest correct for what x264 actually produced,
|
|
24
|
+
// which varies with how hard the footage is to compress.
|
|
25
|
+
const MAX_ATTEMPTS = 3;
|
|
26
|
+
|
|
27
|
+
/** A handle the caller can cancel through. */
|
|
28
|
+
function control() {
|
|
29
|
+
return { child: null, cancelled: false, cancel() {
|
|
30
|
+
this.cancelled = true;
|
|
31
|
+
if (this.child) this.child.kill();
|
|
32
|
+
} };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function run(bin, args, { onProgress, durationSec, ctl } = {}) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
// Cancel pressed before this started (while the file was being read, say):
|
|
38
|
+
// nothing is spawned, or the press would be lost and the encode would run on.
|
|
39
|
+
if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
|
|
40
|
+
const child = spawn(bin, args, { windowsHide: true });
|
|
41
|
+
if (ctl) ctl.child = child;
|
|
42
|
+
let stderr = '';
|
|
43
|
+
|
|
44
|
+
child.stdout.on('data', (chunk) => {
|
|
45
|
+
if (!onProgress || !durationSec) return;
|
|
46
|
+
// -progress emits key=value lines, which beats scraping the banner.
|
|
47
|
+
for (const line of String(chunk).split('\n')) {
|
|
48
|
+
const m = /^out_time_us=(\d+)/.exec(line.trim());
|
|
49
|
+
if (m) onProgress(Math.max(0, Math.min(1, Number(m[1]) / 1e6 / durationSec)));
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Keep the tail only. A failing ffmpeg says why in the last few lines and
|
|
54
|
+
// a working one can produce megabytes we would otherwise hold in memory.
|
|
55
|
+
child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000); });
|
|
56
|
+
|
|
57
|
+
child.on('error', reject);
|
|
58
|
+
child.on('close', (code) => {
|
|
59
|
+
if (ctl) ctl.child = null;
|
|
60
|
+
if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
|
|
61
|
+
if (code !== 0) {
|
|
62
|
+
const why = stderr.trim().split('\n').filter(Boolean).slice(-3).join('\n');
|
|
63
|
+
return reject(new Error(why || `ffmpeg exited with ${code}`));
|
|
64
|
+
}
|
|
65
|
+
resolve();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function ffprobeOut(ffprobe, args) {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const child = spawn(ffprobe, args, { windowsHide: true });
|
|
73
|
+
let out = '';
|
|
74
|
+
let err = '';
|
|
75
|
+
child.stdout.on('data', (c) => { out += c; });
|
|
76
|
+
child.stderr.on('data', (c) => { err += c; });
|
|
77
|
+
child.on('error', reject);
|
|
78
|
+
// ffprobe's own lines carry a demuxer tag and a memory address
|
|
79
|
+
// ("[mov,mp4,... @ 0x1234] moov atom not found"), which changes every run
|
|
80
|
+
// and means nothing to a person or a script; the line after it says why.
|
|
81
|
+
const reason = () => err.split('\n').map((l) => l.trim())
|
|
82
|
+
.filter((l) => l && !/^\[[^\]]* @ 0x[0-9a-f]+\]/i.test(l)).pop();
|
|
83
|
+
child.on('close', (code) => (code === 0 ? resolve(out) : reject(new Error(reason() || 'Could not read that file'))));
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// "00:01:02.500000000", as Matroska writes its DURATION tag.
|
|
88
|
+
function clockSeconds(value) {
|
|
89
|
+
const m = /^(\d+):(\d+):(\d+(?:\.\d+)?)$/.exec(String(value || '').trim());
|
|
90
|
+
return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The last packet's timestamp. Only reached for files whose header carries no
|
|
94
|
+
// duration at all (a webm recorded live by a browser), so the cost of reading
|
|
95
|
+
// every packet header is paid only when there is no other way to know.
|
|
96
|
+
async function scanDuration(ffprobe, file) {
|
|
97
|
+
try {
|
|
98
|
+
const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', 'v:0',
|
|
99
|
+
'-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file]);
|
|
100
|
+
let last = 0;
|
|
101
|
+
for (const line of packets.split('\n')) {
|
|
102
|
+
const t = Number(line.split(',')[0]);
|
|
103
|
+
if (Number.isFinite(t) && t > last) last = t;
|
|
104
|
+
}
|
|
105
|
+
return last;
|
|
106
|
+
} catch {
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The animation flag in a WebP's extended header (VP8X): RIFF, size, WEBP,
|
|
112
|
+
// then the VP8X chunk, whose flags byte carries 0x02 for animation.
|
|
113
|
+
function isAnimatedWebp(file) {
|
|
114
|
+
try {
|
|
115
|
+
const fd = fs.openSync(file, 'r');
|
|
116
|
+
const head = Buffer.alloc(21);
|
|
117
|
+
try { fs.readSync(fd, head, 0, 21, 0); } finally { fs.closeSync(fd); }
|
|
118
|
+
return head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP' &&
|
|
119
|
+
head.toString('latin1', 12, 16) === 'VP8X' && (head[20] & 0x02) !== 0;
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function probe(ffprobe, file) {
|
|
126
|
+
// ffmpeg reads only the first frame of an animated WebP, so it would come
|
|
127
|
+
// out as one still JPEG while saying it worked. Refused instead, from the
|
|
128
|
+
// file's own header, whatever this ffprobe makes of it.
|
|
129
|
+
if (isAnimatedWebp(file)) {
|
|
130
|
+
throw Object.assign(new Error(`${path.basename(file)} is an animated WebP, which Just Fits cannot shrink without losing the animation. Convert it to a video first.`), { code: 'animated-webp' });
|
|
131
|
+
}
|
|
132
|
+
// Stream groups (how a phone's HEIC says its tiles make one picture) came in
|
|
133
|
+
// ffprobe 7.0, and an older one refuses the option outright. The command line
|
|
134
|
+
// uses whatever ffprobe is on the PATH, and Debian 12 and Ubuntu 24.04 ship
|
|
135
|
+
// older ones, so it asks again without it rather than calling every file
|
|
136
|
+
// unreadable. A tiled HEIC then reads as its first tile, as before 1.3.0.
|
|
137
|
+
const args = ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams'];
|
|
138
|
+
let json;
|
|
139
|
+
try {
|
|
140
|
+
json = await ffprobeOut(ffprobe, [...args, '-show_stream_groups', file]);
|
|
141
|
+
} catch {
|
|
142
|
+
// Its message is only "Option not found" on the last line, so any failure
|
|
143
|
+
// is asked again; a file that is really unreadable fails the second time too.
|
|
144
|
+
json = await ffprobeOut(ffprobe, [...args, file]);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const info = JSON.parse(json);
|
|
148
|
+
const streams = info.streams || [];
|
|
149
|
+
// Cover art in an mp3 or m4a is a video stream too, but it is not the
|
|
150
|
+
// picture anyone means to send, so it never counts as one.
|
|
151
|
+
const video = streams.find((s) => s.codec_type === 'video' && !(s.disposition && s.disposition.attached_pic));
|
|
152
|
+
const audio = streams.find((s) => s.codec_type === 'audio');
|
|
153
|
+
if (!video) throw new Error('There is no picture in that file');
|
|
154
|
+
// A damaged picture can still be named a stream, with no size: a few stray
|
|
155
|
+
// bytes called .jpg would otherwise be "already small enough".
|
|
156
|
+
if (!(video.width > 0 && video.height > 0)) throw new Error('There is no picture in that file');
|
|
157
|
+
|
|
158
|
+
const imageFormat = /^(image2|png_pipe|jpeg_pipe|webp_pipe)/.test((info.format && info.format.format_name) || '');
|
|
159
|
+
let durationSec = Number(info.format && info.format.duration) ||
|
|
160
|
+
Number(video.duration) ||
|
|
161
|
+
clockSeconds(video.tags && (video.tags.DURATION || video.tags.duration)) || 0;
|
|
162
|
+
// No duration in the header does not make a video a still: a live-recorded
|
|
163
|
+
// webm has none, and treating it as an image turned it into one JPEG frame.
|
|
164
|
+
if (!durationSec && !imageFormat && video.nb_frames !== '1') {
|
|
165
|
+
durationSec = await scanDuration(ffprobe, file);
|
|
166
|
+
}
|
|
167
|
+
// A still is a video stream with no duration and a single frame.
|
|
168
|
+
const still = !durationSec || video.nb_frames === '1' || imageFormat;
|
|
169
|
+
|
|
170
|
+
// Phones store portrait video landscape with a rotation flag, and ffmpeg
|
|
171
|
+
// rotates before the scale filter runs, so plan in the shape that is shown
|
|
172
|
+
// or a portrait clip gets squashed into a landscape frame.
|
|
173
|
+
// A phone's HEIC is a grid of 512 pixel tiles, and its first stream is only
|
|
174
|
+
// the first tile. The picture's real size is the grid's, and ffmpeg puts the
|
|
175
|
+
// tiles together itself, so the scale has to follow that join (see fitImage).
|
|
176
|
+
const grid = (info.stream_groups || []).find((g) => g.type === 'Tile Grid');
|
|
177
|
+
const gridSize = grid && grid.components && grid.components[0];
|
|
178
|
+
const shape = gridSize || video;
|
|
179
|
+
|
|
180
|
+
// A portrait photo from a phone is a landscape grid with its rotation on the
|
|
181
|
+
// grid, not on the tile, so the rotation is read from whichever gives the size.
|
|
182
|
+
// ffprobe builds differ on where a grid's turn goes: on its component, or
|
|
183
|
+
// (newer builds) on the group itself, so both are read.
|
|
184
|
+
const sides = [...(shape.side_data_list || []), ...((grid && grid.side_data_list) || [])];
|
|
185
|
+
const sideRotation = sides.find((d) => d.rotation !== undefined);
|
|
186
|
+
const rotation = Number(sideRotation ? sideRotation.rotation : (video.tags && video.tags.rotate)) || 0;
|
|
187
|
+
// A turn that is only in the EXIF (some phones write no rotation box) is not
|
|
188
|
+
// applied by ffmpeg for HEIC, so it is read here and applied in fitImage.
|
|
189
|
+
const orientation = still && !rotation ? heifOrientation(file) : 1;
|
|
190
|
+
const sideways = Math.abs(Math.round(rotation)) % 180 === 90 || orientation >= 5;
|
|
191
|
+
|
|
192
|
+
const [num, den] = String(video.r_frame_rate || '30/1').split('/').map(Number);
|
|
193
|
+
const fps = den ? num / den : 30;
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
kind: still ? 'image' : 'video',
|
|
197
|
+
durationSec,
|
|
198
|
+
width: Number(sideways ? shape.height : shape.width) || 0,
|
|
199
|
+
height: Number(sideways ? shape.width : shape.height) || 0,
|
|
200
|
+
fps: Number.isFinite(fps) && fps > 0 ? fps : 30,
|
|
201
|
+
hasAudio: Boolean(audio),
|
|
202
|
+
bytes: fs.statSync(file).size,
|
|
203
|
+
...(gridSize ? { grid: true } : {}),
|
|
204
|
+
...(orientation > 1 ? { orientation } : {}),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/*
|
|
209
|
+
* Beside the original, never over it. The source is the one file here that
|
|
210
|
+
* cannot be recreated, so it is never a candidate for the output path. The
|
|
211
|
+
* suffix is always -fits today; it stays a parameter for a caller that needs
|
|
212
|
+
* another.
|
|
213
|
+
*/
|
|
214
|
+
function outputPath(source, ext, exists = fs.existsSync, suffix = '-fits') {
|
|
215
|
+
const dir = path.dirname(source);
|
|
216
|
+
const base = path.basename(source, path.extname(source));
|
|
217
|
+
let candidate = path.join(dir, `${base}${suffix}${ext}`);
|
|
218
|
+
for (let n = 2; exists(candidate) && n < 1000; n++) {
|
|
219
|
+
candidate = path.join(dir, `${base}${suffix} ${n}${ext}`);
|
|
220
|
+
}
|
|
221
|
+
return candidate;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/*
|
|
225
|
+
* ffmpeg's complaints name the files it was handed: the pass log in the temp
|
|
226
|
+
* folder, and for a pipe the temp file it was buffered into. Neither means
|
|
227
|
+
* anything to a person, so the log becomes "its working file" and the input
|
|
228
|
+
* goes back to the name the person knows (called, or the file's own).
|
|
229
|
+
*/
|
|
230
|
+
function plainError(err, replacements) {
|
|
231
|
+
if (!err || typeof err.message !== 'string') return err;
|
|
232
|
+
let message = err.message;
|
|
233
|
+
for (const [from, to] of replacements) {
|
|
234
|
+
if (!from) continue;
|
|
235
|
+
// A name that ends where the log's suffix ("-0.log.mbtree") ends, whole.
|
|
236
|
+
const re = new RegExp(from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (to === 'its working file' ? '[\\w.-]*' : ''), 'g');
|
|
237
|
+
message = message.replace(re, to);
|
|
238
|
+
}
|
|
239
|
+
if (message !== err.message) err.message = message;
|
|
240
|
+
return err;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
|
|
244
|
+
const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.mp4', fs.existsSync, suffix);
|
|
245
|
+
const logFile = path.join(os.tmpdir(), `justfits-${process.pid}-${Date.now()}`);
|
|
246
|
+
let correction = 1;
|
|
247
|
+
let result = null;
|
|
248
|
+
let lastPlan = null;
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
252
|
+
const p = plan.planVideo({ ...info, targetBytes, correction });
|
|
253
|
+
// At the floors a smaller correction changes nothing, and encoding the
|
|
254
|
+
// same plan again only repeats a slow two-pass for the same result.
|
|
255
|
+
const key = [p.width, p.height, p.fps, p.videoKbps, p.audioKbps, p.audioChannels].join(',');
|
|
256
|
+
if (key === lastPlan) break;
|
|
257
|
+
lastPlan = key;
|
|
258
|
+
|
|
259
|
+
const filters = [];
|
|
260
|
+
if (p.width !== info.width || p.height !== info.height) {
|
|
261
|
+
filters.push(`scale=${p.width}:${p.height}:flags=lanczos`);
|
|
262
|
+
}
|
|
263
|
+
if (Math.abs(p.fps - info.fps) > 0.01) filters.push(`fps=${p.fps}`);
|
|
264
|
+
|
|
265
|
+
const common = [
|
|
266
|
+
'-hide_banner', '-nostats', '-progress', 'pipe:1', '-y',
|
|
267
|
+
'-i', file,
|
|
268
|
+
'-c:v', 'libx264', '-b:v', `${p.videoKbps}k`,
|
|
269
|
+
'-preset', 'slow', '-pix_fmt', 'yuv420p',
|
|
270
|
+
...(filters.length ? ['-vf', filters.join(',')] : []),
|
|
271
|
+
// Scoped to the video stream. Unscoped, -pass also reaches the audio
|
|
272
|
+
// encoder in pass 2, and the Windows ffmpeg build then looks for a
|
|
273
|
+
// two-pass log for the audio, finds none, and fails the encode.
|
|
274
|
+
'-passlogfile:v', logFile,
|
|
275
|
+
];
|
|
276
|
+
|
|
277
|
+
// Two passes, because hitting a size is precisely what two-pass is for.
|
|
278
|
+
// The first sees the whole clip so the second can spend the budget
|
|
279
|
+
// where the picture actually needs it.
|
|
280
|
+
await run(ffmpeg, [...common, '-pass:v', '1', '-an', '-f', 'mp4', NULL_DEVICE], {
|
|
281
|
+
durationSec: info.durationSec, ctl,
|
|
282
|
+
onProgress: (v) => onProgress({ stage: 'Looking at the video', progress: v * 0.35, attempt }),
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
const audioArgs = p.audioKbps
|
|
286
|
+
? ['-c:a', 'aac', '-b:a', `${p.audioKbps}k`, '-ac', String(p.audioChannels)]
|
|
287
|
+
: ['-an'];
|
|
288
|
+
|
|
289
|
+
await run(ffmpeg, [...common, '-pass:v', '2', ...audioArgs, '-movflags', '+faststart', out], {
|
|
290
|
+
durationSec: info.durationSec, ctl,
|
|
291
|
+
onProgress: (v) => onProgress({ stage: 'Compressing', progress: 0.35 + v * 0.65, attempt }),
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
const bytes = fs.statSync(out).size;
|
|
295
|
+
result = { path: out, bytes, plan: p, attempts: attempt + 1 };
|
|
296
|
+
if (bytes <= targetBytes) return result;
|
|
297
|
+
|
|
298
|
+
// Overshot. Measure by how much and aim lower rather than guess again.
|
|
299
|
+
correction = plan.correctionFor(bytes, targetBytes, correction);
|
|
300
|
+
}
|
|
301
|
+
} catch (err) {
|
|
302
|
+
// A cancelled or failed encode leaves a half-written file under a name
|
|
303
|
+
// that says it fits. Nothing should be left that looks sendable.
|
|
304
|
+
try { fs.unlinkSync(out); } catch {}
|
|
305
|
+
plainError(err, [[logFile, 'its working file'], [file, called || path.basename(file)]]);
|
|
306
|
+
// Fedora's default ffmpeg and other LGPL builds have no x264, and ffmpeg's
|
|
307
|
+
// own wording for that does not say what to do about it.
|
|
308
|
+
if (/Unknown encoder 'libx264'/.test(err.message) && !err.cancelled) {
|
|
309
|
+
throw new Error(`This ffmpeg has no H.264 encoder (libx264), which video needs. Install a full ffmpeg build.\n${err.message}`);
|
|
310
|
+
}
|
|
311
|
+
throw err;
|
|
312
|
+
} finally {
|
|
313
|
+
// x264 writes each pass log as .temp and renames it when the pass ends, so
|
|
314
|
+
// an encode stopped mid-pass (Cancel, which on Windows ends ffmpeg outright)
|
|
315
|
+
// leaves the .temp forms.
|
|
316
|
+
for (const suffix of ['-0.log', '-0.log.mbtree', '.log', '.log.mbtree', '-0.log.temp', '-0.log.mbtree.temp', '.log.temp', '.log.mbtree.temp']) {
|
|
317
|
+
try { fs.unlinkSync(logFile + suffix); } catch {}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return { ...result, over: true };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function fitImage({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
|
|
325
|
+
const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.jpg', fs.existsSync, suffix);
|
|
326
|
+
let result = null;
|
|
327
|
+
// The turn a HEIC keeps only in its EXIF (see probe), before the scale.
|
|
328
|
+
const turn = orientationFilters(info.orientation).map((f) => `${f},`).join('');
|
|
329
|
+
|
|
330
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
331
|
+
const p = plan.planImage({ targetBytes, width: info.width, height: info.height, attempt });
|
|
332
|
+
onProgress({ stage: attempt ? 'Trying harder' : 'Compressing', progress: attempt / 5, attempt });
|
|
333
|
+
|
|
334
|
+
try {
|
|
335
|
+
await run(ffmpeg, [
|
|
336
|
+
'-hide_banner', '-nostats', '-y', '-i', file,
|
|
337
|
+
// A tiled picture (HEIC) is joined by ffmpeg in a graph of its own, and
|
|
338
|
+
// a plain -vf on that stream is refused, so the scale joins that graph.
|
|
339
|
+
...(info.grid
|
|
340
|
+
? ['-filter_complex', `[0:g:0]${turn}scale=${p.width}:${p.height}:flags=lanczos`]
|
|
341
|
+
: ['-vf', `${turn}scale=${p.width}:${p.height}:flags=lanczos`]),
|
|
342
|
+
'-q:v', String(p.quality), out,
|
|
343
|
+
], { ctl });
|
|
344
|
+
} catch (err) {
|
|
345
|
+
// Same as video: no half-written file left behind under a "fits" name.
|
|
346
|
+
try { fs.unlinkSync(out); } catch {}
|
|
347
|
+
throw plainError(err, [[file, called || path.basename(file)]]);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const bytes = fs.statSync(out).size;
|
|
351
|
+
result = { path: out, bytes, plan: p, attempts: attempt + 1 };
|
|
352
|
+
if (bytes <= targetBytes) return result;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return { ...result, over: true };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
module.exports = { run, plainError, control, probe, outputPath, fitVideo, fitImage, isAnimatedWebp, MAX_ATTEMPTS };
|
package/src/heif.cjs
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* The turn a phone HEIC carries only in its EXIF.
|
|
5
|
+
*
|
|
6
|
+
* Most phones store a portrait photo as a landscape picture with a rotation
|
|
7
|
+
* box (irot) that ffmpeg applies by itself. Some (an iPhone 7, for one) write
|
|
8
|
+
* no box and only set the Orientation tag in the EXIF item, which ffmpeg
|
|
9
|
+
* ignores for HEIC, so the photo came out on its side. This reads that tag
|
|
10
|
+
* straight from the file's boxes. It answers 1 (no turn) whenever the file has
|
|
11
|
+
* a rotation or mirror box, because ffmpeg has already applied that one and
|
|
12
|
+
* turning again would put the picture on its side the other way.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
|
|
17
|
+
const u16 = (b, o, le) => (le ? b[o] | (b[o + 1] << 8) : (b[o] << 8) | b[o + 1]);
|
|
18
|
+
const u32 = (b, o, le) => (le
|
|
19
|
+
? b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)
|
|
20
|
+
: (b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
|
|
21
|
+
|
|
22
|
+
function* boxes(b, start, end) {
|
|
23
|
+
let p = start;
|
|
24
|
+
while (p + 8 <= end) {
|
|
25
|
+
let size = u32(b, p, false);
|
|
26
|
+
const type = b.toString('latin1', p + 4, p + 8);
|
|
27
|
+
let header = 8;
|
|
28
|
+
if (size === 1) {
|
|
29
|
+
if (p + 16 > end) return;
|
|
30
|
+
size = u32(b, p + 12, false);
|
|
31
|
+
header = 16;
|
|
32
|
+
} else if (size === 0) {
|
|
33
|
+
size = end - p;
|
|
34
|
+
}
|
|
35
|
+
if (size < header || p + size > end) return;
|
|
36
|
+
yield { type, body: p + header, end: p + size };
|
|
37
|
+
p += size;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function findBox(b, start, end, names) {
|
|
42
|
+
const [head, ...rest] = names;
|
|
43
|
+
for (const box of boxes(b, start, end)) {
|
|
44
|
+
if (box.type !== head) continue;
|
|
45
|
+
const body = head === 'meta' ? box.body + 4 : box.body; // meta is a FullBox
|
|
46
|
+
return rest.length ? findBox(b, body, box.end, rest) : { ...box, body };
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function exifItemId(b, iinf) {
|
|
52
|
+
const version = b[iinf.body];
|
|
53
|
+
let p = iinf.body + 4;
|
|
54
|
+
p += version === 0 ? 2 : 4;
|
|
55
|
+
for (const box of boxes(b, p, iinf.end)) {
|
|
56
|
+
if (box.type !== 'infe') continue;
|
|
57
|
+
const v = b[box.body];
|
|
58
|
+
if (v < 2) continue;
|
|
59
|
+
let q = box.body + 4;
|
|
60
|
+
let id;
|
|
61
|
+
if (v === 2) { id = u16(b, q, false); q += 2; } else { id = u32(b, q, false); q += 4; }
|
|
62
|
+
q += 2;
|
|
63
|
+
if (b.toString('latin1', q, q + 4) === 'Exif') return id;
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function itemRange(b, iloc, wanted) {
|
|
69
|
+
const version = b[iloc.body];
|
|
70
|
+
let p = iloc.body + 4;
|
|
71
|
+
const offsetSize = b[p] >> 4;
|
|
72
|
+
const lengthSize = b[p] & 0x0f;
|
|
73
|
+
const baseSize = b[p + 1] >> 4;
|
|
74
|
+
const indexSize = b[p + 1] & 0x0f;
|
|
75
|
+
p += 2;
|
|
76
|
+
let count;
|
|
77
|
+
if (version < 2) { count = u16(b, p, false); p += 2; } else { count = u32(b, p, false); p += 4; }
|
|
78
|
+
const sized = (at, size) => (size === 4 ? u32(b, at, false) : size === 8 ? u32(b, at + 4, false) : size === 2 ? u16(b, at, false) : 0);
|
|
79
|
+
|
|
80
|
+
for (let i = 0; i < count; i++) {
|
|
81
|
+
let id;
|
|
82
|
+
if (version < 2) { id = u16(b, p, false); p += 2; } else { id = u32(b, p, false); p += 4; }
|
|
83
|
+
if (version === 1 || version === 2) p += 2;
|
|
84
|
+
p += 2;
|
|
85
|
+
const base = sized(p, baseSize); p += baseSize;
|
|
86
|
+
const extents = u16(b, p, false); p += 2;
|
|
87
|
+
for (let e = 0; e < extents; e++) {
|
|
88
|
+
if ((version === 1 || version === 2) && indexSize) p += indexSize;
|
|
89
|
+
const off = sized(p, offsetSize); p += offsetSize;
|
|
90
|
+
const len = sized(p, lengthSize); p += lengthSize;
|
|
91
|
+
if (id === wanted) return { offset: base + off, length: len };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function tiffOrientation(t) {
|
|
98
|
+
if (t.length < 8) return 1;
|
|
99
|
+
const le = u16(t, 0, false) === 0x4949;
|
|
100
|
+
const ifd = u32(t, 4, le);
|
|
101
|
+
if (ifd + 2 > t.length) return 1;
|
|
102
|
+
const count = u16(t, ifd, le);
|
|
103
|
+
for (let i = 0; i < count; i++) {
|
|
104
|
+
const e = ifd + 2 + i * 12;
|
|
105
|
+
if (e + 12 > t.length) break;
|
|
106
|
+
if (u16(t, e, le) === 0x0112) {
|
|
107
|
+
const v = u16(t, e + 8, le);
|
|
108
|
+
return v >= 1 && v <= 8 ? v : 1;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return 1;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The EXIF orientation (1..8) a HEIC file leaves for the viewer to apply; 1 when none, or when a box already carries the turn. */
|
|
115
|
+
function heifOrientation(file) {
|
|
116
|
+
try {
|
|
117
|
+
const fd = fs.openSync(file, 'r');
|
|
118
|
+
let head;
|
|
119
|
+
try {
|
|
120
|
+
head = Buffer.alloc(12);
|
|
121
|
+
fs.readSync(fd, head, 0, 12, 0);
|
|
122
|
+
// Only an ISO base media file with a heif-family brand; anything else is none of our business.
|
|
123
|
+
if (head.toString('latin1', 4, 8) !== 'ftyp' || !/^(hei|hev|mif|msf)/.test(head.toString('latin1', 8, 12))) return 1;
|
|
124
|
+
} finally { fs.closeSync(fd); }
|
|
125
|
+
const b = fs.readFileSync(file);
|
|
126
|
+
const ipco = findBox(b, 0, b.length, ['meta', 'iprp', 'ipco']);
|
|
127
|
+
if (ipco) {
|
|
128
|
+
for (const box of boxes(b, ipco.body, ipco.end)) if (box.type === 'irot' || box.type === 'imir') return 1;
|
|
129
|
+
}
|
|
130
|
+
const iinf = findBox(b, 0, b.length, ['meta', 'iinf']);
|
|
131
|
+
const iloc = findBox(b, 0, b.length, ['meta', 'iloc']);
|
|
132
|
+
if (!iinf || !iloc) return 1;
|
|
133
|
+
const id = exifItemId(b, iinf);
|
|
134
|
+
if (id == null) return 1;
|
|
135
|
+
const loc = itemRange(b, iloc, id);
|
|
136
|
+
if (!loc || loc.offset + loc.length > b.length) return 1;
|
|
137
|
+
const payload = b.subarray(loc.offset, loc.offset + loc.length);
|
|
138
|
+
// The item starts with a 4-byte offset to the TIFF header (usually 6, past "Exif\0\0").
|
|
139
|
+
const at = 4 + (payload.length >= 4 ? u32(payload, 0, false) : 0);
|
|
140
|
+
const t = payload.subarray(at);
|
|
141
|
+
if (t.length >= 4 && ((t[0] === 0x49 && t[1] === 0x49) || (t[0] === 0x4d && t[1] === 0x4d))) return tiffOrientation(t);
|
|
142
|
+
return 1;
|
|
143
|
+
} catch {
|
|
144
|
+
return 1;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The ffmpeg filters that turn pixels upright for an EXIF orientation. */
|
|
149
|
+
function orientationFilters(o) {
|
|
150
|
+
return ({
|
|
151
|
+
2: ['hflip'], 3: ['hflip', 'vflip'], 4: ['vflip'],
|
|
152
|
+
5: ['transpose=0'], 6: ['transpose=1'], 7: ['transpose=3'], 8: ['transpose=2'],
|
|
153
|
+
})[o] || [];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = { heifOrientation, orientationFilters };
|
package/src/kit/scan.cjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/* PonderDev kit 1.0.0, built from kit/src. Do not edit: run bin/kit-sync. */
|
|
2
|
+
'use strict';
|
|
3
|
+
/*
|
|
4
|
+
* The family's intake for several files or a folder (decided 2026-11-20:
|
|
5
|
+
* every tool takes a dropped folder, and several files). It runs on the main
|
|
6
|
+
* side, and in a tool's command line, so a folder means the same thing in the
|
|
7
|
+
* window and in a terminal, and in every tool.
|
|
8
|
+
*
|
|
9
|
+
* const { scan } = require('./kit/scan.cjs');
|
|
10
|
+
* const { files, folders, missing } = await scan(paths, {
|
|
11
|
+
* extensions: ['.mp4', '.mov'], // what a tool takes from inside a folder
|
|
12
|
+
* ours: /-fits( \d+)?$/i, // its own results, passed over in a folder
|
|
13
|
+
* anyNamed: true, // a file named on its own is taken whatever its name
|
|
14
|
+
* word: 'fitted', // its results folders ("Holiday (fitted)"), passed over
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* files is [{ path, name, bytes, from }], resolved, each once, in the order a file
|
|
18
|
+
* browser lists them (numbers counted, so "clip 2" comes before "clip 10").
|
|
19
|
+
* folders counts the folders named; missing lists named paths that are not
|
|
20
|
+
* there. Inside a folder, subfolders too, only names with one of the
|
|
21
|
+
* extensions are taken, and hidden files and folders, the AppleDouble files
|
|
22
|
+
* ("._name") a Mac leaves on other disks, and the tool's own results are
|
|
23
|
+
* passed over, so a folder done once and then again is not done on top of
|
|
24
|
+
* itself. A file named on its own is taken when anyNamed is set (the tool's
|
|
25
|
+
* probe then says whether it can read it), or else only with one of the
|
|
26
|
+
* extensions. from is the folder named that the file was found in, or null
|
|
27
|
+
* for a file named on its own. It never throws: a folder it cannot read is
|
|
28
|
+
* passed over.
|
|
29
|
+
*
|
|
30
|
+
* Where results go (decided 2026-11-20): a file named on its own gets its
|
|
31
|
+
* result beside it, as always. A folder's results go into a new folder beside
|
|
32
|
+
* it, named for what the tool did ("Holiday (fitted)", "Holiday (JPEG)"),
|
|
33
|
+
* with the folder's subfolders mirrored inside and the folder itself left
|
|
34
|
+
* untouched. A name that is taken gets " 2", then 3: nothing is written over.
|
|
35
|
+
* A tool may offer "Save next to the originals instead", which puts every
|
|
36
|
+
* result beside its own original.
|
|
37
|
+
*
|
|
38
|
+
* const into = resultsFolder(file.from, 'fitted'); // once per folder, per run
|
|
39
|
+
* const dir = resultDir(file, into); // where this file's result goes
|
|
40
|
+
*/
|
|
41
|
+
const fs = require('node:fs');
|
|
42
|
+
const path = require('node:path');
|
|
43
|
+
|
|
44
|
+
async function scan(paths, options = {}) {
|
|
45
|
+
const extensions = new Set((options.extensions || []).map((e) => e.toLowerCase()));
|
|
46
|
+
const ours = options.ours || null;
|
|
47
|
+
const anyNamed = options.anyNamed !== false;
|
|
48
|
+
const resultsName = options.word ? new RegExp(` \\(${options.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\)( \\d+)?$`, 'i') : null;
|
|
49
|
+
const found = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
const missing = [];
|
|
52
|
+
let folders = 0;
|
|
53
|
+
|
|
54
|
+
async function walk(target, named, from) {
|
|
55
|
+
let stat;
|
|
56
|
+
try { stat = await fs.promises.stat(target); } catch { if (named) missing.push(target); return; }
|
|
57
|
+
|
|
58
|
+
if (stat.isDirectory()) {
|
|
59
|
+
if (named) folders++;
|
|
60
|
+
else if (resultsName && resultsName.test(path.basename(target))) return;
|
|
61
|
+
let entries;
|
|
62
|
+
try { entries = await fs.promises.readdir(target, { withFileTypes: true }); } catch { return; }
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (entry.name.startsWith('.')) continue;
|
|
65
|
+
await walk(path.join(target, entry.name), false, named ? path.resolve(target) : from);
|
|
66
|
+
}
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!stat.isFile()) return;
|
|
71
|
+
const ext = path.extname(target).toLowerCase();
|
|
72
|
+
if (!(named && anyNamed) && !extensions.has(ext)) return;
|
|
73
|
+
if (!named && path.basename(target).startsWith('._')) return;
|
|
74
|
+
if (!named && ours && ours.test(path.parse(target).name)) return;
|
|
75
|
+
const key = path.resolve(target);
|
|
76
|
+
if (seen.has(key)) return;
|
|
77
|
+
seen.add(key);
|
|
78
|
+
found.push({ path: key, name: path.basename(target), bytes: stat.size, from: named ? null : from });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const p of paths) await walk(p, true, null);
|
|
82
|
+
found.sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true }));
|
|
83
|
+
return { files: found, folders, missing };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A new folder beside the one named, for its results: "Holiday (fitted)", or
|
|
87
|
+
// "Holiday (fitted) 2" when that is taken (by anything: a file, a folder, an
|
|
88
|
+
// earlier run). Nothing is made here; the tool makes it when a result is ready.
|
|
89
|
+
function resultsFolder(folder, word, exists = fs.existsSync) {
|
|
90
|
+
const base = `${path.resolve(folder)} (${word})`;
|
|
91
|
+
let candidate = base;
|
|
92
|
+
for (let n = 2; exists(candidate) && n < 1000; n++) candidate = `${base} ${n}`;
|
|
93
|
+
return candidate;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Where one file's result goes: beside it when it was named on its own or no
|
|
97
|
+
// results folder is given (Save next to the originals), or else at the same
|
|
98
|
+
// place inside the results folder as it sits inside its own folder.
|
|
99
|
+
function resultDir(file, into) {
|
|
100
|
+
if (!file.from || !into) return path.dirname(file.path);
|
|
101
|
+
return path.join(into, path.relative(file.from, path.dirname(file.path)));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { scan, resultsFolder, resultDir };
|
|
105
|
+
module.exports.VERSION = '1.0.0';
|