@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/engine.cjs CHANGED
@@ -16,6 +16,12 @@ 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');
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();
19
25
 
20
26
  const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
21
27
 
@@ -33,6 +39,9 @@ function control() {
33
39
 
34
40
  function run(bin, args, { onProgress, durationSec, ctl } = {}) {
35
41
  return new Promise((resolve, reject) => {
42
+ // Cancel pressed before this started (while the file was being read, say):
43
+ // nothing is spawned, or the press would be lost and the encode would run on.
44
+ if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
36
45
  const child = spawn(bin, args, { windowsHide: true });
37
46
  if (ctl) ctl.child = child;
38
47
  let stderr = '';
@@ -56,7 +65,7 @@ function run(bin, args, { onProgress, durationSec, ctl } = {}) {
56
65
  if (ctl && ctl.cancelled) return reject(Object.assign(new Error('Cancelled'), { cancelled: true }));
57
66
  if (code !== 0) {
58
67
  const why = stderr.trim().split('\n').filter(Boolean).slice(-3).join('\n');
59
- return reject(new Error(why || `ffmpeg exited with ${code}`));
68
+ return reject(new Error(why || say().t('ffmpeg exited with {code}', { code })));
60
69
  }
61
70
  resolve();
62
71
  });
@@ -76,7 +85,7 @@ function ffprobeOut(ffprobe, args) {
76
85
  // and means nothing to a person or a script; the line after it says why.
77
86
  const reason = () => err.split('\n').map((l) => l.trim())
78
87
  .filter((l) => l && !/^\[[^\]]* @ 0x[0-9a-f]+\]/i.test(l)).pop();
79
- 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')))));
80
89
  });
81
90
  }
82
91
 
