@ponderdev/justfits 1.3.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/README.md CHANGED
@@ -1,12 +1,17 @@
1
1
  # Just Fits
2
2
 
3
- Makes a video small enough to send. Point it at a file, pick a limit, and it
3
+ Makes a video, picture or sound file small enough to send. Point it at a file, pick a limit, and it
4
4
  compresses to land just under that limit. Everything happens on your machine.
5
5
 
6
6
  Built because "compress for Discord" is a thing everyone needs and every
7
7
  existing answer is either a website you upload your footage to, or a wall of
8
8
  ffmpeg flags you have to get right yourself.
9
9
 
10
+ Pictures and short clips of it, the newest set for each release, are in its
11
+ press kit on ponderdev.com:
12
+ [press-kit/justfits/manifest.json](https://ponderdev.com/press-kit/justfits/manifest.json)
13
+ lists every one with its address.
14
+
10
15
  ## How it decides
11
16
 
12
17
  Hitting an exact size is arithmetic, not guesswork:
@@ -29,6 +34,17 @@ All of that lives in `src/plan.js` as pure functions, with no ffmpeg and no
29
34
  filesystem anywhere near it, because whether your file comes in under the line
30
35
  is the one thing this has to get right. `test/plan.test.cjs` covers it.
31
36
 
37
+ ### Sound on its own
38
+
39
+ A sound file (mp3, m4a, aac, wav, flac, ogg, opus, aif, aiff) goes through the
40
+ same arithmetic with nothing else to share the budget: the target, minus 5
41
+ percent and a few KB for the m4a's own headers, becomes one AAC bitrate. It is
42
+ never higher than the source's own bitrate or 192kbps, it is stereo from 64kbps
43
+ and mono below that (only for a source that has two channels), and under 16kbps
44
+ it cannot fit and says so the way a video does. If the result comes out over,
45
+ it tries once more, lower by what it measured. The result is an `.m4a`, and
46
+ cover art is left out, since the size is the point.
47
+
32
48
  ## The presets
33
49
 
34
50
  Checked August 2026, and they move, so they live in one list in `src/plan.js`
@@ -82,6 +98,10 @@ npm install -g @ponderdev/justfits
82
98
  justfits clip.mp4 --to discord
83
99
  ```
84
100
 
101
+ Installing or upgrading over Just Fits 1.1.0 or earlier, which installed from
102
+ GitHub under the plain name `justfits`, uninstall that one first with
103
+ `npm uninstall -g justfits`, or npm stops with EEXIST on the `justfits` command.
104
+
85
105
  No dependencies and no bundled encoder, so the install is under 2MB. It uses
86
106
  whatever ffmpeg is on your PATH, which on Linux is one package away
87
107
  (`pacman -S ffmpeg`, `apt install ffmpeg`). The desktop app carries its own
@@ -90,11 +110,19 @@ told to install a video encoder.
90
110
 
91
111
  Needs Node 22 or newer, and an ffmpeg with libx264 on the PATH (no minimum version has been tested).
92
112
 
113
+ What it takes in:
114
+
115
+ - Video: mp4, mov, m4v, mkv, webm, avi. Comes out as `.mp4`.
116
+ - Pictures: jpg, png, heic, webp, gif (not an animated webp). Come out as `.jpg`.
117
+ - Sound: mp3, m4a, aac, wav, flac, ogg, opus, aif, aiff. Comes out as `.m4a`
118
+ (AAC), without cover art.
119
+
93
120
  ```sh
94
121
  justfits clip.mp4 # beside it, as clip-fits.mp4 (a picture becomes clip-fits.jpg)
95
122
  justfits clip.mp4 --to gmail # any preset, or a size like 25MB
96
123
  justfits clip.mp4 -o small.mp4 # somewhere specific
97
124
  justfits clip.mp4 --json # for scripting
125
+ justfits song.wav --to gmail # sound comes out as song-fits.m4a (AAC, no cover art)
98
126
  justfits a.mp4 b.mov photo.heic # several, each fitted on its own
99
127
  justfits "Beach day" # a folder, its subfolders too, into "Beach day (fitted)"
100
128
  justfits "Beach day" --beside # a folder, each saved beside its original as name-fits
@@ -108,7 +136,7 @@ its subfolders mirrored and each result named `name-fits` as beside the original
108
136
  so the new folder holds the whole folder), and the folder itself
