-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpng2gif.mjs
More file actions
executable file
·402 lines (352 loc) · 11.7 KB
/
Copy pathpng2gif.mjs
File metadata and controls
executable file
·402 lines (352 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env node
// PNG frames -> animated GIF, using nothing but Node's built-in zlib.
//
// Exists so that recording the demo needs no ffmpeg, no ImageMagick and no
// npm install: `git clone` and run. Handles 8-bit non-interlaced RGB/RGBA PNGs,
// which is what headless Chrome produces.
import { readFileSync, writeFileSync } from 'node:fs';
import { inflateSync } from 'node:zlib';
/* --------------------------------- PNG ---------------------------------- */
function decodePNG(buf) {
if (buf.readUInt32BE(0) !== 0x89504e47) throw new Error('not a PNG');
let pos = 8;
let width = 0;
let height = 0;
let channels = 0;
const idat = [];
while (pos < buf.length) {
const len = buf.readUInt32BE(pos);
const type = buf.toString('ascii', pos + 4, pos + 8);
const data = buf.subarray(pos + 8, pos + 8 + len);
pos += 12 + len;
if (type === 'IHDR') {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
const depth = data[8];
const colorType = data[9];
if (depth !== 8) throw new Error(`unsupported bit depth ${depth}`);
if (data[12] !== 0) throw new Error('interlaced PNG unsupported');
channels = { 2: 3, 6: 4, 0: 1, 4: 2 }[colorType];
if (!channels) throw new Error(`unsupported color type ${colorType}`);
} else if (type === 'IDAT') {
idat.push(data);
} else if (type === 'IEND') {
break;
}
}
const raw = inflateSync(Buffer.concat(idat));
const stride = width * channels;
const out = Buffer.alloc(height * stride);
let src = 0;
for (let y = 0; y < height; y++) {
const filter = raw[src++];
const line = raw.subarray(src, src + stride);
src += stride;
const cur = out.subarray(y * stride, (y + 1) * stride);
const prev = y > 0 ? out.subarray((y - 1) * stride, y * stride) : null;
for (let x = 0; x < stride; x++) {
const a = x >= channels ? cur[x - channels] : 0;
const b = prev ? prev[x] : 0;
const c = prev && x >= channels ? prev[x - channels] : 0;
let v = line[x];
switch (filter) {
case 0: break;
case 1: v += a; break;
case 2: v += b; break;
case 3: v += (a + b) >> 1; break;
case 4: {
const p = a + b - c;
const pa = Math.abs(p - a);
const pb = Math.abs(p - b);
const pc = Math.abs(p - c);
v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
break;
}
default: throw new Error(`bad filter ${filter}`);
}
cur[x] = v & 0xff;
}
}
return { width, height, pixels: out, channels };
}
/* ------------------------------ Quantising ------------------------------ */
const key15 = (r, g, b) => ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
/** Median cut over a 15-bit histogram. The UI is a flat, limited palette, so
* 256 entries is comfortably enough and no dithering is needed. */
function buildPalette(histogram, max = 256) {
const present = [];
for (let k = 0; k < histogram.length; k++) if (histogram[k]) present.push(k);
if (present.length === 0) throw new Error('empty image');
let boxes = [makeBox(present, histogram)];
while (boxes.length < max) {
let target = -1;
let best = 0;
boxes.forEach((box, i) => {
if (box.keys.length < 2) return;
const score = box.count * Math.max(box.range[0], box.range[1], box.range[2]);
if (score > best) {
best = score;
target = i;
}
});
if (target < 0) break;
const box = boxes[target];
const axis = box.range.indexOf(Math.max(...box.range));
const shift = [10, 5, 0][axis];
const sorted = box.keys.slice().sort((p, q) => ((p >> shift) & 31) - ((q >> shift) & 31));
// Split at the median *pixel*, not the median colour: rare colours should
// not get the same share of the palette as dominant ones.
let acc = 0;
let cut = 0;
for (; cut < sorted.length - 1; cut++) {
acc += histogram[sorted[cut]];
if (acc >= box.count / 2) break;
}
boxes.splice(target, 1,
makeBox(sorted.slice(0, cut + 1), histogram),
makeBox(sorted.slice(cut + 1), histogram));
}
return boxes.map((box) => {
let r = 0;
let g = 0;
let b = 0;
for (const k of box.keys) {
const w = histogram[k];
r += (((k >> 10) & 31) << 3) * w;
g += (((k >> 5) & 31) << 3) * w;
b += ((k & 31) << 3) * w;
}
return [Math.round(r / box.count), Math.round(g / box.count), Math.round(b / box.count)];
});
}
function makeBox(keys, histogram) {
let count = 0;
const lo = [31, 31, 31];
const hi = [0, 0, 0];
for (const k of keys) {
count += histogram[k];
const c = [(k >> 10) & 31, (k >> 5) & 31, k & 31];
for (let i = 0; i < 3; i++) {
if (c[i] < lo[i]) lo[i] = c[i];
if (c[i] > hi[i]) hi[i] = c[i];
}
}
return { keys, count, range: [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]] };
}
function buildLookup(palette) {
const map = new Uint8Array(32768);
for (let k = 0; k < 32768; k++) {
const r = ((k >> 10) & 31) << 3;
const g = ((k >> 5) & 31) << 3;
const b = (k & 31) << 3;
let best = 0;
let bestDist = Infinity;
for (let i = 0; i < palette.length; i++) {
const dr = r - palette[i][0];
const dg = g - palette[i][1];
const db = b - palette[i][2];
const d = dr * dr + dg * dg + db * db;
if (d < bestDist) {
bestDist = d;
best = i;
}
}
map[k] = best;
}
return map;
}
/* --------------------------------- LZW ---------------------------------- */
function lzwEncode(minCodeSize, indices) {
const out = [];
const CLEAR = 1 << minCodeSize;
const END = CLEAR + 1;
let codeSize = minCodeSize + 1;
let next = END + 1;
let dict = new Map();
let bitBuf = 0;
let bitCount = 0;
const emit = (code) => {
bitBuf |= code << bitCount;
bitCount += codeSize;
while (bitCount >= 8) {
out.push(bitBuf & 0xff);
bitBuf >>>= 8;
bitCount -= 8;
}
};
emit(CLEAR);
let prefix = indices[0];
for (let i = 1; i < indices.length; i++) {
const k = indices[i];
const combined = prefix * 256 + k;
const found = dict.get(combined);
if (found !== undefined) {
prefix = found;
continue;
}
emit(prefix);
dict.set(combined, next++);
if (next > 4095) {
emit(CLEAR);
dict = new Map();
next = END + 1;
codeSize = minCodeSize + 1;
} else if (next > 1 << codeSize) {
codeSize++;
}
prefix = k;
}
emit(prefix);
emit(END);
if (bitCount > 0) out.push(bitBuf & 0xff);
return out;
}
/** Decode our own output and compare. Getting the code-size growth off by one
* produces a file that some viewers render and others do not, so this is
* checked rather than assumed. */
function lzwDecode(minCodeSize, bytes) {
const CLEAR = 1 << minCodeSize;
const END = CLEAR + 1;
let codeSize = minCodeSize + 1;
let dict = [];
const reset = () => {
dict = [];
for (let i = 0; i < CLEAR; i++) dict.push([i]);
dict.push(null, null);
codeSize = minCodeSize + 1;
};
reset();
const out = [];
let bitBuf = 0;
let bitCount = 0;
let pos = 0;
let prev = null;
for (;;) {
while (bitCount < codeSize) {
if (pos >= bytes.length) return out;
bitBuf |= bytes[pos++] << bitCount;
bitCount += 8;
}
const code = bitBuf & ((1 << codeSize) - 1);
bitBuf >>>= codeSize;
bitCount -= codeSize;
if (code === CLEAR) {
reset();
prev = null;
continue;
}
if (code === END) return out;
let entry;
if (code < dict.length && dict[code]) entry = dict[code];
else if (prev) entry = [...prev, prev[0]];
else throw new Error('corrupt stream');
out.push(...entry);
if (prev) {
dict.push([...prev, entry[0]]);
// `dict.length` is the next code that would be assigned, so it must grow
// as soon as that code no longer fits — one step ahead of the encoder,
// which is exactly the lag between the two dictionaries.
if (dict.length >= 1 << codeSize && codeSize < 12) codeSize++;
}
prev = entry;
}
}
/* --------------------------------- GIF ---------------------------------- */
function subBlocks(bytes) {
const out = [];
for (let i = 0; i < bytes.length; i += 255) {
const chunk = bytes.slice(i, i + 255);
out.push(chunk.length, ...chunk);
}
out.push(0);
return out;
}
function encodeGIF(frames, width, height, palette, delays) {
const bytes = [];
const push = (...v) => bytes.push(...v);
const u16 = (v) => push(v & 0xff, (v >> 8) & 0xff);
push(...Buffer.from('GIF89a'));
u16(width);
u16(height);
push(0x80 | (7 << 4) | 7, 0, 0); // global colour table, 256 entries
for (let i = 0; i < 256; i++) {
const c = palette[i] || [0, 0, 0];
push(c[0], c[1], c[2]);
}
push(0x21, 0xff, 0x0b, ...Buffer.from('NETSCAPE2.0'), 0x03, 0x01, 0x00, 0x00, 0x00);
frames.forEach((indices, i) => {
push(0x21, 0xf9, 0x04, 0x04); // disposal: do not dispose
u16(delays[i]);
push(0x00, 0x00);
push(0x2c);
u16(0);
u16(0);
u16(width);
u16(height);
push(0x00);
const data = lzwEncode(8, indices);
const decoded = lzwDecode(8, data);
if (decoded.length !== indices.length) {
throw new Error(`LZW round-trip length mismatch on frame ${i}`);
}
for (let p = 0; p < indices.length; p++) {
if (decoded[p] !== indices[p]) throw new Error(`LZW round-trip mismatch at ${p}`);
}
push(8, ...subBlocks(data));
});
push(0x3b);
return Buffer.from(bytes);
}
/* --------------------------------- main --------------------------------- */
const [out, ...inputs] = process.argv.slice(2);
if (!out || inputs.length === 0) {
console.error('usage: png2gif.mjs out.gif frame0.png frame1.png ...');
process.exit(1);
}
// Hold on the states worth reading; skip through the typing. Centiseconds.
const DEFAULT_DELAYS = (process.env.BUOY_GIF_DELAYS || '130,190,45,190,180,280')
.split(',')
.map(Number);
const decoded = inputs.map((f) => decodePNG(readFileSync(f)));
for (const img of decoded) {
if (img.width !== decoded[0].width || img.height !== decoded[0].height) {
throw new Error('frame size mismatch');
}
}
// BUOY_GIF_CROP="x,y,w,h" — capture taller than needed and trim, which is how
// we keep the panel's bottom edge (and its rendering seam) out of the frame.
const crop = (process.env.BUOY_GIF_CROP || '').split(',').map(Number);
const box =
crop.length === 4 && crop.every((v) => Number.isFinite(v))
? { x: crop[0], y: crop[1], w: crop[2], h: crop[3] }
: { x: 0, y: 0, w: decoded[0].width, h: decoded[0].height };
const width = Math.min(box.w, decoded[0].width - box.x);
const height = Math.min(box.h, decoded[0].height - box.y);
function pixelAt(img, x, y) {
return ((y + box.y) * img.width + (x + box.x)) * img.channels;
}
const histogram = new Uint32Array(32768);
for (const img of decoded) {
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const p = pixelAt(img, x, y);
histogram[key15(img.pixels[p], img.pixels[p + 1], img.pixels[p + 2])]++;
}
}
}
const palette = buildPalette(histogram);
const lookup = buildLookup(palette);
const frames = decoded.map((img) => {
const idx = new Uint8Array(width * height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const p = pixelAt(img, x, y);
idx[y * width + x] = lookup[key15(img.pixels[p], img.pixels[p + 1], img.pixels[p + 2])];
}
}
return idx;
});
const delays = frames.map((_, i) => DEFAULT_DELAYS[i] ?? 120);
writeFileSync(out, encodeGIF(frames, width, height, palette, delays));
const kb = (Buffer.byteLength(readFileSync(out)) / 1024).toFixed(0);
console.log(`${out}: ${frames.length} frames, ${width}x${height}, ${palette.length} colours, ${kb} KB`);