-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathProcessScreenshots.java
More file actions
1128 lines (1066 loc) · 44.3 KB
/
ProcessScreenshots.java
File metadata and controls
1128 lines (1066 loc) · 44.3 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
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
public class ProcessScreenshots {
private static final int MAX_COMMENT_BASE64 = 60_000;
private static final int[] JPEG_QUALITY_CANDIDATES = {70, 60, 50, 40, 30, 20, 10};
private static final byte[] PNG_SIGNATURE = new byte[]{
(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A
};
private static final int MAX_RETRIES = 5;
private static final long RETRY_DELAY_MS = 2000;
public static void main(String[] args) throws Exception {
Arguments arguments = Arguments.parse(args);
if (arguments == null) {
System.exit(2);
return;
}
Map<String, Object> payload = buildResults(
arguments.referenceDir,
arguments.actualEntries,
arguments.emitBase64,
arguments.previewDir,
arguments.maxChannelDelta,
arguments.maxMismatchPercent
);
String json = JsonUtil.stringify(payload);
System.out.print(json);
}
static Map<String, Object> buildResults(
Path referenceDir,
List<Map.Entry<String, Path>> actualEntries,
boolean emitBase64,
Path previewDir,
int maxChannelDelta,
double maxMismatchPercent
) throws IOException {
List<Map<String, Object>> results = new ArrayList<>();
for (Map.Entry<String, Path> entry : actualEntries) {
String testName = entry.getKey();
Path actualPath = entry.getValue();
Path expectedPath = referenceDir.resolve(testName + ".png");
Map<String, Object> record = new LinkedHashMap<>();
record.put("test", testName);
record.put("actual_path", actualPath.toString());
record.put("expected_path", expectedPath.toString());
if (!Files.exists(actualPath)) {
record.put("status", "missing_actual");
record.put("message", "Actual screenshot not found");
} else if (!Files.exists(expectedPath)) {
record.put("status", "missing_expected");
if (emitBase64) {
CommentPayload payload = loadPreviewOrBuild(testName, actualPath, previewDir);
recordPayload(record, payload, actualPath.getFileName().toString(), previewDir);
}
} else {
try {
PNGImage actual = loadPngWithRetry(actualPath);
PNGImage expected = loadPngWithRetry(expectedPath);
Map<String, Object> outcome = compareImages(expected, actual, maxChannelDelta, maxMismatchPercent);
if (Boolean.TRUE.equals(outcome.get("equal"))) {
record.put("status", "equal");
} else {
record.put("status", "different");
record.put("details", outcome);
if (emitBase64) {
CommentPayload payload = loadPreviewOrBuild(testName, actualPath, previewDir, actual);
recordPayload(record, payload, actualPath.getFileName().toString(), previewDir);
}
}
} catch (Exception ex) {
record.put("status", "error");
record.put("message", ex.getMessage());
}
}
results.add(record);
}
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("results", results);
return payload;
}
private static CommentPayload loadPreviewOrBuild(String testName, Path actualPath, Path previewDir) throws IOException {
return loadPreviewOrBuild(testName, actualPath, previewDir, null);
}
private static CommentPayload loadPreviewOrBuild(String testName, Path actualPath, Path previewDir, PNGImage cached) throws IOException {
if (previewDir != null) {
CommentPayload external = loadExternalPreviewPayload(testName, previewDir);
if (external != null) {
return external;
}
}
PNGImage image = cached != null ? cached : loadPngWithRetry(actualPath);
return buildCommentPayload(image, MAX_COMMENT_BASE64);
}
private static CommentPayload loadExternalPreviewPayload(String testName, Path previewDir) throws IOException {
String slug = slugify(testName);
Path jpg = previewDir.resolve(slug + ".jpg");
Path jpeg = previewDir.resolve(slug + ".jpeg");
Path png = previewDir.resolve(slug + ".png");
List<Path> candidates = new ArrayList<>();
if (Files.exists(jpg)) candidates.add(jpg);
if (Files.exists(jpeg)) candidates.add(jpeg);
if (Files.exists(png)) candidates.add(png);
if (candidates.isEmpty()) {
return null;
}
Path path = candidates.get(0);
byte[] data = Files.readAllBytes(path);
String encoded = Base64.getEncoder().encodeToString(data);
String mime = path.toString().toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
if (encoded.length() <= MAX_COMMENT_BASE64) {
return new CommentPayload(encoded.length(), encoded, mime, mime.endsWith("jpeg") ? "jpeg" : "png", null, null, "Preview provided by instrumentation", data);
}
return new CommentPayload(encoded.length(), null, mime, mime.endsWith("jpeg") ? "jpeg" : "png", null, "too_large", "Preview provided by instrumentation", data);
}
private static void recordPayload(Map<String, Object> record, CommentPayload payload, String defaultName, Path previewDir) throws IOException {
if (payload == null) {
return;
}
if (payload.base64 != null) {
record.put("base64", payload.base64);
} else {
record.put("base64_omitted", payload.omittedReason);
record.put("base64_length", payload.base64Length);
}
record.put("base64_mime", payload.mime);
record.put("base64_codec", payload.codec);
if (payload.quality != null) {
record.put("base64_quality", payload.quality);
}
if (payload.note != null) {
record.put("base64_note", payload.note);
}
if (previewDir != null && payload.data != null) {
Files.createDirectories(previewDir);
String suffix = payload.mime.equals("image/jpeg") ? ".jpg" : ".png";
String baseName = slugify(defaultName.contains(".") ? defaultName.substring(0, defaultName.lastIndexOf('.')) : defaultName);
Path previewPath = previewDir.resolve(baseName + suffix);
Files.write(previewPath, payload.data);
Map<String, Object> preview = new HashMap<>();
preview.put("path", previewPath.toString());
preview.put("name", previewPath.getFileName().toString());
preview.put("mime", payload.mime);
preview.put("codec", payload.codec);
if (payload.quality != null) {
preview.put("quality", payload.quality);
}
if (payload.note != null) {
preview.put("note", payload.note);
}
record.put("preview", preview);
}
}
private static String slugify(String name) {
StringBuilder sb = new StringBuilder();
for (char ch : name.toCharArray()) {
if (Character.isLetterOrDigit(ch)) {
sb.append(Character.toLowerCase(ch));
} else {
sb.append('_');
}
}
if (sb.length() == 0) {
sb.append("preview");
}
return sb.toString();
}
private static CommentPayload buildCommentPayload(PNGImage image, int maxLength) {
BufferedImage rgbImage = toRgbImage(image);
List<Double> scales = List.of(1.0, 0.7, 0.5, 0.35, 0.25);
byte[] smallestData = null;
Integer smallestQuality = null;
for (double scale : scales) {
BufferedImage candidate = rgbImage;
if (scale < 0.999) {
candidate = scaleImage(rgbImage, scale);
}
for (int quality : JPEG_QUALITY_CANDIDATES) {
byte[] data = writeJpeg(candidate, quality);
if (data == null) {
continue;
}
smallestData = data;
smallestQuality = quality;
String encoded = Base64.getEncoder().encodeToString(data);
if (encoded.length() <= maxLength) {
String note = "JPEG preview quality " + quality;
if (scale < 0.999) {
note += "; downscaled to " + candidate.getWidth() + "x" + candidate.getHeight();
}
return new CommentPayload(encoded.length(), encoded, "image/jpeg", "jpeg", quality, null, note, data);
}
}
}
if (smallestData != null) {
String encoded = Base64.getEncoder().encodeToString(smallestData);
return new CommentPayload(encoded.length(), null, "image/jpeg", "jpeg", smallestQuality, "too_large", "All JPEG previews exceeded limit even after downscaling", smallestData);
}
byte[] pngBytes = encodePng(image);
String encoded = Base64.getEncoder().encodeToString(pngBytes);
if (encoded.length() <= maxLength) {
return new CommentPayload(encoded.length(), encoded, "image/png", "png", null, null, null, pngBytes);
}
return new CommentPayload(encoded.length(), null, "image/png", "png", null, "too_large", null, pngBytes);
}
private static BufferedImage scaleImage(BufferedImage source, double scale) {
int width = Math.max(1, (int) Math.round(source.getWidth() * scale));
int height = Math.max(1, (int) Math.round(source.getHeight() * scale));
BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = dest.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawImage(source, 0, 0, width, height, null);
g.dispose();
return dest;
}
private static byte[] writeJpeg(BufferedImage image, int quality) {
try {
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (MemoryCacheImageOutputStream ios = new MemoryCacheImageOutputStream(baos)) {
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(Math.max(0.0f, Math.min(1.0f, quality / 100f)));
}
writer.write(null, new IIOImage(image, null, null), param);
} finally {
writer.dispose();
}
return baos.toByteArray();
} catch (Exception ex) {
return null;
}
}
private static BufferedImage toRgbImage(PNGImage image) {
BufferedImage output = new BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_RGB);
int stride = image.width * image.bytesPerPixel;
int offset = 0;
for (int y = 0; y < image.height; y++) {
for (int x = 0; x < image.width; x++) {
int r, g, b, a;
switch (image.colorType) {
case 0 -> {
int v = image.pixels[offset] & 0xFF;
r = g = b = v;
a = 255;
offset += 1;
}
case 2 -> {
r = image.pixels[offset] & 0xFF;
g = image.pixels[offset + 1] & 0xFF;
b = image.pixels[offset + 2] & 0xFF;
a = 255;
offset += 3;
}
case 4 -> {
int v = image.pixels[offset] & 0xFF;
a = image.pixels[offset + 1] & 0xFF;
r = g = b = v;
offset += 2;
}
case 6 -> {
r = image.pixels[offset] & 0xFF;
g = image.pixels[offset + 1] & 0xFF;
b = image.pixels[offset + 2] & 0xFF;
a = image.pixels[offset + 3] & 0xFF;
offset += 4;
}
default -> throw new IllegalArgumentException("Unsupported PNG color type: " + image.colorType);
}
int rgb = compositePixel(r, g, b, a);
output.setRGB(x, y, rgb);
}
}
return output;
}
private static int compositePixel(int r, int g, int b, int a) {
if (a >= 255) {
return (r << 16) | (g << 8) | b;
}
double alpha = a / 255.0;
int outR = (int) Math.round(r * alpha + 255 * (1 - alpha));
int outG = (int) Math.round(g * alpha + 255 * (1 - alpha));
int outB = (int) Math.round(b * alpha + 255 * (1 - alpha));
return (clamp(outR) << 16) | (clamp(outG) << 8) | clamp(outB);
}
private static int clamp(int value) {
return Math.max(0, Math.min(255, value));
}
private static Map<String, Object> compareImages(PNGImage expected, PNGImage actual, int maxChannelDelta, double maxMismatchPercent) {
boolean equal = expected.width == actual.width
&& expected.height == actual.height
&& expected.bitDepth == actual.bitDepth
&& expected.colorType == actual.colorType
&& java.util.Arrays.equals(expected.pixels, actual.pixels);
Map<String, Object> result = new LinkedHashMap<>();
result.put("width", actual.width);
result.put("height", actual.height);
result.put("bit_depth", actual.bitDepth);
result.put("color_type", actual.colorType);
if (!equal && maxChannelDelta > 0 && maxMismatchPercent >= 0 && expected.width == actual.width && expected.height == actual.height) {
int totalPixels = actual.width * actual.height;
int mismatchCount = countMismatchedPixels(expected, actual, maxChannelDelta);
double mismatchPercent = totalPixels == 0 ? 0d : (mismatchCount * 100d) / totalPixels;
result.put("mismatch_count", mismatchCount);
result.put("mismatch_percent", mismatchPercent);
result.put("max_channel_delta", maxChannelDelta);
result.put("max_mismatch_percent", maxMismatchPercent);
equal = mismatchPercent <= maxMismatchPercent;
}
result.put("equal", equal);
return result;
}
private static int countMismatchedPixels(PNGImage expected, PNGImage actual, int maxChannelDelta) {
int[] expectedRgb = toRgbArray(expected);
int[] actualRgb = toRgbArray(actual);
int mismatched = 0;
for (int i = 0; i < expectedRgb.length; i++) {
int e = expectedRgb[i];
int a = actualRgb[i];
int er = (e >> 16) & 0xff;
int eg = (e >> 8) & 0xff;
int eb = e & 0xff;
int ar = (a >> 16) & 0xff;
int ag = (a >> 8) & 0xff;
int ab = a & 0xff;
if (Math.abs(er - ar) > maxChannelDelta
|| Math.abs(eg - ag) > maxChannelDelta
|| Math.abs(eb - ab) > maxChannelDelta) {
mismatched++;
}
}
return mismatched;
}
private static int[] toRgbArray(PNGImage image) {
BufferedImage rgbImage = toRgbImage(image);
int[] pixels = new int[image.width * image.height];
rgbImage.getRGB(0, 0, image.width, image.height, pixels, 0, image.width);
return pixels;
}
private static PNGImage loadPngWithRetry(Path path) throws IOException {
int attempt = 0;
long lastSize = -1;
while (true) {
try {
// Stabilize check: if file size is changing, wait
if (Files.exists(path)) {
long size = Files.size(path);
if (size != lastSize) {
lastSize = size;
if (attempt > 0) {
// If size changed, we should wait and retry
Thread.sleep(RETRY_DELAY_MS);
attempt++;
if (attempt >= MAX_RETRIES) {
break; // fall through to try loading anyway, will likely fail
}
continue;
}
}
}
return loadPng(path);
} catch (IOException e) {
// Only retry on truncated chunk or premature end of file
if (e.getMessage() != null &&
(e.getMessage().contains("PNG chunk truncated") ||
e.getMessage().contains("Premature end of file") ||
e.getMessage().contains("Missing IHDR"))) {
attempt++;
if (attempt >= MAX_RETRIES) {
throw e;
}
try {
System.err.println("Retrying load of " + path + " (attempt " + (attempt + 1) + "/" + MAX_RETRIES + "): " + e.getMessage());
Thread.sleep(RETRY_DELAY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while waiting to retry load of " + path, ie);
}
} else {
throw e;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while loading " + path, e);
}
}
return loadPng(path); // Final attempt
}
private static PNGImage loadPng(Path path) throws IOException {
byte[] data = Files.readAllBytes(path);
for (int i = 0; i < PNG_SIGNATURE.length; i++) {
if (data[i] != PNG_SIGNATURE[i]) {
throw new IOException(path + " is not a PNG file (missing signature) on " + path);
}
}
int offset = PNG_SIGNATURE.length;
int width = 0;
int height = 0;
int bitDepth = 0;
int colorType = 0;
int interlace = 0;
List<byte[]> idatChunks = new ArrayList<>();
while (offset + 8 <= data.length) {
int length = readInt(data, offset);
byte[] type = java.util.Arrays.copyOfRange(data, offset + 4, offset + 8);
offset += 8;
if (offset + length + 4 > data.length) {
throw new IOException("PNG chunk truncated before CRC while processing: " + path);
}
byte[] chunkData = java.util.Arrays.copyOfRange(data, offset, offset + length);
offset += length + 4; // skip data + CRC
String chunkType = new String(type, StandardCharsets.US_ASCII);
if ("IHDR".equals(chunkType)) {
width = readInt(chunkData, 0);
height = readInt(chunkData, 4);
bitDepth = chunkData[8] & 0xFF;
colorType = chunkData[9] & 0xFF;
int compression = chunkData[10] & 0xFF;
int filter = chunkData[11] & 0xFF;
interlace = chunkData[12] & 0xFF;
if (compression != 0 || filter != 0) {
throw new IOException("Unsupported PNG compression or filter method on " + path);
}
} else if ("IDAT".equals(chunkType)) {
idatChunks.add(chunkData);
} else if ("IEND".equals(chunkType)) {
break;
}
}
if (width <= 0 || height <= 0) {
throw new IOException("Missing IHDR chunk on " + path);
}
if (interlace != 0) {
throw new IOException("Interlaced PNGs are not supported " + path);
}
int bytesPerPixel = bytesPerPixel(bitDepth, colorType);
byte[] combined = concat(idatChunks);
byte[] raw = inflate(combined);
byte[] pixels = unfilter(width, height, bytesPerPixel, raw);
return new PNGImage(width, height, bitDepth, colorType, pixels, bytesPerPixel);
}
private static byte[] encodePng(PNGImage image) {
try {
ByteArrayOutputStream raw = new ByteArrayOutputStream();
int stride = image.width * image.bytesPerPixel;
for (int y = 0; y < image.height; y++) {
raw.write(0);
raw.write(image.pixels, y * stride, stride);
}
byte[] compressed = deflate(raw.toByteArray());
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(PNG_SIGNATURE);
out.write(chunk("IHDR", buildIhdr(image)));
out.write(chunk("IDAT", compressed));
out.write(chunk("IEND", new byte[0]));
return out.toByteArray();
} catch (IOException ex) {
return new byte[0];
}
}
private static byte[] deflate(byte[] data) throws IOException {
java.util.zip.Deflater deflater = new java.util.zip.Deflater();
deflater.setInput(data);
deflater.finish();
byte[] buffer = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
out.write(buffer, 0, count);
}
deflater.end();
return out.toByteArray();
}
private static byte[] buildIhdr(PNGImage image) {
byte[] ihdr = new byte[13];
writeInt(ihdr, 0, image.width);
writeInt(ihdr, 4, image.height);
ihdr[8] = (byte) image.bitDepth;
ihdr[9] = (byte) image.colorType;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return ihdr;
}
private static byte[] chunk(String type, byte[] payload) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
writeInt(out, payload.length);
byte[] typeBytes = type.getBytes(StandardCharsets.US_ASCII);
out.write(typeBytes);
out.write(payload);
java.util.zip.CRC32 crc = new java.util.zip.CRC32();
crc.update(typeBytes);
crc.update(payload);
writeInt(out, (int) crc.getValue());
return out.toByteArray();
}
private static void writeInt(ByteArrayOutputStream out, int value) {
out.write((value >>> 24) & 0xFF);
out.write((value >>> 16) & 0xFF);
out.write((value >>> 8) & 0xFF);
out.write(value & 0xFF);
}
private static void writeInt(byte[] array, int offset, int value) {
array[offset] = (byte) ((value >>> 24) & 0xFF);
array[offset + 1] = (byte) ((value >>> 16) & 0xFF);
array[offset + 2] = (byte) ((value >>> 8) & 0xFF);
array[offset + 3] = (byte) (value & 0xFF);
}
private static byte[] concat(List<byte[]> chunks) {
int total = 0;
for (byte[] chunk : chunks) {
total += chunk.length;
}
byte[] combined = new byte[total];
int offset = 0;
for (byte[] chunk : chunks) {
System.arraycopy(chunk, 0, combined, offset, chunk.length);
offset += chunk.length;
}
return combined;
}
private static byte[] inflate(byte[] data) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(data);
byte[] buffer = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
if (count == 0 && inflater.needsInput()) {
break;
}
out.write(buffer, 0, count);
}
} catch (DataFormatException ex) {
throw new IOException("Failed to decompress IDAT data: " + ex.getMessage(), ex);
} finally {
inflater.end();
}
return out.toByteArray();
}
private static byte[] unfilter(int width, int height, int bytesPerPixel, byte[] raw) throws IOException {
int stride = width * bytesPerPixel;
int expected = height * (stride + 1);
if (raw.length != expected) {
throw new IOException("PNG IDAT payload has unexpected length");
}
byte[] result = new byte[height * stride];
int inOffset = 0;
int outOffset = 0;
for (int row = 0; row < height; row++) {
int filter = raw[inOffset++] & 0xFF;
switch (filter) {
case 0 -> {
System.arraycopy(raw, inOffset, result, outOffset, stride);
}
case 1 -> {
for (int i = 0; i < stride; i++) {
int left = i >= bytesPerPixel ? result[outOffset + i - bytesPerPixel] & 0xFF : 0;
int val = (raw[inOffset + i] & 0xFF) + left;
result[outOffset + i] = (byte) (val & 0xFF);
}
}
case 2 -> {
for (int i = 0; i < stride; i++) {
int up = row > 0 ? result[outOffset + i - stride] & 0xFF : 0;
int val = (raw[inOffset + i] & 0xFF) + up;
result[outOffset + i] = (byte) (val & 0xFF);
}
}
case 3 -> {
for (int i = 0; i < stride; i++) {
int left = i >= bytesPerPixel ? result[outOffset + i - bytesPerPixel] & 0xFF : 0;
int up = row > 0 ? result[outOffset + i - stride] & 0xFF : 0;
int val = (raw[inOffset + i] & 0xFF) + ((left + up) / 2);
result[outOffset + i] = (byte) (val & 0xFF);
}
}
case 4 -> {
for (int i = 0; i < stride; i++) {
int left = i >= bytesPerPixel ? result[outOffset + i - bytesPerPixel] & 0xFF : 0;
int up = row > 0 ? result[outOffset + i - stride] & 0xFF : 0;
int upLeft = (row > 0 && i >= bytesPerPixel) ? result[outOffset + i - stride - bytesPerPixel] & 0xFF : 0;
int paeth = paethPredictor(left, up, upLeft);
int val = (raw[inOffset + i] & 0xFF) + paeth;
result[outOffset + i] = (byte) (val & 0xFF);
}
}
default -> throw new IOException("Unsupported PNG filter type: " + filter);
}
inOffset += stride;
outOffset += stride;
}
return result;
}
private static int paethPredictor(int a, int b, int c) {
int p = a + b - c;
int pa = Math.abs(p - a);
int pb = Math.abs(p - b);
int pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) {
return a;
}
if (pb <= pc) {
return b;
}
return c;
}
private static int bytesPerPixel(int bitDepth, int colorType) throws IOException {
if (bitDepth != 8) {
throw new IOException("Unsupported bit depth: " + bitDepth);
}
return switch (colorType) {
case 0 -> 1;
case 2 -> 3;
case 4 -> 2;
case 6 -> 4;
default -> throw new IOException("Unsupported color type: " + colorType);
};
}
private static int readInt(byte[] data, int offset) {
return ((data[offset] & 0xFF) << 24)
| ((data[offset + 1] & 0xFF) << 16)
| ((data[offset + 2] & 0xFF) << 8)
| (data[offset + 3] & 0xFF);
}
private static final class CommentPayload {
final int base64Length;
final String base64;
final String mime;
final String codec;
final Integer quality;
final String omittedReason;
final String note;
final byte[] data;
CommentPayload(int base64Length, String base64, String mime, String codec, Integer quality, String omittedReason, String note, byte[] data) {
this.base64Length = base64Length;
this.base64 = base64;
this.mime = mime;
this.codec = codec;
this.quality = quality;
this.omittedReason = omittedReason;
this.note = note;
this.data = data;
}
}
private record PNGImage(int width, int height, int bitDepth, int colorType, byte[] pixels, int bytesPerPixel) {
}
private static class Arguments {
final Path referenceDir;
final List<Map.Entry<String, Path>> actualEntries;
final boolean emitBase64;
final Path previewDir;
final int maxChannelDelta;
final double maxMismatchPercent;
private Arguments(Path referenceDir, List<Map.Entry<String, Path>> actualEntries, boolean emitBase64, Path previewDir,
int maxChannelDelta, double maxMismatchPercent) {
this.referenceDir = referenceDir;
this.actualEntries = actualEntries;
this.emitBase64 = emitBase64;
this.previewDir = previewDir;
this.maxChannelDelta = maxChannelDelta;
this.maxMismatchPercent = maxMismatchPercent;
}
static Arguments parse(String[] args) {
Path reference = null;
boolean emitBase64 = false;
Path previewDir = null;
int maxChannelDelta = 4;
double maxMismatchPercent = 0.30d;
List<Map.Entry<String, Path>> actuals = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
switch (arg) {
case "--reference-dir" -> {
if (++i >= args.length) {
System.err.println("Missing value for --reference-dir");
return null;
}
reference = Path.of(args[i]);
}
case "--emit-base64" -> emitBase64 = true;
case "--preview-dir" -> {
if (++i >= args.length) {
System.err.println("Missing value for --preview-dir");
return null;
}
previewDir = Path.of(args[i]);
}
case "--actual" -> {
if (++i >= args.length) {
System.err.println("Missing value for --actual");
return null;
}
String value = args[i];
int idx = value.indexOf('=');
if (idx < 0) {
System.err.println("Invalid --actual value: " + value);
return null;
}
String name = value.substring(0, idx);
Path path = Path.of(value.substring(idx + 1));
actuals.add(Map.entry(name, path));
}
case "--max-channel-delta" -> {
if (++i >= args.length) {
System.err.println("Missing value for --max-channel-delta");
return null;
}
maxChannelDelta = parseIntArg("--max-channel-delta", args[i]);
if (maxChannelDelta < 0) {
return null;
}
}
case "--max-mismatch-percent" -> {
if (++i >= args.length) {
System.err.println("Missing value for --max-mismatch-percent");
return null;
}
maxMismatchPercent = parseDoubleArg("--max-mismatch-percent", args[i]);
if (maxMismatchPercent < 0) {
return null;
}
}
default -> {
System.err.println("Unknown argument: " + arg);
return null;
}
}
}
if (reference == null) {
System.err.println("--reference-dir is required");
return null;
}
return new Arguments(reference, actuals, emitBase64, previewDir, maxChannelDelta, maxMismatchPercent);
}
private static int parseIntArg(String flag, String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Invalid integer for " + flag + ": " + value);
return -1;
}
}
private static double parseDoubleArg(String flag, String value) {
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
System.err.println("Invalid number for " + flag + ": " + value);
return -1d;
}
}
}
}
class JsonUtil {
private JsonUtil() {}
public static Object parse(String text) {
return new Parser(text).parseValue();
}
public static String stringify(Object value) {
StringBuilder sb = new StringBuilder();
writeValue(sb, value);
return sb.toString();
}
@SuppressWarnings("unchecked")
public static Map<String, Object> asObject(Object value) {
if (value instanceof Map<?, ?> map) {
Map<String, Object> result = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object key = entry.getKey();
if (key instanceof String s) {
result.put(s, entry.getValue());
}
}
return result;
}
return new LinkedHashMap<>();
}
@SuppressWarnings("unchecked")
public static List<Object> asArray(Object value) {
if (value instanceof List<?> list) {
return new ArrayList<>((List<Object>) list);
}
return new ArrayList<>();
}
private static void writeValue(StringBuilder sb, Object value) {
if (value == null) {
sb.append("null");
} else if (value instanceof String s) {
writeString(sb, s);
} else if (value instanceof Number || value instanceof Boolean) {
sb.append(value.toString());
} else if (value instanceof Map<?, ?> map) {
sb.append('{');
boolean first = true;
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object key = entry.getKey();
if (!(key instanceof String sKey)) {
continue;
}
if (!first) {
sb.append(',');
}
first = false;
writeString(sb, sKey);
sb.append(':');
writeValue(sb, entry.getValue());
}
sb.append('}');
} else if (value instanceof List<?> list) {
sb.append('[');
boolean first = true;
for (Object item : list) {
if (!first) {
sb.append(',');
}
first = false;
writeValue(sb, item);
}
sb.append(']');
} else {
writeString(sb, value.toString());
}
}
private static void writeString(StringBuilder sb, String value) {
sb.append('"');
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
switch (ch) {
case '"' -> sb.append("\\\"");
case '\\' -> sb.append("\\\\");
case '\b' -> sb.append("\\b");
case '\f' -> sb.append("\\f");
case '\n' -> sb.append("\\n");
case '\r' -> sb.append("\\r");
case '\t' -> sb.append("\\t");
default -> {
if (ch < 0x20) {
sb.append(String.format("\\u%04x", (int) ch));
} else {
sb.append(ch);
}
}
}
}
sb.append('"');
}
private static final class Parser {
private final String text;
private int index;
Parser(String text) {
this.text = text;
}
Object parseValue() {
skipWhitespace();
if (index >= text.length()) {
throw new IllegalArgumentException("Unexpected end of JSON");
}
char ch = text.charAt(index);
return switch (ch) {
case '{' -> parseObject();
case '[' -> parseArray();
case '"' -> parseString();
case 't' -> parseLiteral("true", Boolean.TRUE);
case 'f' -> parseLiteral("false", Boolean.FALSE);
case 'n' -> parseLiteral("null", null);
default -> parseNumber();
};
}
private Map<String, Object> parseObject() {
index++;
Map<String, Object> result = new LinkedHashMap<>();
skipWhitespace();
if (peek('}')) {
index++;
return result;
}
while (true) {
skipWhitespace();
String key = parseString();
skipWhitespace();
expect(':');
index++;
Object value = parseValue();
result.put(key, value);
skipWhitespace();
if (peek('}')) {
index++;
break;
}
expect(',');
index++;
}
return result;
}
private List<Object> parseArray() {
index++;
List<Object> result = new ArrayList<>();
skipWhitespace();
if (peek(']')) {
index++;
return result;
}
while (true) {
Object value = parseValue();
result.add(value);
skipWhitespace();
if (peek(']')) {
index++;
break;
}
expect(',');
index++;
}
return result;
}
private String parseString() {
expect('"');
index++;
StringBuilder sb = new StringBuilder();
while (index < text.length()) {
char ch = text.charAt(index++);
if (ch == '"') {
return sb.toString();
}