109
137
  is left as it was; done again, they go into `Beach day (fitted) 2`. `--beside`
110
138
  (in the app, Save next to the originals instead) saves each beside its original
111
- as `name-fits` instead. In a folder it takes the videos and pictures, and
139
+ as `name-fits` instead. In a folder it takes the videos, pictures and sound files, and
112
140
  passes over hidden files, the `._name` files a Mac leaves on other disks, and
113
141
  its own earlier results (`name-fits.mp4` and the `(fitted)` folders), so a
114
142
  folder done twice is not fitted on top of itself. `-o` and stdin take one file
@@ -118,11 +146,11 @@ brings one in). Cancel stops at once: the file being fitted is left as it was,
118
146
  the ones already fitted are kept, and no more are started.
119
147
 
120
148
  `-o` names the one result. A video has to be given an `.mp4` name and a picture
121
- a `.jpg` name, and anything else is refused before the encode (a file that
149
+ a `.jpg` name, and a sound file an `.m4a` name, and anything else is refused before the encode (a file that
122
150
  already fits is copied to `-o` as it is, so it may keep its own extension).
123
151
 
124
152
  If the name is taken it writes `clip-fits 2.mp4`, then 3, and never over an
125
- existing file. A file that is neither video nor picture is refused with a
153
+ existing file. A file that is none of video, picture or sound is refused with a
126
154
  sentence saying so (exit 1). With input from stdin and no `-o`, the result goes
127
155
  to stdout.
128
156
 
@@ -168,8 +196,12 @@ The package carries an agent skill, `agents/skills/justfits/SKILL.md`, that
168
196
  tells an AI assistant when to reach for Just Fits and how to drive it. Installing
169
197
  the command line with `npm install -g` links it in for the assistants set up on
170
198
  the machine: into Claude Code's skills folder (`~/.claude/skills/justfits`, or
171
- under `$CLAUDE_CONFIG_DIR`), and into `~/.agents/skills/justfits`, the shared
172
- folder that Codex, Gemini CLI, Copilot, Cursor, OpenCode, Amp and Goose read.
199
+ under `$CLAUDE_CONFIG_DIR`) when that folder exists, and into
200
+ `~/.agents/skills/justfits`, the shared folder that Codex, Gemini CLI, Copilot,
201
+ Cursor, OpenCode, Amp and Goose read, only when `~/.agents` is there or one of
202
+ those assistants has its own folder (`~/.codex`, `~/.gemini`, `~/.copilot`,
203
+ `~/.cursor`, or `opencode`, `amp` or `goose` under `~/.config`). With Claude Code
204
+ alone, only the Claude link is made.
173
205
  Updating the package updates the skill with it. It never replaces a folder, or
174
206
  a link to anywhere else; it only mends a link that an earlier install of Just
