-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
read.go
881 lines (792 loc) · 29.7 KB
/
read.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
package dicom
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
"unicode"
"github.com/suyashkumar/dicom/pkg/debug"
"github.com/suyashkumar/dicom/pkg/vrraw"
"github.com/suyashkumar/dicom/pkg/dicomio"
"github.com/suyashkumar/dicom/pkg/frame"
"github.com/suyashkumar/dicom/pkg/tag"
"golang.org/x/exp/constraints"
)
var (
// ErrorOWRequiresEvenVL indicates that an element with VR=OW had a not even
// value length which is not allowed.
ErrorOWRequiresEvenVL = errors.New("vr of OW requires even value length")
// ErrorUnsupportedVR indicates that this VR is not supported.
ErrorUnsupportedVR = errors.New("unsupported VR")
// ErrorUnsupportedBitsAllocated indicates that the BitsAllocated in the
// NativeFrame PixelData is unsupported. In this situation, the rest of the
// dataset returned is still valid.
ErrorUnsupportedBitsAllocated = errors.New("unsupported BitsAllocated")
errorUnableToParseFloat = errors.New("unable to parse float type")
ErrorExpectedEvenLength = errors.New("field length is not even, in violation of DICOM spec")
)
// reader is responsible for mid-level dicom parsing capabilities, like
// reading tags, VRs, and elements from the low-level *dicomio.Reader dicom data.
// TODO(suyashkumar): consider revisiting naming of this struct "reader" as it
// interplays with the rawReader *dicomio.Reader. We could consider combining
// them, or embedding the *dicomio.Reader struct into reader.
type reader struct {
rawReader *dicomio.Reader
opts parseOptSet
}
func (r *reader) readTag() (*tag.Tag, error) {
group, gerr := r.rawReader.ReadUInt16()
element, eerr := r.rawReader.ReadUInt16()
if gerr == nil && eerr == nil {
return &tag.Tag{Group: group, Element: element}, nil
}
return nil, fmt.Errorf("error reading tag: %w", errors.Join(gerr, eerr))
}
// TODO: Parsed VR should be an enum. Will require refactors of tag pkg.
func (r *reader) readVR(isImplicit bool, t tag.Tag) (string, error) {
if isImplicit {
if entry, err := tag.Find(t); err == nil {
switch entry.Tag {
case tag.PixelData, tag.OverlayData:
// OW takes priority in these cases. See notes at:
// 1. https://dicom.nema.org/medical/dicom/2024a/output/html/part05.html#sect_8.1.2
// 2. https://dicom.nema.org/medical/dicom/2024a/output/html/part05.html#sect_8.2
return "OW", nil
default:
return entry.VRs[0], nil
}
}
return tag.UnknownVR, nil
}
// Explicit Transfer Syntax, read 2 byte VR:
return r.rawReader.ReadString(2)
}
func (r *reader) readVL(isImplicit bool, t tag.Tag, vr string) (uint32, error) {
if isImplicit {
return r.rawReader.ReadUInt32()
}
// Explicit Transfer Syntax
// More details here: https://dicom.nema.org/medical/dicom/current/output/html/part05.html#sect_7.1.2
switch vr {
// TODO: Parsed VR should be an enum. Will require refactors of tag pkg.
case "NA", vrraw.OtherByte, vrraw.OtherDouble, vrraw.OtherFloat,
vrraw.OtherLong, vrraw.OtherWord, vrraw.Sequence, vrraw.Unknown,
vrraw.UnlimitedCharacters, vrraw.UniversalResourceIdentifier,
vrraw.UnlimitedText:
_ = r.rawReader.Skip(2) // ignore two reserved bytes (0000H)
vl, err := r.rawReader.ReadUInt32()
if err != nil {
return 0, err
}
if vl == tag.VLUndefinedLength &&
(vr == vrraw.UnlimitedCharacters ||
vr == vrraw.UniversalResourceIdentifier ||
vr == vrraw.UnlimitedText) {
return 0, errors.New("UC, UR and UT may not have an Undefined Length, i.e.,a Value Length of FFFFFFFFH")
}
return vl, nil
default:
vl16, err := r.rawReader.ReadUInt16()
if err != nil {
return 0, err
}
vl := uint32(vl16)
// Rectify Undefined Length VL
if vl == 0xffff {
vl = tag.VLUndefinedLength
}
return vl, nil
}
}
func (r *reader) readValue(t tag.Tag, vr string, vl uint32, isImplicit bool, d *Dataset, fc chan<- *frame.Frame) (Value, error) {
vrkind := tag.GetVRKind(t, vr)
// TODO: if we keep consistent function signature, consider a static map of VR to func?
switch vrkind {
case tag.VRBytes:
return r.readBytes(t, vr, vl)
case tag.VRString:
return r.readString(t, vr, vl)
case tag.VRDate:
return r.readDate(t, vr, vl)
case tag.VRUInt16List, tag.VRUInt32List, tag.VRInt16List, tag.VRInt32List, tag.VRTagList:
return r.readInt(t, vr, vl)
case tag.VRSequence:
return r.readSequence(t, vr, vl, d)
case tag.VRItem:
return r.readSequenceItem(t, vr, vl, d)
case tag.VRPixelData:
return r.readPixelData(vl, d, fc)
case tag.VRFloat32List, tag.VRFloat64List:
return r.readFloat(t, vr, vl)
// More details on how we treat Unknown VRs can be found at
// https://github.com/suyashkumar/dicom/issues/220
// and
// https://github.com/suyashkumar/dicom/issues/231.
// TODO(suyashkumar): consider replacing UN VRs with SQ earlier on if they
// meet this criteria, so users of the Dataset can interact with it
// correctly.
case tag.VRUnknown:
if vl == tag.VLUndefinedLength {
return r.readSequence(t, vr, vl, d)
}
return r.readBytes(t, vr, vl)
default:
return r.readString(t, vr, vl)
}
}
// readHeader reads the DICOM magic header and group two metadata elements.
// This should only be called once per DICOM at the start of parsing.
func (r *reader) readHeader() ([]*Element, error) {
// Check for Preamble (128 bytes) + magic word (4 bytes).
data, err := r.rawReader.Peek(128 + 4)
if err != nil {
return nil, fmt.Errorf("error reading DICOM header preamble: %w", err)
}
if string(data[128:]) != magicWord {
// If magic word is not at byte offset 128 this is a non-standard
// non-compliant DICOM. We try to read this DICOM in a compatibility
// mode, where we rewind to position 0 and blindly attempt to parse
// a Dataset (and do not parse metadata in the usual way), which is
// why we return nil error.
return nil, nil
}
err = r.rawReader.Skip(128 + 4) // skip preamble + magic word
if err != nil {
return nil, err
}
// Must read metadata as LittleEndian explicit VR
// Read the length of the metadata elements: (0002,0000) MetaElementGroupLength
maybeMetaLen, err := r.readElement(nil, nil)
if err != nil {
return nil, fmt.Errorf("error reading DICOM header element: %w", err)
}
metaElems := []*Element{maybeMetaLen} // TODO: maybe set capacity to a reasonable initial size
metaElementGroupLengthDefined := true
if maybeMetaLen.Tag != tag.FileMetaInformationGroupLength || maybeMetaLen.Value.ValueType() != Ints {
// MetaInformationGroupLength is not present or of the wrong value type.
if !r.opts.allowMissingMetaElementGroupLength {
return nil, ErrorMetaElementGroupLength
}
metaElementGroupLengthDefined = false
}
if metaElementGroupLengthDefined {
metaLen := maybeMetaLen.Value.GetValue().([]int)[0]
// Read the metadata elements
err = r.rawReader.PushLimit(int64(metaLen))
if err != nil {
return nil, err
}
defer r.rawReader.PopLimit()
for !r.rawReader.IsLimitExhausted() {
elem, err := r.readElement(nil, nil)
if err != nil {
// TODO: see if we can skip over malformed elements somehow
return nil, fmt.Errorf("error reading DICOM header element: %w", err)
}
metaElems = append(metaElems, elem)
}
} else {
// We cannot use the limit functionality
debug.Log("Proceeding without metadata group length")
for {
// Lets peek into the tag field until we get to end-of-header
groupBytes, err := r.rawReader.Peek(2)
if err != nil {
return nil, ErrorMetaElementGroupLength
}
var group uint16
buff := bytes.NewBuffer(groupBytes)
if err := binary.Read(buff, binary.LittleEndian, &group); err != nil {
return nil, err
}
debug.Logf("header-group: %v", group)
// Only read group 2 data
if group != 0x0002 {
break
}
elem, err := r.readElement(nil, nil)
if err != nil {
// TODO: see if we can skip over malformed elements somehow
return nil, fmt.Errorf("error reading DICOM header element (with no meta element group length defined): %w", err)
}
metaElems = append(metaElems, elem)
}
}
return metaElems, nil
}
func (r *reader) readPixelData(vl uint32, d *Dataset, fc chan<- *frame.Frame) (Value,
error) {
if vl == tag.VLUndefinedLength {
var image PixelDataInfo
image.IsEncapsulated = true
// The first Item in PixelData is the basic offset table. Skip this for now.
// TODO: use basic offset table
_, _, err := r.readRawItem(true /*shouldSkip*/)
if err != nil {
return nil, fmt.Errorf("readPixelData: error skipping basic offset table: %w", err)
}
for !r.rawReader.IsLimitExhausted() {
data, endOfItems, err := r.readRawItem(r.opts.skipPixelData /*shouldSkip*/)
if err != nil {
break
}
if endOfItems {
break
}
f := frame.Frame{
Encapsulated: true,
EncapsulatedData: frame.EncapsulatedFrame{
Data: data,
},
}
if fc != nil {
fc <- &f
}
image.Frames = append(image.Frames, &f)
}
image.IntentionallySkipped = r.opts.skipPixelData
return &pixelDataValue{PixelDataInfo: image}, nil
}
if r.opts.skipPixelData {
// If we're here, it means the VL isn't undefined length, so we should
// be able to safely skip the native PixelData.
if err := r.rawReader.Skip(int64(vl)); err != nil {
return nil, fmt.Errorf("readPixelData: skipPixelData option was set, and had error skipping PixelData: %w", err)
}
return &pixelDataValue{PixelDataInfo{IntentionallySkipped: true}}, nil
}
if r.opts.skipProcessingPixelDataValue {
val := &pixelDataValue{PixelDataInfo{IntentionallyUnprocessed: true}}
val.PixelDataInfo.UnprocessedValueData = make([]byte, vl)
_, err := io.ReadFull(r.rawReader, val.PixelDataInfo.UnprocessedValueData)
return val, err
}
// Assume we're reading NativeData data since we have a defined value length as per Part 5 Sec A.4 of DICOM spec.
// We need Elements that have been already parsed (rows, cols, etc) to parse frames out of NativeData Pixel data
if d == nil {
return nil, errors.New("the Dataset context cannot be nil in order to read Native PixelData")
}
i, _, err := r.readNativeFrames(d, fc, vl)
if err != nil {
return nil, err
}
// TODO: avoid this copy
return &pixelDataValue{PixelDataInfo: *i}, nil
}
func getNthBit(data byte, n int) int {
debug.Logf("mask: %0b", 1<<n)
if (1 << n & uint8(data)) > 0 {
return 1
}
return 0
}
func fillBufferSingleBitAllocated(pixelData []int, d *dicomio.Reader, bo binary.ByteOrder) error {
debug.Logf("len of pixeldata: %d", len(pixelData))
if len(pixelData)%8 > 0 {
return errors.New("when bitsAllocated is 1, we can't read a number of samples that is not a multiple of 8")
}
var currentByte byte
for i := 0; i < len(pixelData)/8; i++ {
rawData := make([]byte, 1)
_, err := d.Read(rawData)
if err != nil {
return err
}
currentByte = rawData[0]
debug.Logf("currentByte: %0b", currentByte)
// Read in the 8 bits from the current byte.
// Always treat the data as LittleEndian encoded.
// This is what pydicom appears to do, and I can't get Go to properly
// write out bytes literals in BigEndian, even using binary.Write
// (in order to test what BigEndian might look like). We should consider
// revisiting this more closely, and see if the most significant bit tag
// should be used to determine the read order here.
idx := 0
for j := 7; j >= 0; j-- {
pixelData[(8*i)+idx] = getNthBit(currentByte, j)
debug.Logf("getbit #%d: %d", j, getNthBit(currentByte, j))
idx++
}
}
return nil
}
func makeErrorPixelData(reader io.Reader, vl uint32, fc chan<- *frame.Frame, parseErr error) (*PixelDataInfo, error) {
data := make([]byte, vl)
_, err := io.ReadFull(reader, data)
if err != nil {
return nil, fmt.Errorf("makeErrorPixelData: read pixelData: %w", err)
}
f := frame.Frame{
EncapsulatedData: frame.EncapsulatedFrame{
Data: data,
},
}
if fc != nil {
fc <- &f
}
image := PixelDataInfo{
ParseErr: parseErr,
Frames: []*frame.Frame{&f},
}
return &image, nil
}
// readNativeFrames reads NativeData frames from a Decoder based on already parsed pixel information
// that should be available in parsedData (elements like NumberOfFrames, rows, columns, etc)
func (r *reader) readNativeFrames(parsedData *Dataset, fc chan<- *frame.Frame, vl uint32) (pixelData *PixelDataInfo,
bytesToRead int, err error) {
// Parse information from previously parsed attributes that are needed to parse NativeData Frames:
rows, err := parsedData.FindElementByTag(tag.Rows)
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error finding Rows tag: %w", err)
}
cols, err := parsedData.FindElementByTag(tag.Columns)
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error finding Columns tag: %w", err)
}
nof, err := parsedData.FindElementByTag(tag.NumberOfFrames)
nFrames := 0
if err == nil {
// No error, so parse number of frames
nFrames, err = strconv.Atoi(MustGetStrings(nof.Value)[0]) // odd that number of frames is encoded as a string...
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error converting NumberOfFrames from string to int: %w", err)
}
} else {
// error fetching NumberOfFrames, so default to 1. TODO: revisit
nFrames = 1
}
b, err := parsedData.FindElementByTag(tag.BitsAllocated)
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error finding BitsAllocated tag: %w", err)
}
bitsAllocated := MustGetInts(b.Value)[0]
s, err := parsedData.FindElementByTag(tag.SamplesPerPixel)
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error finding SamplesPerPixel tag: %w", err)
}
samplesPerPixel := MustGetInts(s.Value)[0]
pixelsPerFrame := MustGetInts(rows.Value)[0] * MustGetInts(cols.Value)[0]
debug.Logf("readNativeFrames:\nRows: %d\nCols:%d\nFrames::%d\nBitsAlloc:%d\nSamplesPerPixel:%d", MustGetInts(rows.Value)[0], MustGetInts(cols.Value)[0], nFrames, bitsAllocated, samplesPerPixel)
bytesAllocated := bitsAllocated / 8
bytesToRead = bytesAllocated * samplesPerPixel * pixelsPerFrame * nFrames
if bitsAllocated == 1 {
bytesToRead = pixelsPerFrame * samplesPerPixel / 8 * nFrames
}
skipFinalPaddingByte := false
if uint32(bytesToRead) != vl {
switch {
case uint32(bytesToRead) == vl-1 && vl%2 == 0:
skipFinalPaddingByte = true
case uint32(bytesToRead) == vl-1 && vl%2 != 0:
return nil, 0, fmt.Errorf("error when reading Native PixelData, got vl=%d, expected even VL: %w", vl, ErrorExpectedEvenLength)
default:
// calculated bytesToRead and actual VL mismatch
if !r.opts.allowMismatchPixelDataLength {
return nil, 0, fmt.Errorf("error when reading Native PixelData: expected_vl=%d actual_vl=%d %w", bytesToRead, vl, ErrorMismatchPixelDataLength)
}
image, err := makeErrorPixelData(r.rawReader, vl, fc, ErrorMismatchPixelDataLength)
if err != nil {
return nil, 0, fmt.Errorf("readNativeFrames: error making error pixel data: %w", err)
}
return image, int(vl), nil
}
}
// Parse the pixels:
image := PixelDataInfo{
IsEncapsulated: false,
}
image.Frames = make([]*frame.Frame, nFrames)
bo := r.rawReader.ByteOrder()
pixelBuf := make([]byte, bytesAllocated)
for frameIdx := 0; frameIdx < nFrames; frameIdx++ {
// Init current frame
currentFrame := frame.Frame{
Encapsulated: false,
}
if bitsAllocated == 1 {
buf := make([]int, pixelsPerFrame*samplesPerPixel) // override buf for now
if err := fillBufferSingleBitAllocated(buf, r.rawReader, bo); err != nil {
return nil, bytesToRead, err
}
nativeFrame := frame.NewNativeFrame[int](bitsAllocated, MustGetInts(rows.Value)[0], MustGetInts(cols.Value)[0], pixelsPerFrame, samplesPerPixel)
for pixel := 0; pixel < pixelsPerFrame; pixel++ {
for value := 0; value < samplesPerPixel; value++ {
nativeFrame.RawData[(pixel*samplesPerPixel)+value] = buf[pixel*samplesPerPixel+value]
}
}
currentFrame.NativeData = nativeFrame
} else {
switch bitsAllocated {
case 8:
currentFrame, _, err = readNativeFrame[uint8](bitsAllocated, MustGetInts(rows.Value)[0], MustGetInts(cols.Value)[0], bytesToRead, samplesPerPixel, pixelsPerFrame, pixelBuf, r.rawReader)
case 16:
currentFrame, _, err = readNativeFrame[uint16](bitsAllocated, MustGetInts(rows.Value)[0], MustGetInts(cols.Value)[0], bytesToRead, samplesPerPixel, pixelsPerFrame, pixelBuf, r.rawReader)
case 32:
currentFrame, _, err = readNativeFrame[uint32](bitsAllocated, MustGetInts(rows.Value)[0], MustGetInts(cols.Value)[0], bytesToRead, samplesPerPixel, pixelsPerFrame, pixelBuf, r.rawReader)
default:
return nil, bytesToRead, fmt.Errorf("unsupported bitsAllocated, got: %v, %w", bitsAllocated, ErrorUnsupportedBitsAllocated)
}
}
if err != nil {
return nil, bytesToRead, err
}
image.Frames[frameIdx] = ¤tFrame
if fc != nil {
fc <- ¤tFrame // write the current frame to the frame channel
}
}
if skipFinalPaddingByte {
err := r.rawReader.Skip(1)
if err != nil {
return nil, bytesToRead, fmt.Errorf("error when reading Native PixelData: could not read padding byte, when one needed to be skipped: %w", err)
}
bytesToRead++
}
return &image, bytesToRead, nil
}
// readNativeFrame builds and reads a single NativeFrame[I] from the rawReader.
// TODO(suyashkumar): refactor args to an options struct, or something more compact and readable.
func readNativeFrame[I constraints.Integer](bitsAllocated, rows, cols, bytesToRead, samplesPerPixel, pixelsPerFrame int, pixelBuf []byte, rawReader *dicomio.Reader) (frame.Frame, int, error) {
nativeFrame := frame.NewNativeFrame[I](bitsAllocated, rows, cols, pixelsPerFrame, samplesPerPixel)
currentFrame := frame.Frame{
Encapsulated: false,
NativeData: nativeFrame,
}
bo := rawReader.ByteOrder()
for pixel := 0; pixel < pixelsPerFrame; pixel++ {
for value := 0; value < samplesPerPixel; value++ {
_, err := io.ReadFull(rawReader, pixelBuf)
if err != nil {
return frame.Frame{}, bytesToRead,
fmt.Errorf("could not read uint%d from input: %w", bitsAllocated, err)
}
switch bitsAllocated {
case 8:
v, ok := any(pixelBuf[0]).(I)
if !ok {
return frame.Frame{}, bytesToRead, fmt.Errorf("internal error - readNativeFrame unexpectedly unable to type cast pixel buffer data to the I type (%T), where bitsAllocated=%v", *new(I), bitsAllocated)
}
nativeFrame.RawData[(pixel*samplesPerPixel)+value] = v
case 16:
v, ok := any(bo.Uint16(pixelBuf)).(I)
if !ok {
return frame.Frame{}, bytesToRead, fmt.Errorf("internal error - readNativeFrame unexpectedly unable to type cast pixel buffer data to the I type (%T), where bitsAllocated=%v", *new(I), bitsAllocated)
}
nativeFrame.RawData[(pixel*samplesPerPixel)+value] = v
case 32:
v, ok := any(bo.Uint32(pixelBuf)).(I)
if !ok {
return frame.Frame{}, bytesToRead, fmt.Errorf("internal error - readNativeFrame unexpectedly unable to type cast pixel buffer data to the I type (%T), where bitsAllocated=%v", *new(I), bitsAllocated)
}
nativeFrame.RawData[(pixel*samplesPerPixel)+value] = v
default:
return frame.Frame{}, bytesToRead, fmt.Errorf("readNativeFrame unsupported bitsAllocated=%d : %w", bitsAllocated, ErrorUnsupportedBitsAllocated)
}
}
}
return currentFrame, bytesToRead, nil
}
// readSequence reads a sequence element (VR = SQ) that contains a subset of Items. Each item contains
// a set of Elements.
// See https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html#table_7.5-1
func (r *reader) readSequence(t tag.Tag, vr string, vl uint32, d *Dataset) (Value, error) {
var sequences sequencesValue
seqElements := &Dataset{}
if vl == tag.VLUndefinedLength {
for {
subElement, err := r.readElement(seqElements, nil)
if err != nil {
// Stop reading due to error
return nil, fmt.Errorf("readSequence: error reading subitem in a sequence: %w", err)
}
if subElement.Tag == tag.SequenceDelimitationItem {
// Stop reading
break
}
if subElement.Tag != tag.Item || subElement.Value.ValueType() != SequenceItem {
// This is an error, should be an Item!
// TODO: use error var
log.Println("Tag is ", subElement.Tag)
return nil, fmt.Errorf("readSequence: error, non item element found in sequence. got: %v", subElement)
}
// Append the Item element's dataset of elements to this Sequence's sequencesValue.
sequences.value = append(sequences.value, subElement.Value.(*SequenceItemValue))
}
} else {
// Sequence of elements for a total of VL bytes
err := r.rawReader.PushLimit(int64(vl))
if err != nil {
return nil, err
}
for !r.rawReader.IsLimitExhausted() {
subElement, err := r.readElement(seqElements, nil)
if err != nil {
// TODO: option to ignore errors parsing subelements?
return nil, fmt.Errorf("readSequence: error reading subitem in a sequence: %w", err)
}
// Append the Item element's dataset of elements to this Sequence's sequencesValue.
sequences.value = append(sequences.value, subElement.Value.(*SequenceItemValue))
}
r.rawReader.PopLimit()
}
return &sequences, nil
}
// readSequenceItem reads an item component of a sequence dicom element and returns an Element
// with a SequenceItem value.
func (r *reader) readSequenceItem(t tag.Tag, vr string, vl uint32, d *Dataset) (Value, error) {
var sequenceItem SequenceItemValue
// seqElements holds items read so far.
// TODO: deduplicate with sequenceItem above
seqElements := Dataset{}
if vl == tag.VLUndefinedLength {
for {
subElem, err := r.readElement(&seqElements, nil)
if err != nil {
return nil, fmt.Errorf("readSequenceItem: error reading subitem in a sequence item: %w", err)
}
if subElem.Tag == tag.ItemDelimitationItem {
break
}
sequenceItem.elements = append(sequenceItem.elements, subElem)
seqElements.Elements = append(seqElements.Elements, subElem)
}
} else {
err := r.rawReader.PushLimit(int64(vl))
if err != nil {
return nil, err
}
for !r.rawReader.IsLimitExhausted() {
subElem, err := r.readElement(&seqElements, nil)
if err != nil {
return nil, fmt.Errorf("readSequenceItem: error reading subitem in a sequence item: %w", err)
}
sequenceItem.elements = append(sequenceItem.elements, subElem)
seqElements.Elements = append(seqElements.Elements, subElem)
}
r.rawReader.PopLimit()
}
return &sequenceItem, nil
}
func (r *reader) readBytes(t tag.Tag, vr string, vl uint32) (Value, error) {
// TODO: add special handling of PixelData
if vr == vrraw.OtherByte || vr == vrraw.Unknown {
data := make([]byte, vl)
_, err := io.ReadFull(r.rawReader, data)
return &bytesValue{value: data}, err
} else if vr == vrraw.OtherWord {
// OW -> stream of 16 bit words
if vl%2 != 0 {
return nil, fmt.Errorf("error reading bytes element (%v) value: %w", t, ErrorOWRequiresEvenVL)
}
buf := bytes.NewBuffer(make([]byte, 0, vl))
numWords := int(vl / 2)
for i := 0; i < numWords; i++ {
word, err := r.rawReader.ReadUInt16()
if err != nil {
return nil, fmt.Errorf("error reading bytes element (%v) value: %w", t, err)
}
// TODO: support bytes.BigEndian byte ordering
err = binary.Write(buf, binary.LittleEndian, word)
if err != nil {
return nil, err
}
}
return &bytesValue{value: buf.Bytes()}, nil
}
return nil, fmt.Errorf("error reading bytes element (%v): %w", t, ErrorUnsupportedVR)
}
func (r *reader) readString(t tag.Tag, vr string, vl uint32) (Value, error) {
str, err := r.rawReader.ReadString(vl)
if err != nil {
return nil, fmt.Errorf("error reading string element (%v) value: %w", t, err)
}
onlySpaces := true
for _, char := range str {
if !unicode.IsSpace(char) {
onlySpaces = false
}
}
if !onlySpaces {
// String may have '\0' suffix if its length is odd.
str = strings.Trim(str, " \000")
}
// Split multiple strings
strs := strings.Split(str, "\\")
return &stringsValue{value: strs}, nil
}
func (r *reader) readFloat(t tag.Tag, vr string, vl uint32) (Value, error) {
err := r.rawReader.PushLimit(int64(vl))
if err != nil {
return nil, err
}
retVal := &floatsValue{value: make([]float64, 0, vl/2)}
for !r.rawReader.IsLimitExhausted() {
switch vr {
case vrraw.FloatingPointSingle:
val, err := r.rawReader.ReadFloat32()
if err != nil {
return nil, fmt.Errorf("error reading floating point element (%v) value: %w", t, err)
}
// TODO(suyashkumar): revisit this hack to prevent some internal representation issues upconverting from
// float32 to float64. There is no loss of precision, but the value gets some additional significant digits
// when using golang casting. This approach prevents those artifacts, but is less efficient.
pval, err := strconv.ParseFloat(fmt.Sprint(val), 64)
if err != nil {
return nil, fmt.Errorf("error reading floating point element (%v) value during strconv.ParseFloat: %w", t, err)
}
retVal.value = append(retVal.value, pval)
break
case vrraw.FloatingPointDouble:
val, err := r.rawReader.ReadFloat64()
if err != nil {
return nil, fmt.Errorf("error reading floating point element (%v) value: %w", t, err)
}
retVal.value = append(retVal.value, val)
break
default:
return nil, fmt.Errorf("error reading floating point element(%v) value: unsupported VR: %w", t, errorUnableToParseFloat)
}
}
r.rawReader.PopLimit()
return retVal, nil
}
func (r *reader) readDate(t tag.Tag, vr string, vl uint32) (Value, error) {
rawDate, err := r.rawReader.ReadString(vl)
if err != nil {
return nil, fmt.Errorf("error reading date element (%v) value: %w", t, err)
}
date := strings.Trim(rawDate, " \000")
return &stringsValue{value: []string{date}}, nil
}
func (r *reader) readInt(t tag.Tag, vr string, vl uint32) (Value, error) {
// TODO: add other integer types here
err := r.rawReader.PushLimit(int64(vl))
if err != nil {
return nil, err
}
retVal := &intsValue{value: make([]int, 0, vl/2)}
for !r.rawReader.IsLimitExhausted() {
switch vr {
case vrraw.UnsignedShort, vrraw.AttributeTag:
val, err := r.rawReader.ReadUInt16()
if err != nil {
return nil, fmt.Errorf("error reading int element (%v) value (ReadUInt16): %w", t, err)
}
retVal.value = append(retVal.value, int(val))
break
case vrraw.UnsignedLong:
val, err := r.rawReader.ReadUInt32()
if err != nil {
return nil, fmt.Errorf("error reading int element (%v) value (ReadUInt32): %w", t, err)
}
retVal.value = append(retVal.value, int(val))
break
case vrraw.SignedLong:
val, err := r.rawReader.ReadInt32()
if err != nil {
return nil, fmt.Errorf("error reading int element (%v) value (ReadInt32): %w", t, err)
}
retVal.value = append(retVal.value, int(val))
break
case vrraw.SignedShort:
val, err := r.rawReader.ReadInt16()
if err != nil {
return nil, fmt.Errorf("error reading int element (%v) value (ReadInt16): %w", t, err)
}
retVal.value = append(retVal.value, int(val))
break
default:
return nil, fmt.Errorf("unable to parse integer type due to unknown VR %v", vr)
}
}
r.rawReader.PopLimit()
return retVal, err
}
// readElement reads the next element. If the next element is a sequence element,
// it may result in a collection of Elements. It takes a pointer to the Dataset of
// elements read so far, since previously read elements may be needed to parse
// certain Elements (like native PixelData). If the Dataset is nil, it is
// treated as an empty Dataset.
func (r *reader) readElement(d *Dataset, fc chan<- *frame.Frame) (*Element, error) {
t, err := r.readTag()
if err != nil {
return nil, fmt.Errorf("readElement: error when reading element tag: %w", err)
}
debug.Logf("readElement: tag: %s", t.String())
readImplicit := r.rawReader.IsImplicit()
if *t == tag.Item {
// Always read implicit for item elements
readImplicit = true
}
vr, err := r.readVR(readImplicit, *t)
if err != nil {
return nil, fmt.Errorf("readElement: error when reading VR for element %v: %w", t, err)
}
debug.Logf("readElement: vr: %s", vr)
vl, err := r.readVL(readImplicit, *t, vr)
if err != nil {
return nil, fmt.Errorf("readElement: error when reading VL for element %v: %w", t, err)
}
debug.Logf("readElement: vl: %d", vl)
val, err := r.readValue(*t, vr, vl, readImplicit, d, fc)
if err != nil {
return nil, fmt.Errorf("readElement: error when reading value for element %v: %w", t, err)
}
return &Element{Tag: *t, ValueRepresentation: tag.GetVRKind(*t, vr), RawValueRepresentation: vr, ValueLength: vl, Value: val}, nil
}
// Read an Item object as raw bytes, useful when parsing encapsulated PixelData.
// This returns the read raw item, an indication if this is the end of the set
// of items, and a possible errorawReader.
func (r *reader) readRawItem(shouldSkip bool) ([]byte, bool, error) {
t, err := r.readTag()
if err != nil {
return nil, true, fmt.Errorf("readRawItem: error when reading item tag: %w", err)
}
// Item is always encoded implicit. PS3.6 7.5
vr, err := r.readVR(true, *t)
if err != nil {
return nil, true, fmt.Errorf("readRawItem: error when reading VR for item %v: %w", t, err)
}
vl, err := r.readVL(true, *t, vr)
if err != nil {
return nil, true, fmt.Errorf("readRawItem: error when reading VL for item %v: %w", t, err)
}
if *t == tag.SequenceDelimitationItem {
if vl != 0 {
log.Printf("SequenceDelimitationItem's VL != 0: %d", vl)
}
return nil, true, nil
}
if *t != tag.Item {
log.Printf("Expect Item in pixeldata but found tag %s", tag.DebugString(*t))
return nil, false, nil
}
if vl == tag.VLUndefinedLength {
log.Println("Expect defined-length item in pixeldata")
return nil, false, nil
}
if vr != "NA" {
return nil, true, fmt.Errorf("readRawItem: expected VR=NA, got VR=%s", vr)
}
if shouldSkip {
if err := r.rawReader.Skip(int64(vl)); err != nil {
return nil, false, fmt.Errorf("readRawItem: error when skipping item %v (vl=%d): %w", t, vl, err)
}
} else {
data := make([]byte, vl)
_, err = io.ReadFull(r.rawReader, data)
if err != nil {
return nil, false, fmt.Errorf("readRawItem: error when reading item %v value: %w", t, err)
}
return data, false, nil
}
return nil, false, nil
}
// moreToRead returns true if there is more to read from the underlying dicom.
func (r *reader) moreToRead() bool {
return !r.rawReader.IsLimitExhausted()
}