@ponderdev/justfits 1.2.0 → 1.4.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, EXTENSIONS } = 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,20 @@ 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 AUDIO_RIGHT = ['.m4a'];
34
+ const VIDEO_WRONG = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mov', '.mkv', '.webm', '.avi', '.heic'];
35
+
36
+ // What each kind comes out as, and the engine call that makes it.
37
+ const EXT_OF = { image: '.jpg', audio: '.m4a', video: '.mp4' };
38
+ const fitterFor = (kind) => (kind === 'image' ? engine.fitImage : kind === 'audio' ? engine.fitAudio : engine.fitVideo);
39
+
40
+ // The line of a result that says how it was made: a frame for a picture or
41
+ // video, a bitrate and channels for sound.
42
+ const madeFields = (info, plan1) => (info.kind === 'audio'
43
+ ? { kind: 'audio', kbps: plan1.kbps, channels: plan1.channels }
44
+ : { kind: info.kind, width: plan1.width, height: plan1.height });
30
45
 
31
46
  function human(bytes) {
32
47
  if (bytes >= 1000 * MB) return (bytes / 1000 / MB).toFixed(1) + 'GB';
@@ -42,9 +57,10 @@ const VERSION = require('../package.json').version;
42
57
  */
43
58
  const OPTIONS = [
44
59
  { 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' },
60
+ { 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 (sound: name-fits.m4a); a folder\'s go into a new "folder (fitted)" beside it' },
46
61
  { flags: ['--json'], name: 'json', type: 'boolean', help: 'results as JSON lines on stdout (stderr when the file goes to stdout)' },
47
62
  { flags: ['--progress'], name: 'progress', type: 'boolean', help: 'with --json, progress as JSON lines on stderr' },
63
+ { 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
64
  { flags: ['--dry-run'], name: 'dry-run', type: 'boolean', help: 'say what would happen and write nothing' },
49
65
  { flags: ['-q', '--quiet'], name: 'quiet', type: 'boolean', help: 'nothing on stderr but errors' },
50
66
  { flags: ['-h', '--help'], name: 'help', type: 'boolean', help: 'this, and nothing else' },
@@ -56,6 +72,7 @@ const EXIT = [
56
72
  { code: 0, meaning: 'Done, or it already fit.' },
57
73
  { code: 1, meaning: 'Failed. Nothing usable was written.' },
58
74
  { code: 2, meaning: 'Usage: a bad option, a missing value, an unknown target or a missing input. Nothing was started.' },
75
+ { code: 3, meaning: 'Several files: some were done and some failed. Each file has its own line under --json.' },
59
76
  { code: 4, meaning: 'Done, but still over the target after every try. The closest result was written.' },
60
77
  { code: 129, meaning: 'Stopped by a hang-up. Part files removed.' },
61
78
  { code: 130, meaning: 'Stopped with Ctrl-C. Part files removed.' },
@@ -69,10 +86,18 @@ function usage() {
69
86
  return `${left.padEnd(30)} ${o.help}`;
70
87
  }).join('\n');
71
88
  return `Just Fits ${VERSION}
72
- Makes a file small enough to send.
89
+ Makes a video, picture or sound file small enough to send.
73
90
 
74
91
  justfits <file> [options]
92
+ justfits <file> <file> ... [options]
93
+ justfits <folder> [options]
75
94
  cat clip.mp4 | justfits --to discord > small.mp4
95
+ justfits song.wav --to gmail (sound comes out as an AAC .m4a, without cover art)
96
+
97
+ Several files, or a folder (its subfolders too), are each fitted on their
98
+ own to the same target. Files are saved beside their originals; a folder's
99
+ go into a new folder beside it, "folder (fitted)", with the files that
100
+ already fit copied in so it is complete (--beside: beside each original).
76
101
 
77
102
  Options
78
103
  ${opts}
@@ -80,7 +105,8 @@ ${opts}
80
105
  Targets
81
106
  ${targets}
82
107
 
83
- Exit status: 0 done, 1 failed, 2 usage, 4 still over the target after every try.
108
+ Exit status: 0 done, 1 failed, 2 usage, 3 some of several failed,
109
+ 4 still over the target after every try.
84
110
 
85
111
  Your original is only ever read. Nothing is uploaded.`;
86
112
  }
@@ -92,16 +118,18 @@ function describe() {
92
118
  product: 'Just Fits',
93
119
  version: VERSION,
94
120
  licence: require('../package.json').license,
121
+ // The kit the app is built with (decided 2026-11-20), from the kit's own copy.
122
+ kit: require('./kit/scan.cjs').VERSION,
95
123
  command: 'justfits',
96
- job: 'Make a video or image small enough to send, under an exact size limit.',
124
+ job: 'Make a video, image or sound file small enough to send, under an exact size limit.',
97
125
  network: false,
98
- accepts: { mediaTypes: ['video/*', 'image/*'], extensions: ['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.jpg', '.jpeg', '.png', '.webp', '.gif'] },
99
- 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' }],
126
+ accepts: { mediaTypes: ['video/*', 'image/*', 'audio/*'], extensions: [...EXTENSIONS] },
127
+ emits: { mediaTypes: ['video/mp4', 'image/jpeg', 'audio/mp4'], extensions: ['.mp4', '.jpg', '.m4a'] },
128
+ 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
129
  options: OPTIONS.map((o) => (o.name === 'to' ? { ...o, values: plan.TARGETS.map((t) => t.id), valuesOpen: true } : o)),
102
130
  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' } },
131
+ output: { video: 'name-fits.mp4 beside the input', picture: 'name-fits.jpg beside the input', sound: 'name-fits.m4a beside the input (AAC, cover art left out)', taken: 'name-fits 2.mp4, then 3, never over an existing file', withO: '-o names the result: a video must end in .mp4, a picture in .jpg and a sound file in .m4a. 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' },
132
+ result: { fields: { input: 'path', output: 'path', path: 'path', before: 'integer', after: 'integer', target: 'integer', attempts: 'integer', width: 'integer', height: 'integer', kind: "'video', 'image' or 'audio'", kbps: 'integer, sound only: the bitrate it was encoded at', channels: 'integer, sound only: 1 or 2', notes: 'array of strings, present when the video is long for the target (a small, blurry or softer picture), or a sound file is too long for it' } },
105
133
  // The desktop app carries ffmpeg; the npm command line uses the one on the
106
134
  // PATH, and says how to install it if there is none.
107
135
  needs: [{ id: 'ffmpeg', kind: 'binary', bundled: 'in the desktop app; the npm install uses ffmpeg from the PATH' }],
@@ -122,8 +150,11 @@ function parseTarget(value) {
122
150
  const preset = plan.TARGETS.find((t) => t.id === value.toLowerCase());
123
151
  if (preset) return preset;
124
152
 
125
- const m = /^(\d+(?:\.\d+)?)\s*(g|m|k)?b?$/i.exec(value.trim());
153
+ const m = /^(\d+(?:\.\d+)?)\s*(?:(g|m|k)b?|(b))?$/i.exec(value.trim());
126
154
  if (!m) throw new UsageError(`Unknown target "${value}". Try a preset from --help, or a size like 25MB.`);
155
+ // "8b" is eight bytes, which nothing fits in, and it used to be read as 8MB.
156
+ // Refused rather than guessed: 8MB and 8KB are both one letter away.
157
+ if (m[3]) throw new UsageError(`Target "${value}" is in bytes. Did you mean ${m[1]}MB or ${m[1]}KB?`);
127
158
  const n = Number(m[1]);
128
159
  const unit = (m[2] || 'm').toLowerCase();
129
160
  const bytes = Math.round(n * (unit === 'g' ? 1000 * MB : unit === 'k' ? 1000 : MB));
@@ -142,18 +173,19 @@ function needValue(flag, value, dashOk) {
142
173
  }
143
174
 
144
175
  function parseArgs(argv) {
145
- const opts = { file: null, to: null, out: null, json: false, quiet: false, progress: false, dryRun: false };
176
+ const opts = { file: null, files: [], to: null, out: null, json: false, quiet: false, progress: false, dryRun: false, beside: false };
146
177
  let positional = false;
147
178
  for (let i = 0; i < argv.length; i++) {
148
179
  const a = argv[i];
149
180
  if (positional || a === '-' || !a.startsWith('-')) {
150
- if (opts.file !== null) throw new UsageError('Only one input file at a time');
151
- opts.file = a;
181
+ opts.files.push(a);
182
+ if (opts.file === null) opts.file = a;
152
183
  }
153
184
  else if (a === '--') positional = true;
154
185
  else if (a === '--json') opts.json = true;
155
186
  else if (a === '--progress') opts.progress = true;
156
187
  else if (a === '--dry-run') opts.dryRun = true;
188
+ else if (a === '--beside') opts.beside = true;
157
189
  else if (a === '-q' || a === '--quiet') opts.quiet = true;
158
190
  else if (a === '--to') opts.to = needValue(a, argv[++i], false);
159
191
  else if (a === '-o' || a === '--out' || a === '--output') opts.out = needValue(a, argv[++i], true);
@@ -221,12 +253,21 @@ const report = {
221
253
  line(obj) { if (this.on) this.stream.write(JSON.stringify(obj) + '\n'); },
222
254
  result(obj) { this.counts.results++; this.line({ type: 'result', ...obj }); },
223
255
  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 }); },
256
+ error(code, message, input) { this.counts.failed++; this.line({ type: 'error', ok: false, code, message, ...(input ? { input } : {}) }); },
225
257
  done(exit) { this.line({ type: 'done', ok: exit === 0, ...this.counts, exit }); },
226
258
  };
227
259
 
228
260
  // Files to remove if a signal stops the run before it finishes.
229
261
  const cleanup = new Set();
262
+ // A results folder made for the file being fitted ([dir, folder]), removed on
263
+ // a signal only if it is still empty.
264
+ let emptyIfStopped = null;
265
+ function removeIfEmpty([dir, folder]) {
266
+ for (; dir.startsWith(folder); dir = path.dirname(dir)) {
267
+ try { fs.rmdirSync(dir); } catch { break; }
268
+ if (dir === folder) break;
269
+ }
270
+ }
230
271
 
231
272
  async function main(argv) {
232
273
  // Answered before anything else is looked at: a bad option beside them still
@@ -240,6 +281,13 @@ async function main(argv) {
240
281
 
241
282
  const target = parseTarget(opts.to);
242
283
 
284
+ // Several inputs, or a folder: each one fitted on its own (fitMany). One file
285
+ // goes the way it always has, below, so its output and JSON are unchanged.
286
+ const isFolder = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
287
+ if (opts.files.length > 1 || (opts.files.length === 1 && opts.files[0] !== '-' && isFolder(opts.files[0]))) {
288
+ return fitMany(opts, target);
289
+ }
290
+
243
291
  // Piped input has to be buffered, because two-pass encoding reads the input
244
292
  // twice and a pipe cannot be rewound. Said plainly rather than hidden.
245
293
  let input = opts.file;
@@ -275,13 +323,39 @@ async function main(argv) {
275
323
  try {
276
324
  info = await engine.probe(ffprobe, input);
277
325
  } catch (err) {
326
+ // A file it can read but will not shrink says why in its own words.
327
+ if (err.code === 'animated-webp') throw err;
278
328
  // ffmpeg's own words ("Invalid data found when processing input") say
279
329
  // nothing to a person. The same sentence the window uses.
280
- 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' });
330
+ throw Object.assign(new Error(`${fromStdin ? 'What arrived on stdin' : path.basename(input)} is not a video, picture or sound file that Just Fits can read.`), { code: 'not-media' });
331
+ }
332
+ // A picture comes out as a JPEG and a video as an MP4. Asked for the other,
333
+ // the encode would fail late or write a file named for what it is not. A
334
+ // file that already fits is copied as it is, so it may keep its own kind of
335
+ // name (an already small PNG to copy.png). Stdin has no name of its own, and
336
+ // the temp file it is buffered into must not turn up in a sentence.
337
+ if (outPath) {
338
+ const ext = path.extname(outPath).toLowerCase();
339
+ const same = !fromStdin && ext === path.extname(input).toLowerCase();
340
+ const called = fromStdin ? 'What arrived on stdin' : path.basename(input);
341
+ if (info.kind === 'image' && !['.jpg', '.jpeg'].includes(ext) && !(same && info.bytes <= target.bytes)) {
342
+ throw new UsageError(`${called} is a picture, so it comes out as a JPEG. Give -o a name ending in .jpg.`);
343
+ }
344
+ if (info.kind === 'video' && VIDEO_WRONG.includes(ext) && !(same && info.bytes <= target.bytes)) {
345
+ throw new UsageError(`${called} is a video, so it comes out as an MP4. Give -o a name ending in .mp4.`);
346
+ }
347
+ // A sound file that already fits is copied as it is, so an .m4a name on a FLAC, Opus or WAV
348
+ // would label it as something it is not. Checked before the .m4a rule, so the two never disagree.
349
+ if (info.kind === 'audio' && !same && info.bytes <= target.bytes && !toStdout) {
350
+ throw new UsageError(`${called} already fits under ${human(target.bytes)}, so it would be copied as it is. Give -o a name ending in ${path.extname(input) || 'its own extension'}, or leave -o out.`);
351
+ }
352
+ if (info.kind === 'audio' && !AUDIO_RIGHT.includes(ext) && info.bytes > target.bytes) {
353
+ throw new UsageError(`${called} is sound, so it comes out as an M4A. Give -o a name ending in .m4a.`);
354
+ }
281
355
  }
282
356
  const fits = info.bytes <= target.bytes && !toStdout;
283
357
  if (opts.dryRun) {
284
- const ext = info.kind === 'image' ? '.jpg' : '.mp4';
358
+ const ext = EXT_OF[info.kind];
285
359
  const would = fits ? (outPath || path.resolve(input)) : (outPath || (toStdout ? '-' : engine.outputPath(path.resolve(input), ext)));
286
360
  report.result({ ok: true, dryRun: true, input: fromStdin ? '-' : path.resolve(input), output: would, before: info.bytes, target: target.bytes, fits });
287
361
  if (!opts.quiet && !report.on) {
@@ -310,6 +384,17 @@ async function main(argv) {
310
384
  return 0;
311
385
  }
312
386
 
387
+ // Too long for the target at any quality worth having: say so before
388
+ // minutes of encoding, not after. It still tries, and exit 4 says if it
389
+ // stayed over.
390
+ const notes = [];
391
+ if (info.kind === 'video' || info.kind === 'audio') {
392
+ const planned = info.kind === 'audio' ? plan.planAudio({ ...info, targetBytes: target.bytes }) : plan.planVideo({ ...info, targetBytes: target.bytes });
393
+ const note = plan.lengthNote(planned, human(target.bytes));
394
+ if (note) notes.push(note);
395
+ if (notes.length && !report.on && !opts.quiet) process.stderr.write(notes[0] + '\n');
396
+ }
397
+
313
398
  let last = '';
314
399
  const onProgress = ({ stage, progress }) => {
315
400
  if (report.on && opts.progress) {
@@ -321,13 +406,13 @@ async function main(argv) {
321
406
  if (line !== last) { process.stderr.write(line); last = line; }
322
407
  };
323
408
 
324
- const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress };
409
+ const args = { ffmpeg, file: input, info, targetBytes: target.bytes, onProgress, called: fromStdin ? 'what arrived on stdin' : undefined };
325
410
  // Writing to stdout still encodes to a real file first, for the same
326
411
  // reason: the encoder needs somewhere it can seek.
327
412
  if (toStdout) { args.outDir = encodeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-out-')); cleanup.add(encodeDir); }
328
413
  else if (outPath) args.outDir = path.dirname(outPath);
329
414
 
330
- const result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
415
+ const result = await fitterFor(info.kind)(args);
331
416
  if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
332
417
 
333
418
  let finalPath = result.path;
@@ -350,7 +435,8 @@ async function main(argv) {
350
435
  ok: !result.over, path: finalPath, input: fromStdin ? '-' : path.resolve(opts.file), output: finalPath,
351
436
  before: info.bytes, after: result.bytes, bytes: result.bytes,
352
437
  target: target.bytes, attempts: result.attempts,
353
- width: result.plan.width, height: result.plan.height,
438
+ ...madeFields(info, result.plan),
439
+ ...(notes.length ? { notes } : {}),
354
440
  });
355
441
  if (!report.on && !opts.quiet) {
356
442
  const saved = Math.round((1 - result.bytes / info.bytes) * 100);
@@ -366,6 +452,145 @@ async function main(argv) {
366
452
  }
367
453
  }
368
454
 
455
+ /*
456
+ * Several files, or a folder of them: each fitted on its own to the same
457
+ * target, one after another: a file named on its own beside its original, a
458
+ * folder's into a new "folder (fitted)" beside it (--beside: beside each
459
+ * original instead). Every file gets its own
460
+ * JSON line, a result, a skip or an error with its input, so one that fails
461
+ * does not stop the rest. Exit 0 when all fit, 4 when none failed but some
462
+ * stayed over, 3 when some failed and 1 when all did.
463
+ */
464
+ async function fitMany(opts, target) {
465
+ if (opts.out) throw new UsageError('-o names one file. With several files or a folder, each result is saved beside its original.');
466
+ if (opts.files.includes('-')) throw new UsageError('stdin ("-") is one file on its own, and cannot be mixed with other inputs.');
467
+ const found = await scan(opts.files);
468
+ if (found.missing.length) throw new UsageError(`No such file: ${found.missing[0]}`);
469
+ if (!found.files.length) throw new UsageError(`There are no videos or pictures in ${opts.files.join(', ')}.`);
470
+
471
+ const ffmpeg = binaries.resolve('ffmpeg', VENDOR);
472
+ const ffprobe = binaries.resolve('ffprobe', VENDOR);
473
+ const say = (line) => { if (!report.on && !opts.quiet) process.stderr.write(line + '\n'); };
474
+ const total = found.files.length;
475
+ const tally = { fitted: 0, over: 0, skipped: 0, failed: 0 };
476
+ const place = places({ beside: opts.beside });
477
+ const folders = new Set();
478
+
479
+ for (const [i, f] of found.files.entries()) {
480
+ const tag = `[${i + 1}/${total}] ${f.name}`;
481
+ let info;
482
+ try {
483
+ info = await engine.probe(ffprobe, f.path);
484
+ } catch (err) {
485
+ const animated = err.code === 'animated-webp';
486
+ const message = animated ? err.message : `${f.name} is not a video, picture or sound file that Just Fits can read.`;
487
+ report.error(animated ? 'animated-webp' : 'not-media', message, f.path);
488
+ tally.failed++;
489
+ say(`${tag}: ${message}`);
490
+ continue;
491
+ }
492
+
493
+ const fits = info.bytes <= target.bytes;
494
+ const where = place(f);
495
+ // Already small enough in a folder's results folder: copied in as it is,
496
+ // so the results folder holds the whole folder (decided 2026-11-20).
497
+ const copyIn = fits && Boolean(where.folder);
498
+ const ext = fits ? path.extname(f.path) : EXT_OF[info.kind];
499
+ if (opts.dryRun) {
500
+ const would = fits && !copyIn ? f.path : engine.outputPath(where.outDir ? path.join(where.outDir, f.name) : f.path, ext, fs.existsSync, where.suffix);
501
+ report.result({ ok: true, dryRun: true, input: f.path, output: would, before: info.bytes, target: target.bytes, fits });
502
+ say(`${tag}: ${fits ? `${human(info.bytes)} already fits. Nothing would change.` : `${human(info.bytes)} would be fitted under ${human(target.bytes)}.`}`);
503
+ continue;
504
+ }
505
+ if (fits) {
506
+ let output = f.path;
507
+ if (copyIn) {
508
+ try {
509
+ fs.mkdirSync(where.outDir, { recursive: true });
510
+ output = engine.outputPath(path.join(where.outDir, f.name), ext, fs.existsSync, where.suffix);
511
+ fs.copyFileSync(f.path, output, fs.constants.COPYFILE_EXCL);
512
+ folders.add(where.folder);
513
+ } catch (err) {
514
+ report.error('failed', String(err.message || err), f.path);
515
+ tally.failed++;
516
+ say(`${tag}: ${String(err.message || err)}`);
517
+ continue;
518
+ }
519
+ }
520
+ report.skip({
521
+ ok: true, skipped: true, path: output, input: f.path, output,
522
+ before: info.bytes, after: info.bytes, target: target.bytes, bytes: info.bytes,
523
+ reason: 'fits-already', ...(copyIn ? { copied: true } : {}),
524
+ message: `${human(info.bytes)} already fits under ${human(target.bytes)}.${copyIn ? ' Copied in as it is.' : ''}`,
525
+ });
526
+ tally.skipped++;
527
+ say(`${tag}: ${human(info.bytes)} already fits under ${human(target.bytes)}. ${copyIn ? `Copied in as it is. ${output}` : 'Nothing to do.'}`);
528
+ continue;
529
+ }
530
+
531
+ const notes = [];
532
+ if (info.kind === 'video' || info.kind === 'audio') {
533
+ const planned = info.kind === 'audio' ? plan.planAudio({ ...info, targetBytes: target.bytes }) : plan.planVideo({ ...info, targetBytes: target.bytes });
534
+ const note = plan.lengthNote(planned, human(target.bytes));
535
+ if (note) notes.push(note);
536
+ }
537
+
538
+ let last = '';
539
+ const onProgress = ({ stage, progress }) => {
540
+ if (report.on && opts.progress) {
541
+ process.stderr.write(JSON.stringify({ type: 'progress', stage, percent: Math.round(progress * 100), input: f.path, file: i + 1, files: total }) + '\n');
542
+ return;
543
+ }
544
+ if (opts.quiet || opts.json || !process.stderr.isTTY) return;
545
+ const line = `\r${tag} ${stage} ${Math.round(progress * 100)}% `;
546
+ if (line !== last) { process.stderr.write(line); last = line; }
547
+ };
548
+
549
+ let result;
550
+ try {
551
+ if (where.outDir) fs.mkdirSync(where.outDir, { recursive: true });
552
+ if (where.folder) emptyIfStopped = [where.outDir, where.folder];
553
+ const args = { ffmpeg, file: f.path, info, targetBytes: target.bytes, onProgress, outDir: where.outDir, suffix: where.suffix };
554
+ result = await fitterFor(info.kind)(args);
555
+ emptyIfStopped = null;
556
+ if (where.folder) folders.add(where.folder);
557
+ } catch (err) {
558
+ // A results folder made for this file and left empty goes again.
559
+ if (where.folder) removeIfEmpty([where.outDir, where.folder]);
560
+ emptyIfStopped = null;
561
+ if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
562
+ report.error(err.code || 'failed', String(err.message || err), f.path);
563
+ tally.failed++;
564
+ say(`${tag}: ${String(err.message || err)}`);
565
+ continue;
566
+ }
567
+ if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
568
+
569
+ report.result({
570
+ ok: !result.over, path: result.path, input: f.path, output: result.path,
571
+ before: info.bytes, after: result.bytes, bytes: result.bytes,
572
+ target: target.bytes, attempts: result.attempts,
573
+ ...madeFields(info, result.plan),
574
+ ...(notes.length ? { notes } : {}),
575
+ });
576
+ if (result.over) tally.over++; else tally.fitted++;
577
+ const saved = Math.round((1 - result.bytes / info.bytes) * 100);
578
+ say(result.over
579
+ ? `${tag}: got to ${human(result.bytes)}, still over ${human(target.bytes)}. ${result.path}`
580
+ : `${tag}: ${human(info.bytes)} to ${human(result.bytes)}, ${saved}% smaller. ${result.path}`);
581
+ }
582
+
583
+ const bits = [`${tally.fitted} fitted`];
584
+ if (tally.skipped) bits.push(`${tally.skipped} already small enough`);
585
+ if (tally.over) bits.push(`${tally.over} still over ${human(target.bytes)}`);
586
+ if (tally.failed) bits.push(`${tally.failed} failed`);
587
+ if (!opts.dryRun) say(`${total} files: ${bits.join(', ')}.${folders.size ? ` Saved in ${[...folders].join(', ')}` : ''}`);
588
+
589
+ if (tally.failed === total) return 1;
590
+ if (tally.failed) return 3;
591
+ return tally.over ? 4 : 0;
592
+ }
593
+
369
594
  // A reader that stops early (`| head`) is not an error worth a stack trace.
370
595
  process.stdout.on('error', (err) => {
371
596
  if (err.code === 'EPIPE') process.exit(0);
@@ -378,6 +603,7 @@ process.stdout.on('error', (err) => {
378
603
  for (const [sig, code] of [['SIGHUP', 129], ['SIGINT', 130], ['SIGTERM', 143]]) {
379
604
  process.on(sig, () => {
380
605
  for (const p of cleanup) { try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* gone already */ } }
606
+ if (emptyIfStopped) removeIfEmpty(emptyIfStopped);
381
607
  process.exit(code);
382
608
  });
383
609
  }