175
207
  Fits left behind (an uninstall leaves one pointing at nothing). `npm install -g
@@ -195,7 +227,7 @@ The two versions share your settings. A newer version's settings are kept when t
195
227
 
196
228
  ## Licences
197
229
 
198
- Built with kit 1.0.0, the parts every Just tool shares (the start screen, the
230
+ Built with kit 1.1.0, the parts every Just tool shares (the start screen, the
199
231
  run, the footer, the folder intake), from PonderDev's tools workshop. The app's
200
232
  licences page and `justfits --describe` (`"kit"`) say the same.
201
233
 
@@ -231,9 +263,13 @@ container is a real test of it. The GUI is not testable this way.
231
263
  redistribute through our history, and they move on someone else's schedule.
232
264
  `npm run fetch-ffmpeg` pulls them, `--all` gets every arch a release needs.
233
265
 
234
- Any GPL build with libx264 works. If a host moves, drop the binaries in by
235
- hand as `ffmpeg-x64`, `ffmpeg-arm64`, `ffprobe-x64`, `ffprobe-arm64`, or with
236
- `.exe` on Windows. Nothing in the app cares where they came from.
266
+ Any GPL build with libx264 works, and never a nonfree one: every build, fetched
267
+ or already there, is checked by the configure line it carries, and refused if
268
+ it was built with `--enable-nonfree`, without `--enable-gpl`, or (for ffmpeg)
269
+ without libx264. If a host moves, drop the binaries in by hand as
270
+ `ffmpeg-darwin-arm64`, `ffprobe-linux-x64`, `ffmpeg-win32-x64.exe` and so on
271
+ (the full list is at the top of `scripts/fetch-ffmpeg.mjs`), then run
272
+ `node scripts/fetch-ffmpeg.mjs --verify`, which checks them and fetches nothing.
237
273
 
238
274
  **Apple Silicon** builds come from osxexperts.net, since evermeet publishes
239
275
  x86_64 only. Those are checked against a published SHA256 before installing,
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: justfits
3
- description: Shrink a video or picture to fit a size limit with Just Fits (`justfits`), PonderDev's free command line and app, so it can be sent on Discord, email, WhatsApp, Signal, Slack and the rest. Use when the user wants to send, share, upload or attach a file that is too big: "make this fit Discord", "compress this video", "it's too big to send", "get this under 50MB", "shrink this clip for Gmail", "make every video in this folder fit". Runs entirely on the user's machine. Covers checking it's installed, picking the target, running it, and checking the result.
3
+ description: Shrink a video, picture or sound file to fit a size limit with Just Fits (`justfits`), PonderDev's free command line and app, so it can be sent on Discord, email, WhatsApp, Signal, Slack and the rest. Use when the user wants to send, share, upload or attach a file that is too big: "make this fit Discord", "compress this video", "it's too big to send", "get this under 50MB", "shrink this clip for Gmail", "make every video in this folder fit". Runs entirely on the user's machine. Covers checking it's installed, picking the target, running it, and checking the result.
4
4
  ---
5
5
 
6
6
  # Making a file fit with Just Fits
7
7
 
8
- **Just Fits** (`justfits`) compresses a video, or a picture, to land just under
8
+ **Just Fits** (`justfits`) compresses a video, a picture or a sound file to land just under
9
9
  a size limit, and measures the result. It is PonderDev's free tool: page
10
10
  https://ponderdev.com/justfits, source `ponder-dev/just-fits`. Use it instead of
11
11
  hand-written ffmpeg: it works out the bitrate and size, makes as many tries as
@@ -61,23 +61,25 @@ nothing: send the original.
61
61
  complete, the folder untouched). `--beside` saves each beside its original as
62
62
  `name-fits` instead. In a folder, hidden files, earlier `-fits` results and
63
63
  `(fitted)` folders are passed over. `-o` and stdin take one file only.
64
- - A video comes out as `name-fits.mp4` beside it, a picture as `name-fits.jpg`.
64
+ - A video comes out as `name-fits.mp4` beside it, a picture as `name-fits.jpg`, a sound file as `name-fits.m4a` (AAC; cover art is
65
+ left out, since the size is the point).
65
66
  Then `name-fits 2.mp4` and so on: it never writes over a file, and the
66
67
  original is only read. `-o path` writes somewhere else.
67
- - `-o path` names the one result: a video must end in `.mp4` and a picture in
68
- `.jpg` (a `.mov` or `.png` for the wrong kind is refused with exit 2, before
68
+ - `-o path` names the one result: a video must end in `.mp4`, a picture in
69
+ `.jpg` and a sound file in `.m4a` (a `.mov` or `.png` for the wrong kind is refused with exit 2, before
69
70
  anything is encoded). If the file already fits, `-o` still gets a copy of it,
70
71
  as a `result` line; without `-o` it is a `skip` line and nothing is written.
71
- - It reads video (mp4, mov, m4v, mkv, webm, avi) and pictures (jpg, png, heic,
72
- webp, gif). An animated WebP is refused (exit 1, code `animated-webp`) because
72
+ - It reads video (mp4, mov, m4v, mkv, webm, avi), pictures (jpg, png, heic,
73
+ webp, gif) and sound (mp3, m4a, aac, wav, flac, ogg, opus, aif, aiff). An animated WebP is refused (exit 1, code `animated-webp`) because
73
74
  it would lose its animation. A file that is damaged or is not a video or
74
75
  picture is refused with exit 1, never reported as "already fits".
75
76
  - `--to` takes a preset or a size such as `25MB`, `800KB` or `1.5GB`. `8b` is
76
77
  refused as bytes, since it is one letter from 8MB or 8KB.
77
78
  - `--dry-run` says what it would do and writes nothing.
78
79
  - With `--json`, stdout is JSON lines: a `result` line (`output`, `before` and
79
- `after` in bytes, `target`, `attempts`, `width`, `height`, and `notes` when the video is long
80
- for the target), or a `skip` line
80
+ `after` in bytes, `target`, `attempts`, `kind` (`video`, `image` or `audio`),
81
+ `width` and `height` (a sound file has `kbps` and `channels` instead), and `notes`
82
+ when the video or sound is long for the target), or a `skip` line
81
83
  when it already fits, or an `error` line; then always a `done` line. With
82
84
  several files that is one line per file, each with its `input`.
83
85
  - Exit codes: 0 done or already fit; 2 a usage mistake (bad option, unknown
@@ -92,7 +94,7 @@ nothing: send the original.
92
94
  ## Report back
93
95
 
94
96
  Give the output path in full, the size before and after, and the resolution it
95
- chose (`width` x `height`). If the resolution came out low, say so and offer
97
+ chose (`width` x `height`), or for sound the bitrate (`kbps`). If the resolution came out low, say so and offer
96
98
  the next target up, or trimming the video first. A `notes` entry or a line on
97
99
  stderr saying the video is long for the target means the picture will be soft
98
100
  or blurry: pass that on. On exit 4, say it's still
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ponderdev/justfits",
3
3
  "productName": "Just Fits",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "description": "Make a file small enough to send. Compresses video and images to an exact size limit, entirely on your own machine.",
6
6
  "author": {
7
7
  "name": "PonderDev",
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "scripts": {
25
25
  "start": "node scripts/electron.cjs .",
26
- "test": "node test/plan.test.cjs && node test/contract.test.cjs && node test/skill.test.cjs && node test/scripts.test.cjs && node test/linux-launcher.test.cjs && node test/encode.test.cjs",
26
+ "test": "node test/plan.test.cjs && node test/contract.test.cjs && node test/skill.test.cjs && node test/scripts.test.cjs && node test/linux-launcher.test.cjs && node test/encode.test.cjs && node test/words.test.cjs",
27
27
  "fetch-ffmpeg": "node scripts/fetch-ffmpeg.mjs",
28
28
  "licences": "node scripts/make-licenses.mjs",
29
29
  "icon": "npm run icon:svg && npm run icon:raster && npm run icon:icns",
package/src/cli.cjs CHANGED
@@ -19,7 +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
+ const { scan, places, EXTENSIONS } = require('./scan.cjs');
23
23
 
24
24
  // Inside a packaged app the extras sit in the app's resources folder (as
25
25
  // extraResources put them), not in vendor/. Run that way, by the tool belt or
@@ -30,8 +30,19 @@ const VENDOR = [...packaged('ffmpeg'), path.join(__dirname, '..', 'vendor', 'ffm
30
30
  const MB = 1000 * 1000;
31
31
  // Names a video must not be given with -o: it comes out as an MP4, so a .mov or
32
32
  // a .png would be a file named for what it is not.
33
+ const AUDIO_RIGHT = ['.m4a'];
33
34
  const VIDEO_WRONG = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mov', '.mkv', '.webm', '.avi', '.heic'];
34
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 });
45
+
35
46
  function human(bytes) {
36
47
  if (bytes >= 1000 * MB) return (bytes / 1000 / MB).toFixed(1) + 'GB';
37
48
  if (bytes >= MB) return (bytes / MB).toFixed(bytes >= 100 * MB ? 0 : 1) + 'MB';
@@ -46,7 +57,7 @@ const VERSION = require('../package.json').version;
46
57
  */
47
58
  const OPTIONS = [
48
59
  { 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' },
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' },
50
61
  { flags: ['--json'], name: 'json', type: 'boolean', help: 'results as JSON lines on stdout (stderr when the file goes to stdout)' },
51
62
  { flags: ['--progress'], name: 'progress', type: 'boolean', help: 'with --json, progress as JSON lines on stderr' },
52
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)"' },
@@ -75,12 +86,13 @@ function usage() {
75
86
  return `${left.padEnd(30)} ${o.help}`;
76
87
  }).join('\n');
77
88
  return `Just Fits ${VERSION}
