-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder_test.go
More file actions
1211 lines (1060 loc) · 28.9 KB
/
Copy pathencoder_test.go
File metadata and controls
1211 lines (1060 loc) · 28.9 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
package jpeg2000
import (
"bytes"
"image"
"image/color"
"math"
"testing"
)
// --- BitWriter Tests ---
func TestBitWriterRoundTrip(t *testing.T) {
// Write bits with BitWriter, read them back with bitReader
tests := []struct {
name string
bits []int
}{
{"single zero", []int{0}},
{"single one", []int{1}},
{"byte 0xA5", []int{1, 0, 1, 0, 0, 1, 0, 1}},
{"byte 0xFF", []int{1, 1, 1, 1, 1, 1, 1, 1}},
{"12 bits", []int{1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1}},
{"16 zeros", []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := newBitWriter()
for _, bit := range tt.bits {
w.WriteBit(bit)
}
data := w.Flush()
r := newBitReader(data)
for i, expected := range tt.bits {
got, err := r.ReadBit()
if err != nil {
t.Fatalf("bit %d: ReadBit error: %v", i, err)
}
if got != expected {
t.Errorf("bit %d: got %d, want %d", i, got, expected)
}
}
})
}
}
func TestBitWriterWriteBits(t *testing.T) {
w := newBitWriter()
w.WriteBits(0b10110011, 8)
w.WriteBits(0b1010, 4)
data := w.Flush()
r := newBitReader(data)
got, err := r.ReadBits(8)
if err != nil {
t.Fatalf("ReadBits(8): %v", err)
}
if got != 0b10110011 {
t.Errorf("first 8 bits: got 0x%X, want 0xB3", got)
}
got, err = r.ReadBits(4)
if err != nil {
t.Fatalf("ReadBits(4): %v", err)
}
if got != 0b1010 {
t.Errorf("next 4 bits: got 0x%X, want 0xA", got)
}
}
func TestBitWriterByteStuffing(t *testing.T) {
// When bit-stuffing is enabled, a 0xFF byte should be followed by a
// byte whose MSB is 0 (stuffed bit).
w := newBitWriterWithStuffing()
// Write 0xFF (8 ones)
for range 8 {
w.WriteBit(1)
}
// Write 4 more ones
for range 4 {
w.WriteBit(1)
}
data := w.Flush()
// First byte should be 0xFF
if len(data) < 2 {
t.Fatalf("expected at least 2 bytes, got %d", len(data))
}
if data[0] != 0xFF {
t.Errorf("first byte: got 0x%02X, want 0xFF", data[0])
}
// Second byte's MSB must be 0 (stuffed bit)
if data[1]&0x80 != 0 {
t.Errorf("second byte MSB should be 0 (stuffed), got 0x%02X", data[1])
}
}
func TestBitWriterByteAlign(t *testing.T) {
w := newBitWriter()
w.WriteBit(1)
w.WriteBit(0)
w.WriteBit(1)
w.ByteAlign()
w.WriteBit(1)
data := w.Flush()
if len(data) != 2 {
t.Fatalf("expected 2 bytes after align, got %d", len(data))
}
// First byte: 101_00000 = 0xA0
if data[0] != 0xA0 {
t.Errorf("first byte: got 0x%02X, want 0xA0", data[0])
}
}
func TestBitWriterReset(t *testing.T) {
w := newBitWriter()
w.WriteBits(0xFF, 8)
w.Reset()
if w.Len() != 0 {
t.Errorf("after reset, Len() = %d, want 0", w.Len())
}
w.WriteBit(1)
data := w.Flush()
if data[0] != 0x80 {
t.Errorf("after reset+write: got 0x%02X, want 0x80", data[0])
}
}
// --- MQ Encoder Tests ---
func TestMQEncoderProducesOutput(t *testing.T) {
// Verify that the MQ encoder produces non-empty output for various symbol sequences.
// Note: The MQ encoder's C register convention follows ITU-T T.800 Annex C
// while the decoder follows OpenJPEG's convention (C shifted by 16). Direct
// round-trip testing requires matching conventions. The real validation is
// done via EBCOT encode→decode and full Encode→Decode round-trip tests.
tests := []struct {
name string
ctx int
symbols []int
}{
{"all MPS ctx0", 0, []int{0, 0, 0, 0, 0, 0, 0, 0}},
{"alternating ctx0", 0, []int{1, 0, 1, 0, 1, 0, 1, 0}},
{"mixed ctx0", 0, []int{0, 1, 0, 0, 1, 0, 1, 1, 0, 0}},
{"uniform ctx18", 18, []int{0, 1, 0, 1, 0, 1, 0, 1}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
enc := newMQEncoder()
for _, sym := range tt.symbols {
enc.Encode(tt.ctx, sym)
}
data := enc.Flush()
if len(data) == 0 {
t.Fatal("encoded data is empty")
}
// Verify no accidental marker sequences in output (no 0xFF followed by 0x90-0xFF)
for i := 0; i < len(data)-1; i++ {
if data[i] == 0xFF && data[i+1] >= 0x90 {
t.Errorf("accidental marker at offset %d: FF %02X", i, data[i+1])
}
}
})
}
}
func TestMQEncoderContextTransitions(t *testing.T) {
// Verify that encoding LPS symbols causes context state transitions
enc := newMQEncoder()
// Context 0 starts at state 4 (per initialization)
initialState := enc.contexts[0].index
// Encode several MPS symbols - should transition via nmps
for range 10 {
enc.Encode(0, 0)
}
afterMPS := enc.contexts[0].index
if afterMPS == initialState {
t.Log("MPS encoding did not change context state (may be expected for short sequences)")
}
// Reset and encode LPS - should transition via nlps
enc.ResetContexts()
enc.Reset()
initialState = enc.contexts[0].index
for range 5 {
enc.Encode(0, 1) // LPS
}
afterLPS := enc.contexts[0].index
if afterLPS == initialState {
t.Error("LPS encoding did not change context state")
}
}
// --- DWT Forward+Inverse Round-Trip Tests ---
func TestDWT2D_53_RoundTrip(t *testing.T) {
// Forward DWT then inverse DWT should give exact original for 5/3 (lossless)
tests := []struct {
name string
width int
height int
levels int
}{
{"8x8 1-level", 8, 8, 1},
{"8x8 2-levels", 8, 8, 2},
{"16x16 3-levels", 16, 16, 3},
{"odd 7x9 1-level", 7, 9, 1},
{"odd 7x9 2-levels", 7, 9, 2},
{"non-square 12x8 2-levels", 12, 8, 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create test data
original := make([][]int32, tt.height)
coeffs := make([][]int32, tt.height)
for y := range tt.height {
original[y] = make([]int32, tt.width)
coeffs[y] = make([]int32, tt.width)
for x := range tt.width {
original[y][x] = int32((y*tt.width + x) % 256)
coeffs[y][x] = original[y][x]
}
}
// Forward transform
Analyze2D_53(coeffs, tt.width, tt.height, tt.levels)
// Inverse transform
Synthesize2D_53(coeffs, tt.width, tt.height, tt.levels)
// Compare
for y := range tt.height {
for x := range tt.width {
if coeffs[y][x] != original[y][x] {
t.Errorf("pixel (%d,%d): got %d, want %d", x, y, coeffs[y][x], original[y][x])
}
}
}
})
}
}
func TestDWT2D_97_RoundTrip(t *testing.T) {
// Forward DWT then inverse DWT for 9/7 should be near-lossless
tests := []struct {
name string
width int
height int
levels int
maxError float64
}{
// 9/7 wavelet uses floating point with K scaling factors, so
// round-trip errors accumulate. Tolerances are relaxed accordingly.
{"8x8 1-level", 8, 8, 1, 0.001},
{"8x8 2-levels", 8, 8, 2, 0.01},
{"16x16 3-levels", 16, 16, 3, 0.01},
{"odd 7x9 1-level", 7, 9, 1, 0.001},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create test data
original := make([][]float64, tt.height)
coeffs := make([][]float64, tt.height)
for y := range tt.height {
original[y] = make([]float64, tt.width)
coeffs[y] = make([]float64, tt.width)
for x := range tt.width {
original[y][x] = float64((y*tt.width + x) % 256)
coeffs[y][x] = original[y][x]
}
}
// Forward transform
Analyze2D_97(coeffs, tt.width, tt.height, tt.levels)
// Inverse transform
Synthesize2D_97(coeffs, tt.width, tt.height, tt.levels)
// Compare with tolerance
maxErr := 0.0
for y := range tt.height {
for x := range tt.width {
err := math.Abs(coeffs[y][x] - original[y][x])
if err > maxErr {
maxErr = err
}
}
}
if maxErr > tt.maxError {
t.Errorf("max error %g exceeds threshold %g", maxErr, tt.maxError)
}
})
}
}
// --- Color Transform Round-Trip Tests ---
func TestForwardInverseRCT(t *testing.T) {
width, height := 8, 8
// Create RGB data
r := make([][]int32, height)
g := make([][]int32, height)
b := make([][]int32, height)
for y := range height {
r[y] = make([]int32, width)
g[y] = make([]int32, width)
b[y] = make([]int32, width)
for x := range width {
r[y][x] = int32((y*width+x)*7) % 256
g[y][x] = int32((y*width+x)*13) % 256
b[y][x] = int32((y*width+x)*19) % 256
}
}
// Save original
origR := clone2DInt32(r)
origG := clone2DInt32(g)
origB := clone2DInt32(b)
// Forward RCT
yy, cb, cr := forwardRCT(r, g, b)
// Inverse RCT
r2, g2, b2 := applyRCT(yy, cb, cr)
// Must be exact (lossless)
for y := range height {
for x := range width {
if r2[y][x] != origR[y][x] || g2[y][x] != origG[y][x] || b2[y][x] != origB[y][x] {
t.Errorf("pixel (%d,%d): RGB got (%d,%d,%d), want (%d,%d,%d)",
x, y, r2[y][x], g2[y][x], b2[y][x], origR[y][x], origG[y][x], origB[y][x])
}
}
}
}
func TestForwardInverseICT(t *testing.T) {
width, height := 8, 8
// Create RGB data
r := make([][]float64, height)
g := make([][]float64, height)
b := make([][]float64, height)
for y := range height {
r[y] = make([]float64, width)
g[y] = make([]float64, width)
b[y] = make([]float64, width)
for x := range width {
r[y][x] = float64((y*width+x)*7) / 256.0
g[y][x] = float64((y*width+x)*13) / 256.0
b[y][x] = float64((y*width+x)*19) / 256.0
}
}
// Forward ICT
yy, cb, cr := forwardICT(r, g, b)
// Inverse ICT
r2, g2, b2 := applyICT(yy, cb, cr)
// Should be near-exact (floating-point round-trip tolerance)
maxErr := 0.0
for y := range height {
for x := range width {
dr := math.Abs(r2[y][x] - r[y][x])
dg := math.Abs(g2[y][x] - g[y][x])
db := math.Abs(b2[y][x] - b[y][x])
maxErr = max(maxErr, dr, dg, db)
}
}
if maxErr > 1e-4 {
t.Errorf("max ICT round-trip error: %.2e (threshold: 1e-4)", maxErr)
}
}
// --- EBCOT Encoder Tests ---
func TestEBCOTEncodeZeroBlock(t *testing.T) {
// All-zero block should produce minimal output
coeffs := make([][]int32, 4)
for y := range coeffs {
coeffs[y] = make([]int32, 4)
}
enc := newEBCOTEncoder(4, 4)
block := enc.EncodeCodeBlock(coeffs, SubbandLL, 8)
if block.NumBitPlanes != 0 {
t.Errorf("zero block: NumBitPlanes = %d, want 0", block.NumBitPlanes)
}
if block.NumPasses != 0 {
t.Errorf("zero block: NumPasses = %d, want 0", block.NumPasses)
}
}
func TestEBCOTEncodeSingleCoeff(t *testing.T) {
// Block with a single non-zero coefficient
coeffs := make([][]int32, 4)
for y := range coeffs {
coeffs[y] = make([]int32, 4)
}
coeffs[1][1] = 5 // Binary: 101, needs 3 bit planes
enc := newEBCOTEncoder(4, 4)
block := enc.EncodeCodeBlock(coeffs, SubbandLL, 8)
if block.NumBitPlanes != 3 {
t.Errorf("single coeff: NumBitPlanes = %d, want 3", block.NumBitPlanes)
}
if block.NumPasses == 0 {
t.Error("single coeff: expected at least 1 pass")
}
// First pass is cleanup for the MSB
if block.Passes[0].Type != passTypeCleanup {
t.Errorf("first pass type = %d, want %d (cleanup)", block.Passes[0].Type, passTypeCleanup)
}
}
func TestEBCOTEncodePassCounts(t *testing.T) {
// For N bit planes: 1 cleanup pass for MSB, then 3 passes per remaining bit plane
// Total = 1 + 3*(N-1) = 3N - 2
coeffs := make([][]int32, 8)
for y := range coeffs {
coeffs[y] = make([]int32, 8)
for x := range coeffs[y] {
coeffs[y][x] = int32((y*8 + x) * 3) // Various magnitudes
}
}
enc := newEBCOTEncoder(8, 8)
block := enc.EncodeCodeBlock(coeffs, SubbandLH, 10)
expectedPasses := 3*block.NumBitPlanes - 2
if block.NumPasses != expectedPasses {
t.Errorf("NumPasses = %d, want %d (for %d bit planes)", block.NumPasses, expectedPasses, block.NumBitPlanes)
}
}
func TestEBCOTEncodeNegativeCoeffs(t *testing.T) {
// Test with mixed positive/negative coefficients
coeffs := [][]int32{
{-10, 5, -3, 7},
{2, -8, 4, -1},
{-6, 9, -2, 11},
{3, -7, 5, -4},
}
enc := newEBCOTEncoder(4, 4)
block := enc.EncodeCodeBlock(coeffs, SubbandHH, 10)
if block.NumPasses == 0 {
t.Error("negative coeffs: expected passes")
}
// In continuous MQ mode (standard JPEG2000 without ERTERM), all encoded
// data is stored on the last pass. Verify the last pass has data.
lastPass := block.Passes[len(block.Passes)-1]
if lastPass.Length == 0 {
t.Error("last pass has zero length")
}
totalLen := 0
for _, p := range block.Passes {
totalLen += p.Length
}
if totalLen == 0 {
t.Error("total data length is zero")
}
}
// --- Quantization Tests ---
func TestQuantize97RoundTrip(t *testing.T) {
stepSize := 2.0
original := [][]float64{
{10.5, -3.2, 0.8, -7.1},
{4.3, -0.5, 6.7, -2.9},
}
// Quantize
quantized := quantize97(original, stepSize)
// Dequantize
reconstructed := dequantize97(quantized, stepSize)
// Check: reconstruction should be within stepSize of original
for y := range original {
for x := range original[y] {
err := math.Abs(reconstructed[y][x] - original[y][x])
if err > stepSize {
t.Errorf("(%d,%d): error %g exceeds step size %g", x, y, err, stepSize)
}
}
}
}
func TestQuantizeDeadZone(t *testing.T) {
stepSize := 5.0
// Values smaller than stepSize should quantize to 0
data := [][]float64{
{4.9, -4.9, 0.0, 3.0},
}
quantized := quantize97(data, stepSize)
for x := range quantized[0] {
if quantized[0][x] != 0 {
t.Errorf("value %g quantized to %d, want 0 (dead zone)", data[0][x], quantized[0][x])
}
}
}
func TestComputeStepSizeRoundTrip(t *testing.T) {
bitDepth := 8
testSteps := []float64{0.5, 1.0, 2.0, 4.0, 8.0, 16.0}
for _, step := range testSteps {
exp, mant := computeExpMantissa(step, bitDepth)
reconstructed := computeStepSize(bitDepth, exp, mant)
// Should be within ~0.1% due to 11-bit mantissa quantization
relErr := math.Abs(reconstructed-step) / step
if relErr > 0.001 {
t.Errorf("step %g: exp=%d, mant=%d, reconstructed=%g, relErr=%g",
step, exp, mant, reconstructed, relErr)
}
}
}
// --- Rate Control Tests ---
func TestRateControlAllPasses(t *testing.T) {
// When target is larger than total, all passes should be included
blocks := []*EncodedBlock{
{
Passes: []EncodedPass{
{Length: 10, Distortion: 100},
{Length: 20, Distortion: 50},
{Length: 30, Distortion: 25},
},
NumPasses: 3,
},
}
rc := NewRateController(blocks)
passes := rc.OptimizeSingleLayer(1000)
if passes[0] != 3 {
t.Errorf("with large target: got %d passes, want 3", passes[0])
}
}
func TestRateControlZeroTarget(t *testing.T) {
blocks := []*EncodedBlock{
{
Passes: []EncodedPass{{Length: 10}},
NumPasses: 1,
},
}
rc := NewRateController(blocks)
passes := rc.OptimizeSingleLayer(0)
if passes[0] != 0 {
t.Errorf("with zero target: got %d passes, want 0", passes[0])
}
}
func TestRateControlUniformTruncation(t *testing.T) {
// Without distortion info, should use uniform truncation
blocks := make([]*EncodedBlock, 3)
for i := range blocks {
blocks[i] = &EncodedBlock{
Passes: []EncodedPass{
{Length: 10, Distortion: 0},
{Length: 20, Distortion: 0},
{Length: 30, Distortion: 0},
},
NumPasses: 3,
}
}
rc := NewRateController(blocks)
// Total is 3*60=180 bytes, target is 90 (half)
passes := rc.OptimizeSingleLayer(90)
totalBytes := 0
for i, blk := range blocks {
for p := 0; p < passes[i]; p++ {
totalBytes += blk.Passes[p].Length
}
}
if totalBytes > 90 {
t.Errorf("total bytes %d exceeds target 90", totalBytes)
}
}
// --- Subband Bounds Tests ---
func TestSubbandBounds(t *testing.T) {
// Test with 2 decomposition levels on a 16x16 tile
numLevels := 2
tileW, tileH := 16, 16
// LL at coarsest level: 16/4 = 4
sbType, x0, y0, w, h := subbandBounds(0, numLevels, tileW, tileH)
if sbType != SubbandLL {
t.Errorf("sb0: type = %d, want LL", sbType)
}
if w != 4 || h != 4 {
t.Errorf("sb0 (LL): size %dx%d, want 4x4", w, h)
}
if x0 != 0 || y0 != 0 {
t.Errorf("sb0 (LL): origin (%d,%d), want (0,0)", x0, y0)
}
// Check total area equals tile area
totalArea := 0
for sbIdx := range 3*numLevels + 1 {
_, _, _, sw, sh := subbandBounds(sbIdx, numLevels, tileW, tileH)
totalArea += sw * sh
}
if totalArea != tileW*tileH {
t.Errorf("total subband area = %d, want %d", totalArea, tileW*tileH)
}
}
func TestSubbandGain53(t *testing.T) {
numLevels := 3
// LL: gain=0
if g := subbandGain53(0, numLevels); g != 0 {
t.Errorf("LL gain = %d, want 0", g)
}
// LH (idx 1): gain=1
if g := subbandGain53(1, numLevels); g != 1 {
t.Errorf("LH gain = %d, want 1", g)
}
// HL (idx 2): gain=1
if g := subbandGain53(2, numLevels); g != 1 {
t.Errorf("HL gain = %d, want 1", g)
}
// HH (idx 3): gain=2
if g := subbandGain53(3, numLevels); g != 2 {
t.Errorf("HH gain = %d, want 2", g)
}
}
// --- Encoder Integration Tests ---
func TestEncodeLosslessGray(t *testing.T) {
// Create a small grayscale image and verify lossless round-trip
width, height := 32, 32
img := image.NewGray(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetGray(x, y, color.Gray{Y: uint8((x*7 + y*13) % 256)})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 3,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode: %v", err)
}
if buf.Len() == 0 {
t.Fatal("encoded data is empty")
}
// Verify it starts with SOC marker (0xFF4F)
data := buf.Bytes()
if len(data) < 2 || data[0] != 0xFF || data[1] != 0x4F {
t.Errorf("missing SOC marker: first bytes = %02X %02X", data[0], data[1])
}
// Verify it ends with EOC marker (0xFFD9)
if len(data) < 2 || data[len(data)-2] != 0xFF || data[len(data)-1] != 0xD9 {
t.Errorf("missing EOC marker: last bytes = %02X %02X", data[len(data)-2], data[len(data)-1])
}
}
func TestEncodeLosslessRGB(t *testing.T) {
width, height := 32, 32
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetNRGBA(x, y, color.NRGBA{
R: uint8((x*7 + y*3) % 256),
G: uint8((x*11 + y*5) % 256),
B: uint8((x*13 + y*17) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 3,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode: %v", err)
}
if buf.Len() == 0 {
t.Fatal("encoded data is empty")
}
// Basic structure check
data := buf.Bytes()
if data[0] != 0xFF || data[1] != 0x4F {
t.Error("missing SOC marker")
}
}
func TestEncodeLossyRGB(t *testing.T) {
width, height := 64, 64
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetNRGBA(x, y, color.NRGBA{
R: uint8((x*7 + y*3) % 256),
G: uint8((x*11 + y*5) % 256),
B: uint8((x*13 + y*17) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: false,
Quality: 0.8,
NumResolutions: 4,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode: %v", err)
}
if buf.Len() == 0 {
t.Fatal("encoded data is empty")
}
// Lossy should generally be smaller than lossless
var losslessBuf bytes.Buffer
_ = Encode(&losslessBuf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 4,
FileFormat: FormatJ2K,
})
t.Logf("lossy size: %d bytes, lossless size: %d bytes", buf.Len(), losslessBuf.Len())
}
func TestEncodeJP2Format(t *testing.T) {
width, height := 16, 16
img := image.NewGray(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetGray(x, y, color.Gray{Y: uint8(x * y)})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 2,
FileFormat: FormatJP2,
})
if err != nil {
t.Fatalf("Encode JP2: %v", err)
}
// JP2 files start with the JP2 signature box: 0x0000000C 6A502020
data := buf.Bytes()
if len(data) < 12 {
t.Fatal("JP2 data too short")
}
// Signature box length (4 bytes) + type (4 bytes) + content
// Box length = 12 (0x0000000C)
if data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 12 {
t.Errorf("JP2 signature box length: got %02X%02X%02X%02X, want 0000000C",
data[0], data[1], data[2], data[3])
}
// Box type = "jP " (0x6A502020)
if data[4] != 0x6A || data[5] != 0x50 || data[6] != 0x20 || data[7] != 0x20 {
t.Errorf("JP2 signature box type: got %02X%02X%02X%02X, want 6A502020",
data[4], data[5], data[6], data[7])
}
}
func TestEncodeTargetSize(t *testing.T) {
width, height := 64, 64
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetNRGBA(x, y, color.NRGBA{
R: uint8(x * 4),
G: uint8(y * 4),
B: uint8((x + y) * 2),
A: 255,
})
}
}
targetSize := 500
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: false,
TargetSize: targetSize,
NumResolutions: 3,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode with target size: %v", err)
}
t.Logf("target: %d bytes, actual: %d bytes", targetSize, buf.Len())
}
func TestEncodeSmallImage(t *testing.T) {
// Test edge case: very small image
sizes := []struct {
w, h int
}{
{1, 1},
{2, 2},
{3, 3},
{4, 4},
{1, 8},
{8, 1},
}
for _, sz := range sizes {
t.Run(
func() string { return image.Rect(0, 0, sz.w, sz.h).String() }(),
func(t *testing.T) {
img := image.NewGray(image.Rect(0, 0, sz.w, sz.h))
for y := range sz.h {
for x := range sz.w {
img.SetGray(x, y, color.Gray{Y: 128})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 2,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode %dx%d: %v", sz.w, sz.h, err)
}
if buf.Len() == 0 {
t.Fatalf("Encode %dx%d: empty output", sz.w, sz.h)
}
},
)
}
}
func TestEncodeDefaultOptions(t *testing.T) {
// Test encoding with nil options (all defaults)
img := image.NewGray(image.Rect(0, 0, 16, 16))
for y := range 16 {
for x := range 16 {
img.SetGray(x, y, color.Gray{Y: uint8(x + y)})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, nil)
if err != nil {
t.Fatalf("Encode with nil opts: %v", err)
}
if buf.Len() == 0 {
t.Fatal("empty output with nil opts")
}
}
// --- Encode+Decode Round-Trip Tests ---
func TestLosslessRoundTrip(t *testing.T) {
// Encode lossless then decode: pixels should match exactly
width, height := 32, 32
img := image.NewGray(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetGray(x, y, color.Gray{Y: uint8((x*17 + y*31) % 256)})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: true,
NumResolutions: 3,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode: %v", err)
}
decoded, err := Decode(bytes.NewReader(buf.Bytes()))
if err != nil {
t.Fatalf("Decode: %v", err)
}
bounds := decoded.Bounds()
if bounds.Dx() != width || bounds.Dy() != height {
t.Fatalf("decoded size: %dx%d, want %dx%d", bounds.Dx(), bounds.Dy(), width, height)
}
// Compare pixels
mismatches := 0
for y := range height {
for x := range width {
origR, origG, origB, _ := img.At(x, y).RGBA()
decR, decG, decB, _ := decoded.At(x, y).RGBA()
if origR != decR || origG != decG || origB != decB {
mismatches++
if mismatches <= 5 {
t.Errorf("pixel (%d,%d): original (%d,%d,%d) != decoded (%d,%d,%d)",
x, y, origR>>8, origG>>8, origB>>8, decR>>8, decG>>8, decB>>8)
}
}
}
}
if mismatches > 0 {
t.Errorf("total mismatches: %d out of %d pixels", mismatches, width*height)
}
}
func TestLossyRoundTrip(t *testing.T) {
// Encode lossy then decode: check PSNR is reasonable
width, height := 64, 64
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetNRGBA(x, y, color.NRGBA{
R: uint8((x*7 + y*3) % 256),
G: uint8((x*11 + y*5) % 256),
B: uint8((x*13 + y*17) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
err := Encode(&buf, img, &EncodeOptions{
Lossless: false,
Quality: 0.9,
NumResolutions: 3,
FileFormat: FormatJ2K,
})
if err != nil {
t.Fatalf("Encode: %v", err)
}
decoded, err := Decode(bytes.NewReader(buf.Bytes()))
if err != nil {
t.Fatalf("Decode: %v", err)
}
bounds := decoded.Bounds()
if bounds.Dx() != width || bounds.Dy() != height {
t.Fatalf("decoded size: %dx%d, want %dx%d", bounds.Dx(), bounds.Dy(), width, height)
}
// Compute PSNR
psnr := computePSNR(img, decoded, width, height)
t.Logf("lossy PSNR: %.2f dB (size: %d bytes)", psnr, buf.Len())
// A reasonable quality=0.9 encoding should yield PSNR > 20 dB
if psnr < 20.0 {
t.Errorf("PSNR %.2f dB is below threshold of 20 dB", psnr)
}
}
func TestLosslessRoundTripRGB(t *testing.T) {
width, height := 32, 32
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
img.SetNRGBA(x, y, color.NRGBA{