@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/cli.cjs
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Just Fits on the command line.
|
|
6
|
+
*
|
|
7
|
+
* The decisions live in plan.js and the ffmpeg work in engine.cjs, neither of
|
|
8
|
+
* which knows anything about Electron, so this is a wrapper rather than a
|
|
9
|
+
* second implementation. The desktop app and this produce identical output for
|
|
10
|
+
* identical input.
|
|
11
|
+
*
|
|
12
|
+
* Progress goes to stderr so stdout stays clean enough to pipe.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const os = require('node:os');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
|
|
19
|
+
const plan = require('./plan.js');
|
|
20
|
+
const engine = require('./engine.cjs');
|
|
21
|
+
const binaries = require('./binaries.cjs');
|
|
22
|
+
const { scan, places } = require('./scan.cjs');
|
|
23
|
+
|
|
24
|
+
// Inside a packaged app the extras sit in the app's resources folder (as
|
|
25
|
+
// extraResources put them), not in vendor/. Run that way, by the tool belt or
|
|
26
|
+
// anyone, process.resourcesPath says where; under plain node it is undefined
|
|
27
|
+
// and only vendor/ is looked in.
|
|
28
|
+
const packaged = (name) => (process.resourcesPath ? [path.join(process.resourcesPath, name)] : []);
|
|
29
|
+
const VENDOR = [...packaged('ffmpeg'), path.join(__dirname, '..', 'vendor', 'ffmpeg')];
|
|
30
|
+
const MB = 1000 * 1000;
|
|
31
|
+
// Names a video must not be given with -o: it comes out as an MP4, so a .mov or
|
|
32
|
+
// a .png would be a file named for what it is not.
|
|
33
|
+
const VIDEO_WRONG = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mov', '.mkv', '.webm', '.avi', '.heic'];
|
|
34
|
+
|
|
35
|
+
function human(bytes) {
|
|
36
|
+
if (bytes >= 1000 * MB) return (bytes / 1000 / MB).toFixed(1) + 'GB';
|
|
37
|
+
if (bytes >= MB) return (bytes / MB).toFixed(bytes >= 100 * MB ? 0 : 1) + 'MB';
|
|
38
|
+
return Math.max(1, Math.round(bytes / 1000)) + 'KB';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const VERSION = require('../package.json').version;
|
|
42
|
+
|
|
43
|
+
/*
|
|
44
|
+
* Every option, once. --help is printed from this and --describe is built from
|
|
45
|
+
* it, so the two cannot drift apart (CONTRACT.md section 3).
|
|
46
|
+
*/
|
|
47
|
+
const OPTIONS = [
|
|
48
|
+
{ flags: ['--to'], name: 'to', metavar: 'target', type: 'string', default: 'discord', help: 'where it is going, or a plain size like 25MB' },
|
|
49
|
+
{ flags: ['-o', '--output', '--out'], name: 'output', metavar: 'path', type: 'path', default: null, help: 'where to write it (one file). "-" means stdout. default: beside the input as name-fits.mp4; a folder\'s go into a new "folder (fitted)" beside it' },
|
|
50
|
+
{ flags: ['--json'], name: 'json', type: 'boolean', help: 'results as JSON lines on stdout (stderr when the file goes to stdout)' },
|
|
51
|
+
{ flags: ['--progress'], name: 'progress', type: 'boolean', help: 'with --json, progress as JSON lines on stderr' },
|
|
52
|
+
{ flags: ['--beside'], name: 'beside', type: 'boolean', help: 'with a folder, save each result beside its original as name-fits instead of in a new "folder (fitted)"' },
|
|
53
|
+
{ flags: ['--dry-run'], name: 'dry-run', type: 'boolean', help: 'say what would happen and write nothing' },
|
|
54
|
+
{ flags: ['-q', '--quiet'], name: 'quiet', type: 'boolean', help: 'nothing on stderr but errors' },
|
|
55
|
+
{ flags: ['-h', '--help'], name: 'help', type: 'boolean', help: 'this, and nothing else' },
|
|
56
|
+
{ flags: ['-V', '--version'], name: 'version', type: 'boolean', help: 'the version number' },
|
|
57
|
+
{ flags: ['--describe'], name: 'describe', type: 'boolean', help: 'what this command line accepts, as JSON' },
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
const EXIT = [
|
|
61
|
+
{ code: 0, meaning: 'Done, or it already fit.' },
|
|
62
|
+
{ code: 1, meaning: 'Failed. Nothing usable was written.' },
|
|
63
|
+
{ code: 2, meaning: 'Usage: a bad option, a missing value, an unknown target or a missing input. Nothing was started.' },
|
|
64
|
+
{ code: 3, meaning: 'Several files: some were done and some failed. Each file has its own line under --json.' },
|
|
65
|
+
{ code: 4, meaning: 'Done, but still over the target after every try. The closest result was written.' },
|
|
66
|
+
{ code: 129, meaning: 'Stopped by a hang-up. Part files removed.' },
|
|
67
|
+
{ code: 130, meaning: 'Stopped with Ctrl-C. Part files removed.' },
|
|
68
|
+
{ code: 143, meaning: 'Stopped by a terminate signal. Part files removed.' },
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
function usage() {
|
|
72
|
+
const targets = plan.TARGETS.map((t) => ` ${t.id.padEnd(16)} ${human(t.bytes).padStart(7)} ${t.label}`).join('\n');
|
|
73
|
+
const opts = OPTIONS.map((o) => {
|
|
74
|
+
const left = ` ${o.flags.join(', ')}${o.metavar ? ` <${o.metavar}>` : ''}`;
|
|
75
|
+
return `${left.padEnd(30)} ${o.help}`;
|
|
76
|
+
}).join('\n');
|
|
77
|
+
return `Just Fits ${VERSION}
|
|
78
|
+
Makes a file small enough to send.
|
|
79
|
+
|
|
80
|
+
justfits <file> [options]
|
|
81
|
+
justfits <file> <file> ... [options]
|
|
82
|
+
justfits <folder> [options]
|
|
83
|
+
cat clip.mp4 | justfits --to discord > small.mp4
|
|
84
|
+
|
|
85
|
+
Several files, or a folder (its subfolders too), are each fitted on their
|
|
86
|
+
own to the same target. Files are saved beside their originals; a folder's
|
|
87
|
+
go into a new folder beside it, "folder (fitted)", with the files that
|
|
88
|
+
already fit copied in so it is complete (--beside: beside each original).
|
|
89
|
+
|
|
90
|
+
Options
|
|
91
|
+
${opts}
|
|
92
|
+
|
|
93
|
+
Targets
|
|
94
|
+
${targets}
|
|
95
|
+
|
|
96
|
+
Exit status: 0 done, 1 failed, 2 usage, 3 some of several failed,
|
|
97
|
+
4 still over the target after every try.
|
|
98
|
+
|
|
99
|
+
Your original is only ever read. Nothing is uploaded.`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function describe() {
|
|
103
|
+
return {
|
|
104
|
+
schema: 'ponderdev.cli-describe/1',
|
|
105
|
+
name: 'justfits',
|
|
106
|
+
product: 'Just Fits',
|
|
107
|
+
version: VERSION,
|
|
108
|
+
licence: require('../package.json').license,
|
|
109
|
+
// The kit the app is built with (decided 2026-11-20), from the kit's own copy.
|
|
110
|
+
kit: require('./kit/scan.cjs').VERSION,
|
|
111
|
+
command: 'justfits',
|
|
112
|
+
job: 'Make a video or image small enough to send, under an exact size limit.',
|
|
113
|
+
network: false,
|
|
114
|
+
accepts: { mediaTypes: ['video/*', 'image/*'], extensions: ['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.jpg', '.jpeg', '.png', '.heic', '.webp', '.gif'] },
|
|
115
|
+
emits: { mediaTypes: ['video/mp4', 'image/jpeg'], extensions: ['.mp4', '.jpg'] },
|
|
116
|
+
arguments: [{ name: 'file', type: 'path', required: false, repeatable: true, help: 'the file to shrink, or several, or a folder of them (subfolders too). "-" or none reads stdin' }],
|
|
117
|
+
options: OPTIONS.map((o) => (o.name === 'to' ? { ...o, values: plan.TARGETS.map((t) => t.id), valuesOpen: true } : o)),
|
|
118
|
+
targets: plan.TARGETS.map((t) => ({ id: t.id, bytes: t.bytes, label: t.label })),
|
|
119
|
+
output: { video: 'name-fits.mp4 beside the input', picture: 'name-fits.jpg beside the input', taken: 'name-fits 2.mp4, then 3, never over an existing file', withO: '-o names the result: a video must end in .mp4 and a picture in .jpg. A file that already fits is copied to -o as it is and reported as a result line, not a skip, and may keep its own extension', several: 'each file fitted on its own; files named on their own beside their originals, a folder\'s into a new folder beside it, "folder (fitted)" (then "folder (fitted) 2"), subfolders mirrored, each result named name-fits as beside its original, files that already fit copied in under that name so the folder is complete, the folder itself untouched; --beside puts every result beside its original instead; -o and stdin take one file only' },
|
|
120
|
+
result: { fields: { input: 'path', output: 'path', path: 'path', before: 'integer', after: 'integer', target: 'integer', attempts: 'integer', width: 'integer', height: 'integer', notes: 'array of strings, present when the video is long for the target (a small, blurry or softer picture)' } },
|
|
121
|
+
// The desktop app carries ffmpeg; the npm command line uses the one on the
|
|
122
|
+
// PATH, and says how to install it if there is none.
|
|
123
|
+
needs: [{ id: 'ffmpeg', kind: 'binary', bundled: 'in the desktop app; the npm install uses ffmpeg from the PATH' }],
|
|
124
|
+
io: {
|
|
125
|
+
stdin: 'read when the file is "-", or when no file is named and stdin is not a terminal (gives up after 10 seconds of nothing)',
|
|
126
|
+
stdout: 'the file itself with -o -, or when the input came from stdin and no -o was given; otherwise JSON lines with --json, otherwise nothing',
|
|
127
|
+
stderr: 'progress and messages for people; JSON lines when stdout carries the file',
|
|
128
|
+
},
|
|
129
|
+
exitCodes: EXIT,
|
|
130
|
+
guarantees: ['never writes over an input or an existing file', 'nothing is uploaded'],
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
class UsageError extends Error {}
|
|
135
|
+
|
|
136
|
+
function parseTarget(value) {
|
|
137
|
+
if (value === null) return plan.TARGETS[0];
|
|
138
|
+
const preset = plan.TARGETS.find((t) => t.id === value.toLowerCase());
|
|
139
|
+
if (preset) return preset;
|
|
140
|
+
|
|
141
|
+
const m = /^(\d+(?:\.\d+)?)\s*(?:(g|m|k)b?|(b))?$/i.exec(value.trim());
|
|
142
|
+
if (!m) throw new UsageError(`Unknown target "${value}". Try a preset from --help, or a size like 25MB.`);
|
|
143
|
+
// "8b" is eight bytes, which nothing fits in, and it used to be read as 8MB.
|
|
144
|
+
// Refused rather than guessed: 8MB and 8KB are both one letter away.
|
|
145
|
+
if (m[3]) throw new UsageError(`Target "${value}" is in bytes. Did you mean ${m[1]}MB or ${m[1]}KB?`);
|
|
146
|
+
const n = Number(m[1]);
|
|
147
|
+
const unit = (m[2] || 'm').toLowerCase();
|
|
148
|
+
const bytes = Math.round(n * (unit === 'g' ? 1000 * MB : unit === 'k' ? 1000 : MB));
|
|
149
|
+
if (!(bytes > 0)) throw new UsageError(`Target "${value}" is not more than zero.`);
|
|
150
|
+
return { id: 'custom', label: `${value}`, bytes };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// A missing or empty value is an error, never a silent default: a script
|
|
154
|
+
// passing an empty variable must not get a 10MB Discord file it did not ask
|
|
155
|
+
// for, or a file named after the next flag.
|
|
156
|
+
function needValue(flag, value, dashOk) {
|
|
157
|
+
if (value === undefined || value === '' || (value.startsWith('-') && !(dashOk && value === '-'))) {
|
|
158
|
+
throw new UsageError(`${flag} needs a value`);
|
|
159
|
+
}
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function parseArgs(argv) {
|
|
164
|
+
const opts = { file: null, files: [], to: null, out: null, json: false, quiet: false, progress: false, dryRun: false, beside: false };
|
|
165
|
+
let positional = false;
|
|
166
|
+
for (let i = 0; i < argv.length; i++) {
|
|
167
|
+
const a = argv[i];
|
|
168
|
+
if (positional || a === '-' || !a.startsWith('-')) {
|
|
169
|
+
opts.files.push(a);
|
|
170
|
+
if (opts.file === null) opts.file = a;
|
|
171
|
+
}
|
|
172
|
+
else if (a === '--') positional = true;
|
|
173
|
+
else if (a === '--json') opts.json = true;
|
|
174
|
+
else if (a === '--progress') opts.progress = true;
|
|
175
|
+
else if (a === '--dry-run') opts.dryRun = true;
|
|
176
|
+
else if (a === '--beside') opts.beside = true;
|
|
177
|
+
else if (a === '-q' || a === '--quiet') opts.quiet = true;
|
|
178
|
+
else if (a === '--to') opts.to = needValue(a, argv[++i], false);
|
|
179
|
+
else if (a === '-o' || a === '--out' || a === '--output') opts.out = needValue(a, argv[++i], true);
|
|
180
|
+
else if (a.startsWith('--to=')) opts.to = needValue('--to', a.slice(5), false);
|
|
181
|
+
else if (a.startsWith('--out=')) opts.out = needValue('--out', a.slice(6), true);
|
|
182
|
+
else if (a.startsWith('--output=')) opts.out = needValue('--output', a.slice(9), true);
|
|
183
|
+
else throw new UsageError(`Unknown option "${a}"`);
|
|
184
|
+
}
|
|
185
|
+
return opts;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Checked before the encode rather than left to ffmpeg, whose complaint would
|
|
189
|
+
// name the working file it writes beside the result instead of the folder
|
|
190
|
+
// that is missing.
|
|
191
|
+
function checkFolder(requested, outPath) {
|
|
192
|
+
const dir = path.dirname(outPath);
|
|
193
|
+
let stat = null;
|
|
194
|
+
try { stat = fs.statSync(dir); } catch (e) { /* missing, said below */ }
|
|
195
|
+
if (!stat) throw new UsageError(`The folder ${path.dirname(requested)} does not exist.`);
|
|
196
|
+
if (!stat.isDirectory()) throw new UsageError(`${path.dirname(requested)} is not a folder.`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Reads all of stdin into a file. When nobody asked for stdin (no file named,
|
|
200
|
+
// no "-"), an open pipe that never sends anything is almost always a harness
|
|
201
|
+
// or CI job with a missing file argument, so give up with a usage error
|
|
202
|
+
// instead of hanging forever.
|
|
203
|
+
function readStdin(dest, implicit) {
|
|
204
|
+
return new Promise((resolve, reject) => {
|
|
205
|
+
const out = fs.createWriteStream(dest);
|
|
206
|
+
let got = 0;
|
|
207
|
+
const timer = implicit ? setTimeout(() => {
|
|
208
|
+
if (got) return;
|
|
209
|
+
process.stdin.unpipe(out);
|
|
210
|
+
process.stdin.destroy();
|
|
211
|
+
out.destroy();
|
|
212
|
+
reject(new Error('No input file, and nothing arrived on stdin. Name a file, or pass "-" to wait for stdin.'));
|
|
213
|
+
}, 10000) : null;
|
|
214
|
+
process.stdin.on('data', (c) => { got += c.length; });
|
|
215
|
+
process.stdin.pipe(out);
|
|
216
|
+
out.on('finish', () => {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
if (!got) reject(new Error('Nothing arrived on stdin.'));
|
|
219
|
+
else resolve();
|
|
220
|
+
});
|
|
221
|
+
out.on('error', (err) => { clearTimeout(timer); reject(err); });
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Waits until everything written to stdout has been handed to the OS, so
|
|
226
|
+
// exiting straight after cannot cut the end off a piped file.
|
|
227
|
+
function drainStdout() {
|
|
228
|
+
return new Promise((resolve) => process.stdout.write('', () => resolve()));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/*
|
|
232
|
+
* JSON lines (CONTRACT.md section 4): result, skip and error lines, then a
|
|
233
|
+
* done line, always. They go to stdout, or to stderr when stdout carries the
|
|
234
|
+
* file. The released fields (ok, path, before, after...) are kept as they were
|
|
235
|
+
* so a script reading them keeps working; type, input, output and done are new.
|
|
236
|
+
*/
|
|
237
|
+
const report = {
|
|
238
|
+
stream: process.stdout,
|
|
239
|
+
on: false,
|
|
240
|
+
counts: { results: 0, skipped: 0, failed: 0 },
|
|
241
|
+
line(obj) { if (this.on) this.stream.write(JSON.stringify(obj) + '\n'); },
|
|
242
|
+
result(obj) { this.counts.results++; this.line({ type: 'result', ...obj }); },
|
|
243
|
+
skip(obj) { this.counts.skipped++; this.line({ type: 'skip', ...obj }); },
|
|
244
|
+
error(code, message, input) { this.counts.failed++; this.line({ type: 'error', ok: false, code, message, ...(input ? { input } : {}) }); },
|
|
245
|
+
done(exit) { this.line({ type: 'done', ok: exit === 0, ...this.counts, exit }); },
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
// Files to remove if a signal stops the run before it finishes.
|
|
249
|
+
const cleanup = new Set();
|
|
250
|
+
// A results folder made for the file being fitted ([dir, folder]), removed on
|
|
251
|
+
// a signal only if it is still empty.
|
|
252
|
+
let emptyIfStopped = null;
|
|
253
|
+
function removeIfEmpty([dir, folder]) {
|
|
254
|
+
for (; dir.startsWith(folder); dir = path.dirname(dir)) {
|
|
255
|
+
try { fs.rmdirSync(dir); } catch { break; }
|
|
256
|
+
if (dir === folder) break;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function main(argv) {
|
|
261
|
+
// Answered before anything else is looked at: a bad option beside them still
|
|
262
|
+
// gets an answer, no file is opened and stdin is never read.
|
|
263
|
+
if (argv.includes('-h') || argv.includes('--help')) { console.log(usage()); return 0; }
|
|
264
|
+
if (argv.includes('-V') || argv.includes('--version')) { console.log(VERSION); return 0; }
|
|
265
|
+
if (argv.includes('--describe')) { console.log(JSON.stringify(describe(), null, 2)); return 0; }
|
|
266
|
+
|
|
267
|
+
report.on = argv.includes('--json');
|
|
268
|
+
const opts = parseArgs(argv);
|
|
269
|
+
|
|
270
|
+
const target = parseTarget(opts.to);
|
|
271
|
+
|
|
272
|
+
// Several inputs, or a folder: each one fitted on its own (fitMany). One file
|
|
273
|
+
// goes the way it always has, below, so its output and JSON are unchanged.
|
|
274
|
+
const isFolder = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
|
|
275
|
+
if (opts.files.length > 1 || (opts.files.length === 1 && opts.files[0] !== '-' && isFolder(opts.files[0]))) {
|
|
276
|
+
return fitMany(opts, target);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Piped input has to be buffered, because two-pass encoding reads the input
|
|
280
|
+
// twice and a pipe cannot be rewound. Said plainly rather than hidden.
|
|
281
|
+
let input = opts.file;
|
|
282
|
+
let temp = null;
|
|
283
|
+
const fromStdin = input === '-' || (!input && !process.stdin.isTTY);
|
|
284
|
+
const toStdout = opts.out === '-' || (fromStdin && !opts.out);
|
|
285
|
+
if (toStdout) report.stream = process.stderr;
|
|
286
|
+
// Never over an existing file, the input included: `-o clip.mp4` on
|
|
287
|
+
// clip.mp4 used to replace the original with the compressed copy.
|
|
288
|
+
const outPath = opts.out && !toStdout ? path.resolve(opts.out) : null;
|
|
289
|
+
// Before the exists check, which a device can pass on Windows.
|
|
290
|
+
if (outPath && plan.isDeviceName(opts.out)) {
|
|
291
|
+
throw new UsageError(`${opts.out.split(/[\\/]/).pop()} is a name Windows keeps for a device, so nothing would be saved. Choose another name.`);
|
|
292
|
+
}
|
|
293
|
+
if (outPath && fs.existsSync(outPath)) throw new UsageError(`Will not overwrite ${outPath}, it already exists.`);
|
|
294
|
+
if (outPath) checkFolder(opts.out, outPath);
|
|
295
|
+
if (!fromStdin && !fs.existsSync(input)) throw new UsageError(`No such file: ${input}`);
|
|
296
|
+
|
|
297
|
+
const ffmpeg = binaries.resolve('ffmpeg', VENDOR);
|
|
298
|
+
const ffprobe = binaries.resolve('ffprobe', VENDOR);
|
|
299
|
+
|
|
300
|
+
let encodeDir = null;
|
|
301
|
+
try {
|
|
302
|
+
if (fromStdin) {
|
|
303
|
+
temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-')), 'input');
|
|
304
|
+
cleanup.add(path.dirname(temp));
|
|
305
|
+
if (!opts.quiet) process.stderr.write('Buffering stdin, two passes cannot read a pipe twice\n');
|
|
306
|
+
await readStdin(temp, input !== '-');
|
|
307
|
+
input = temp;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
let info;
|
|
311
|
+
try {
|
|
312
|
+
info = await engine.probe(ffprobe, input);
|
|
313
|
+
} catch (err) {
|
|
314
|
+
// A file it can read but will not shrink says why in its own words.
|
|
315
|
+
if (err.code === 'animated-webp') throw err;
|
|
316
|
+
// ffmpeg's own words ("Invalid data found when processing input") say
|
|
317
|
+
// nothing to a person. The same sentence the window uses.
|
|
318
|
+
throw Object.assign(new Error(`${fromStdin ? 'What arrived on stdin' : path.basename(input)} is not a video or picture that Just Fits can read.`), { code: 'not-media' });
|
|
319
|
+
}
|
|
320
|
+
// A picture comes out as a JPEG and a video as an MP4. Asked for the other,
|
|
321
|
+
// the encode would fail late or write a file named for what it is not. A
|
|
322
|
+
// file that already fits is copied as it is, so it may keep its own kind of
|
|
323
|
+
// name (an already small PNG to copy.png). Stdin has no name of its own, and
|
|
324
|
+
// the temp file it is buffered into must not turn up in a sentence.
|
|
325
|
+
if (outPath) {
|
|
326
|
+
const ext = path.extname(outPath).toLowerCase();
|
|
327
|
+
const same = !fromStdin && ext === path.extname(input).toLowerCase();
|
|
328
|
+
const called = fromStdin ? 'What arrived on stdin' : path.basename(input);
|
|
329
|
+
if (info.kind === 'image' && !['.jpg', '.jpeg'].includes(ext) && !(same && info.bytes <= target.bytes)) {
|
|
330
|
+
throw new UsageError(`${called} is a picture, so it comes out as a JPEG. Give -o a name ending in .jpg.`);
|
|
331
|
+
}
|
|
332
|
+
if (info.kind === 'video' && VIDEO_WRONG.includes(ext) && !(same && info.bytes <= target.bytes)) {
|
|
333
|
+
throw new UsageError(`${called} is a video, so it comes out as an MP4. Give -o a name ending in .mp4.`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const fits = info.bytes <= target.bytes && !toStdout;
|
|
337
|
+
if (opts.dryRun) {
|
|
338
|
+
const ext = info.kind === 'image' ? '.jpg' : '.mp4';
|
|
339
|
+
const would = fits ? (outPath || path.resolve(input)) : (outPath || (toStdout ? '-' : engine.outputPath(path.resolve(input), ext)));
|
|
340
|
+
report.result({ ok: true, dryRun: true, input: fromStdin ? '-' : path.resolve(input), output: would, before: info.bytes, target: target.bytes, fits });
|
|
341
|
+
if (!opts.quiet && !report.on) {
|
|
342
|
+
process.stderr.write(fits ? `${human(info.bytes)} already fits under ${human(target.bytes)}. Nothing would change.\n`
|
|
343
|
+
: `${human(info.bytes)} would be fitted under ${human(target.bytes)}${outPath ? `, to ${outPath}` : ''}.\n`);
|
|
344
|
+
}
|
|
345
|
+
return 0;
|
|
346
|
+
}
|
|
347
|
+
if (fits) {
|
|
348
|
+
// Same streams and same JSON shape as a real fit, and the file is where
|
|
349
|
+
// the caller asked for it, so a script can use the path either way.
|
|
350
|
+
let finalPath = path.resolve(input);
|
|
351
|
+
if (outPath) {
|
|
352
|
+
fs.copyFileSync(input, outPath, fs.constants.COPYFILE_EXCL);
|
|
353
|
+
finalPath = outPath;
|
|
354
|
+
}
|
|
355
|
+
const fields = {
|
|
356
|
+
ok: true, skipped: true, path: finalPath, input: path.resolve(input), output: finalPath,
|
|
357
|
+
before: info.bytes, after: info.bytes, target: target.bytes, bytes: info.bytes,
|
|
358
|
+
};
|
|
359
|
+
if (outPath) report.result(fields);
|
|
360
|
+
else report.skip({ ...fields, reason: 'fits-already', message: `${human(info.bytes)} already fits under ${human(target.bytes)}.` });
|
|
361
|
+
if (!report.on && !opts.quiet) {
|
|
362
|
+
process.stderr.write(`${human(info.bytes)} already fits under ${human(target.bytes)}. Nothing to do.${outPath ? ` ${outPath}` : ''}\n`);
|
|
363
|
+
}
|
|
364
|
+
return 0;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// Too long for the target at any quality worth having: say so before
|
|
368
|
+
// minutes of encoding, not after. It still tries, and exit 4 says if it
|
|
369
|
+
// stayed over.
|
|
370
|
+
const notes = [];
|
|
371
|
+
if (info.kind === 'video') {
|
|
372
|
+
const note = plan.lengthNote(plan.planVideo({ ...info, targetBytes: target.bytes }), human(target.bytes));
|
|
373
|
+
if (note) notes.push(note);
|
|
374
|
+
if (notes.length && !report.on && !opts.quiet) process.stderr.write(notes[0] + '\n');
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let last = '';
|
|
378
|
+
const onProgress = ({ stage, progress }) => {
|
|
379
|
+
if (report.on && opts.progress) {
|
|
380
|
+
process.stderr.write(JSON.stringify({ type: 'progress', stage, percent: Math.round(progress * 100) }) + '\n');
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (opts.quiet || opts.json || !process.stderr.isTTY) return;
|
|
384
|
+
const line = `\r${stage} ${Math.round(progress * 100)}% `;
|
|
385
|
+
if (line !== last) { process.stderr.write(line); last = line; }
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress, called: fromStdin ? 'what arrived on stdin' : undefined };
|
|
389
|
+
// Writing to stdout still encodes to a real file first, for the same
|
|
390
|
+
// reason: the encoder needs somewhere it can seek.
|
|
391
|
+
if (toStdout) { args.outDir = encodeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-out-')); cleanup.add(encodeDir); }
|
|
392
|
+
else if (outPath) args.outDir = path.dirname(outPath);
|
|
393
|
+
|
|
394
|
+
const result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
|
|
395
|
+
if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
396
|
+
|
|
397
|
+
let finalPath = result.path;
|
|
398
|
+
if (toStdout) {
|
|
399
|
+
await new Promise((res, rej) => {
|
|
400
|
+
const rs = fs.createReadStream(result.path);
|
|
401
|
+
rs.pipe(process.stdout);
|
|
402
|
+
rs.on('end', res); rs.on('error', rej);
|
|
403
|
+
});
|
|
404
|
+
await drainStdout();
|
|
405
|
+
finalPath = '-';
|
|
406
|
+
} else if (outPath) {
|
|
407
|
+
// Checked again, since the encode can take minutes.
|
|
408
|
+
if (fs.existsSync(outPath)) throw new Error(`Will not overwrite ${outPath}, it appeared during the encode. The result is at ${result.path}`);
|
|
409
|
+
fs.renameSync(result.path, outPath);
|
|
410
|
+
finalPath = outPath;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
report.result({
|
|
414
|
+
ok: !result.over, path: finalPath, input: fromStdin ? '-' : path.resolve(opts.file), output: finalPath,
|
|
415
|
+
before: info.bytes, after: result.bytes, bytes: result.bytes,
|
|
416
|
+
target: target.bytes, attempts: result.attempts,
|
|
417
|
+
width: result.plan.width, height: result.plan.height,
|
|
418
|
+
...(notes.length ? { notes } : {}),
|
|
419
|
+
});
|
|
420
|
+
if (!report.on && !opts.quiet) {
|
|
421
|
+
const saved = Math.round((1 - result.bytes / info.bytes) * 100);
|
|
422
|
+
const where = finalPath === '-' ? '' : ` ${finalPath}`;
|
|
423
|
+
process.stderr.write(result.over
|
|
424
|
+
? `Got to ${human(result.bytes)}, still over ${human(target.bytes)}.${where}\n`
|
|
425
|
+
: `${human(info.bytes)} to ${human(result.bytes)}, ${saved}% smaller.${where}\n`);
|
|
426
|
+
}
|
|
427
|
+
return result.over ? 4 : 0;
|
|
428
|
+
} finally {
|
|
429
|
+
if (temp) fs.rmSync(path.dirname(temp), { recursive: true, force: true });
|
|
430
|
+
if (encodeDir) fs.rmSync(encodeDir, { recursive: true, force: true });
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/*
|
|
435
|
+
* Several files, or a folder of them: each fitted on its own to the same
|
|
436
|
+
* target, one after another: a file named on its own beside its original, a
|
|
437
|
+
* folder's into a new "folder (fitted)" beside it (--beside: beside each
|
|
438
|
+
* original instead). Every file gets its own
|
|
439
|
+
* JSON line, a result, a skip or an error with its input, so one that fails
|
|
440
|
+
* does not stop the rest. Exit 0 when all fit, 4 when none failed but some
|
|
441
|
+
* stayed over, 3 when some failed and 1 when all did.
|
|
442
|
+
*/
|
|
443
|
+
async function fitMany(opts, target) {
|
|
444
|
+
if (opts.out) throw new UsageError('-o names one file. With several files or a folder, each result is saved beside its original.');
|
|
445
|
+
if (opts.files.includes('-')) throw new UsageError('stdin ("-") is one file on its own, and cannot be mixed with other inputs.');
|
|
446
|
+
const found = await scan(opts.files);
|
|
447
|
+
if (found.missing.length) throw new UsageError(`No such file: ${found.missing[0]}`);
|
|
448
|
+
if (!found.files.length) throw new UsageError(`There are no videos or pictures in ${opts.files.join(', ')}.`);
|
|
449
|
+
|
|
450
|
+
const ffmpeg = binaries.resolve('ffmpeg', VENDOR);
|
|
451
|
+
const ffprobe = binaries.resolve('ffprobe', VENDOR);
|
|
452
|
+
const say = (line) => { if (!report.on && !opts.quiet) process.stderr.write(line + '\n'); };
|
|
453
|
+
const total = found.files.length;
|
|
454
|
+
const tally = { fitted: 0, over: 0, skipped: 0, failed: 0 };
|
|
455
|
+
const place = places({ beside: opts.beside });
|
|
456
|
+
const folders = new Set();
|
|
457
|
+
|
|
458
|
+
for (const [i, f] of found.files.entries()) {
|
|
459
|
+
const tag = `[${i + 1}/${total}] ${f.name}`;
|
|
460
|
+
let info;
|
|
461
|
+
try {
|
|
462
|
+
info = await engine.probe(ffprobe, f.path);
|
|
463
|
+
} catch (err) {
|
|
464
|
+
const animated = err.code === 'animated-webp';
|
|
465
|
+
const message = animated ? err.message : `${f.name} is not a video or picture that Just Fits can read.`;
|
|
466
|
+
report.error(animated ? 'animated-webp' : 'not-media', message, f.path);
|
|
467
|
+
tally.failed++;
|
|
468
|
+
say(`${tag}: ${message}`);
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const fits = info.bytes <= target.bytes;
|
|
473
|
+
const where = place(f);
|
|
474
|
+
// Already small enough in a folder's results folder: copied in as it is,
|
|
475
|
+
// so the results folder holds the whole folder (decided 2026-11-20).
|
|
476
|
+
const copyIn = fits && Boolean(where.folder);
|
|
477
|
+
const ext = fits ? path.extname(f.path) : info.kind === 'image' ? '.jpg' : '.mp4';
|
|
478
|
+
if (opts.dryRun) {
|
|
479
|
+
const would = fits && !copyIn ? f.path : engine.outputPath(where.outDir ? path.join(where.outDir, f.name) : f.path, ext, fs.existsSync, where.suffix);
|
|
480
|
+
report.result({ ok: true, dryRun: true, input: f.path, output: would, before: info.bytes, target: target.bytes, fits });
|
|
481
|
+
say(`${tag}: ${fits ? `${human(info.bytes)} already fits. Nothing would change.` : `${human(info.bytes)} would be fitted under ${human(target.bytes)}.`}`);
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (fits) {
|
|
485
|
+
let output = f.path;
|
|
486
|
+
if (copyIn) {
|
|
487
|
+
try {
|
|
488
|
+
fs.mkdirSync(where.outDir, { recursive: true });
|
|
489
|
+
output = engine.outputPath(path.join(where.outDir, f.name), ext, fs.existsSync, where.suffix);
|
|
490
|
+
fs.copyFileSync(f.path, output, fs.constants.COPYFILE_EXCL);
|
|
491
|
+
folders.add(where.folder);
|
|
492
|
+
} catch (err) {
|
|
493
|
+
report.error('failed', String(err.message || err), f.path);
|
|
494
|
+
tally.failed++;
|
|
495
|
+
say(`${tag}: ${String(err.message || err)}`);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
report.skip({
|
|
500
|
+
ok: true, skipped: true, path: output, input: f.path, output,
|
|
501
|
+
before: info.bytes, after: info.bytes, target: target.bytes, bytes: info.bytes,
|
|
502
|
+
reason: 'fits-already', ...(copyIn ? { copied: true } : {}),
|
|
503
|
+
message: `${human(info.bytes)} already fits under ${human(target.bytes)}.${copyIn ? ' Copied in as it is.' : ''}`,
|
|
504
|
+
});
|
|
505
|
+
tally.skipped++;
|
|
506
|
+
say(`${tag}: ${human(info.bytes)} already fits under ${human(target.bytes)}. ${copyIn ? `Copied in as it is. ${output}` : 'Nothing to do.'}`);
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const notes = [];
|
|
511
|
+
if (info.kind === 'video') {
|
|
512
|
+
const note = plan.lengthNote(plan.planVideo({ ...info, targetBytes: target.bytes }), human(target.bytes));
|
|
513
|
+
if (note) notes.push(note);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
let last = '';
|
|
517
|
+
const onProgress = ({ stage, progress }) => {
|
|
518
|
+
if (report.on && opts.progress) {
|
|
519
|
+
process.stderr.write(JSON.stringify({ type: 'progress', stage, percent: Math.round(progress * 100), input: f.path, file: i + 1, files: total }) + '\n');
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
if (opts.quiet || opts.json || !process.stderr.isTTY) return;
|
|
523
|
+
const line = `\r${tag} ${stage} ${Math.round(progress * 100)}% `;
|
|
524
|
+
if (line !== last) { process.stderr.write(line); last = line; }
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
let result;
|
|
528
|
+
try {
|
|
529
|
+
if (where.outDir) fs.mkdirSync(where.outDir, { recursive: true });
|
|
530
|
+
if (where.folder) emptyIfStopped = [where.outDir, where.folder];
|
|
531
|
+
const args = { ffmpeg, file: f.path, info, targetBytes: target.bytes, onProgress, outDir: where.outDir, suffix: where.suffix };
|
|
532
|
+
result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
|
|
533
|
+
emptyIfStopped = null;
|
|
534
|
+
if (where.folder) folders.add(where.folder);
|
|
535
|
+
} catch (err) {
|
|
536
|
+
// A results folder made for this file and left empty goes again.
|
|
537
|
+
if (where.folder) removeIfEmpty([where.outDir, where.folder]);
|
|
538
|
+
emptyIfStopped = null;
|
|
539
|
+
if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
540
|
+
report.error(err.code || 'failed', String(err.message || err), f.path);
|
|
541
|
+
tally.failed++;
|
|
542
|
+
say(`${tag}: ${String(err.message || err)}`);
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
|
|
546
|
+
|
|
547
|
+
report.result({
|
|
548
|
+
ok: !result.over, path: result.path, input: f.path, output: result.path,
|
|
549
|
+
before: info.bytes, after: result.bytes, bytes: result.bytes,
|
|
550
|
+
target: target.bytes, attempts: result.attempts,
|
|
551
|
+
width: result.plan.width, height: result.plan.height,
|
|
552
|
+
...(notes.length ? { notes } : {}),
|
|
553
|
+
});
|
|
554
|
+
if (result.over) tally.over++; else tally.fitted++;
|
|
555
|
+
const saved = Math.round((1 - result.bytes / info.bytes) * 100);
|
|
556
|
+
say(result.over
|
|
557
|
+
? `${tag}: got to ${human(result.bytes)}, still over ${human(target.bytes)}. ${result.path}`
|
|
558
|
+
: `${tag}: ${human(info.bytes)} to ${human(result.bytes)}, ${saved}% smaller. ${result.path}`);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const bits = [`${tally.fitted} fitted`];
|
|
562
|
+
if (tally.skipped) bits.push(`${tally.skipped} already small enough`);
|
|
563
|
+
if (tally.over) bits.push(`${tally.over} still over ${human(target.bytes)}`);
|
|
564
|
+
if (tally.failed) bits.push(`${tally.failed} failed`);
|
|
565
|
+
if (!opts.dryRun) say(`${total} files: ${bits.join(', ')}.${folders.size ? ` Saved in ${[...folders].join(', ')}` : ''}`);
|
|
566
|
+
|
|
567
|
+
if (tally.failed === total) return 1;
|
|
568
|
+
if (tally.failed) return 3;
|
|
569
|
+
return tally.over ? 4 : 0;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// A reader that stops early (`| head`) is not an error worth a stack trace.
|
|
573
|
+
process.stdout.on('error', (err) => {
|
|
574
|
+
if (err.code === 'EPIPE') process.exit(0);
|
|
575
|
+
process.stderr.write(String(err.message || err) + '\n');
|
|
576
|
+
process.exit(1);
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
// Stopped by a signal: remove what this run made, and say so with the code
|
|
580
|
+
// the contract gives each signal.
|
|
581
|
+
for (const [sig, code] of [['SIGHUP', 129], ['SIGINT', 130], ['SIGTERM', 143]]) {
|
|
582
|
+
process.on(sig, () => {
|
|
583
|
+
for (const p of cleanup) { try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* gone already */ } }
|
|
584
|
+
if (emptyIfStopped) removeIfEmpty(emptyIfStopped);
|
|
585
|
+
process.exit(code);
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
module.exports = { describe, usage, OPTIONS, EXIT };
|
|
590
|
+
|
|
591
|
+
if (require.main === module) {
|
|
592
|
+
main(process.argv.slice(2))
|
|
593
|
+
.then(async (code) => { report.done(code); await drainStdout(); process.exit(code); })
|
|
594
|
+
.catch(async (err) => {
|
|
595
|
+
const usageError = err instanceof UsageError;
|
|
596
|
+
const code = usageError ? 2 : 1;
|
|
597
|
+
report.error(usageError ? 'usage' : (err.code || 'failed'), String(err.message || err));
|
|
598
|
+
process.stderr.write(String(err.message || err) + '\n');
|
|
599
|
+
report.done(code);
|
|
600
|
+
await drainStdout();
|
|
601
|
+
process.exit(code);
|
|
602
|
+
});
|
|
603
|
+
}
|