78
- Makes a file small enough to send.
89
+ Makes a video, picture or sound file small enough to send.
79
90
 
80
91
  justfits <file> [options]
81
92
  justfits <file> <file> ... [options]
82
93
  justfits <folder> [options]
83
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)
84
96
 
85
97
  Several files, or a folder (its subfolders too), are each fitted on their
86
98
  own to the same target. Files are saved beside their originals; a folder's
@@ -109,15 +121,15 @@ function describe() {
109
121
  // The kit the app is built with (decided 2026-11-20), from the kit's own copy.
110
122
  kit: require('./kit/scan.cjs').VERSION,
111
123
  command: 'justfits',
112
- 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.',
113
125
  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'] },
126
+ accepts: { mediaTypes: ['video/*', 'image/*', 'audio/*'], extensions: [...EXTENSIONS] },
127
+ emits: { mediaTypes: ['video/mp4', 'image/jpeg', 'audio/mp4'], extensions: ['.mp4', '.jpg', '.m4a'] },
116
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' }],
117
129
  options: OPTIONS.map((o) => (o.name === 'to' ? { ...o, values: plan.TARGETS.map((t) => t.id), valuesOpen: true } : o)),
118
130
  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)' } },
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' } },
121
133
  // The desktop app carries ffmpeg; the npm command line uses the one on the