@@ -89,9 +98,9 @@ function clockSeconds(value) {
89
98
  // The last packet's timestamp. Only reached for files whose header carries no
90
99
  // duration at all (a webm recorded live by a browser), so the cost of reading
91
100
  // every packet header is paid only when there is no other way to know.
92
- async function scanDuration(ffprobe, file) {
101
+ async function scanDuration(ffprobe, file, stream = 'v:0') {
93
102
  try {
94
- const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', 'v:0',
103
+ const packets = await ffprobeOut(ffprobe, ['-v', 'error', '-select_streams', stream,
95
104
  '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', file]);
96
105
  let last = 0;
97
106
  for (const line of packets.split('\n')) {
@@ -104,8 +113,41 @@ async function scanDuration(ffprobe, file) {
104
113
  }
105
114
  }
106
115
 
116
+ // The animation flag in a WebP's extended header (VP8X): RIFF, size, WEBP,
117
+ // then the VP8X chunk, whose flags byte carries 0x02 for animation.
118
+ function isAnimatedWebp(file) {
119
+ try {
120
+ const fd = fs.openSync(file, 'r');
121
+ const head = Buffer.alloc(21);
122
+ try { fs.readSync(fd, head, 0, 21, 0); } finally { fs.closeSync(fd); }
123
+ return head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP' &&
124
+ head.toString('latin1', 12, 16) === 'VP8X' && (head[20] & 0x02) !== 0;
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+
107
130
  async function probe(ffprobe, file) {
108
- const json = await ffprobeOut(ffprobe, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', file]);
131
+ // ffmpeg reads only the first frame of an animated WebP, so it would come
132
+ // out as one still JPEG while saying it worked. Refused instead, from the
133
+ // file's own header, whatever this ffprobe makes of it.
134
+ if (isAnimatedWebp(file)) {
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' });
136
+ }
137
+ // Stream groups (how a phone's HEIC says its tiles make one picture) came in
138
+ // ffprobe 7.0, and an older one refuses the option outright. The command line
139
+ // uses whatever ffprobe is on the PATH, and Debian 12 and Ubuntu 24.04 ship
140
+ // older ones, so it asks again without it rather than calling every file
141
+ // unreadable. A tiled HEIC then reads as its first tile, as before 1.3.0.
142
+ const args = ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams'];
143
+ let json;
144
+ try {
145
+ json = await ffprobeOut(ffprobe, [...args, '-show_stream_groups', file]);
146
+ } catch {
147
+ // Its message is only "Option not found" on the last line, so any failure
148
+ // is asked again; a file that is really unreadable fails the second time too.
149
+ json = await ffprobeOut(ffprobe, [...args, file]);
150
+ }
109
151
 
110
152
  const info = JSON.parse(json);
111
153
  const streams = info.streams || [];
@@ -113,7 +155,27 @@ async function probe(ffprobe, file) {
113
155
  // picture anyone means to send, so it never counts as one.
114
156
  const video = streams.find((s) => s.codec_type === 'video' && !(s.disposition && s.disposition.attached_pic));
115
157
  const audio = streams.find((s) => s.codec_type === 'audio');
116
- 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'));
176
+ // A damaged picture can still be named a stream, with no size: a few stray
177
+ // bytes called .jpg would otherwise be "already small enough".
178
+ if (!(video.width > 0 && video.height > 0)) throw new Error(say().t('There is no picture in that file'));
117
179
 
118
180
  const imageFormat = /^(image2|png_pipe|jpeg_pipe|webp_pipe)/.test((info.format && info.format.format_name) || '');
119
181
  let durationSec = Number(info.format && info.format.duration) ||
@@ -130,9 +192,24 @@ async function probe(ffprobe, file) {
130
192
  // Phones store portrait video landscape with a rotation flag, and ffmpeg
131
193
  // rotates before the scale filter runs, so plan in the shape that is shown
132
194
  // or a portrait clip gets squashed into a landscape frame.
133
- const sideRotation = (video.side_data_list || []).find((d) => d.rotation !== undefined);
195
+ // A phone's HEIC is a grid of 512 pixel tiles, and its first stream is only
196
+ // the first tile. The picture's real size is the grid's, and ffmpeg puts the
197
+ // tiles together itself, so the scale has to follow that join (see fitImage).
198
+ const grid = (info.stream_groups || []).find((g) => g.type === 'Tile Grid');
199
+ const gridSize = grid && grid.components && grid.components[0];
200
+ const shape = gridSize || video;
201
+
202
+ // A portrait photo from a phone is a landscape grid with its rotation on the
203
+ // grid, not on the tile, so the rotation is read from whichever gives the size.
204
+ // ffprobe builds differ on where a grid's turn goes: on its component, or
205
+ // (newer builds) on the group itself, so both are read.
206
+ const sides = [...(shape.side_data_list || []), ...((grid && grid.side_data_list) || [])];
207
+ const sideRotation = sides.find((d) => d.rotation !== undefined);
134
208
  const rotation = Number(sideRotation ? sideRotation.rotation : (video.tags && video.tags.rotate)) || 0;
135
- const sideways = Math.abs(Math.round(rotation)) % 180 === 90;
209
+ // A turn that is only in the EXIF (some phones write no rotation box) is not
210
+ // applied by ffmpeg for HEIC, so it is read here and applied in fitImage.
211
+ const orientation = still && !rotation ? heifOrientation(file) : 1;
212
+ const sideways = Math.abs(Math.round(rotation)) % 180 === 90 || orientation >= 5;
136
213
 
137
214
  const [num, den] = String(video.r_frame_rate || '30/1').split('/').map(Number);
138
215
  const fps = den ? num / den : 30;
@@ -140,30 +217,53 @@ async function probe(ffprobe, file) {
140
217
  return {
141
218
  kind: still ? 'image' : 'video',
142
219
  durationSec,
143
- width: Number(sideways ? video.height : video.width) || 0,
144
- height: Number(sideways ? video.width : video.height) || 0,
220
+ width: Number(sideways ? shape.height : shape.width) || 0,
221
+ height: Number(sideways ? shape.width : shape.height) || 0,
145
222
  fps: Number.isFinite(fps) && fps > 0 ? fps : 30,
146
223
  hasAudio: Boolean(audio),
147
224
  bytes: fs.statSync(file).size,
225
+ ...(gridSize ? { grid: true } : {}),
226
+ ...(orientation > 1 ? { orientation } : {}),
148
227
  };
149
228
  }
150
229
 
151
230
  /*
152
231
  * 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.
232
+ * cannot be recreated, so it is never a candidate for the output path. The
233
+ * suffix is always -fits today; it stays a parameter for a caller that needs
234
+ * another.
154
235
  */
155
- function outputPath(source, ext, exists = fs.existsSync) {
236
+ function outputPath(source, ext, exists = fs.existsSync, suffix = '-fits') {
156
237
  const dir = path.dirname(source);
157
238
  const base = path.basename(source, path.extname(source));
158
- let candidate = path.join(dir, `${base}-fits${ext}`);
239
+ let candidate = path.join(dir, `${base}${suffix}${ext}`);
159
240
  for (let n = 2; exists(candidate) && n < 1000; n++) {
160
- candidate = path.join(dir, `${base}-fits ${n}${ext}`);
241
+ candidate = path.join(dir, `${base}${suffix} ${n}${ext}`);
161
242
  }
162
243
  return candidate;
163
244
  }
164
245
 
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');
246
+ /*
247
+ * ffmpeg's complaints name the files it was handed: the pass log in the temp
248
+ * folder, and for a pipe the temp file it was buffered into. Neither means
249
+ * anything to a person, so the log becomes "its working file" and the input
250
+ * goes back to the name the person knows (called, or the file's own).
251
+ */
252
+ function plainError(err, replacements) {
253
+ if (!err || typeof err.message !== 'string') return err;
254
+ let message = err.message;
255
+ for (const [from, to] of replacements) {
256
+ if (!from) continue;
257
+ // A name that ends where the log's suffix ("-0.log.mbtree") ends, whole.
258
+ const re = new RegExp(from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (to === 'its working file' ? '[\\w.-]*' : ''), 'g');
259
+ message = message.replace(re, to);
260
+ }
261
+ if (message !== err.message) err.message = message;
262
+ return err;
263
+ }
264
+
265
+ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
266
+ const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.mp4', fs.existsSync, suffix);
167
267
  const logFile = path.join(os.tmpdir(), `justfits-${process.pid}-${Date.now()}`);
168
268
  let correction = 1;
169
269
  let result = null;
@@ -201,7 +301,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
201
301
  // where the picture actually needs it.
202
302
  await run(ffmpeg, [...common, '-pass:v', '1', '-an', '-f', 'mp4', NULL_DEVICE], {
203
303
  durationSec: info.durationSec, ctl,
204
- 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 }),
205
305
  });
206
306
 
207
307
  const audioArgs = p.audioKbps
@@ -210,7 +310,7 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
210
310
 
211
311
  await run(ffmpeg, [...common, '-pass:v', '2', ...audioArgs, '-movflags', '+faststart', out], {
212
312
  durationSec: info.durationSec, ctl,
213
- 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 }),
214
314
  });
215
315
 
216
316
  const bytes = fs.statSync(out).size;
@@ -224,14 +324,18 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
224
324
  // A cancelled or failed encode leaves a half-written file under a name
225
325
  // that says it fits. Nothing should be left that looks sendable.
226
326
  try { fs.unlinkSync(out); } catch {}
327
+ plainError(err, [[logFile, 'its working file'], [file, called || path.basename(file)]]);
227
328
  // Fedora's default ffmpeg and other LGPL builds have no x264, and ffmpeg's
228
329
  // own wording for that does not say what to do about it.
229
330
  if (/Unknown encoder 'libx264'/.test(err.message) && !err.cancelled) {
230
- 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}`);
231
332
  }
232
333
  throw err;
233
334
  } finally {
234
- for (const suffix of ['-0.log', '-0.log.mbtree', '.log', '.log.mbtree']) {
335
+ // x264 writes each pass log as .temp and renames it when the pass ends, so
336
+ // an encode stopped mid-pass (Cancel, which on Windows ends ffmpeg outright)
337
+ // leaves the .temp forms.
338
+ 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
339
  try { fs.unlinkSync(logFile + suffix); } catch {}
236
340
  }
237
341
  }
@@ -239,24 +343,75 @@ async function fitVideo({ ffmpeg, file, info, targetBytes, outDir, onProgress =
239
343
  return { ...result, over: true };
240
344
  }
241
345
 
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');
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
+
391
+ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, suffix, called, onProgress = () => {}, ctl = control() }) {
392
+ const out = outputPath(outDir ? path.join(outDir, path.basename(file)) : file, '.jpg', fs.existsSync, suffix);
244
393
  let result = null;
394
+ // The turn a HEIC keeps only in its EXIF (see probe), before the scale.
395
+ const turn = orientationFilters(info.orientation).map((f) => `${f},`).join('');
245
396
 
246
397
  for (let attempt = 0; attempt < 5; attempt++) {
247
398
  const p = plan.planImage({ targetBytes, width: info.width, height: info.height, attempt });
248
- 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 });
249
400
 
250
401
  try {
251
402
  await run(ffmpeg, [
252
403
  '-hide_banner', '-nostats', '-y', '-i', file,
253
- '-vf', `scale=${p.width}:${p.height}:flags=lanczos`,
404
+ // A tiled picture (HEIC) is joined by ffmpeg in a graph of its own, and
405
+ // a plain -vf on that stream is refused, so the scale joins that graph.
406
+ ...(info.grid
407
+ ? ['-filter_complex', `[0:g:0]${turn}scale=${p.width}:${p.height}:flags=lanczos`]
408
+ : ['-vf', `${turn}scale=${p.width}:${p.height}:flags=lanczos`]),
254
409
  '-q:v', String(p.quality), out,
255
410
  ], { ctl });
256
411
  } catch (err) {
257
412
  // Same as video: no half-written file left behind under a "fits" name.
258
413
  try { fs.unlinkSync(out); } catch {}
259
- throw err;
414
+ throw plainError(err, [[file, called || path.basename(file)]]);
260
415
  }
261
416
 
262
417
  const bytes = fs.statSync(out).size;
@@ -267,4 +422,4 @@ async function fitImage({ ffmpeg, file, info, targetBytes, outDir, onProgress =
267
422
  return { ...result, over: true };
268
423
  }
269
424
 
270
- module.exports = { control, probe, outputPath, fitVideo, fitImage, MAX_ATTEMPTS };
425
+ module.exports = { run, plainError, control, probe, outputPath, fitVideo, fitAudio, fitImage, isAnimatedWebp, MAX_ATTEMPTS };
package/src/heif.cjs ADDED
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * The turn a phone HEIC carries only in its EXIF.
5
+ *
6
+ * Most phones store a portrait photo as a landscape picture with a rotation
7
+ * box (irot) that ffmpeg applies by itself. Some (an iPhone 7, for one) write
8
+ * no box and only set the Orientation tag in the EXIF item, which ffmpeg
9
+ * ignores for HEIC, so the photo came out on its side. This reads that tag
10
+ * straight from the file's boxes. It answers 1 (no turn) whenever the file has
11
+ * a rotation or mirror box, because ffmpeg has already applied that one and
12
+ * turning again would put the picture on its side the other way.
13
+ */
14
+
15
+ const fs = require('node:fs');
16
+
17
+ const u16 = (b, o, le) => (le ? b[o] | (b[o + 1] << 8) : (b[o] << 8) | b[o + 1]);
18
+ const u32 = (b, o, le) => (le
19
+ ? b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)
20
+ : (b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
21
+
22
+ function* boxes(b, start, end) {
23
+ let p = start;
24
+ while (p + 8 <= end) {
25
+ let size = u32(b, p, false);
26
+ const type = b.toString('latin1', p + 4, p + 8);
27
+ let header = 8;
28
+ if (size === 1) {
29
+ if (p + 16 > end) return;
30
+ size = u32(b, p + 12, false);
31
+ header = 16;
32
+ } else if (size === 0) {
33
+ size = end - p;
34
+ }
35
+ if (size < header || p + size > end) return;
36
+ yield { type, body: p + header, end: p + size };
37
+ p += size;
38
+ }
39
+ }
40
+
41
+ function findBox(b, start, end, names) {
42
+ const [head, ...rest] = names;
43
+ for (const box of boxes(b, start, end)) {
44
+ if (box.type !== head) continue;
45
+ const body = head === 'meta' ? box.body + 4 : box.body; // meta is a FullBox
46
+ return rest.length ? findBox(b, body, box.end, rest) : { ...box, body };
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function exifItemId(b, iinf) {
52
+ const version = b[iinf.body];
53
+ let p = iinf.body + 4;
54
+ p += version === 0 ? 2 : 4;
55
+ for (const box of boxes(b, p, iinf.end)) {
56
+ if (box.type !== 'infe') continue;
57
+ const v = b[box.body];
58
+ if (v < 2) continue;
59
+ let q = box.body + 4;
60
+ let id;
61
+ if (v === 2) { id = u16(b, q, false); q += 2; } else { id = u32(b, q, false); q += 4; }
62
+ q += 2;
63
+ if (b.toString('latin1', q, q + 4) === 'Exif') return id;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ function itemRange(b, iloc, wanted) {
69
+ const version = b[iloc.body];
70
+ let p = iloc.body + 4;
71
+ const offsetSize = b[p] >> 4;
72
+ const lengthSize = b[p] & 0x0f;
73
+ const baseSize = b[p + 1] >> 4;
74
+ const indexSize = b[p + 1] & 0x0f;
75
+ p += 2;
76
+ let count;
77
+ if (version < 2) { count = u16(b, p, false); p += 2; } else { count = u32(b, p, false); p += 4; }
78
+ const sized = (at, size) => (size === 4 ? u32(b, at, false) : size === 8 ? u32(b, at + 4, false) : size === 2 ? u16(b, at, false) : 0);
79
+
80
+ for (let i = 0; i < count; i++) {
81
+ let id;
82
+ if (version < 2) { id = u16(b, p, false); p += 2; } else { id = u32(b, p, false); p += 4; }
83
+ if (version === 1 || version === 2) p += 2;
84
+ p += 2;
85
+ const base = sized(p, baseSize); p += baseSize;
86
+ const extents = u16(b, p, false); p += 2;
87
+ for (let e = 0; e < extents; e++) {
88
+ if ((version === 1 || version === 2) && indexSize) p += indexSize;
89
+ const off = sized(p, offsetSize); p += offsetSize;
90
+ const len = sized(p, lengthSize); p += lengthSize;
91
+ if (id === wanted) return { offset: base + off, length: len };
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+
97
+ function tiffOrientation(t) {
98
+ if (t.length < 8) return 1;
99
+ const le = u16(t, 0, false) === 0x4949;
100
+ const ifd = u32(t, 4, le);
101
+ if (ifd + 2 > t.length) return 1;
102
+ const count = u16(t, ifd, le);
103
+ for (let i = 0; i < count; i++) {
104
+ const e = ifd + 2 + i * 12;
105
+ if (e + 12 > t.length) break;
106
+ if (u16(t, e, le) === 0x0112) {
107
+ const v = u16(t, e + 8, le);
108
+ return v >= 1 && v <= 8 ? v : 1;
109
+ }
110
+ }
111
+ return 1;
112
+ }
113
+
114
+ /** The EXIF orientation (1..8) a HEIC file leaves for the viewer to apply; 1 when none, or when a box already carries the turn. */
115
+ function heifOrientation(file) {
116
+ try {
117
+ const fd = fs.openSync(file, 'r');
118
+ let head;
119
+ try {
120
+ head = Buffer.alloc(12);
121
+ fs.readSync(fd, head, 0, 12, 0);
122
+ // Only an ISO base media file with a heif-family brand; anything else is none of our business.
123
+ if (head.toString('latin1', 4, 8) !== 'ftyp' || !/^(hei|hev|mif|msf)/.test(head.toString('latin1', 8, 12))) return 1;
124
+ } finally { fs.closeSync(fd); }
125
+ const b = fs.readFileSync(file);
126
+ const ipco = findBox(b, 0, b.length, ['meta', 'iprp', 'ipco']);
127
+ if (ipco) {
128
+ for (const box of boxes(b, ipco.body, ipco.end)) if (box.type === 'irot' || box.type === 'imir') return 1;
129
+ }
130
+ const iinf = findBox(b, 0, b.length, ['meta', 'iinf']);
131
+ const iloc = findBox(b, 0, b.length, ['meta', 'iloc']);
132
+ if (!iinf || !iloc) return 1;
133
+ const id = exifItemId(b, iinf);
134
+ if (id == null) return 1;
135
+ const loc = itemRange(b, iloc, id);
136
+ if (!loc || loc.offset + loc.length > b.length) return 1;
137
+ const payload = b.subarray(loc.offset, loc.offset + loc.length);
138
+ // The item starts with a 4-byte offset to the TIFF header (usually 6, past "Exif\0\0").
139
+ const at = 4 + (payload.length >= 4 ? u32(payload, 0, false) : 0);
140
+ const t = payload.subarray(at);
141
+ if (t.length >= 4 && ((t[0] === 0x49 && t[1] === 0x49) || (t[0] === 0x4d && t[1] === 0x4d))) return tiffOrientation(t);
142
+ return 1;
143
+ } catch {
144
+ return 1;
145
+ }
146
+ }
147
+
148
+ /** The ffmpeg filters that turn pixels upright for an EXIF orientation. */
149
+ function orientationFilters(o) {
150
+ return ({
151
+ 2: ['hflip'], 3: ['hflip', 'vflip'], 4: ['vflip'],
152
+ 5: ['transpose=0'], 6: ['transpose=1'], 7: ['transpose=3'], 8: ['transpose=2'],
153
+ })[o] || [];
154
+ }
155
+
156
+ module.exports = { heifOrientation, orientationFilters };
@@ -0,0 +1,136 @@
1
+ /* PonderDev kit 1.1.0, built from kit/src. Do not edit: run bin/kit-sync. */
2
+ 'use strict';
3
+ /*
4
+ * kit, main side: a Linux AppImage puts itself in the applications menu, once
5
+ * asked (decided 2026-11-21).
6
+ *
7
+ * An AppImage run straight from Downloads has no menu entry, so GNOME's dock
8
+ * shows a grey gear for it and the person has to find the file again next
9
+ * time. On its first run the tool asks once: "Add Just Zip to your
10
+ * applications menu?" Yes writes a menu entry and the icon into the person's
11
+ * own folders (~/.local/share, nothing system wide, no password); Not now is
12
+ * remembered and never asked again. Once there is an entry, a run from a new
13
+ * place (the file was moved) quietly points the entry at the new place.
14
+ *
15
+ * const { offerMenuEntry } = require('./kit/desktop.cjs');
16
+ * app.whenReady().then(() => { ...make the window...; offerMenuEntry({ app, dialog, win, words }); });
17
+ *
18
+ * Only on Linux, only when run as an AppImage (APPIMAGE is set), never under
19
+ * a test (JUST_TEST_NO_WINDOW) and never when the person said Not now. A
20
+ * folder that cannot be written is left alone: the tool runs as before.
21
+ */
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+ const os = require('node:os');
25
+
26
+ // The menu entry's file name and the icon's name: the app id, lower case,
27
+ // no spaces ("Just Zip" -> "justzip").
28
+ const idOf = (app) => String(app.getName()).toLowerCase().replace(/[^a-z0-9]+/g, '');
29
+
30
+ function places(app, env = process.env, home = os.homedir()) {
31
+ const data = env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : path.join(home, '.local', 'share');
32
+ const id = idOf(app);
33
+ return {
34
+ id,
35
+ entry: path.join(data, 'applications', `ponderdev-${id}.desktop`),
36
+ icon: path.join(data, 'icons', 'hicolor', '256x256', 'apps', `ponderdev-${id}.png`),
37
+ answer: path.join(app.getPath('userData'), 'kit-menu-entry.json'),
38
+ };
39
+ }
40
+
41
+ // Quoted for a desktop entry's Exec line (the spec's rules: double quotes,
42
+ // with backslash before ", `, $ and \).
43
+ const quoteExec = (p) => `"${String(p).replace(/(["`$\\])/g, '\\$1')}"`;
44
+
45
+ function entryText({ name, exec, icon, comment }) {
46
+ return [
47
+ '[Desktop Entry]',
48
+ 'Type=Application',
49
+ `Name=${name}`,
50
+ comment ? `Comment=${comment.replace(/\n/g, ' ')}` : null,
51
+ `Exec=${quoteExec(exec)} %U`,
52
+ `Icon=${icon}`,
53
+ // the window's app id is the product name (window.cjs), so the dock ties the window to this entry
54
+ `StartupWMClass=${name}`,
55
+ 'Terminal=false',
56
+ 'Categories=Utility;',
57
+ 'X-PonderDev-Kit=menu-entry',
58
+ '',
59
+ ].filter((l) => l !== null).join('\n');
60
+ }
61
+
62
+ // The AppImage carries its icon at the mount point's root (.DirIcon) and in usr/share/icons.
63
+ function iconSource(env = process.env, id = '') {
64
+ const dir = env.APPDIR;
65
+ if (!dir) return null;
66
+ const tries = [
67
+ path.join(dir, 'usr', 'share', 'icons', 'hicolor', '256x256', 'apps', `${id}.png`),
68
+ path.join(dir, `${id}.png`),
69
+ path.join(dir, '.DirIcon'),
70
+ ];
71
+ return tries.find((p) => { try { return fs.statSync(p).isFile(); } catch { return false; } }) || null;
72
+ }
73
+
74
+ function readAnswer(file) {
75
+ try { const a = JSON.parse(fs.readFileSync(file, 'utf8')); return a && typeof a === 'object' ? a : {}; } catch { return {}; }
76
+ }
77
+
78
+ function write(p, { app, env = process.env }) {
79
+ const exec = env.APPIMAGE;
80
+ fs.mkdirSync(path.dirname(p.entry), { recursive: true });
81
+ const src = iconSource(env, p.id);
82
+ let icon = p.id;
83
+ if (src) {
84
+ fs.mkdirSync(path.dirname(p.icon), { recursive: true });
85
+ fs.copyFileSync(src, p.icon);
86
+ icon = p.icon;
87
+ }
88
+ fs.writeFileSync(p.entry, entryText({ name: app.getName(), exec, icon }), { mode: 0o644 });
89
+ }
90
+
91
+ // What the entry says it runs, or null.
92
+ function entryExec(file) {
93
+ try {
94
+ const m = /^Exec="((?:\\.|[^"\\])*)"/m.exec(fs.readFileSync(file, 'utf8'));
95
+ return m ? m[1].replace(/\\(.)/g, '$1') : null;
96
+ } catch { return null; }
97
+ }
98
+
99
+ /**
100
+ * Returns what it did: 'not-appimage', 'test', 'declined', 'moved' (the entry
101
+ * now points at the new place), 'current', 'added', 'not-now', or 'failed'.
102
+ */
103
+ async function offerMenuEntry({ app, dialog, win, words, env = process.env, platform = process.platform, home } = {}) {
104
+ if (platform !== 'linux' || !env.APPIMAGE) return 'not-appimage';
105
+ if (env.JUST_TEST_NO_WINDOW) return 'test';
106
+ const p = places(app, env, home);
107
+ const t = (s, v) => (words ? words.t(s, v) : String(s).replace(/\{(\w+)\}/g, (m, k) => (v && k in v ? v[k] : m)));
108
+ try {
109
+ if (fs.existsSync(p.entry)) {
110
+ if (entryExec(p.entry) === env.APPIMAGE) return 'current';
111
+ write(p, { app, env });
112
+ return 'moved';
113
+ }
114
+ const answer = readAnswer(p.answer);
115
+ if (answer.menuEntry === 'not-now') return 'declined';
116
+ const { response } = await dialog.showMessageBox(win, {
117
+ type: 'question',
118
+ buttons: [t('Add it'), t('Not now')],
119
+ defaultId: 0,
120
+ cancelId: 1,
121
+ message: t('Add {name} to your applications menu?', { name: app.getName() }),
122
+ detail: t('Then you can open it from the menu and the dock like any other app. It is only added for you, and you will not be asked again.'),
123
+ });
124
+ if (response !== 0) {
125
+ fs.mkdirSync(path.dirname(p.answer), { recursive: true });
126
+ fs.writeFileSync(p.answer, JSON.stringify(Object.assign(answer, { menuEntry: 'not-now' })) + '\n');
127
+ return 'not-now';
128
+ }
129
+ write(p, { app, env });
130
+ return 'added';
131
+ } catch (e) {
132
+ return 'failed';
133
+ }
134
+ }
135
+
136
+ module.exports = { offerMenuEntry, entryText, quoteExec, places, entryExec, iconSource };
@@ -0,0 +1,29 @@
1
+ /* PonderDev kit 1.1.0, built from kit/src. Do not edit: run bin/kit-sync. */
2
+ 'use strict';
3
+ /*
4
+ * kit, main side: family hints. The window's "Try Just Zip" asks for
5
+ * a sibling by id; this opens that tool's page on ponderdev.com and nothing
6
+ * else. The window never sends an address.
7
+ *
8
+ * const { family } = require('./kit/family.cjs');
9
+ * family({ ipcMain, shell });
10
+ *
11
+ * The preload exposes it as `openSibling: (id) => ipcRenderer.invoke('kit:open-sibling', id)`.
12
+ */
13
+
14
+ // The released tools a hint may point to (kit/src/parts/family.js holds the same list).
15
+ const FAMILY = ['justzip', 'justfits', 'justjpeg', 'justcut'];
16
+
17
+ const pageOf = (id) => (FAMILY.includes(id) ? `https://ponderdev.com/${id}` : null);
18
+
19
+ function family({ ipcMain, shell } = {}) {
20
+ if (!ipcMain) return;
21
+ ipcMain.handle('kit:open-sibling', async (_event, id) => {
22
+ const url = pageOf(id);
23
+ if (!url) return false;
24
+ if (shell) await shell.openExternal(url);
25
+ return true;
26
+ });
27
+ }
28
+
29
+ module.exports = { family, pageOf, FAMILY };