-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
read_test.go
1020 lines (961 loc) · 32 KB
/
read_test.go
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 dicom
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"io"
"math/rand"
"strconv"
"testing"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/suyashkumar/dicom/pkg/vrraw"
"github.com/suyashkumar/dicom/pkg/dicomio"
"github.com/suyashkumar/dicom/pkg/frame"
"github.com/google/go-cmp/cmp"
"github.com/suyashkumar/dicom/pkg/tag"
)
func TestReadTag(t *testing.T) {
cases := []struct {
name string
data []byte
wantTag tag.Tag
wantErr error
}{
{
name: "basic",
data: buildTagData(t, tag.Rows),
wantTag: tag.Rows,
wantErr: nil,
},
{
name: "custom",
data: buildTagData(t, tag.Tag{0x0011, 0x0010}),
wantTag: tag.Tag{0x0011, 0x0010},
wantErr: nil,
},
{
name: "expected EOF on group read",
data: []byte{0x1},
wantErr: io.EOF,
},
{
name: "expected EOF on element read",
data: []byte{0x1, 0x2},
wantErr: io.EOF,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
data := bytes.NewBuffer(tc.data)
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(data), binary.LittleEndian, int64(data.Len())),
}
gotTag, err := r.readTag()
if !errors.Is(err, tc.wantErr) {
t.Errorf("TestReadTag: unexpected err. got: %v, want: %v", err, tc.wantErr)
}
if gotTag != nil && !gotTag.Equals(tc.wantTag) {
t.Errorf("TestReadTag: unexpected output. got: %v, want: %v", gotTag, tc.wantTag)
}
})
}
}
func TestReadFloat_float64(t *testing.T) {
cases := []struct {
name string
floats []float64
VR string
want Value
expectedErr error
}{
{
name: "float64",
floats: []float64{20.1, 32.22},
VR: vrraw.FloatingPointDouble,
want: &floatsValue{value: []float64{20.1, 32.22}},
expectedErr: nil,
},
{
name: "float64 with wrong VR",
floats: []float64{20.1, 32.22},
VR: "XX",
want: nil,
expectedErr: errorUnableToParseFloat,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
data := bytes.Buffer{}
for _, fl := range tc.floats {
if err := binary.Write(&data, binary.LittleEndian, fl); err != nil {
t.Errorf("TestReadFloat: Unable to setup test buffer")
}
}
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(&data), binary.LittleEndian, int64(data.Len())),
}
got, err := r.readFloat(tag.Tag{}, tc.VR, uint32(data.Len()))
if !errors.Is(err, tc.expectedErr) {
t.Fatalf("readFloat(r, tg, %s, %d) got unexpected error: got: %v, want: %v", tc.VR, data.Len(), err, tc.expectedErr)
}
if diff := cmp.Diff(got, tc.want, cmp.AllowUnexported(floatsValue{})); diff != "" {
t.Errorf("readFloat(r, tg, %s, %d) unexpected diff: %s", tc.VR, data.Len(), diff)
}
})
}
}
func TestReadFloat_float32(t *testing.T) {
cases := []struct {
name string
floats []float32
VR string
want Value
expectedErr error
}{
{
name: "float32",
floats: []float32{20.1001, 32.22},
VR: vrraw.FloatingPointSingle,
want: &floatsValue{value: []float64{20.1001, 32.22}},
expectedErr: nil,
},
{
name: "float32 with wrong VR",
floats: []float32{20.1001, 32.22},
VR: "XX",
want: nil,
expectedErr: errorUnableToParseFloat,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
data := bytes.Buffer{}
for _, fl := range tc.floats {
if err := binary.Write(&data, binary.LittleEndian, fl); err != nil {
t.Errorf("TestReadFloat: Unable to setup test buffer")
}
}
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(&data), binary.LittleEndian, int64(data.Len())),
}
got, err := r.readFloat(tag.Tag{}, tc.VR, uint32(data.Len()))
if !errors.Is(err, tc.expectedErr) {
t.Fatalf("readFloat(r, tg, %s, %d) got unexpected error: got: %v, want: %v", tc.VR, data.Len(), err, tc.expectedErr)
}
if diff := cmp.Diff(got, tc.want, cmp.AllowUnexported(floatsValue{})); diff != "" {
t.Errorf("readFloat(r, tg, %s, %d) unexpected diff: %s", tc.VR, data.Len(), diff)
}
})
}
}
func TestReadOWBytes(t *testing.T) {
cases := []struct {
name string
bytes []byte
VR string
want Value
expectedErr error
}{
{
name: "OW VR with even-number bytes",
bytes: []byte{0x1, 0x2, 0x3, 0x4},
VR: vrraw.OtherWord,
want: &bytesValue{value: []byte{0x1, 0x2, 0x3, 0x4}},
expectedErr: nil,
},
{
name: "UN VR even-number bytes",
bytes: []byte{0x1, 0x2, 0x3, 0x4},
VR: vrraw.Unknown,
want: &bytesValue{value: []byte{0x1, 0x2, 0x3, 0x4}},
expectedErr: nil,
},
{
name: "error on odd-number bytes",
bytes: []byte{0x1, 0x2, 0x3},
VR: vrraw.OtherWord,
want: nil,
expectedErr: ErrorOWRequiresEvenVL,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
data := bytes.Buffer{}
if err := binary.Write(&data, binary.LittleEndian, tc.bytes); err != nil {
t.Errorf("TestReadOWBytes: Unable to setup test buffer")
}
r := &reader{rawReader: dicomio.NewReader(bufio.NewReader(&data), binary.LittleEndian, int64(data.Len()))}
got, err := r.readBytes(tag.Tag{}, tc.VR, uint32(data.Len()))
if !errors.Is(err, tc.expectedErr) {
t.Fatalf("readBytes(r, tg, %s, %d) got unexpected error: got: %v, want: %v", tc.VR, data.Len(), err, tc.expectedErr)
}
if diff := cmp.Diff(got, tc.want, cmp.AllowUnexported(bytesValue{})); diff != "" {
t.Errorf("readBytes(r, tg, %s, %d) unexpected diff: %s", tc.VR, data.Len(), diff)
}
})
}
}
func TestReadNativeFrames(t *testing.T) {
cases := []struct {
Name string
existingData Dataset
uint16Data []uint16
dataBytes []byte
uint32Data []uint32
expectedPixelData *PixelDataInfo
expectedError error
pixelVLOverride uint32
parseOptSet parseOptSet
}{
{
Name: "5x5, 1 frame, 1 samples/pixel, bitsAllocated=16",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{5}),
mustNewElement(tag.Columns, []int{5}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{16}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
uint16Data: []uint16{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 5,
InternalCols: 5,
InternalSamplesPerPixel: 1,
RawData: []uint16{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
},
},
},
},
expectedError: nil,
},
{
Name: "2x2, 3 frames, 1 samples/pixel, bitsAllocated=16",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{2}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"3"}),
mustNewElement(tag.BitsAllocated, []int{16}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
uint16Data: []uint16{1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 0},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 2,
InternalCols: 2,
InternalSamplesPerPixel: 1,
RawData: []uint16{1, 2, 3, 2},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 2,
InternalCols: 2,
InternalSamplesPerPixel: 1,
RawData: []uint16{1, 2, 3, 2},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 2,
InternalCols: 2,
InternalSamplesPerPixel: 1,
RawData: []uint16{1, 2, 3, 0},
},
},
},
},
expectedError: nil,
},
{
Name: "2x2, 2 frames, 2 samples/pixel, bitsAllocated=16",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{2}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"2"}),
mustNewElement(tag.BitsAllocated, []int{16}),
mustNewElement(tag.SamplesPerPixel, []int{2}),
}},
uint16Data: []uint16{1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 5},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 2,
InternalCols: 2,
InternalSamplesPerPixel: 2,
RawData: []uint16{1, 2, 3, 2, 1, 2, 3, 2},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint16]{
InternalBitsPerSample: 16,
InternalRows: 2,
InternalCols: 2,
InternalSamplesPerPixel: 2,
RawData: []uint16{1, 2, 3, 2, 1, 2, 3, 5},
},
},
},
},
expectedError: nil,
},
{
Name: "bitsAllocated=32",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{5}),
mustNewElement(tag.Columns, []int{5}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{32}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
uint32Data: []uint32{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint32]{
InternalBitsPerSample: 32,
InternalRows: 5,
InternalCols: 5,
InternalSamplesPerPixel: 1,
RawData: []uint32{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
},
},
},
},
expectedError: nil,
},
{
Name: "insufficient bytes, uint32",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{2}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"2"}),
mustNewElement(tag.BitsAllocated, []int{32}),
mustNewElement(tag.SamplesPerPixel, []int{2}),
}},
uint16Data: []uint16{1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3},
expectedPixelData: nil,
expectedError: ErrorMismatchPixelDataLength,
},
{
Name: "redundant bytes, uint32",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{2}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{32}),
mustNewElement(tag.SamplesPerPixel, []int{2}),
}},
uint16Data: []uint16{1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 2},
expectedPixelData: nil,
expectedError: ErrorMismatchPixelDataLength,
},
{
Name: "redundant bytes, uint32 with allowing mismatch length",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{2}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{32}),
mustNewElement(tag.SamplesPerPixel, []int{2}),
}},
uint16Data: []uint16{1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 2},
expectedPixelData: &PixelDataInfo{
ParseErr: ErrorMismatchPixelDataLength,
Frames: []*frame.Frame{
{
EncapsulatedData: frame.EncapsulatedFrame{
Data: []byte{1, 0, 2, 0, 3, 0, 2, 0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0, 2, 0, 3, 0, 2, 0, 2, 0},
},
},
},
},
parseOptSet: parseOptSet{allowMismatchPixelDataLength: true},
expectedError: nil,
},
{
Name: "missing Columns",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{5}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{16}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
uint16Data: []uint16{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
expectedPixelData: nil,
expectedError: ErrorElementNotFound,
},
{
Name: "unsupported BitsAllocated",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{5}),
mustNewElement(tag.Columns, []int{2}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{24}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
uint16Data: []uint16{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
expectedPixelData: nil,
expectedError: ErrorUnsupportedBitsAllocated,
},
{
Name: "3x3, 3 frames, 1 samples/pixel, bytes data (uint8) with padded 0",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{3}),
mustNewElement(tag.Columns, []int{3}),
mustNewElement(tag.NumberOfFrames, []string{"3"}),
mustNewElement(tag.BitsAllocated, []int{8}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
dataBytes: []byte{11, 12, 13, 21, 22, 23, 31, 32, 33, 11, 12, 13, 21, 22, 23, 31, 32, 33, 11, 12, 13, 21, 22, 23, 31, 32, 33, 0}, // there is a 28th byte to make total value length even, as required by DICOM spec
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 3,
InternalCols: 3,
InternalSamplesPerPixel: 1,
RawData: []uint8{11, 12, 13, 21, 22, 23, 31, 32, 33},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 3,
InternalCols: 3,
InternalSamplesPerPixel: 1,
RawData: []uint8{11, 12, 13, 21, 22, 23, 31, 32, 33},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 3,
InternalCols: 3,
InternalSamplesPerPixel: 1,
RawData: []uint8{11, 12, 13, 21, 22, 23, 31, 32, 33},
},
},
},
},
expectedError: nil,
},
{
Name: "1x1, 3 frames, 3 samples/pixel, bytes data (uint8) with padded 0",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{1}),
mustNewElement(tag.Columns, []int{1}),
mustNewElement(tag.NumberOfFrames, []string{"3"}),
mustNewElement(tag.BitsAllocated, []int{8}),
mustNewElement(tag.SamplesPerPixel, []int{3}),
}},
dataBytes: []byte{1, 2, 3, 1, 2, 3, 1, 2, 3, 0}, // 10th byte to make total value length even
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 1,
InternalCols: 1,
InternalSamplesPerPixel: 3,
RawData: []uint8{1, 2, 3},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 1,
InternalCols: 1,
InternalSamplesPerPixel: 3,
RawData: []uint8{1, 2, 3},
},
},
{
Encapsulated: false,
NativeData: &frame.NativeFrame[uint8]{
InternalBitsPerSample: 8,
InternalRows: 1,
InternalCols: 1,
InternalSamplesPerPixel: 3,
RawData: []uint8{1, 2, 3},
},
},
},
},
expectedError: nil,
},
{
Name: "1x1, 2 frames, 3 samples/pixel, bad pixel length",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{1}),
mustNewElement(tag.Columns, []int{1}),
mustNewElement(tag.NumberOfFrames, []string{"2"}),
mustNewElement(tag.BitsAllocated, []int{8}),
mustNewElement(tag.SamplesPerPixel, []int{3}),
}},
dataBytes: []byte{1, 2, 3, 1, 2, 3},
expectedPixelData: nil,
pixelVLOverride: 7,
expectedError: ErrorExpectedEvenLength,
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
dcmdata := bytes.Buffer{}
var expectedBytes int
if len(tc.dataBytes) != 0 {
// writing byte-by-byte
expectedBytes = len(tc.dataBytes)
for _, item := range tc.dataBytes {
if err := binary.Write(&dcmdata, binary.LittleEndian, item); err != nil {
t.Errorf("TestReadNativeFrames: Unable to setup test buffer")
}
}
} else if len(tc.uint16Data) != 0 {
// writing 2 bytes (uint16) at a time
expectedBytes = len(tc.uint16Data) * 2
for _, item := range tc.uint16Data {
if err := binary.Write(&dcmdata, binary.LittleEndian, item); err != nil {
t.Errorf("TestReadNativeFrames: Unable to setup test buffer")
}
}
} else if len(tc.uint32Data) != 0 {
expectedBytes = len(tc.uint32Data) * 4
for _, item := range tc.uint32Data {
if err := binary.Write(&dcmdata, binary.LittleEndian, item); err != nil {
t.Errorf("TestReadNativeFrames: Unable to setup test buffer")
}
}
}
var vl uint32
if tc.pixelVLOverride > 0 {
vl = tc.pixelVLOverride
} else {
vl = uint32(dcmdata.Len())
}
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(&dcmdata), binary.LittleEndian, int64(dcmdata.Len())),
opts: tc.parseOptSet,
}
pixelData, bytesRead, err := r.readNativeFrames(&tc.existingData, nil, vl)
if !errors.Is(err, tc.expectedError) {
t.Errorf("TestReadNativeFrames(%+v): did not get expected error. got: %v, want: %v", tc, err, tc.expectedError)
}
if err == nil && bytesRead != expectedBytes {
t.Errorf("TestReadNativeFrames(%+v): did not read expected number of bytes. got: %d, want: %d", tc, bytesRead, expectedBytes)
}
if diff := cmp.Diff(tc.expectedPixelData, pixelData, cmpopts.EquateErrors()); diff != "" {
t.Errorf("TestReadNativeFrames(%+v): unexpected diff: %v", tc, diff)
}
})
}
}
func TestReadPixelData_SkipPixelData(t *testing.T) {
cases := []struct {
name string
vl uint32
data []byte
}{
{
name: "NativePixelData",
vl: 6,
data: []byte{1, 2, 3, 4, 5, 6},
},
{
name: "EncapsulatedPixelData",
vl: tag.VLUndefinedLength,
data: makeEncapsulatedSequence(t),
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
opts := parseOptSet{skipPixelData: true}
dcmdata := bytes.NewBuffer(tc.data)
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(dcmdata), binary.LittleEndian, int64(dcmdata.Len())),
opts: opts,
}
val, err := r.readPixelData(tc.vl, &Dataset{}, nil)
if err != nil {
t.Errorf("unexpected error in readPixelData: %v", err)
}
pixelVal, ok := val.GetValue().(PixelDataInfo)
if !ok {
t.Errorf("Expected value to be of type PixelDataInfo")
}
if !pixelVal.IntentionallySkipped {
t.Errorf("Expected PixelDataInfo to have IntentionallySkipped=true")
}
})
}
}
// Used to encode the data from the generated headers.
type headerData struct {
// The byte encoded header data.
HeaderBytes *bytes.Buffer
// The decoded elements conforming the header.
Elements []*Element
}
// Write a collection of elements and return them as an encoded buffer of bytes.
func writeElements(elements []*Element) ([]byte, error) {
buff := bytes.Buffer{}
dcmWriter, err := NewWriter(&buff)
if err != nil {
return []byte{}, err
}
dcmWriter.SetTransferSyntax(binary.LittleEndian, true)
for _, e := range elements {
err := dcmWriter.WriteElement(e)
if err != nil {
return nil, err
}
}
data := buff.Bytes()
return data, nil
}
// Returns a fake DICOM group 2 header with the FileMetaInformationGroupLength tag missing (0x0002,0x0000).
func headerWithNoFileMetaInformationGroupLength() (*headerData, error) {
headerData := new(headerData)
elements := []*Element{
mustNewElement(tag.MediaStorageSOPClassUID, []string{"SecondaryCapture"}),
mustNewElement(tag.MediaStorageSOPInstanceUID, []string{"1.3.6.1.4.1.35190.4.1.20210608.607733549593"}),
mustNewElement(tag.TransferSyntaxUID, []string{"=RLELossless"}),
mustNewElement(tag.ImplementationClassUID, []string{"1.6.6.1.4.1.9590.100.1.0.100.4.0"}),
mustNewElement(tag.SOPInstanceUID, []string{"1.3.6.1.4.1.35190.4.1.20210608.607733549593"}),
}
data, err := writeElements(elements)
if err != nil {
return nil, err
}
// Construct valid DICOM header preamble.
magicWord := []byte("DICM")
preamble := make([]byte, 128)
preamble = append(preamble, magicWord...)
headerBytes := append(preamble, data...)
headerData.HeaderBytes = bytes.NewBuffer(headerBytes)
headerData.Elements = elements[0 : len(elements)-1]
return headerData, nil
}
// Returns a fake DICOM group 2 header with a FileMetaInformationGroupLength tag (0x0002,0x0000).
func headerWithFileMetaInformationGroupLength() (*headerData, error) {
headerData := new(headerData)
sopInstanceUidElement := mustNewElement(tag.SOPInstanceUID, []string{"1.3.6.1.4.1.35190.4.1.20210608.607733549593"})
elements := []*Element{
mustNewElement(tag.FileMetaInformationVersion, []byte{0x00, 0x01}),
mustNewElement(tag.MediaStorageSOPClassUID, []string{"1.2.276.0.7230010.3.1.0.1"}),
mustNewElement(tag.MediaStorageSOPInstanceUID, []string{"1.3.6.1.4.1.35190.4.1.20210608.607733549593"}),
mustNewElement(tag.TransferSyntaxUID, []string{"=RLELossless"}),
mustNewElement(tag.ImplementationClassUID, []string{"1.2.276.0.7230010.3.0.3.6.7"}),
mustNewElement(tag.ImplementationVersionName, []string{"OFFIS_DCMTK_367"}),
}
dataHeader, err := writeElements(elements)
if err != nil {
return nil, err
}
fileMetaInfoElement := mustNewElement(tag.FileMetaInformationGroupLength, []int{len(dataHeader)})
dataFileMetaInfo, err := writeElements([]*Element{fileMetaInfoElement})
if err != nil {
return nil, err
}
dataSopInstanceUid, err := writeElements([]*Element{sopInstanceUidElement})
if err != nil {
return nil, err
}
data := append(dataFileMetaInfo, dataHeader...)
data = append(data, dataSopInstanceUid...)
// Construct valid DICOM header preamble.
magicWord := []byte("DICM")
preamble := make([]byte, 128)
preamble = append(preamble, magicWord...)
headerBytes := append(preamble, data...)
headerData.HeaderBytes = bytes.NewBuffer(headerBytes)
headerData.Elements = append([]*Element{fileMetaInfoElement}, elements...)
return headerData, nil
}
func TestReadHeader_TryAllowErrorMetaElementGroupLength(t *testing.T) {
opts := parseOptSet{allowMissingMetaElementGroupLength: true}
t.Run("NoFileMetaInformationGroupLength", func(t *testing.T) {
dcmheaderNoInfoGrpLen, err := headerWithNoFileMetaInformationGroupLength()
if err != nil {
t.Fatalf("unsuccessful generation of fake header data")
} else {
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(dcmheaderNoInfoGrpLen.HeaderBytes), binary.LittleEndian, int64(dcmheaderNoInfoGrpLen.HeaderBytes.Len())),
opts: opts,
}
r.rawReader.SetTransferSyntax(binary.LittleEndian, true)
wantElements, err := r.readHeader()
if err != nil {
t.Errorf("unsuccessful readHeader when parse option %v is turned on and header has no MetaElementGroupLength tag", opts.allowMissingMetaElementGroupLength)
}
// Ensure dataset read from readHeader and the test header are the same except for the ValueLength field.
if diff := cmp.Diff(wantElements, dcmheaderNoInfoGrpLen.Elements, cmp.AllowUnexported(allValues...), cmpopts.IgnoreFields(Element{}, "ValueLength")); diff != "" {
t.Errorf("Elements parsed from test header do not match: %v", diff)
}
}
})
t.Run("WithFileMetaInformationGroupLength", func(t *testing.T) {
dcmHeaderInfoGrpLen, err := headerWithFileMetaInformationGroupLength()
if err != nil {
t.Fatalf("unsuccessful generation of fake header data with FileMetaInformationGroupLength")
} else {
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(dcmHeaderInfoGrpLen.HeaderBytes), binary.LittleEndian, int64(dcmHeaderInfoGrpLen.HeaderBytes.Len())),
opts: opts,
}
r.rawReader.SetTransferSyntax(binary.LittleEndian, true)
wantElements, err := r.readHeader()
if err != nil {
t.Errorf("unsuccessful readHeader when parse option %v is turned on and header has no MetaElementGroupLength tag", opts.allowMissingMetaElementGroupLength)
}
// Ensure dataset read from readHeader and the test header are the same except for the ValueLength field.
if diff := cmp.Diff(wantElements, dcmHeaderInfoGrpLen.Elements, cmp.AllowUnexported(allValues...), cmpopts.IgnoreFields(Element{}, "ValueLength")); diff != "" {
t.Errorf("Elements parsed from test header do not match: %v", diff)
}
}
})
}
func TestReadPixelData_TrySkipProcessingPixelDataValue(t *testing.T) {
opts := parseOptSet{skipProcessingPixelDataValue: true}
valueBytes := []byte{1, 2, 3, 4, 5, 6}
dcmdata := bytes.NewBuffer(valueBytes)
r := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(dcmdata), binary.LittleEndian, int64(dcmdata.Len())),
opts: opts,
}
val, err := r.readPixelData(6, &Dataset{}, nil)
if err != nil {
t.Errorf("unexpected error in readPixelData: %v", err)
}
pixelVal, ok := val.GetValue().(PixelDataInfo)
if !ok {
t.Errorf("Expected value to be of type PixelDataInfo")
}
if !pixelVal.IntentionallyUnprocessed {
t.Errorf("Expected PixelDataInfo to have IntentionallyUnprocessed=true")
}
if !cmp.Equal(pixelVal.UnprocessedValueData, valueBytes) {
t.Errorf("expected UnprocessedValueData to match valueBytes. got: %v, want: %v", pixelVal.UnprocessedValueData, valueBytes)
}
}
func makeEncapsulatedSequence(t *testing.T) []byte {
t.Helper()
buf := &bytes.Buffer{}
w := dicomio.NewWriter(buf, binary.LittleEndian, true)
writePixelData(w, tag.PixelData, &pixelDataValue{PixelDataInfo{IsEncapsulated: true, Frames: []*frame.Frame{
{
Encapsulated: true,
EncapsulatedData: frame.EncapsulatedFrame{
Data: []byte{1, 2, 3, 4},
},
},
}}}, "", tag.VLUndefinedLength)
return buf.Bytes()
}
func TestReadNativeFrames_OneBitAllocated(t *testing.T) {
cases := []struct {
Name string
existingData Dataset
data []byte
expectedPixelData *PixelDataInfo
expectedError error
byteOrder binary.ByteOrder
}{
{
Name: "LittleEndian, 4x4, 1 frames, 1 samples/pixel",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{4}),
mustNewElement(tag.Columns, []int{4}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{1}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
data: []byte{0b00010111, 0b10010111},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[int]{
InternalBitsPerSample: 1,
InternalRows: 4,
InternalCols: 4,
InternalSamplesPerPixel: 1,
RawData: []int{0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1},
},
},
},
},
expectedError: nil,
byteOrder: binary.LittleEndian,
},
{
Name: "\"BigEndian\" (maybe), 4x4, 1 frames, 1 samples/pixel",
existingData: Dataset{Elements: []*Element{
mustNewElement(tag.Rows, []int{4}),
mustNewElement(tag.Columns, []int{4}),
mustNewElement(tag.NumberOfFrames, []string{"1"}),
mustNewElement(tag.BitsAllocated, []int{1}),
mustNewElement(tag.SamplesPerPixel, []int{1}),
}},
data: []byte{0b00010111, 0b10010111},
expectedPixelData: &PixelDataInfo{
IsEncapsulated: false,
Frames: []*frame.Frame{
{
Encapsulated: false,
NativeData: &frame.NativeFrame[int]{
InternalBitsPerSample: 1,
InternalRows: 4,
InternalCols: 4,
InternalSamplesPerPixel: 1,
RawData: []int{0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1},
},
},
},
},
expectedError: nil,
// For some reason, this doesn't make a difference, even though we
// don't change the order in which we read the bits in the
// implementation. For some reason, binary.Write isn't changing the
// order of the bits (or it is, and we somehow always read it back
// in the correct order).
byteOrder: binary.BigEndian,
},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
dcmdata := bytes.Buffer{}
for _, item := range tc.data {
if err := binary.Write(&dcmdata, tc.byteOrder, item); err != nil {
t.Errorf("TestReadNativeFrames: Unable to setup test buffer")
}
}
r := &reader{rawReader: dicomio.NewReader(bufio.NewReader(&dcmdata), tc.byteOrder, int64(dcmdata.Len()))}
pixelData, _, err := r.readNativeFrames(&tc.existingData, nil, uint32(dcmdata.Len()))
if !errors.Is(err, tc.expectedError) {
t.Errorf("TestReadNativeFrames(%v): did not get expected error. got: %v, want: %v", tc.data, err, tc.expectedError)
}
if diff := cmp.Diff(tc.expectedPixelData, pixelData); diff != "" {
t.Errorf("TestReadNativeFrames(%v): unexpected diff: %v\ndata:%v", tc.data, diff, pixelData)
}
})
}
}
func BenchmarkReadNativeFrames(b *testing.B) {
cases := []struct {
Name string
Rows int
Cols int
NumFrames int
SamplesPerPixel int
}{
{
Name: "10x10, 10 frames, 1 sample/pixel",
Rows: 10,
Cols: 10,
NumFrames: 10,
SamplesPerPixel: 1,
},
{
Name: "100x100, 10 frames, 1 sample/pixel",
Rows: 100,
Cols: 100,
NumFrames: 10,
SamplesPerPixel: 1,
},
{
Name: "512x512, 10 frames, 1 sample/pixel",
Rows: 512,
Cols: 512,
NumFrames: 10,
SamplesPerPixel: 1,
},
{
Name: "512x512, 10 frames, 5 sample/pixel",
Rows: 512,
Cols: 512,
NumFrames: 10,
SamplesPerPixel: 5,
},
}
for _, c := range cases {
b.Run(c.Name, func(b *testing.B) {
dataset, rawReader := buildReadNativeFramesInput(c.Rows, c.Cols, c.NumFrames, c.SamplesPerPixel, b)
r := &reader{rawReader: rawReader}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, _ = r.readNativeFrames(dataset, nil, uint32(c.Rows*c.Cols*c.NumFrames))
}
})
}
}
func buildReadNativeFramesInput(rows, cols, numFrames, samplesPerPixel int, b *testing.B) (*Dataset, *dicomio.Reader) {
b.Helper()
dataset := Dataset{
Elements: []*Element{
mustNewElement(tag.Rows, []int{rows}),
mustNewElement(tag.Columns, []int{cols}),
mustNewElement(tag.NumberOfFrames, []string{strconv.Itoa(numFrames)}),
mustNewElement(tag.BitsAllocated, []int{16}),
mustNewElement(tag.SamplesPerPixel, []int{samplesPerPixel}),
},
}
dcmdata := bytes.Buffer{}
dcmdata.Grow(2 * numFrames * rows * cols * samplesPerPixel)
for fr := 0; fr < numFrames; fr++ {
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
for pxs := 0; pxs < samplesPerPixel; pxs++ {
if err := binary.Write(&dcmdata, binary.LittleEndian, uint16(rand.Intn(100))); err != nil {
b.Fatalf("TestReadNativeFrames: Unable to setup test buffer")
}