122
134
  // PATH, and says how to install it if there is none.
123
135
  needs: [{ id: 'ffmpeg', kind: 'binary', bundled: 'in the desktop app; the npm install uses ffmpeg from the PATH' }],
@@ -315,7 +327,7 @@ async function main(argv) {
315
327
  if (err.code === 'animated-webp') throw err;
316
328
  // ffmpeg's own words ("Invalid data found when processing input") say
317
329
  // 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' });
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' });
319
331
  }
320
332
  // A picture comes out as a JPEG and a video as an MP4. Asked for the other,
321
333
  // the encode would fail late or write a file named for what it is not. A
@@ -332,10 +344,18 @@ async function main(argv) {
332
344
  if (info.kind === 'video' && VIDEO_WRONG.includes(ext) && !(same && info.bytes <= target.bytes)) {
333
345
  throw new UsageError(`${called} is a video, so it comes out as an MP4. Give -o a name ending in .mp4.`);
334
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
+ }
335
355
  }
336
356
  const fits = info.bytes <= target.bytes && !toStdout;
337
357
  if (opts.dryRun) {
338
- const ext = info.kind === 'image' ? '.jpg' : '.mp4';
358
+ const ext = EXT_OF[info.kind];
339
359
  const would = fits ? (outPath || path.resolve(input)) : (outPath || (toStdout ? '-' : engine.outputPath(path.resolve(input), ext)));
340
360
  report.result({ ok: true, dryRun: true, input: fromStdin ? '-' : path.resolve(input), output: would, before: info.bytes, target: target.bytes, fits });
341
361
  if (!opts.quiet && !report.on) {
@@ -368,8 +388,9 @@ async function main(argv) {
368
388
  // minutes of encoding, not after. It still tries, and exit 4 says if it
369
389
  // stayed over.
370
390
  const notes = [];
371
- if (info.kind === 'video') {
372
- const note = plan.lengthNote(plan.planVideo({ ...info, targetBytes: target.bytes }), human(target.bytes));
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));
373
394
  if (note) notes.push(note);
374
395
  if (notes.length && !report.on && !opts.quiet) process.stderr.write(notes[0] + '\n');
375
396
  }
@@ -391,7 +412,7 @@ async function main(argv) {
391
412
  if (toStdout) { args.outDir = encodeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'justfits-out-')); cleanup.add(encodeDir); }
392
413
  else if (outPath) args.outDir = path.dirname(outPath);
393
414
 
394
- const result = info.kind === 'image' ? await engine.fitImage(args) : await engine.fitVideo(args);
415
+ const result = await fitterFor(info.kind)(args);
395
416
  if (!opts.quiet && !opts.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
396
417
 
397
418
  let finalPath = result.path;
@@ -414,7 +435,7 @@ async function main(argv) {
414
435
  ok: !result.over, path: finalPath, input: fromStdin ? '-' : path.resolve(opts.file), output: finalPath,
415
436
  before: info.bytes, after: result.bytes, bytes: result.bytes,
416
437
  target: target.bytes, attempts: result.attempts,
417
- width: result.plan.width, height: result.plan.height,
438
+ ...madeFields(info, result.plan),
418
439
  ...(notes.length ? { notes } : {}),
419
440
  });
