-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathharness.html
More file actions
1429 lines (1329 loc) · 44.7 KB
/
harness.html
File metadata and controls
1429 lines (1329 loc) · 44.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
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
<!doctype html>
<!-- SPDX-License-Identifier: MIT Copyright (c) 2026 Mozilla Foundation -->
<html lang="en">
<head>
<meta charset="utf-8" />
<title>pdf.js.comparator harness</title>
<!-- Zilla Slab Highlight powers the "moz://a" wordmark in the top-left
corner. preconnect cuts the font-fetch latency on first paint. -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Zilla+Slab+Highlight:wght@700&display=swap"
rel="stylesheet"
/>
<style>
:root {
--border: #ccc;
--error: #b00;
--heading: #444;
--mono: ui-monospace, monospace;
--muted: #555;
--text: #222;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
/* top margin clears the fixed-positioned .moz-corner (bottom edge
~2.6rem) and .github-corner (~3.05rem) so the h1 doesn't sit
underneath either of them. */
margin: 3.5rem 1rem 1rem;
color: var(--text);
&.drag-over::before {
content: "";
position: fixed;
inset: 0.5rem;
border: 2px dashed var(--heading);
background: rgb(255 255 255 / 0.55);
pointer-events: none;
z-index: 1000;
}
}
/* Mozilla "moz://a" wordmark in the top-left corner. Renders with
Zilla Slab Highlight, the slab serif Mozilla's wordmark uses (each
glyph sits on a coloured highlight rectangle). z-index sits below
the drag-over overlay (1000) so dropping a PDF still works. */
.moz-corner {
position: fixed;
top: 0.5rem;
left: 0.5rem;
z-index: 100;
font-family: "Zilla Slab Highlight", "Zilla Slab", serif;
font-weight: 700;
font-size: 1.5rem;
line-height: 1;
color: #000;
text-decoration: none;
padding: 0.3rem 0.5rem;
border-radius: 4px;
transition: background 0.15s ease;
}
.moz-corner:hover,
.moz-corner:focus-visible {
background: rgb(0 0 0 / 0.08);
outline: none;
}
/* Small "view source" mark in the top-right corner. Uses inline SVG
so the harness stays self-contained. z-index sits below the
drag-over overlay (1000) so dropping a PDF doesn't get blocked. */
.github-corner {
position: fixed;
top: 0.5rem;
right: 0.5rem;
z-index: 100;
color: var(--heading);
display: inline-flex;
padding: 0.4rem;
border-radius: 50%;
text-decoration: none;
transition: background 0.15s ease;
}
.github-corner:hover,
.github-corner:focus-visible {
background: rgb(0 0 0 / 0.08);
outline: none;
}
.row {
display: flex;
gap: 0.75rem;
align-items: center;
flex-wrap: wrap;
margin-bottom: 0.75rem;
}
label {
display: inline-flex;
gap: 0.25rem;
align-items: center;
}
input[type="number"] {
width: 5rem;
}
button {
padding: 0.25rem 0.75rem;
}
fieldset {
padding: 0.25rem 0.5rem;
& legend {
font-size: 0.85rem;
color: var(--muted);
}
}
#status {
font-family: var(--mono);
font-size: 0.85rem;
color: var(--muted);
min-height: 1.2em;
&.err {
color: var(--error);
}
}
#renders {
display: flex;
flex-wrap: wrap;
gap: 1rem;
margin-top: 1rem;
align-items: flex-start;
& > .render {
flex: 0 1 auto;
max-width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
& > h3 {
margin: 0;
font-size: 0.85rem;
font-family: var(--mono);
color: var(--muted);
}
}
}
.canvas-wrap {
border: 1px solid var(--border);
background: repeating-conic-gradient(#eee 0% 25%, #fff 0% 50%) 50% /
16px 16px;
width: fit-content;
max-width: 100%;
overflow: auto;
& > canvas {
display: block;
}
}
#diffs {
margin-top: 1rem;
& .pair {
margin-bottom: 1.25rem;
& > h2 {
margin: 0 0 0.5rem;
font-size: 0.95rem;
font-family: var(--mono);
color: var(--heading);
}
& .pair-row {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: flex-start;
& > .diff {
flex: 0 1 auto;
max-width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
font-family: var(--mono);
font-size: 0.8rem;
color: var(--muted);
& > h3 {
margin: 0;
font-size: 0.8rem;
color: var(--heading);
}
}
}
}
}
.diff-info,
.diff-note {
font-family: var(--mono);
font-size: 0.8rem;
}
.diff-info {
color: var(--muted);
}
.diff-note {
color: var(--error);
}
.diff-image {
display: block;
border: 1px solid var(--border);
}
.ssim-readout {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2rem;
font-family: var(--mono);
color: var(--text);
border: 1px solid var(--border);
padding: 0.5rem 1rem;
min-width: 8rem;
}
</style>
</head>
<body>
<a
class="moz-corner"
href="https://www.mozilla.org"
target="_blank"
rel="noopener noreferrer"
aria-label="Mozilla"
title="mozilla.org"
>moz://a</a
>
<a
class="github-corner"
href="https://github.com/mozilla/pdf.js.comparator"
target="_blank"
rel="noopener noreferrer"
aria-label="View source on GitHub"
title="View source on GitHub"
>
<!-- Octicons mark-github, MIT-licensed. -->
<svg
viewBox="0 0 16 16"
width="28"
height="28"
fill="currentColor"
aria-hidden="true"
>
<path
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"
></path>
</svg>
</a>
<h1>pdf.js.comparator harness</h1>
<div class="row">
<label
>PDF:
<input type="file" id="file" accept="application/pdf,.pdf" disabled
/></label>
</div>
<div class="row">
<label
>Page: <input type="number" id="page" value="1" min="1" step="1"
/></label>
<span id="pages"></span>
<label
>DPI: <input type="number" id="dpi" value="96" min="1" step="1"
/></label>
<label><input type="checkbox" id="antialias" checked /> antialias</label>
<label><input type="checkbox" id="transparent" /> transparent bg</label>
<fieldset>
<legend>renderer</legend>
<label
><input type="checkbox" class="renderer" value="cairo" checked />
cairo</label
>
<label
><input type="checkbox" class="renderer" value="splash" checked />
splash</label
>
<label
><input type="checkbox" class="renderer" value="pdfium" checked />
pdfium</label
>
<label
><input type="checkbox" class="renderer" value="mupdf" checked />
mupdf</label
>
<label
><input type="checkbox" class="renderer" value="pdfjs" checked />
pdfjs</label
>
<label
><input type="checkbox" class="renderer" value="pdfbox" checked />
pdfbox</label
>
<label
><input type="checkbox" class="renderer" value="gs" checked />
gs</label
>
<label
><input type="checkbox" class="renderer" value="xpdf" checked />
xpdf</label
>
<label
><input type="checkbox" class="renderer" value="icepdf" checked />
icepdf</label
>
</fieldset>
<fieldset>
<legend>comparison</legend>
<label
>from
<select id="compare-a">
<option value="pdfjs" selected>pdf.js</option>
<option value="cairo">cairo</option>
<option value="splash">splash</option>
<option value="pdfium">pdfium</option>
<option value="mupdf">mupdf</option>
<option value="pdfbox">pdfbox</option>
<option value="gs">gs</option>
<option value="xpdf">xpdf</option>
<option value="icepdf">icepdf</option>
</select></label
>
<label
>to
<select id="compare-b">
<option value="cairo">cairo</option>
<option value="splash">splash</option>
<option value="pdfium" selected>pdfium</option>
<option value="mupdf">mupdf</option>
<option value="pdfjs">pdf.js</option>
<option value="pdfbox">pdfbox</option>
<option value="gs">gs</option>
<option value="xpdf">xpdf</option>
<option value="icepdf">icepdf</option>
</select></label
>
</fieldset>
</div>
<div id="status">loading wasm…</div>
<div id="renders"></div>
<div id="diffs"></div>
<script type="module">
// Browser-friendly diff libraries. The heavier wasm diffs run in
// workers so they don't block page rendering.
import pixelmatch from "https://esm.sh/pixelmatch@7";
import resemble from "https://esm.sh/resemblejs@5";
import { ssim } from "https://esm.sh/ssim.js@3";
// Minimal request/response wrapper around worker messages.
const spawn = (url, { module = true } = {}) => {
const worker = new Worker(url, module ? { type: "module" } : undefined);
const pending = new Map();
let resolveReady, rejectReady;
const ready = new Promise((res, rej) => {
resolveReady = res;
rejectReady = rej;
});
// Lazy workers may fail before anyone awaits `ready`.
ready.catch(() => {});
worker.addEventListener("message", (e) => {
if (e.data.type === "ready") {
resolveReady();
return;
}
if (e.data.type === "init-error") {
rejectReady(new Error(e.data.error));
return;
}
const { id, payload, error } = e.data;
const cb = pending.get(id);
if (!cb) return;
pending.delete(id);
if (error) cb.reject(new Error(error));
else cb.resolve(payload);
});
worker.addEventListener("error", (e) => {
const err = e.error || new Error(e.message || "worker error");
// Reject `ready` (no-op if already settled) and every in-flight
// call. Without this, runtime worker errors leave pending calls
// hanging forever — the renderer cards never resolve.
rejectReady(err);
for (const { reject } of pending.values()) reject(err);
pending.clear();
});
return {
ready,
call: async (type, payload, transfers = []) => {
await ready; // throws if init failed; caller catches it
return new Promise((resolve, reject) => {
const id = crypto.randomUUID();
pending.set(id, { resolve, reject });
worker.postMessage({ id, type, payload }, transfers);
});
},
};
};
// Absolute base URL for wasm/pdf.js artifacts. Override with ?base=URL.
const BASE = new URL(
new URL(window.location.href).searchParams.get("base") || "./out",
window.location.href,
).href;
const WORKER_VERSION = "2026-05-11-java-error-iife";
const withVersion = (href, version) => {
const url = new URL(href, window.location.href);
url.searchParams.set("v", version);
return url.href;
};
const artifactVersion = async (name) => {
try {
const url = new URL(
`${BASE}/${name}/source.json`,
window.location.href,
);
url.searchParams.set("t", Date.now());
const response = await fetch(url.href, { cache: "no-store" });
if (response.ok) {
const source = await response.json();
return (
source.fingerprint ||
source.commit ||
source.version ||
WORKER_VERSION
);
}
} catch {
// Older local builds may not have source.json files.
}
return WORKER_VERSION;
};
// Cache the per-renderer fingerprint so each spawned worker can load
// a wasm bundle that matches the source.json currently on disk —
// bumping a renderer publish busts only that renderer's cache.
const artifactVersionCache = new Map();
const cachedArtifactVersion = (name) => {
if (!artifactVersionCache.has(name)) {
artifactVersionCache.set(name, artifactVersion(name));
}
return artifactVersionCache.get(name);
};
const workerUrl = (script, params = {}, version = WORKER_VERSION) =>
`./workers/${script}?${new URLSearchParams({
...params,
base: BASE,
v: version,
})}`;
// Keep the pdf.js main module and worker from the same build.
const PDFJS_BASE = `${BASE}/pdfjs`;
const PDFJS_VERSION = await artifactVersion("pdfjs");
const pdfjsLib = await import(
withVersion(`${PDFJS_BASE}/pdf.mjs`, PDFJS_VERSION)
);
pdfjsLib.GlobalWorkerOptions.workerSrc = withVersion(
`${PDFJS_BASE}/pdf.worker.mjs`,
PDFJS_VERSION,
);
// Renderer workers are spawned lazily, one instance per engine.
// Each worker's URL embeds both the worker-code version (so editing
// workers/*.js busts the cache) and the per-renderer artifact
// fingerprint (so republishing the wasm busts it too). The combined
// string flows through to the worker's inner imports — wasm modules,
// render-result-transport.js, java-error.js — so they all invalidate
// together when either source changes.
const CLI_RENDERERS = ["gs", "xpdf"];
const workerVersionFor = async (name) =>
`${WORKER_VERSION}-${await cachedArtifactVersion(name)}`;
const namedWorkerGetter = (script, rendererParam, workerOptions = {}) => {
const cache = new Map();
return (name) => {
if (!cache.has(name)) {
cache.set(
name,
(async () =>
spawn(
workerUrl(
script,
{ [rendererParam]: name },
await workerVersionFor(name),
),
workerOptions,
))(),
);
}
return cache.get(name);
};
};
const getRendererWorker = namedWorkerGetter("renderer-worker.js", "wasm");
const getCliRendererWorker = namedWorkerGetter(
"cli-renderer-worker.js",
"renderer",
);
// CheerpJ workers are classic workers, not ES module workers.
let pdfboxWorker = null;
const getPdfboxWorker = async () => {
if (!pdfboxWorker) {
pdfboxWorker = spawn(
workerUrl("pdfbox-worker.js", {}, await workerVersionFor("pdfbox")),
{ module: false },
);
}
return pdfboxWorker;
};
let icepdfWorker = null;
const getIcepdfWorker = async () => {
if (!icepdfWorker) {
icepdfWorker = spawn(
workerUrl("icepdf-worker.js", {}, await workerVersionFor("icepdf")),
{ module: false },
);
}
return icepdfWorker;
};
const DIFF_WASMS = ["butteraugli", "dssim", "flip"];
const diffWorkers = Object.fromEntries(
await Promise.all(
DIFF_WASMS.map(async (name) => [
name,
spawn(
workerUrl(
"diff-worker.js",
{ wasm: name },
await workerVersionFor(name),
),
),
]),
),
);
const $ = (id) => document.getElementById(id);
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
const dom = {
antialias: $("antialias"),
compareA: $("compare-a"),
compareB: $("compare-b"),
diffs: $("diffs"),
dpi: $("dpi"),
file: $("file"),
page: $("page"),
pages: $("pages"),
renders: $("renders"),
status: $("status"),
transparent: $("transparent"),
};
const el = (tag, className = "", text = "") => {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== "") node.textContent = text;
return node;
};
const setStatus = (msg, err = false) => {
dom.status.textContent = msg;
dom.status.classList.toggle("err", err);
};
const errorMessage = (err) => err?.message || String(err);
const clearOutput = () => {
dom.renders.replaceChildren();
dom.diffs.replaceChildren();
};
const setDisplaySize = (node, width, height, dpr) => {
node.style.width = `${width / dpr}px`;
node.style.height = `${height / dpr}px`;
};
const createCanvas = (width, height, dpr) => {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
setDisplaySize(canvas, width, height, dpr);
return canvas;
};
const wrapCanvas = (canvas) => {
const wrap = el("div", "canvas-wrap");
wrap.appendChild(canvas);
return wrap;
};
const pdfjsDocumentOptions = (data) => ({
data,
verbosity: 0,
// Use the same auxiliary data a production pdf.js viewer would.
wasmUrl: `${PDFJS_BASE}/wasm/`,
cMapUrl: `${PDFJS_BASE}/cmaps/`,
cMapPacked: true,
standardFontDataUrl: `${PDFJS_BASE}/standard_fonts/`,
iccUrl: `${PDFJS_BASE}/iccs/`,
});
const openPdfjsDocument = async (data) => {
const loadingTask = pdfjsLib.getDocument(pdfjsDocumentOptions(data));
try {
return {
doc: await loadingTask.promise,
loadingTask,
};
} catch (err) {
if (typeof loadingTask.destroy === "function") {
await loadingTask.destroy();
}
throw err;
}
};
const destroyPdfjsDocument = async (doc, loadingTask) => {
if (typeof doc.destroy === "function") {
await doc.destroy();
} else if (typeof loadingTask?.destroy === "function") {
await loadingTask.destroy();
} else if (typeof doc.cleanup === "function") {
await doc.cleanup();
}
};
const getPdfjsPageCount = async (sourcePdfBytes) => {
const dataCopy = sourcePdfBytes.slice();
const { doc, loadingTask } = await openPdfjsDocument(dataCopy);
try {
return doc.numPages || 0;
} finally {
await destroyPdfjsDocument(doc, loadingTask);
}
};
const renderPdfjsAfterOperatorList = async (pdfPage, renderParams) => {
const originalRenderPageChunk = pdfPage._renderPageChunk;
if (typeof originalRenderPageChunk !== "function") {
await pdfPage.render(renderParams).promise;
return;
}
let operatorListComplete = false;
let pendingContinue = null;
const flushPendingContinue = () => {
if (!operatorListComplete || !pendingContinue) {
return;
}
const continueRendering = pendingContinue;
pendingContinue = null;
continueRendering();
};
// For stable captures, wait for the full operator list before drawing.
pdfPage._renderPageChunk = function (operatorListChunk, intentState) {
if (operatorListChunk?.lastChunk) {
try {
return originalRenderPageChunk.call(
this,
operatorListChunk,
intentState,
);
} finally {
operatorListComplete = true;
flushPendingContinue();
}
}
const renderTasks = intentState?.renderTasks;
if (!renderTasks?.size) {
return originalRenderPageChunk.call(
this,
operatorListChunk,
intentState,
);
}
intentState.renderTasks = new Set();
try {
return originalRenderPageChunk.call(
this,
operatorListChunk,
intentState,
);
} finally {
intentState.renderTasks = renderTasks;
}
};
try {
const renderTask = pdfPage.render(renderParams);
renderTask.onContinue = (continueRendering) => {
if (operatorListComplete) {
continueRendering();
return;
}
pendingContinue = continueRendering;
};
await renderTask.promise;
} finally {
pdfPage._renderPageChunk = originalRenderPageChunk;
}
};
const renderPdfjs = async (pdfBytes, page, dpi, transparent) => {
// pdf.js transfers and detaches its input buffer.
const dataCopy = pdfBytes.slice();
const { doc, loadingTask } = await openPdfjsDocument(dataCopy);
try {
const pdfPage = await doc.getPage(page);
const viewport = pdfPage.getViewport({ scale: dpi / 72 });
const canvas = document.createElement("canvas");
canvas.width = Math.ceil(viewport.width);
canvas.height = Math.ceil(viewport.height);
const ctx = canvas.getContext("2d");
if (!transparent) {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
await renderPdfjsAfterOperatorList(pdfPage, {
canvasContext: ctx,
viewport,
canvas,
});
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
const view = pdfPage.view; // [x1, y1, x2, y2] in pt
return {
renderer: "pdfjs",
width: canvas.width,
height: canvas.height,
data: img.data,
page_width_pt: view[2] - view[0],
page_height_pt: view[3] - view[1],
};
} finally {
await destroyPdfjsDocument(doc, loadingTask);
}
};
// Main-thread diff backends. Wasm diffs use `runWasmDiffs`.
const COMPARATORS = [
{
name: "pixelmatch",
run: (a, b) => {
const { width, height } = a;
const diff = new Uint8ClampedArray(width * height * 4);
const n = pixelmatch(a.data, b.data, diff, width, height, {
threshold: 0.1,
includeAA: false,
});
const pct = ((n / (width * height)) * 100).toFixed(2);
return { label: `${n} px diff (${pct}%)`, diffPixels: diff };
},
},
{
name: "resemblejs",
run: (a, b) =>
new Promise((resolve) => {
const ia = new ImageData(a.data, a.width, a.height);
const ib = new ImageData(b.data, b.width, b.height);
resemble(ia)
.compareTo(ib)
.ignoreAntialiasing()
.onComplete((d) => {
resolve({
label: `${parseFloat(d.misMatchPercentage).toFixed(2)}% mismatch`,
diffURL: d.getImageDataUrl(),
});
});
}),
},
{
name: "ssim.js",
run: (a, b) => {
const r = ssim(
{ width: a.width, height: a.height, data: a.data },
{ width: b.width, height: b.height, data: b.data },
);
return { label: `MSSIM = ${r.mssim.toFixed(4)}` };
},
},
];
// Each wasm diff gets its own transferable copy of the image pair.
const runWasmDiffs = async (a, b) => {
const cloneImg = (i) => ({
renderer: i.renderer,
width: i.width,
height: i.height,
data: new Uint8ClampedArray(i.data),
});
const results = await Promise.allSettled(
DIFF_WASMS.map(async (name) => {
const aCopy = cloneImg(a);
const bCopy = cloneImg(b);
return diffWorkers[name].call("diff", { a: aCopy, b: bCopy }, [
aCopy.data.buffer,
bCopy.data.buffer,
]);
}),
);
return results.map((result, index) => {
if (result.status === "fulfilled") {
return result.value;
}
return {
name: DIFF_WASMS[index],
error: result.reason?.message || String(result.reason),
};
});
};
const rendererLabel = (name) => (name === "pdfjs" ? "pdf.js" : name);
const rendererSummary = (images) =>
images
.map((img) => `${img.renderer} ${img.width}×${img.height}`)
.join(" + ");
const appendDiffMessage = (pair, className, text) => {
pair.appendChild(el("div", className, text));
};
const cropImage = (img, width, height) => {
if (img.width === width && img.height === height) {
return img;
}
const data = new Uint8ClampedArray(width * height * 4);
const rowBytes = width * 4;
for (let y = 0; y < height; y++) {
const srcStart = y * img.width * 4;
data.set(
img.data.subarray(srcStart, srcStart + rowBytes),
y * rowBytes,
);
}
return { ...img, width, height, data };
};
// Tiny dimension differences are usually renderer rounding noise.
const renderDiffs = async (
images,
dpr,
myGen,
myDiffGen,
compareA,
compareB,
) => {
if (staleDiff(myGen, myDiffGen)) return;
dom.diffs.replaceChildren();
const pair = el("div", "pair");
pair.appendChild(
el(
"h2",
"",
`${rendererLabel(compareA)} ↔ ${rendererLabel(compareB)}`,
),
);
dom.diffs.appendChild(pair);
if (compareA === compareB) {
appendDiffMessage(
pair,
"diff-note",
"skipped — pick two different renderers",
);
return;
}
let a = images.find((img) => img.renderer === compareA);
let b = images.find((img) => img.renderer === compareB);
if (!a || !b) {
const missing = [!a ? compareA : null, !b ? compareB : null]
.filter(Boolean)
.map(rendererLabel);
appendDiffMessage(
pair,
"diff-note",
`skipped — renderer not available: ${missing.join(", ")}`,
);
return;
}
if (a.width !== b.width || a.height !== b.height) {
const widthDelta = Math.abs(a.width - b.width);
const heightDelta = Math.abs(a.height - b.height);
if (widthDelta > 2 || heightDelta > 2) {
appendDiffMessage(
pair,
"diff-note",
`skipped — dimensions differ (${a.width}×${a.height} vs ${b.width}×${b.height})`,
);
return;
}
const width = Math.min(a.width, b.width);
const height = Math.min(a.height, b.height);
appendDiffMessage(
pair,
"diff-info",
`cropped to ${width}×${height} for diff (${a.width}×${a.height} vs ${b.width}×${b.height})`,
);
a = cropImage(a, width, height);
b = cropImage(b, width, height);
}
const row = el("div", "pair-row");
pair.appendChild(row);
const resetCard = (card, name) => {
card.replaceChildren(el("h3", "", name));
};
const failCard = (card, name, error) => {
resetCard(card, name);
card.append(error?.message || String(error));
};
const fillCard = (card, name, res, dt) => {
resetCard(card, name);
if (res.diffPixels) {
const cv = createCanvas(a.width, a.height, dpr);
cv.getContext("2d").putImageData(
new ImageData(res.diffPixels, a.width, a.height),
0,
0,
);
card.appendChild(wrapCanvas(cv));
} else if (res.diffURL) {
const img = document.createElement("img");
img.src = res.diffURL;
img.className = "diff-image";
setDisplaySize(img, a.width, a.height, dpr);
card.appendChild(img);
} else {
card.appendChild(el("div", "ssim-readout", res.label));
}
card.appendChild(el("div", "", `${res.label} · ${dt.toFixed(0)} ms`));
};
const wasmDiffNames = DIFF_WASMS;
const allNames = [...COMPARATORS.map((c) => c.name), ...wasmDiffNames];
const cards = allNames.map(() => {
const c = el("div", "diff");
row.appendChild(c);
return c;
});
const mainPromises = COMPARATORS.map(async (cmp, idx) => {
const card = cards[idx];
const t0 = performance.now();
try {
const res = await cmp.run(a, b);
if (staleDiff(myGen, myDiffGen)) return;
fillCard(card, cmp.name, res, performance.now() - t0);
} catch (e) {
if (staleDiff(myGen, myDiffGen)) return;
failCard(card, cmp.name, e);
}
});
const wasmPromise = (async () => {
try {
const results = await runWasmDiffs(a, b);
if (staleDiff(myGen, myDiffGen)) return;
for (const r of results) {
const idx = allNames.indexOf(r.name);
if (idx >= 0) {
if (r.error) {
failCard(cards[idx], r.name, r.error);
} else {
fillCard(cards[idx], r.name, r, r.time);
}
}
}
} catch (e) {
if (staleDiff(myGen, myDiffGen)) return;
for (const name of wasmDiffNames) {
const idx = allNames.indexOf(name);
if (idx >= 0) failCard(cards[idx], name, e);
}
}
})();
await Promise.all([...mainPromises, wasmPromise]);
};
let pdfBytes = null;
// Generation counters discard stale async render/diff work.