@ponderdev/justfits 1.2.0 → 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/src/cli.cjs CHANGED
@@ -19,6 +19,7 @@ const path = require('node:path');
19
19
  const plan = require('./plan.js');
20
20
  const engine = require('./engine.cjs');
21
21
  const binaries = require('./binaries.cjs');
22
+ const { scan, places } = require('./scan.cjs');
22
23
 
23
24
  // Inside a packaged app the extras sit in the app's resources folder (as
24
25
  // extraResources put them), not in vendor/. Run that way, by the tool belt or
@@ -27,6 +28,9 @@ const binaries = require('./binaries.cjs');
27
28
  const packaged = (name) => (process.resourcesPath ? [path.join(process.resourcesPath, name)] : []);
28
29
  const VENDOR = [...packaged('ffmpeg'), path.join(__dirname, '..', 'vendor', 'ffmpeg')];
29
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'];
30
34
 
31
35
  function human(bytes) {
32
36
  if (bytes >= 1000 * MB) return (bytes / 1000 / MB).toFixed(1) + 'GB';
@@ -42,9 +46,10 @@ const VERSION = require('../package.json').version;
42
46
  */
43
47
  const OPTIONS = [
44
48
  { flags: ['--to'], name: 'to', metavar: 'target', type: 'string', default: 'discord', help: 'where it is going, or a plain size like 25MB' },
45
- { flags: ['-o', '--output', '--out'], name: 'output', metavar: 'path', type: 'path', default: null, help: 'where to write it. "-" means stdout. default: beside the input as name-fits.mp4' },
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' },
46
50
  { flags: ['--json'], name: 'json', type: 'boolean', help: 'results as JSON lines on stdout (stderr when the file goes to stdout)' },
47
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)"' },
48
53
  { flags: ['--dry-run'], name: 'dry-run', type: 'boolean', help: 'say what would happen and write nothing' },
49
54
  { flags: ['-q', '--quiet'], name: 'quiet', type: 'boolean', help: 'nothing on stderr but errors' },
50
55
  { flags: ['-h', '--help'], name: 'help', type: 'boolean', help: 'this, and nothing else' },
@@ -56,6 +61,7 @@ const EXIT = [
56
61
  { code: 0, meaning: 'Done, or it already fit.' },
57
62
  { code: 1, meaning: 'Failed. Nothing usable was written.' },
58
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.' },
59
65
  { code: 4, meaning: 'Done, but still over the target after every try. The closest result was written.' },
60
66
  { code: 129, meaning: 'Stopped by a hang-up. Part files removed.' },
61
67
  { code: 130, meaning: 'Stopped with Ctrl-C. Part files removed.' },
@@ -72,15 +78,23 @@ function usage() {
72
78
  Makes a file small enough to send.
73
79
 
74
80
  justfits <file> [options]
81
+ justfits <file> <file> ... [options]
82
+ justfits <folder> [options]
75
83
  cat clip.mp4 | justfits --to discord > small.mp4
76
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
+
77
90
  Options
78
91
  ${opts}
79
92
 
80
93
  Targets
81
94
  ${targets}
82
95
 
83
- Exit status: 0 done, 1 failed, 2 usage, 4 still over the target after every try.
96
+ Exit status: 0 done, 1 failed, 2 usage, 3 some of several failed,
97
+ 4 still over the target after every try.
84
98
 
85
99
  Your original is only ever read. Nothing is uploaded.`;
86
100
  }
@@ -92,16 +106,18 @@ function describe() {
92
106
  product: 'Just Fits',
93
107
  version: VERSION,
94
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,
95
111
  command: 'justfits',
96
112
  job: 'Make a video or image small enough to send, under an exact size limit.',
97
113
  network: false,
98
- accepts: { mediaTypes: ['video/*', 'image/*'], extensions: ['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.jpg', '.jpeg', '.png', '.webp', '.gif'] },
114
+ accepts: { mediaTypes: ['video/*', 'image/*'], extensions: ['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.jpg', '.jpeg', '.png', '.heic', '.webp', '.gif'] },
99
115
  emits: { mediaTypes: ['video/mp4', 'image/jpeg'], extensions: ['.mp4', '.jpg'] },
100
- arguments: [{ name: 'file', type: 'path', required: false, repeatable: false, help: 'the file to shrink. "-" or none reads stdin' }],
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' }],
101
117
  options: OPTIONS.map((o) => (o.name === 'to' ? { ...o, values: plan.TARGETS.map((t) => t.id), valuesOpen: true } : o)),
102
118
  targets: plan.TARGETS.map((t) => ({ id: t.id, bytes: t.bytes, label: t.label })),
103
- 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' },
104
- result: { fields: { input: 'path', output: 'path', path: 'path', before: 'integer', after: 'integer', target: 'integer', attempts: 'integer', width: 'integer', height: 'integer' } },
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)' } },
105
121
  // The desktop app carries ffmpeg; the npm command line uses the one on the
106
122
  // PATH, and says how to install it if there is none.
107
123
  needs: [{ id: 'ffmpeg', kind: 'binary', bundled: 'in the desktop app; the npm install uses ffmpeg from the PATH' }],
@@ -122,8 +138,11 @@ function parseTarget(value) {
122
138
  const preset = plan.TARGETS.find((t) => t.id === value.toLowerCase());
123
139
  if (preset) return preset;
124
140
 
125
- const m = /^(\d+(?:\.\d+)?)\s*(g|m|k)?b?$/i.exec(value.trim());
141
+ const m = /^(\d+(?:\.\d+)?)\s*(?:(g|m|k)b?|(b))?$/i.exec(value.trim());
126
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?`);
127
146
  const n = Number(m[1]);
128
147
  const unit = (m[2] || 'm').toLowerCase();
129
148
  const bytes = Math.round(n * (unit === 'g' ? 1000 * MB : unit === 'k' ? 1000 : MB));
@@ -142,18 +161,19 @@ function needValue(flag, value, dashOk) {
142
161
  }
143
162
 
144
163
  function parseArgs(argv) {
145
- const opts = { file: null, to: null, out: null, json: false, quiet: false, progress: false, dryRun: false };
164
+ const opts = { file: null, files: [], to: null, out: null, json: false, quiet: false, progress: false, dryRun: false, beside: false };
146
165
  let positional = false;
147
166
  for (let i = 0; i < argv.length; i++) {
148
167
  const a = argv[i];
149
168
  if (positional || a === '-' || !a.startsWith('-')) {
150
- if (opts.file !== null) throw new UsageError('Only one input file at a time');
151
- opts.file = a;
169
+ opts.files.push(a);
170
+ if (opts.file === null) opts.file = a;
152
171
  }
153
172
  else if (a === '--') positional = true;
154
173
  else if (a === '--json') opts.json = true;
155
174
  else if (a === '--progress') opts.progress = true;
156
175
  else if (a === '--dry-run') opts.dryRun = true;
176
+ else if (a === '--beside') opts.beside = true;
157
177
  else if (a === '-q' || a === '--quiet') opts.quiet = true;
158
178
  else if (a === '--to') opts.to = needValue(a, argv[++i], false);
159
179
  else if (a === '-o' || a === '--out' || a === '--output') opts.out = needValue(a, argv[++i], true);
@@ -221,12 +241,21 @@ const report = {
221
241
  line(obj) { if (this.on) this.stream.write(JSON.stringify(obj) + '\n'); },
222
242
  result(obj) { this.counts.results++; this.line({ type: 'result', ...obj }); },
223
243
  skip(obj) { this.counts.skipped++; this.line({ type: 'skip', ...obj }); },
224
- error(code, message) { this.counts.failed++; this.line({ type: 'error', ok: false, code, message }); },
244
+ error(code, message, input) { this.counts.failed++; this.line({ type: 'error', ok: false, code, message, ...(input ? { input } : {}) }); },
225
245
  done(exit) { this.line({ type: 'done', ok: exit === 0, ...this.counts, exit }); },
226
246
  };
227
247
 
228
248
  // Files to remove if a signal stops the run before it finishes.
229
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
+ }
230
259
 
231
260
  async function main(argv) {
232
261
  // Answered before anything else is looked at: a bad option beside them still
@@ -240,6 +269,13 @@ async function main(argv) {
240
269
 
241
270
  const target = parseTarget(opts.to);
242
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
+
243
279
  // Piped input has to be buffered, because two-pass encoding reads the input
244
280
  // twice and a pipe cannot be rewound. Said plainly rather than hidden.
245
281
  let input = opts.file;
@@ -275,10 +311,28 @@ async function main(argv) {
275
311
  try {
276
312
  info = await engine.probe(ffprobe, input);
277
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;
278
316
  // ffmpeg's own words ("Invalid data found when processing input") say
279
317
  // nothing to a person. The same sentence the window uses.
280
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' });
281
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
+ }
282
336
  const fits = info.bytes <= target.bytes && !toStdout;
283
337
  if (opts.dryRun) {
284
338
  const ext = info.kind === 'image' ? '.jpg' : '.mp4';
@@ -310,6 +364,16 @@ async function main(argv) {
310
364
  return 0;
311
365
  }
312
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
+
313
377
  let last = '';
314
378
  const onProgress = ({ stage, progress }) => {
315
379
  if (report.on && opts.progress) {
@@ -321,7 +385,7 @@ async function main(argv) {
321
385
  if (line !== last) { process.stderr.write(line); last = line; }
322
386
  };
323
387
 
324
- const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress };
388
+ const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress, called: fromStdin ? 'what arrived on stdin' : undefined };
325
389
  // Writing to stdout still encodes to a real file first, for the same
326
390
  // reason: the encoder needs somewhere it can seek.
327
391
  if (toStdout) { args.outDir = encodeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-out-')); cleanup.add(encodeDir); }
@@ -351,6 +415,7 @@ async function main(argv) {
351
415
  before: info.bytes, after: result.bytes, bytes: result.bytes,
352
416
  target: target.bytes, attempts: result.attempts,
353
417
  width: result.plan.width, height: result.plan.height,
418
+ ...(notes.length ? { notes } : {}),
354
419
  });
355
420
  if (!report.on && !opts.quiet) {
356
421
  const saved = Math.round((1 - result.bytes / info.bytes) * 100);
@@ -366,6 +431,144 @@ async function main(argv) {
366
431
  }
367
432
  }
368
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
+
369
572
  // A reader that stops early (`| head`) is not an error worth a stack trace.
370
573
  process.stdout.on('error', (err) => {
371
574
  if (err.code === 'EPIPE') process.exit(0);
@@ -378,6 +581,7 @@ process.stdout.on('error', (err) => {
378
581
  for (const [sig, code] of [['SIGHUP', 129], ['SIGINT', 130], ['SIGTERM', 143]]) {
379
582
  process.on(sig, () => {
380
583
  for (const p of cleanup) { try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* gone already */ } }
584
+ if (emptyIfStopped) removeIfEmpty(emptyIfStopped);
381
585
  process.exit(code);
382
586
  });
383
587
  }
package/src/engine.cjs CHANGED
@@ -16,6 +16,7 @@ const os = require('node:os');
16
16
  const path = require('node:path');
17
17
 
18
18
  const plan = require('./plan.js');
19
+ const { heifOrientation, orientationFilters } = require('./heif.cjs');
19
20
 
20
21
  const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
21
22
 
@@ -33,6 +34,9 @@ function control() {
33
34
 
34
35
  function run(bin, args, { onProgress, durationSec, ctl } = {}) {
35
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 }));
36
40
  const child = spawn(bin, args, { windowsHide: true });
37
41
  if (ctl) ctl.child = child;
38
42
  let stderr = '';
@@ -104,8 +108,41 @@ async function scanDuration(ffprobe, file) {
104
108
  }
105
109
  }
106
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
+
107
125
  async function probe(ffprobe, file) {
108
- const json = await ffprobeOut(ffprobe, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', 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
+ }
109
146
 
110
147
  const info = JSON.parse(json);
111
148
  const streams = info.streams || [];
@@ -114,6 +151,9 @@ async function probe(ffprobe, file) {
114
151
  const video = streams.find((s) => s.codec_type === 'video' && !(s.disposition && s.disposition.attached_pic));
115
152
  const audio = streams.find((s) => s.codec_type === 'audio');
116
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');
117
157
 
118
158
  const imageFormat = /^(image2|png_pipe|jpeg_pipe|webp_pipe)/.test((info.format && info.format.format_name) || '');
119
159
  let durationSec = Number(info.format && info.format.duration) ||
@@ -130,9 +170,24 @@ async function probe(ffprobe, file) {
130
170
  // Phones store portrait video landscape with a rotation flag, and ffmpeg
131
171
  // rotates before the scale filter runs, so plan in the shape that is shown
132
172
  // or a portrait clip gets squashed into a landscape frame.
133
- const sideRotation = (video.side_data_list || []).find((d) => d.rotation !== undefined);
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);
134
186
  const rotation = Number(sideRotation ? sideRotation.rotation : (video.tags && video.tags.rotate)) || 0;
135
- const sideways = Math.abs(Math.round(rotation)) % 180 === 90;
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;
136
191
 
137
192
  const [num, den] = String(video.r_frame_rate || '30/1').split('/').map(Number);
138
193
  const fps = den ? num / den : 30;
@@ -140,30 +195,53 @@ async function probe(ffprobe, file) {
140
195
  return {
141
196
  kind: still ? 'image' : 'video',
142
197
  durationSec,
143
- width: Number(sideways ? video.height : video.width) || 0,
144
- height: Number(sideways ? video.width : video.height) || 0,
198
+ width: Number(sideways ? shape.height : shape.width) || 0,
199
+ height: Number(sideways ? shape.width : shape.height) || 0,
145
200
  fps: Number.isFinite(fps) && fps > 0 ? fps : 30,
146
201
  hasAudio: Boolean(audio),
147
202
  bytes: fs.statSync(file).size,
203
+ ...(gridSize ? { grid: true } : {}),
204
+ ...(orientation > 1 ? { orientation } : {}),
148
205
  };
149
206
  }
150
207
 
151
208
  /*
152
209
  * 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.
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.
154
213
  */
155
- function outputPath(source, ext, exists = fs.existsSync) {
214
+ function outputPath(source, ext, exists = fs.existsSync, suffix = '-fits') {
156
215
  const dir = path.dirname(source);
157
216
  const base = path.basename(source, path.extname(source));
158
- let candidate = path.join(dir, `${base}-fits${ext}`);
217
+ let candidate = path.join(dir, `${base}${suffix}${ext}`);
159
218
  for (let n = 2; exists(candidate) && n < 1000; n++) {
160
- candidate = path.join(dir, `${base}-fits ${n}${ext}`);
219
+ candidate = path.join(dir, `${base}${suffix} ${n}${ext}`);
161
220
  }
162
221
  return candidate;
163
222
  }
164
223
 
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');
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);
167
245
  const logFile = path.join(os.tmpdir(), `justfits-${process.pid}-${Date.now()}`);
168
246
  let correction = 1;
169
247
  let result = null;
@@ -224,6 +302,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
224
302
  // A cancelled or failed encode leaves a half-written file under a name
225
303
  // that says it fits. Nothing should be left that looks sendable.
226
304
  try { fs.unlinkSync(out); } catch {}
305
+ plainError(err, [[logFile, 'its working file'], [file, called || path.basename(file)]]);
227
306
  // Fedora's default ffmpeg and other LGPL builds have no x264, and ffmpeg's
228
307
  // own wording for that does not say what to do about it.
229
308
  if (/Unknown encoder 'libx264'/.test(err.message) && !err.cancelled) {
@@ -231,7 +310,10 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
231
310
  }
232
311
  throw err;
233
312
  } finally {
234
- for (const suffix of ['-0.log', '-0.log.mbtree', '.log', '.log.mbtree']) {
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']) {
235
317
  try { fs.unlinkSync(logFile + suffix); } catch {}
236
318
  }
237
319
  }
@@ -239,9 +321,11 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
239
321
  return { ...result, over: true };
240
322
  }
241
323
 
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');
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);
244
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('');
245
329
 
246
330
  for (let attempt = 0; attempt < 5; attempt++) {
247
331
  const p = plan.planImage({ targetBytes, width: info.width, height: info.height, attempt });
@@ -250,13 +334,17 @@ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, onProgress =
250
334
  try {
251
335
  await run(ffmpeg, [
252
336
  '-hide_banner', '-nostats', '-y', '-i', file,
253
- '-vf', `scale=${p.width}:${p.height}:flags=lanczos`,
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`]),
254
342
  '-q:v', String(p.quality), out,
255
343
  ], { ctl });
256
344
  } catch (err) {
257
345
  // Same as video: no half-written file left behind under a "fits" name.
258
346
  try { fs.unlinkSync(out); } catch {}
259
- throw err;
347
+ throw plainError(err, [[file, called || path.basename(file)]]);
260
348
  }
261
349
 
262
350
  const bytes = fs.statSync(out).size;
@@ -267,4 +355,4 @@ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, onProgress =
267
355
  return { ...result, over: true };
268
356
  }
269
357
 
270
- module.exports = { control, probe, outputPath, fitVideo, fitImage, MAX_ATTEMPTS };
358
+ module.exports = { run, plainError, control, probe, outputPath, fitVideo, fitImage, isAnimatedWebp, MAX_ATTEMPTS };