420
441
  if (!report.on && !opts.quiet) {
@@ -462,7 +483,7 @@ async function fitMany(opts, target) {
462
483
  info = await engine.probe(ffprobe, f.path);
463
484
  } catch (err) {
464
485
  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.`;
486
+ const message = animated ? err.message : `${f.name} is not a video, picture or sound file that Just Fits can read.`;
466
487
  report.error(animated ? 'animated-webp' : 'not-media', message, f.path);
467
488
  tally.failed++;
468
489
  say(`${tag}: ${message}`);
@@ -474,7 +495,7 @@ async function fitMany(opts, target) {
474
495
  // Already small enough in a folder's results folder: copied in as it is,
475
496
  // so the results folder holds the whole folder (decided 2026-11-20).
476
497
  const copyIn = fits && Boolean(where.folder);
477
- const ext = fits ? path.extname(f.path) : info.kind === 'image' ? '.jpg' : '.mp4';
498
+ const ext = fits ? path.extname(f.path) : EXT_OF[info.kind];
478
499
  if (opts.dryRun) {
479
500
  const would = fits && !copyIn ? f.path : engine.outputPath(where.outDir ? path.join(where.outDir, f.name) : f.path, ext, fs.existsSync, where.suffix);
480
501
  report.result({ ok: true, dryRun: true, input: f.path, output: would, before: info.bytes, target: target.bytes, fits });
@@ -508,8 +529,9 @@ async function fitMany(opts, target) {
508
529
  }
509
530
 
510
531
  const notes = [];
511
- if (info.kind === 'video') {
512
- const note = plan.lengthNote(plan.planVideo({ ...info, targetBytes: target.bytes }), human(target.bytes));
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));
513
535
  if (note) notes.push(note);
514
536
  }
515
537
 
@@ -529,7 +551,7 @@ async function fitMany(opts, target) {
529
551
  if (where.outDir) fs.mkdirSync(where.outDir, { recursive: true });
530
552
  if (where.folder) emptyIfStopped = [where.outDir, where.folder];
531
553
  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);
554
+ result = await fitterFor(info.kind)(args);
533
555
  emptyIfStopped = null;
534
556
  if (where.folder) folders.add(where.folder);
535
557
  } catch (err) {
@@ -548,7 +570,7 @@ async function fitMany(opts, target) {
548
570
  ok: !result.over, path: result.path, input: f.path, output: result.path,
549
571
  before: info.bytes, after: result.bytes, bytes: result.bytes,
550
572
  target: target.bytes, attempts: result.attempts,
551
- width: result.plan.width, height: result.plan.height,
573
+ ...madeFields(info, result.plan),
552
574
  ...(notes.length ? { notes } : {}),
553
575
  });
554
576
  if (result.over) tally.over++; else tally.fitted++;
package/src/engine.cjs CHANGED
@@ -18,6 +18,11 @@ const path = require('node:path');
18
18
  const plan = require('./plan.js');
19
19
  const { heifOrientation, orientationFilters } = require('./heif.cjs');
20
20
 
21
+ // What this file says to a person goes through plan's words (plan.useWords):
22
+ // English for the command line, the window's language once main hands its
23
+ // words over. ffmpeg's own lines are passed on as ffmpeg wrote them.
24
+ const say = () => plan.words();
25
+
21
26
  const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
22
27
 
23
28
  // The first go is the plan; the rest correct for what x264 actually produced,
@@ -60,7 +65,7 @@ function run(bin, args, { onProgress, durationSec, ctl } = {}) {
60
65
  if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
61
66
  if (code !== 0) {
62
67
  const why = stderr.trim().split('\n').filter(Boolean).slice(-3).join('\n');
63
- return reject(new Error(why || `ffmpeg exited with ${code}`));
68
+ return reject(new Error(why || say().t('ffmpeg exited with {code}', { code })));
64
69
  }
65
70
  resolve();
66
71
  });
@@ -80,7 +85,7 @@ function ffprobeOut(ffprobe, args) {
80
85
  // and means nothing to a person or a script; the line after it says why.
81
86
  const reason = () => err.split('\n').map((l) => l.trim())
82
87
  .filter((l) => l && !/^\[[^\]]* @ 0x[0-9a-f]+\]/i.test(l)).pop();
83
- child.on('close', (code) => (code === 0 ? resolve(out) : reject(new Error(reason() || 'Could not read that file'))));
88
+ child.on('close', (code) => (code === 0 ? resolve(out) : reject(new Error(reason() || say().t('Could not read that file')))));
84
89
  });
85
90
  }
86
91
 
@@ -93,9 +98,9 @@ function clockSeconds(value) {
93
98
  // The last packet's timestamp. Only reached for files whose header carries no
94
99
  // duration at all (a webm recorded live by a browser), so the cost of reading
95
100
  // every packet header is paid only when there is no other way to know.
96
- async function scanDuration(ffprobe, file) {
101
+ async function scanDuration(ffprobe, file, stream = 'v:0') {
97
102
  try {
98
- const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', 'v:0',
103
+ const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', stream,
99
104
  '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file]);
100
105
  let last = 0;
101
106
  for (const line of packets.split('\n')) {
@@ -127,7 +132,7 @@ async function probe(ffprobe, file) {
127
132
  // out as one still JPEG while saying it worked. Refused instead, from the
128
133
  // file's own header, whatever this ffprobe makes of it.
129
134
  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' });
135
+ throw Object.assign(new Error(say().t('{name} is an animated WebP, which Just Fits cannot shrink without losing the animation. Convert it to a video first.', { name: path.basename(file) })), { code: 'animated-webp' });
131
136
  }
132
137
  // Stream groups (how a phone's HEIC says its tiles make one picture) came in
133
138
  // ffprobe 7.0, and an older one refuses the option outright. The command line
@@ -150,10 +155,27 @@ async function probe(ffprobe, file) {
150
155
  // picture anyone means to send, so it never counts as one.
151
156
  const video = streams.find((s) => s.codec_type === 'video' && !(s.disposition && s.disposition.attached_pic));
152
157
  const audio = streams.find((s) => s.codec_type === 'audio');
153
- if (!video) throw new Error('There is no picture in that file');
158
+ // Sound and nothing to look at (an attached cover picture does not count):
159
+ // a song, a voice memo. It has no picture, and is not refused for that.
160
+ if (!video && audio) {
161
+ let durationSec = Number(info.format && info.format.duration) || Number(audio.duration) ||
162
+ clockSeconds(audio.tags && (audio.tags.DURATION || audio.tags.duration)) || 0;
163
+ if (!durationSec) durationSec = await scanDuration(ffprobe, file, 'a:0');
164
+ if (!(durationSec > 0)) throw new Error(say().t('Could not read that file'));
165
+ const bitRate = Number(audio.bit_rate) || Number(info.format && info.format.bit_rate) || 0;
166
+ return {
167
+ kind: 'audio',
168
+ durationSec,
169
+ hasAudio: true,
170
+ channels: Number(audio.channels) || 2,
171
+ sourceKbps: Math.round(bitRate / 1000),
172
+ bytes: fs.statSync(file).size,
173
+ };
174
+ }
175
+ if (!video) throw new Error(say().t('There is no picture in that file'));
154
176
  // A damaged picture can still be named a stream, with no size: a few stray
155
177
  // 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');
178
+ if (!(video.width > 0 && video.height > 0)) throw new Error(say().t('There is no picture in that file'));
157
179
 
158
180
  const imageFormat = /^(image2|png_pipe|jpeg_pipe|webp_pipe)/.test((info.format && info.format.format_name) || '');
159
181
  let durationSec = Number(info.format && info.format.duration) ||
@@ -279,7 +301,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
279
301
  // where the picture actually needs it.
280
302
  await run(ffmpeg, [...common, '-pass:v', '1', '-an', '-f', 'mp4', NULL_DEVICE], {
281
303
  durationSec: info.durationSec, ctl,
282
- onProgress: (v) => onProgress({ stage: 'Looking at the video', progress: v * 0.35, attempt }),
304
+ onProgress: (v) => onProgress({ stage: say().t('Looking at the video'), progress: v * 0.35, attempt }),
283
305
  });
284
306
 
285
307
  const audioArgs = p.audioKbps
@@ -288,7 +310,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
288
310
 
289
311
  await run(ffmpeg, [...common, '-pass:v', '2', ...audioArgs, '-movflags', '+faststart', out], {
290
312
  durationSec: info.durationSec, ctl,
291
- onProgress: (v) => onProgress({ stage: 'Compressing', progress: 0.35 + v * 0.65, attempt }),
313
+ onProgress: (v) => onProgress({ stage: say().t('Compressing'), progress: 0.35 + v * 0.65, attempt }),
292
314
  });
293
315
 
294
316
  const bytes = fs.statSync(out).size;
@@ -306,7 +328,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
306
328
  // Fedora's default ffmpeg and other LGPL builds have no x264, and ffmpeg's
307
329
  // own wording for that does not say what to do about it.
308
330
  if (/Unknown encoder 'libx264'/.test(err.message) && !err.cancelled) {
309
- throw new Error(`This ffmpeg has no H.264 encoder (libx264), which video needs. Install a full ffmpeg build.\n${err.message}`);
331
+ throw new Error(`${say().t('This ffmpeg has no H.264 encoder (libx264), which video needs. Install a full ffmpeg build.')}\n${err.message}`);
310
332
  }
311
333
  throw err;
312
334
  } finally {
@@ -321,6 +343,51 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
321
343
  return { ...result, over: true };
322
344
  }
323
345
 
346
+ /*
347
+ * Sound on its own, to an AAC .m4a. One pass is enough (AAC at a set bitrate
348
+ * lands within a percent or two of the plan), and if it still comes out over
349
+ * there is one more try, aimed lower by what the first one measured. Cover
350
+ * art is left out: the size is the point.
351
+ */
352
+ const AUDIO_ATTEMPTS = 2;
353
+
354
+ async function fitAudio({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
355
+ const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.m4a', fs.existsSync, suffix);
356
+ let correction = 1;
357
+ let result = null;
358
+ let lastPlan = null;
359
+
360
+ try {
361
+ for (let attempt = 0; attempt < AUDIO_ATTEMPTS; attempt++) {
362
+ const p = plan.planAudio({ ...info, targetBytes, correction });
363
+ const key = `${p.kbps},${p.channels}`;
364
+ if (key === lastPlan) break;
365
+ lastPlan = key;
366
+
367
+ await run(ffmpeg, [
368
+ '-hide_banner', '-nostats', '-progress', 'pipe:1', '-y',
369
+ '-i', file,
370
+ '-map', '0:a:0', '-vn',
371
+ '-c:a', 'aac', '-b:a', `${p.kbps}k`, '-ac', String(p.channels),
372
+ '-map_metadata', '0', '-movflags', '+faststart', out,
373
+ ], {
374
+ durationSec: info.durationSec, ctl,
375
+ onProgress: (v) => onProgress({ stage: say().t('Compressing'), progress: v, attempt }),
376
+ });
377
+
378
+ const bytes = fs.statSync(out).size;
379
+ result = { path: out, bytes, plan: { ...p, audioKbps: p.kbps, audioChannels: p.channels }, attempts: attempt + 1, durationSec: info.durationSec };
380
+ if (bytes <= targetBytes) return result;
381
+ correction = plan.correctionFor(bytes, targetBytes, correction);
382
+ }
383
+ } catch (err) {
384
+ try { fs.unlinkSync(out); } catch {}
385
+ throw plainError(err, [[file, called || path.basename(file)]]);
386
+ }
387
+
388
+ return { ...result, over: true };
389
+ }
390
+
324
391
  async function fitImage({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
325
392
  const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.jpg', fs.existsSync, suffix);
326
393
  let result = null;
@@ -329,7 +396,7 @@ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
329
396
 
330
397
  for (let attempt = 0; attempt < 5; attempt++) {
331
398
  const p = plan.planImage({ targetBytes, width: info.width, height: info.height, attempt });
332
- onProgress({ stage: attempt ? 'Trying harder' : 'Compressing', progress: attempt / 5, attempt });
399
+ onProgress({ stage: attempt ? say().t('Trying harder') : say().t('Compressing'), progress: attempt / 5, attempt });
333
400
 
334
401
  try {
335
402
  await run(ffmpeg, [
@@ -355,4 +422,4 @@ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, suffix, calle
355
422
  return { ...result, over: true };
356
423
  }
357
424
 
358
- module.exports = { run, plainError, control, probe, outputPath, fitVideo, fitImage, isAnimatedWebp, MAX_ATTEMPTS };
425
+ module.exports = { run, plainError, control, probe, outputPath, fitVideo, fitAudio, fitImage, isAnimatedWebp, MAX_ATTEMPTS };