-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1667 lines (1552 loc) · 66.6 KB
/
Copy pathapp.js
File metadata and controls
1667 lines (1552 loc) · 66.6 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// Codec loading
// ============================================================
const $ = id => document.getElementById(id);
function formatBytes(n) {
if (n < 1024) return n + ' B';
if (n < 1024*1024) return (n/1024).toFixed(1) + ' KB';
return (n/1024/1024).toFixed(2) + ' MB';
}
// Module readiness
let goReady = false, mozjpegReady = false, webpReady = false, gifsicleReady = false, svgoReady = false;
let mjEnc = null, mjDec = null, wpEnc = null, wpDec = null;
let svgoOptimize = null, gifsicleMod = null, gif2webpMod = null;
function setGlobalStatus(msg) {
// Helper for showing loading status under drop zone (only before first file)
const els = document.querySelectorAll('.drop .drop-sub');
if (els[0]) els[0].textContent = msg;
}
window.compressorOnReady = () => { goReady = true; checkReady(); };
function checkReady() {
if (goReady && mozjpegReady && webpReady && gifsicleReady && svgoReady) {
setGlobalStatus('compress jpg, png, gif, svg, webp. Multiple files OK. Max 50 MB each.');
}
}
setGlobalStatus('Loading WASM codecs…');
const go = new Go();
WebAssembly.instantiateStreaming(fetch('codecs/png/compressor.wasm'), go.importObject)
.then(({instance}) => go.run(instance))
.catch(err => setGlobalStatus('Failed to load Go-WASM: ' + err.message));
import mozjpegEnc from './codecs/jpeg/mozjpeg_enc.js';
import mozjpegDec from './codecs/jpeg/mozjpeg_dec.js';
Promise.all([
mozjpegEnc({ locateFile: f => 'codecs/jpeg/' + f }),
mozjpegDec({ locateFile: f => 'codecs/jpeg/' + f }),
]).then(([e, d]) => { mjEnc = e; mjDec = d; mozjpegReady = true; checkReady(); })
.catch(err => setGlobalStatus('mozjpeg load failed: ' + err.message));
import webpEnc from './codecs/webp/webp_enc.js';
import webpDec from './codecs/webp/webp_dec.js';
Promise.all([
webpEnc({ locateFile: f => 'codecs/webp/' + f }),
webpDec({ locateFile: f => 'codecs/webp/' + f }),
]).then(([e, d]) => { wpEnc = e; wpDec = d; webpReady = true; checkReady(); })
.catch(err => setGlobalStatus('libwebp load failed: ' + err.message));
import { optimize as svgOptimize } from './codecs/svg/svgo.browser.js';
svgoOptimize = svgOptimize;
svgoReady = true;
checkReady();
import gifsicleBrowser from './codecs/gif/gifsicle.min.js?v=3';
gifsicleMod = gifsicleBrowser;
gifsicleReady = true;
checkReady();
// GIF → animated WebP codec (libwebp WebPAnimEncoder + giflib, wasm). Loaded
// lazily in the background; only needed when the user transcodes a GIF to
// WebP, so it does not gate overall readiness.
import gif2webpFactory from './codecs/gif2webp/gif2webp.js';
gif2webpFactory({ locateFile: f => 'codecs/gif2webp/' + f })
.then(m => { gif2webpMod = m; })
.catch(err => console.error('gif2webp load failed:', err && err.message));
// ============================================================
// Worker pool for parallel raster compression (PNG/JPG/WebP)
//
// Each worker is a real OS thread, so N workers compress N images
// truly in parallel and the UI thread stays responsive. SVG and GIF
// are NOT routed here — SVG rasterisation needs createImageBitmap on
// an <svg> source (DOM-only) and gifsicle/svgo run fine on main.
// ============================================================
const POOL_SIZE = Math.max(1, Math.min(
(navigator.hardwareConcurrency || 4) - 1, // leave one core for the UI
6 // diminishing returns past ~6
));
const pool = []; // [{ worker, busy }]
let jobSeq = 0;
const jobCallbacks = new Map(); // id → { resolve, reject, onProgress }
let poolInitStarted = false;
function ensurePool() {
if (poolInitStarted) return;
poolInitStarted = true;
for (let i = 0; i < POOL_SIZE; i++) {
let worker;
try {
worker = new Worker('./worker.js', { type: 'module' });
} catch (e) {
console.warn('Worker spawn failed, falling back to main thread:', e);
break;
}
const slot = { worker, busy: false };
worker.onmessage = (e) => handleWorkerMessage(slot, e.data);
worker.onerror = (e) => console.error('worker error:', e.message || e);
worker.postMessage({ type: 'init' });
pool.push(slot);
}
}
function handleWorkerMessage(slot, msg) {
if (msg.type === 'ready') return;
const cb = jobCallbacks.get(msg.id);
if (!cb) return;
if (msg.type === 'progress') {
cb.onProgress && cb.onProgress(msg.value);
} else if (msg.type === 'done') {
jobCallbacks.delete(msg.id);
slot.busy = false;
cb.resolve({ data: msg.data, stats: msg.stats, outType: msg.outType });
pumpQueue();
} else if (msg.type === 'error') {
jobCallbacks.delete(msg.id);
slot.busy = false;
cb.reject(new Error(msg.message));
pumpQueue();
}
}
// Pending jobs waiting for a free worker.
const poolQueue = []; // [{ op, bytes, sourceType, target, opts, onProgress, resolve, reject }]
function runInWorker(op, bytes, sourceType, target, opts, onProgress) {
ensurePool();
// No workers available at all → signal caller to use the main thread.
if (!pool.length) return null;
return new Promise((resolve, reject) => {
poolQueue.push({ op, bytes, sourceType, target, opts, onProgress, resolve, reject });
pumpQueue();
});
}
function pumpQueue() {
for (const slot of pool) {
if (slot.busy) continue;
const job = poolQueue.shift();
if (!job) break;
slot.busy = true;
const id = ++jobSeq;
jobCallbacks.set(id, { resolve: job.resolve, reject: job.reject, onProgress: job.onProgress });
// Copy the input buffer (no transfer) so the caller keeps its own
// bytes for the smart-fallback size check / re-download.
slot.worker.postMessage({
type: 'job', id, op: job.op,
bytes: job.bytes, sourceType: job.sourceType, target: job.target, opts: job.opts,
});
}
}
// Warm up the pool right away so the first compression isn't delayed by
// codec loading inside the workers.
ensurePool();
// ============================================================
// Mode (LOSSY / LOSSLESS / CUSTOM)
// ============================================================
let mode = 'lossy';
function bindRange(rangeId, valId, fmt) {
const r = $(rangeId), v = $(valId);
const sync = () => v.textContent = fmt(r.value);
r.addEventListener('input', sync);
sync();
}
bindRange('colors', 'vColors', x => x);
bindRange('dither', 'vDither', x => Number(x).toFixed(2));
bindRange('quality', 'vQuality', x => x);
bindRange('lossy', 'vLossy', x => x);
bindRange('speed', 'vSpeed', x => x);
function applyMode(m) {
mode = m;
[...$('ctypeTabs').querySelectorAll('button')].forEach(b => b.classList.toggle('active', b.dataset.mode === m));
$('controls').hidden = (m !== 'custom');
const lossless = (m === 'lossless');
$('quality').value = lossless ? 95 : 70;
$('lossy').value = lossless ? 0 : 80;
$('colors').value = 256;
$('dither').value = 1;
$('speed').value = 3;
['quality','lossy','colors','dither','speed'].forEach(id => $(id).dispatchEvent(new Event('input', { bubbles: true })));
}
$('ctypeTabs').addEventListener('click', e => {
if (e.target.tagName === 'BUTTON' && e.target.dataset.mode) applyMode(e.target.dataset.mode);
});
applyMode('lossy');
// ============================================================
// Output format (default 'original' = keep input format)
// ============================================================
let outputFormat = 'original';
const outputFormatEl = $('outputFormat');
outputFormatEl.addEventListener('change', () => {
outputFormat = outputFormatEl.value;
outputFormatEl.classList.toggle('active-convert', outputFormat !== 'original');
});
// ============================================================
// Output scale (resize factor before encoding)
// 1.0 = keep source size. Anything else triggers a canvas-based
// bilinear resample inside decodeToRGBA → encodeRGBATo.
// ============================================================
let outputScale = 1;
const outputScaleEl = $('outputScale');
outputScaleEl.addEventListener('change', () => {
outputScale = parseFloat(outputScaleEl.value) || 1;
outputScaleEl.classList.toggle('active-convert', outputScale !== 1);
});
// ============================================================
// Format detection + per-format compress (same as before)
// ============================================================
function detectType(bytes) {
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'png';
if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'jpg';
if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return 'gif';
if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
&& bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'webp';
const head = new TextDecoder('utf-8', { fatal: false }).decode(bytes.slice(0, 512)).toLowerCase();
if (head.includes('<svg')) return 'svg';
return 'png';
}
function readOpts() {
return {
maxColors: parseInt($('colors').value, 10),
dither: parseFloat($('dither').value),
speed: parseInt($('speed').value, 10),
quality: parseInt($('quality').value, 10),
lossy: parseInt($('lossy').value, 10),
lossless: (mode === 'lossless'),
scale: outputScale,
};
}
async function compressPng(bytes, opts, onProgress) {
if (opts.lossless) {
// Lossless: re-encode via canvas → PNG. Canvas's PNG output is
// always lossless. If the original was already an optimized PNG
// this might actually grow the file — that's the price for "no
// quality loss". Most photos shrink anyway because canvas uses
// strong zlib + filters.
onProgress(0.1);
const blob = new Blob([bytes], { type: 'image/png' });
const url = URL.createObjectURL(blob);
const img = await new Promise((res, rej) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = rej;
i.src = url;
});
onProgress(0.4);
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
URL.revokeObjectURL(url);
onProgress(0.7);
const pngBlob = await new Promise(res => canvas.toBlob(res, 'image/png'));
onProgress(0.95);
const out = new Uint8Array(await pngBlob.arrayBuffer());
onProgress(1.0);
return { data: out, stats: { width: img.naturalWidth, height: img.naturalHeight } };
}
const phaseBase = { quantize: 0, dither: 0.5, encode: 0.85 };
const phaseWeight = { quantize: 0.5, dither: 0.35, encode: 0.15 };
const cb = (stage, frac) => onProgress((phaseBase[stage] ?? 0) + (phaseWeight[stage] ?? 0) * frac);
await new Promise(r => setTimeout(r, 10));
const result = window.compressPNG(bytes, opts, cb);
if (result.error) throw new Error(result.error);
return { data: result.data, stats: result.stats };
}
// ---- JPEG metadata helpers ----
// Extract all APP1 (EXIF) and APP2 (ICC_PROFILE) segments from a JPEG.
// Returns an array of raw segment bytes (including the FFE1/FFE2 marker and
// length bytes) suitable for direct re-insertion into another JPEG.
function extractJpegMetadata(bytes) {
const segments = [];
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return segments;
let pos = 2;
while (pos < bytes.length - 1) {
if (bytes[pos] !== 0xff) { pos++; continue; }
// skip 0xff fill bytes
while (pos < bytes.length && bytes[pos] === 0xff) pos++;
const marker = bytes[pos++];
if (marker === 0x00 || marker === 0xd9) continue;
// restart markers - no length
if (marker >= 0xd0 && marker <= 0xd7) continue;
// start of scan - stop scanning meta
if (marker === 0xda || marker === 0xc0 || marker === 0xc1 || marker === 0xc2) break;
const segLen = (bytes[pos] << 8) | bytes[pos+1];
// Only keep APP2 (ICC profile). compressor.io discards EXIF (APP1)
// and Photoshop IRB (APP13) — we mirror that behaviour for byte-exact
// parity and to maximise compression.
if (marker === 0xe2) {
// Slice the FULL chunk: FF + marker + length(2) + data
const start = pos - 2;
const end = pos + segLen;
segments.push(bytes.slice(start, end));
}
pos += segLen;
}
return segments;
}
// Inject the given metadata segments immediately after the JFIF (APP0)
// chunk in a freshly encoded JPEG. If no JFIF is present, inject right
// after SOI.
function injectJpegMetadata(jpgBytes, segments) {
if (!segments.length) return jpgBytes;
if (jpgBytes[0] !== 0xff || jpgBytes[1] !== 0xd8) return jpgBytes;
let insertAt = 2; // right after SOI by default
// If APP0 (JFIF) is the first segment, insert *after* it.
if (jpgBytes[2] === 0xff && jpgBytes[3] === 0xe0) {
const app0Len = (jpgBytes[4] << 8) | jpgBytes[5];
insertAt = 4 + app0Len;
}
const totalExtra = segments.reduce((s, seg) => s + seg.byteLength, 0);
const out = new Uint8Array(jpgBytes.byteLength + totalExtra);
out.set(jpgBytes.subarray(0, insertAt), 0);
let p = insertAt;
for (const seg of segments) {
out.set(seg, p);
p += seg.byteLength;
}
out.set(jpgBytes.subarray(insertAt), p);
return out;
}
// ---- Raw ICC profile extraction (works across source formats) ----
//
// Returns just the ICC profile *payload* (i.e. the .icc bytes themselves,
// without any container-specific framing). This is what we need to embed
// into a different output format. Returns null if no profile present.
function extractIccProfile(bytes, type) {
if (type === 'jpg') return extractIccFromJpeg(bytes);
if (type === 'png') return extractIccFromPng(bytes);
if (type === 'webp') return extractIccFromWebp(bytes);
return null;
}
// JPEG ICC profiles can span multiple APP2 segments. Each starts with the
// signature "ICC_PROFILE\0" followed by chunk-index + chunk-count bytes.
// We reassemble all chunks in order into a single Uint8Array.
function extractIccFromJpeg(bytes) {
const SIG = [0x49,0x43,0x43,0x5f,0x50,0x52,0x4f,0x46,0x49,0x4c,0x45,0x00]; // "ICC_PROFILE\0"
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
let pos = 2;
const chunks = []; // [{ idx, data }]
let total = 0;
while (pos < bytes.length - 1) {
if (bytes[pos] !== 0xff) { pos++; continue; }
while (pos < bytes.length && bytes[pos] === 0xff) pos++;
const marker = bytes[pos++];
if (marker === 0x00 || marker === 0xd9) continue;
if (marker >= 0xd0 && marker <= 0xd7) continue;
if (marker === 0xda || marker === 0xc0 || marker === 0xc1 || marker === 0xc2) break;
const segLen = (bytes[pos] << 8) | bytes[pos+1];
if (marker === 0xe2 && segLen > 16) {
// Check signature
let match = true;
for (let i = 0; i < SIG.length; i++) {
if (bytes[pos + 2 + i] !== SIG[i]) { match = false; break; }
}
if (match) {
const idx = bytes[pos + 2 + SIG.length];
const cnt = bytes[pos + 2 + SIG.length + 1];
const dataStart = pos + 2 + SIG.length + 2;
const dataEnd = pos + segLen;
chunks.push({ idx, total: cnt, data: bytes.slice(dataStart, dataEnd) });
total += dataEnd - dataStart;
}
}
pos += segLen;
}
if (!chunks.length) return null;
chunks.sort((a, b) => a.idx - b.idx);
const out = new Uint8Array(total);
let o = 0;
for (const c of chunks) { out.set(c.data, o); o += c.data.length; }
return out;
}
// PNG ICC read is not currently needed (we route PNG sources through the
// browser canvas which already color-manages to sRGB before we touch the
// pixels). Stubbed for completeness.
function extractIccFromPng(_bytes) { return null; }
// WebP: look for ICCP chunk inside the RIFF container.
// isAnimatedWebp reports whether a WebP is animated. Animated files start with
// a VP8X extended header whose flag byte has bit 1 (0x02) set, and/or contain
// an ANMF frame chunk. The single-frame @jsquash/webp decoder returns null for
// these, so we must detect them up front instead of crashing on decoded.data.
function isAnimatedWebp(bytes) {
if (!bytes || bytes.length < 16) return false;
// 'RIFF' .... 'WEBP'
if (bytes[0] !== 0x52 || bytes[1] !== 0x49 || bytes[2] !== 0x46 || bytes[3] !== 0x46) return false;
if (bytes[8] !== 0x57 || bytes[9] !== 0x45 || bytes[10] !== 0x42 || bytes[11] !== 0x50) return false;
let pos = 12;
while (pos + 8 <= bytes.length) {
const t = String.fromCharCode(bytes[pos], bytes[pos+1], bytes[pos+2], bytes[pos+3]);
const len = bytes[pos+4] | (bytes[pos+5]<<8) | (bytes[pos+6]<<16) | (bytes[pos+7]<<24);
if (t === 'VP8X') {
return ((bytes[pos + 8] >> 1) & 1) === 1; // animation flag
}
if (t === 'ANMF' || t === 'ANIM') return true;
pos += 8 + len + (len & 1);
}
return false;
}
function extractIccFromWebp(bytes) {
if (bytes[0] !== 0x52 || bytes[1] !== 0x49) return null;
let pos = 12; // skip RIFF header + 'WEBP'
while (pos + 8 <= bytes.length) {
const t = String.fromCharCode(bytes[pos], bytes[pos+1], bytes[pos+2], bytes[pos+3]);
const len = bytes[pos+4] | (bytes[pos+5]<<8) | (bytes[pos+6]<<16) | (bytes[pos+7]<<24);
if (t === 'ICCP') {
return bytes.slice(pos + 8, pos + 8 + len);
}
// Chunks are padded to even byte boundaries.
pos += 8 + len + (len & 1);
}
return null;
}
// Async deflate via the native CompressionStream API (Safari 16.4+,
// all evergreens). We use it to wrap the raw ICC payload for PNG iCCP
// chunks. No external pako dependency required.
async function deflateAsync(bytes) {
const cs = new CompressionStream('deflate');
const stream = new Blob([bytes]).stream().pipeThrough(cs);
return new Uint8Array(await new Response(stream).arrayBuffer());
}
// ---- ICC profile injection into WebP / PNG ----
// Insert an ICCP chunk into a WebP RIFF container. Per the WebP spec, when
// ICCP is present, the VP8X (extended) header must be present and its
// "has ICC profile" flag set. If the encoder produced a simple VP8/VP8L
// file, we upgrade it to VP8X first.
function injectIccIntoWebp(webpBytes, icc) {
if (!icc || !icc.length) return webpBytes;
if (webpBytes[0] !== 0x52 || webpBytes[1] !== 0x49) return webpBytes; // not RIFF
// Read 'WEBP' magic.
if (String.fromCharCode(webpBytes[8], webpBytes[9], webpBytes[10], webpBytes[11]) !== 'WEBP') return webpBytes;
const chunks = []; // [{type, data}]
let pos = 12;
while (pos + 8 <= webpBytes.length) {
const t = String.fromCharCode(webpBytes[pos], webpBytes[pos+1], webpBytes[pos+2], webpBytes[pos+3]);
const len = webpBytes[pos+4] | (webpBytes[pos+5]<<8) | (webpBytes[pos+6]<<16) | (webpBytes[pos+7]<<24);
chunks.push({ type: t, data: webpBytes.slice(pos + 8, pos + 8 + len) });
pos += 8 + len + (len & 1);
}
if (!chunks.length) return webpBytes;
// Find image dimensions + alpha info from the first VP8/VP8L/VP8X chunk.
let width = 0, height = 0, hasAlpha = 0, hasAnim = 0;
const first = chunks[0];
if (first.type === 'VP8X') {
width = 1 + (first.data[4] | (first.data[5] << 8) | (first.data[6] << 16));
height = 1 + (first.data[7] | (first.data[8] << 8) | (first.data[9] << 16));
hasAlpha = (first.data[0] >> 4) & 1;
hasAnim = (first.data[0] >> 1) & 1;
} else if (first.type === 'VP8 ') {
// VP8 (lossy) keyframe layout:
// bytes 0..2 : frame tag
// bytes 3..5 : start code 0x9d 0x01 0x2a
// bytes 6..7 : 14-bit width (+ 2-bit horizontal scale)
// bytes 8..9 : 14-bit height (+ 2-bit vertical scale)
const d = first.data;
width = (d[6] | (d[7] << 8)) & 0x3fff;
height = (d[8] | (d[9] << 8)) & 0x3fff;
} else if (first.type === 'VP8L') {
// VP8L: 1 byte signature (0x2f) then 14-bit (w-1) + 14-bit (h-1) + alpha
const d = first.data;
width = 1 + (((d[1]) | (d[2] << 8)) & 0x3fff);
height = 1 + (((d[2] >> 6) | (d[3] << 2) | (d[4] << 10)) & 0x3fff);
hasAlpha = (d[4] >> 4) & 1;
} else {
// Unknown layout — bail and return the original.
return webpBytes;
}
if (!width || !height) return webpBytes;
// Build new VP8X chunk (10 bytes payload).
const vp8x = new Uint8Array(10);
// Flags: ICC profile = bit 5 (0x20). Preserve alpha/anim flags.
vp8x[0] = 0x20 | (hasAlpha ? 0x10 : 0) | (hasAnim ? 0x02 : 0);
vp8x[1] = 0; vp8x[2] = 0; vp8x[3] = 0;
const w1 = width - 1, h1 = height - 1;
vp8x[4] = w1 & 0xff; vp8x[5] = (w1 >> 8) & 0xff; vp8x[6] = (w1 >> 16) & 0xff;
vp8x[7] = h1 & 0xff; vp8x[8] = (h1 >> 8) & 0xff; vp8x[9] = (h1 >> 16) & 0xff;
// Reorder/replace: VP8X first, then ICCP, then any pre-existing chunks
// (skipping any old VP8X / ICCP).
const outChunks = [
{ type: 'VP8X', data: vp8x },
{ type: 'ICCP', data: icc },
];
for (const c of chunks) {
if (c.type === 'VP8X' || c.type === 'ICCP') continue;
outChunks.push(c);
}
// Serialize.
let bodyLen = 4; // 'WEBP' magic
for (const c of outChunks) bodyLen += 8 + c.data.length + (c.data.length & 1);
const out = new Uint8Array(8 + bodyLen);
// RIFF header
out[0] = 0x52; out[1] = 0x49; out[2] = 0x46; out[3] = 0x46; // 'RIFF'
out[4] = bodyLen & 0xff; out[5] = (bodyLen >> 8) & 0xff;
out[6] = (bodyLen >> 16) & 0xff; out[7] = (bodyLen >>> 24) & 0xff;
// 'WEBP'
out[8] = 0x57; out[9] = 0x45; out[10] = 0x42; out[11] = 0x50;
let o = 12;
for (const c of outChunks) {
out[o++] = c.type.charCodeAt(0);
out[o++] = c.type.charCodeAt(1);
out[o++] = c.type.charCodeAt(2);
out[o++] = c.type.charCodeAt(3);
const l = c.data.length;
out[o++] = l & 0xff; out[o++] = (l >> 8) & 0xff;
out[o++] = (l >> 16) & 0xff; out[o++] = (l >>> 24) & 0xff;
out.set(c.data, o); o += l;
if (l & 1) out[o++] = 0; // pad
}
return out;
}
// Build a PNG iCCP chunk and insert it right after the IHDR chunk.
async function injectIccIntoPng(pngBytes, icc) {
if (!icc || !icc.length) return pngBytes;
if (pngBytes[0] !== 0x89 || pngBytes[1] !== 0x50) return pngBytes;
// Find IHDR end (first chunk after the 8-byte signature).
let pos = 8;
const ihdrLen = (pngBytes[pos]<<24) | (pngBytes[pos+1]<<16) | (pngBytes[pos+2]<<8) | pngBytes[pos+3];
if (String.fromCharCode(pngBytes[pos+4], pngBytes[pos+5], pngBytes[pos+6], pngBytes[pos+7]) !== 'IHDR') {
return pngBytes;
}
const ihdrEnd = pos + 12 + ihdrLen; // length(4) + type(4) + data + crc(4)
// Strip any existing iCCP / sRGB / gAMA chunks (they would conflict).
const filtered = [];
filtered.push(pngBytes.subarray(0, ihdrEnd));
let p = ihdrEnd;
while (p + 12 <= pngBytes.length) {
const len = (pngBytes[p]<<24) | (pngBytes[p+1]<<16) | (pngBytes[p+2]<<8) | pngBytes[p+3];
const t = String.fromCharCode(pngBytes[p+4], pngBytes[p+5], pngBytes[p+6], pngBytes[p+7]);
const chunkEnd = p + 12 + len;
if (t !== 'iCCP' && t !== 'sRGB' && t !== 'gAMA') {
filtered.push(pngBytes.subarray(p, chunkEnd));
}
p = chunkEnd;
}
// Build the iCCP chunk: name "icc" + null + compression(0) + deflate(icc).
const compressed = await deflateAsync(icc);
const nameBytes = [0x69, 0x63, 0x63, 0x00]; // "icc\0"
const dataLen = nameBytes.length + 1 + compressed.length; // +1 for compression method
const chunk = new Uint8Array(12 + dataLen);
// length
chunk[0] = (dataLen >>> 24) & 0xff; chunk[1] = (dataLen >>> 16) & 0xff;
chunk[2] = (dataLen >>> 8) & 0xff; chunk[3] = dataLen & 0xff;
// type 'iCCP'
chunk[4] = 0x69; chunk[5] = 0x43; chunk[6] = 0x43; chunk[7] = 0x50;
// data
let q = 8;
chunk.set(nameBytes, q); q += nameBytes.length;
chunk[q++] = 0; // compression method = deflate
chunk.set(compressed, q); q += compressed.length;
// CRC over type + data
const crc = crc32Range(chunk, 4, q);
chunk[q++] = (crc >>> 24) & 0xff; chunk[q++] = (crc >>> 16) & 0xff;
chunk[q++] = (crc >>> 8) & 0xff; chunk[q++] = crc & 0xff;
// Splice: header+IHDR, then iCCP, then the rest.
const head = filtered[0];
const tailParts = filtered.slice(1);
const total = head.length + chunk.length + tailParts.reduce((s, x) => s + x.length, 0);
const out = new Uint8Array(total);
let o = 0;
out.set(head, o); o += head.length;
out.set(chunk, o); o += chunk.length;
for (const part of tailParts) { out.set(part, o); o += part.length; }
return out;
}
// CRC-32 helper for PNG iCCP chunk. Computes CRC over bytes[start..end).
function crc32Range(bytes, start, end) {
if (!crc32Range._table) {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
t[n] = c >>> 0;
}
crc32Range._table = t;
}
const T = crc32Range._table;
let c = 0xFFFFFFFF;
for (let i = start; i < end; i++) c = T[(c ^ bytes[i]) & 0xFF] ^ (c >>> 8);
return (c ^ 0xFFFFFFFF) >>> 0;
}
async function compressJpg(bytes, opts, onProgress) {
onProgress(0.3); await new Promise(r => setTimeout(r, 10));
// Grab ICC profile + EXIF so we can re-insert them after encoding
// (compressor.io behaves the same way — it keeps the ICC).
const meta = extractJpegMetadata(bytes);
const decoded = mjDec.decode(bytes, {});
onProgress(0.6); await new Promise(r => setTimeout(r, 10));
const q = opts.quality;
const encoded = mjEnc.encode(decoded.data, decoded.width, decoded.height, {
// True JPEG lossless does not exist in mozjpeg — we approximate with
// q=100 + no chroma subsampling (4:4:4) + arithmetic coding.
quality: opts.lossless ? 100 : q,
baseline: false,
arithmetic: false,
progressive: true,
optimize_coding: true, smoothing: 0, color_space: 3, quant_table: 3,
trellis_multipass: false, trellis_opt_zero: false, trellis_opt_table: false, trellis_loops: 1,
auto_subsample: opts.lossless ? false : true,
chroma_subsample: opts.lossless ? 1 : 2,
separate_chroma_quality: false,
chroma_quality: opts.lossless ? 100 : q,
});
// Re-attach the original ICC profile / EXIF so the browser keeps the
// intended color gamut (Display P3, Adobe RGB, etc.) — without this
// step a P3 source rendered as sRGB and reds looked washed out.
const withMeta = injectJpegMetadata(new Uint8Array(encoded), meta);
onProgress(1.0);
return { data: withMeta, stats: { width: decoded.width, height: decoded.height } };
}
// webpEncodeOptions centralises the libwebp parameters for the main-thread
// path (mirrors the same helper in codec-core.js used by the worker).
//
// alpha_quality used to be 100 (lossless alpha), which on a smooth
// translucency gradient blew a 95 KB source up to ~104 KB. Dropping it to 70
// for lossy mode collapses the same file to ~13 KB with imperceptible alpha
// error while keeping the alpha channel; opaque photos and sharp binary masks
// are unaffected. method 6 (vs 4) squeezes a few extra percent for free, and
// use_sharp_yuv slightly improves chroma on gradients.
function webpEncodeOptions(opts) {
const lossless = !!opts.lossless;
return {
quality: lossless ? 100 : opts.quality,
target_size: 0, target_PSNR: 0,
method: 6, sns_strength: 50,
filter_strength: 60, filter_sharpness: 0, filter_type: 1, partitions: 0,
segments: 4, pass: 1, show_compressed: 0, preprocessing: 0, autofilter: 0,
partition_limit: 0, alpha_compression: 1, alpha_filtering: 1,
alpha_quality: lossless ? 100 : 70,
lossless: lossless ? 1 : 0, exact: lossless ? 1 : 0,
image_hint: 0, emulate_jpeg_size: 0, thread_level: 0, low_memory: 0,
near_lossless: 100, use_delta_palette: 0,
use_sharp_yuv: lossless ? 0 : 1,
};
}
async function compressWebp(bytes, opts, onProgress) {
onProgress(0.2); await new Promise(r => setTimeout(r, 10));
const decoded = wpDec.decode(bytes);
onProgress(0.5); await new Promise(r => setTimeout(r, 10));
const encoded = wpEnc.encode(decoded.data, decoded.width, decoded.height,
webpEncodeOptions(opts));
onProgress(1.0);
return { data: new Uint8Array(encoded), stats: { width: decoded.width, height: decoded.height } };
}
async function compressGif(bytes, opts, onProgress) {
onProgress(0.1); await new Promise(r => setTimeout(r, 10));
const lossy = opts.lossy;
const cmd = '-O3' + (lossy > 0 ? (' --lossy=' + lossy) : '') + ' input.gif -o /out/output.gif';
const inputBlob = new Blob([bytes], { type: 'image/gif' });
onProgress(0.3);
const files = await gifsicleMod.run({
input: [{ file: inputBlob, name: 'input.gif' }],
command: [cmd],
});
if (!files || !files.length) throw new Error('gifsicle returned no output');
onProgress(0.9);
const out = await files[0].arrayBuffer();
onProgress(1.0);
return { data: new Uint8Array(out), stats: {} };
}
// convertGifToWebp turns an animated/transparent GIF into an animated WebP
// using the gif2webp wasm codec (libwebp WebPAnimEncoder + giflib). Frames,
// loop count, disposal and per-frame alpha are all preserved. To match
// compressor.io's size we encode both a lossy and a lossless variant and keep
// the smaller (mirrors gif2webp -mixed / -min_size).
async function convertGifToWebp(bytes, opts, onProgress) {
onProgress(0.1); await new Promise(r => setTimeout(r, 10));
const M = gif2webpMod;
if (!M) throw new Error('GIF→WebP codec still loading, try again in a moment');
const encodeOnce = (quality, method, lossless) => {
const inPtr = M._malloc(bytes.length);
M.HEAPU8.set(bytes, inPtr);
const lenPtr = M._malloc(4);
let outArr = null;
try {
const outPtr = M._gif2webp_encode(inPtr, bytes.length, quality, method,
lossless ? 1 : 0, lenPtr);
const outLen = M.getValue(lenPtr, 'i32');
if (outPtr && outLen > 0) {
outArr = M.HEAPU8.slice(outPtr, outPtr + outLen);
M._gif2webp_free(outPtr);
}
} finally {
M._free(inPtr);
M._free(lenPtr);
}
return outArr;
};
// WebP encode method. We deliberately use 4 (gif2webp's own default) rather
// than 6: on multi-frame GIFs method 6 is 100x+ slower (a 53-frame 1.6 MB
// GIF took >2 minutes and looked like a hang) while only saving ~2-5%.
const METHOD = 4;
// Encoding both a lossy and a lossless variant ("mixed") doubles the work.
// Only worth it for small GIFs; above this input size we skip the lossless
// probe to keep conversion snappy (large GIFs are almost always
// photographic and win from lossy anyway).
const MIXED_MAX_BYTES = 512 * 1024;
let out;
if (opts.lossless) {
out = encodeOnce(100, METHOD, true);
} else {
onProgress(0.4);
const q = (typeof opts.quality === 'number') ? opts.quality : 70;
const lossy = encodeOnce(q, METHOD, false);
onProgress(0.7);
if (bytes.length <= MIXED_MAX_BYTES) {
const lossless = encodeOnce(100, METHOD, true);
out = (!lossy) ? lossless
: (!lossless) ? lossy
: (lossless.length < lossy.length ? lossless : lossy);
} else {
out = lossy;
}
}
if (!out) throw new Error('GIF→WebP encode failed');
onProgress(1.0);
return { data: out, stats: {} };
}
// recompressAnimatedWebp shrinks an animated WebP by fully decoding every
// frame (WebPAnimDecoder) and re-encoding the animation (WebPAnimEncoder) at
// the requested quality — frames, timings, loop and alpha are preserved. Uses
// method 4 for speed on multi-frame files (see convertGifToWebp).
async function recompressAnimatedWebp(bytes, opts, onProgress) {
onProgress(0.1); await new Promise(r => setTimeout(r, 10));
const M = gif2webpMod;
if (!M) throw new Error('WebP recompression codec still loading, try again in a moment');
const q = opts.lossless ? 100 : ((typeof opts.quality === 'number') ? opts.quality : 70);
const inPtr = M._malloc(bytes.length);
M.HEAPU8.set(bytes, inPtr);
const lenPtr = M._malloc(4);
let out = null;
try {
onProgress(0.4);
const outPtr = M._webp2webp_encode(inPtr, bytes.length, q, 4,
opts.lossless ? 1 : 0, lenPtr);
const outLen = M.getValue(lenPtr, 'i32');
if (outPtr && outLen > 0) {
out = M.HEAPU8.slice(outPtr, outPtr + outLen);
M._gif2webp_free(outPtr);
}
} finally {
M._free(inPtr);
M._free(lenPtr);
}
if (!out) throw new Error('animated WebP re-encode failed');
onProgress(1.0);
return { data: out, stats: {} };
}
async function compressSvg(bytes, opts, onProgress) {
onProgress(0.2); await new Promise(r => setTimeout(r, 10));
const text = new TextDecoder('utf-8').decode(bytes);
const result = svgoOptimize(text, { multipass: true });
const out = new TextEncoder().encode(result.data);
onProgress(1.0);
return { data: out, stats: {} };
}
// ============================================================
// Cross-format conversion (decode → re-encode to target)
// ============================================================
// Decode any supported source into raw RGBA pixels, optionally
// resized by `scale` (1 = original size). For SVG the scale is
// applied at rasterisation time (vector → crisp pixels). For raster
// formats we do a bilinear resample on a 2D canvas.
// Returns { data: Uint8ClampedArray, width, height }.
async function decodeToRGBA(bytes, type, scale = 1) {
// mozjpeg / libwebp expose native decoders that give us RGBA directly.
if (type === 'jpg') {
const d = mjDec.decode(bytes, {});
return resampleRGBA(new Uint8ClampedArray(d.data), d.width, d.height, scale);
}
if (type === 'webp') {
const d = wpDec.decode(bytes);
return resampleRGBA(new Uint8ClampedArray(d.data), d.width, d.height, scale);
}
// PNG / GIF (first frame) / SVG → use the browser's image decoder.
let mime;
if (type === 'png') mime = 'image/png';
else if (type === 'gif') mime = 'image/gif';
else if (type === 'svg') mime = 'image/svg+xml';
else mime = 'image/png';
const blob = new Blob([bytes], { type: mime });
const url = URL.createObjectURL(blob);
try {
const img = await new Promise((res, rej) => {
const i = new Image();
i.onload = () => res(i);
i.onerror = () => rej(new Error('decode failed for ' + type));
i.src = url;
});
let w = img.naturalWidth, h = img.naturalHeight;
// SVG without intrinsic size — fall back to a reasonable default
// so users get something instead of a 0×0 canvas error.
if (!w || !h) { w = 1024; h = 1024; }
// Apply scale by drawing the source image directly onto a
// scaled-down/up canvas. For SVG this re-rasterises the vector at
// the target resolution (no upscale blur). For raster sources it
// produces a bilinear resample in one step.
const dw = Math.max(1, Math.round(w * scale));
const dh = Math.max(1, Math.round(h * scale));
const canvas = document.createElement('canvas');
canvas.width = dw; canvas.height = dh;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, dw, dh);
const imgData = ctx.getImageData(0, 0, dw, dh);
return { data: imgData.data, width: dw, height: dh };
} finally {
URL.revokeObjectURL(url);
}
}
// Resample an RGBA buffer to a new size using the browser's 2D
// canvas bilinear/bicubic engine. No-op when scale === 1.
function resampleRGBA(data, w, h, scale) {
if (scale === 1) return { data, width: w, height: h };
const dw = Math.max(1, Math.round(w * scale));
const dh = Math.max(1, Math.round(h * scale));
// Draw the source pixels onto a same-size canvas, then onto the
// destination-sized canvas. Two-stage avoids ImageData's lack of
// built-in scaling.
const src = document.createElement('canvas');
src.width = w; src.height = h;
src.getContext('2d').putImageData(new ImageData(data, w, h), 0, 0);
const dst = document.createElement('canvas');
dst.width = dw; dst.height = dh;
const dctx = dst.getContext('2d');
dctx.imageSmoothingQuality = 'high';
dctx.drawImage(src, 0, 0, dw, dh);
const out = dctx.getImageData(0, 0, dw, dh);
return { data: out.data, width: dw, height: dh };
}
// Encode RGBA pixels into the target format.
async function encodeRGBATo(target, rgba, width, height, opts) {
if (target === 'jpg') {
const encoded = mjEnc.encode(rgba, width, height, {
quality: opts.lossless ? 100 : opts.quality,
baseline: false, arithmetic: false, progressive: true,
optimize_coding: true, smoothing: 0, color_space: 3, quant_table: 3,
trellis_multipass: false, trellis_opt_zero: false, trellis_opt_table: false, trellis_loops: 1,
auto_subsample: !opts.lossless, chroma_subsample: opts.lossless ? 1 : 2,
separate_chroma_quality: false,
chroma_quality: opts.lossless ? 100 : opts.quality,
});
return new Uint8Array(encoded);
}
if (target === 'webp') {
const encoded = wpEnc.encode(rgba, width, height, webpEncodeOptions(opts));
return new Uint8Array(encoded);
}
if (target === 'png') {
// Canvas → PNG (always lossless). For LOSSY mode on PNG output we
// could optionally run pngquant on top via window.compressPNG, but
// that re-introduces palette quantization across all sources, which
// surprises users converting photos to PNG. Keep canvas PNG simple.
const canvas = document.createElement('canvas');
canvas.width = width; canvas.height = height;
const ctx = canvas.getContext('2d');
const imgData = new ImageData(rgba instanceof Uint8ClampedArray ? rgba : new Uint8ClampedArray(rgba), width, height);
ctx.putImageData(imgData, 0, 0);
const blob = await new Promise(res => canvas.toBlob(res, 'image/png'));
if (!blob) throw new Error('PNG encode failed');
let out = new Uint8Array(await blob.arrayBuffer());
// For LOSSY mode also run pngquant for a real size win.
if (!opts.lossless && window.compressPNG) {
try {
const q = window.compressPNG(out, opts, () => {});
if (!q.error && q.data && q.data.byteLength < out.byteLength) {
out = q.data;
}
} catch (_) { /* fall back to canvas PNG */ }
}
return out;
}
throw new Error('Unsupported target format: ' + target);
}
// Convert a source file to a different output format. Preserves the
// embedded ICC color profile across the transcode — without this, a
// Display-P3 / Adobe-RGB JPG decoded by mozjpeg yields raw RGB samples
// that the browser then displays as sRGB, so wide-gamut reds shift
// cooler. We extract the source ICC and re-embed it in the target.
async function convertTo(target, bytes, sourceType, opts, onProgress) {
onProgress(0.05); await new Promise(r => setTimeout(r, 10));
// Only JPG and WebP source paths give us raw, non-color-managed samples
// (mozjpeg/libwebp decoders ignore the embedded profile). PNG/GIF/SVG
// go through the browser canvas which already applies the source ICC
// and gives us sRGB pixels, so re-embedding would double-apply.
const icc = (sourceType === 'jpg' || sourceType === 'webp')
? extractIccProfile(bytes, sourceType)
: null;
// For SVG the rasterisation size should be set BEFORE drawing so we
// get crisp vector strokes at the target resolution instead of a
// blurry upscale of the default-sized bitmap. Pass scale into
// decodeToRGBA; it bakes the scale into the canvas dimensions for
// SVG and into a post-decode resample for everything else.
let { data, width, height } = await decodeToRGBA(bytes, sourceType, opts.scale || 1);
onProgress(0.5); await new Promise(r => setTimeout(r, 10));
let out = await encodeRGBATo(target, data, width, height, opts);
onProgress(0.85);
// Re-attach ICC profile to the new container. Each target format
// stores it differently:
// JPG → APP2 segment (handled below via injectJpegMetadata).
// WebP → ICCP RIFF chunk + VP8X header upgrade.
// PNG → iCCP chunk (deflate-compressed profile).
if (icc && icc.length) {
try {
if (target === 'webp') {
out = injectIccIntoWebp(out, icc);
} else if (target === 'png') {
out = await injectIccIntoPng(out, icc);
} else if (target === 'jpg') {
// Wrap the raw ICC into a (possibly multi-segment) APP2 chunk
// and inject via the existing JPEG path.
const seg = buildJpegIccApp2(icc);
out = injectJpegMetadata(out, seg);
}
} catch (e) {
console.warn('ICC re-embedding failed for ' + target + ':', e);
}
}
onProgress(1.0);
return { data: out, stats: { width, height } };
}
// Wrap a raw ICC profile blob into one or more JPEG APP2 segments
// (signature "ICC_PROFILE\0" + chunk index + chunk count + payload).
// Each segment must fit in 65533 bytes total (2-byte length covers
// itself, so payload max ≈ 65519 incl. 14-byte header).
function buildJpegIccApp2(icc) {
const SIG = [0x49,0x43,0x43,0x5f,0x50,0x52,0x4f,0x46,0x49,0x4c,0x45,0x00];
const MAX_PAYLOAD = 65519; // 65535 - 2 (length) - 14 (sig+idx+cnt)
const chunks = [];
for (let p = 0; p < icc.length; p += MAX_PAYLOAD) {
chunks.push(icc.slice(p, Math.min(p + MAX_PAYLOAD, icc.length)));
}
const segments = [];
for (let i = 0; i < chunks.length; i++) {
const payload = chunks[i];
const segLen = 2 + SIG.length + 2 + payload.length; // length field includes itself
const seg = new Uint8Array(4 + SIG.length + 2 + payload.length); // FF E2 + length + sig + idx + cnt + payload
seg[0] = 0xff; seg[1] = 0xe2;
seg[2] = (segLen >> 8) & 0xff; seg[3] = segLen & 0xff;
seg.set(SIG, 4);
seg[4 + SIG.length] = i + 1; // chunk index (1-based per spec)
seg[4 + SIG.length + 1] = chunks.length;
seg.set(payload, 4 + SIG.length + 2);
segments.push(seg);
}
return segments;
}
// ============================================================
// File queue with parallel workers
// ============================================================
const items = []; // [{ id, file, type, bytes, status, progress, outBytes, outType, error }]
let nextId = 0;