forked from grailbio/go-dicom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
element.go
768 lines (723 loc) · 23.8 KB
/
element.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
package dicom
import (
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"strings"
"github.com/golang/glog"
"github.com/hxhxhx88/go-dicom/dicomio"
"github.com/hxhxhx88/go-dicom/dicomlog"
"github.com/hxhxhx88/go-dicom/dicomtag"
)
// Constants
const (
itemSeqGroup = 0xFFFE
unknownGroupName = "Unknown Group"
privateGroupName = "Private Data"
)
// Element represents a single DICOM element. Use NewElement() to create a
// element denovo. Avoid creating a struct manually, because setting the VR
// field is a bit tricky.
type Element struct {
// Tag is a pair of <group, element>. See tags.go for possible values.
Tag dicomtag.Tag
// List of values in the element. Their types depends on value
// representation (VR) of the Tag; Cf. tag.go.
//
// If Tag==TagPixelData, len(Value)==1, and Value[0] is PixelDataInfo.
// Else if Tag==TagItem, each Value[i] is a *Element.
// a value's Tag can be any (including TagItem, which represents a nested Item)
// Else if VR=="SQ", Value[i] is a *Element, with Tag=TagItem.
// Else if VR=="OW", "OB", then len(Value)==1, and Value[0] is []byte.
// Else if VR=="LT", or "UT", then len(Value)==1, and Value[0] is string
// Else if VR=="DA", then len(Value)==1, and Value[0] is string. Use ParseDate() to parse the date string.
// Else if VR=="US", Value[] is a list of uint16s
// Else if VR=="UL", Value[] is a list of uint32s
// Else if VR=="SS", Value[] is a list of int16s
// Else if VR=="SL", Value[] is a list of int32s
// Else if VR=="FL", Value[] is a list of float32s
// Else if VR=="FD", Value[] is a list of float64s
// Else if VR=="AT", Value[] is a list of Tag's.
// Else, Value[] is a list of strings.
//
// Note: Use GetVRKind() to map VR string to the go representation of
// VR.
Value []interface{} // Value Multiplicity PS 3.5 6.4
// Note: the following fields are not interesting to most people, but
// are filled for completeness. You can ignore them.
// VR defines the encoding of Value[] in two-letter alphabets, e.g.,
// "AE", "UL". See P3.5 6.2. This field MUST be set.
//
// dicom.ReadElement() will fill this field with the VR of the tag,
// either read from input stream (for explicit repl), or from the dicom
// tag table (for implicit decl). This field need not be set in
// WriteElement().
//
// Note: In a conformant DICOM file, the VR value of an element is
// determined by its Tag, so this field is redundant. This field is
// still required because a non-conformant file with with explicitVR
// encoding may have an element with VR that's different from the
// standard's. In such case, this library honors the VR value found in
// the file, and this field stores the VR used for parsing Values[].
VR string
// UndefinedLength is true if, in the DICOM file, the element is encoded
// as having undefined length, and is delimited by end-sequence or
// end-item element. This flag is meaningful only if VR=="SQ" or
// VR=="NA". Feel free to ignore this field if you don't understand what
// this means. It's one of the pointless complexities in the DICOM
// standard.
UndefinedLength bool
}
// NewElement creates a new Element with the given tag and values. The type of
// each each value must match the VR (value representation) of the tag (see
// tag_definition.go).
func NewElement(tag dicomtag.Tag, values ...interface{}) (*Element, error) {
ti, err := dicomtag.Find(tag)
if err != nil {
return nil, err
}
e := Element{
Tag: tag,
VR: ti.VR,
Value: make([]interface{}, len(values)),
}
vrKind := dicomtag.GetVRKind(tag, ti.VR)
for i, v := range values {
var ok bool
switch vrKind {
case dicomtag.VRStringList, dicomtag.VRDate:
_, ok = v.(string)
case dicomtag.VRBytes:
_, ok = v.([]byte)
case dicomtag.VRUInt16List:
_, ok = v.(uint16)
case dicomtag.VRUInt32List:
_, ok = v.(uint32)
case dicomtag.VRInt16List:
_, ok = v.(int16)
case dicomtag.VRInt32List:
_, ok = v.(int32)
case dicomtag.VRFloat32List:
_, ok = v.(float32)
case dicomtag.VRFloat64List:
_, ok = v.(float64)
case dicomtag.VRPixelData:
_, ok = v.(PixelDataInfo)
case dicomtag.VRTagList:
_, ok = v.(dicomtag.Tag)
case dicomtag.VRSequence:
var subelem *Element
subelem, ok = v.(*Element)
if ok {
ok = (subelem.Tag == dicomtag.Item)
}
case dicomtag.VRItem:
_, ok = v.(*Element)
}
if !ok {
return nil, fmt.Errorf("%v: wrong payload type for NewElement: expect %v, but found %v", dicomtag.DebugString(tag), vrKind, v)
}
e.Value[i] = v
}
return &e, nil
}
// MustNewElement is similar to NewElement, but it crashes the process on any
// error.
func MustNewElement(tag dicomtag.Tag, values ...interface{}) *Element {
elem, err := NewElement(tag, values...)
if err != nil {
panic(fmt.Sprintf("Failed to create element with tag %v: %v", tag, err))
}
return elem
}
// GetUInt32 gets a uint32 value from an element. It returns an error if the
// element contains zero or >1 values, or the value is not a uint32.
func (e *Element) GetUInt32() (uint32, error) {
if len(e.Value) != 1 {
return 0, fmt.Errorf("Found %d value(s) in getuint32 (expect 1): %v", len(e.Value), e)
}
v, ok := e.Value[0].(uint32)
if !ok {
return 0, fmt.Errorf("Uint32 value not found in %v", e)
}
return v, nil
}
// MustGetUInt32 is similar to GetUInt32, but panics on error.
func (e *Element) MustGetUInt32() uint32 {
v, err := e.GetUInt32()
if err != nil {
panic(err)
}
return v
}
// GetUInt16 gets a uint16 value from an element. It returns an error if the
// element contains zero or >1 values, or the value is not a uint16.
func (e *Element) GetUInt16() (uint16, error) {
if len(e.Value) != 1 {
return 0, fmt.Errorf("Found %d value(s) in getuint16 (expect 1): %v", len(e.Value), e)
}
v, ok := e.Value[0].(uint16)
if !ok {
return 0, fmt.Errorf("Uint16 value not found in %v", e)
}
return v, nil
}
// MustGetUInt16 is similar to GetUInt16, but panics on error.
func (e *Element) MustGetUInt16() uint16 {
v, err := e.GetUInt16()
if err != nil {
panic(err)
}
return v
}
// GetString gets a string value from an element. It returns an error if the
// element contains zero or >1 values, or the value is not a string.
func (e *Element) GetString() (string, error) {
if len(e.Value) != 1 {
return "", fmt.Errorf("Found %d value(s) in getstring (expect 1): %v", len(e.Value), e.String())
}
v, ok := e.Value[0].(string)
if !ok {
return "", fmt.Errorf("string value not found in %v", e)
}
return v, nil
}
// MustGetString is similar to GetString(), but panics on error.
//
// TODO(saito): Add other variants of MustGet<type>.
func (e *Element) MustGetString() string {
v, err := e.GetString()
if err != nil {
panic(err)
}
return v
}
// GetStrings returns the list of strings stored in the elment. Returns an error
// if the VR of e.Tag is not a string.
func (e *Element) GetStrings() ([]string, error) {
values := make([]string, 0, len(e.Value))
for _, v := range e.Value {
v, ok := v.(string)
if !ok {
return nil, fmt.Errorf("string value not found in %v", e.String())
}
values = append(values, v)
}
return values, nil
}
// MustGetStrings is similar to GetStrings, but crashes the process on error.
func (e *Element) MustGetStrings() []string {
values, err := e.GetStrings()
if err != nil {
panic(err)
}
return values
}
// GetUint32s returns the list of uint32 values stored in the elment. Returns an
// error if the VR of e.Tag is not a uint32.
func (e *Element) GetUint32s() ([]uint32, error) {
values := make([]uint32, 0, len(e.Value))
for _, v := range e.Value {
v, ok := v.(uint32)
if !ok {
return nil, fmt.Errorf("uint32 value not found in %v", e.String())
}
values = append(values, v)
}
return values, nil
}
// MustGetUint32s is similar to GetUint32s, but crashes the process on error.
func (e *Element) MustGetUint32s() []uint32 {
values, err := e.GetUint32s()
if err != nil {
panic(err)
}
return values
}
// GetUint16s returns the list of uint16 values stored in the elment. Returns an
// error if the VR of e.Tag is not a uint16.
func (e *Element) GetUint16s() ([]uint16, error) {
values := make([]uint16, 0, len(e.Value))
for _, v := range e.Value {
v, ok := v.(uint16)
if !ok {
return nil, fmt.Errorf("uint16 value not found in %v", e.String())
}
values = append(values, v)
}
return values, nil
}
// MustGetUint16s is similar to GetUint16s, but crashes the process on error.
func (e *Element) MustGetUint16s() []uint16 {
values, err := e.GetUint16s()
if err != nil {
panic(err)
}
return values
}
func elementString(e *Element, nestLevel int) string {
doassert(nestLevel < 10)
indent := strings.Repeat(" ", nestLevel)
s := indent
sVl := ""
if e.UndefinedLength {
sVl = "u"
}
s = fmt.Sprintf("%s %s %s %s ", s, dicomtag.DebugString(e.Tag), e.VR, sVl)
if e.VR == "SQ" || e.Tag == dicomtag.Item {
s += fmt.Sprintf(" (#%d)[\n", len(e.Value))
for _, v := range e.Value {
s += elementString(v.(*Element), nestLevel+1) + "\n"
}
s += indent + " ]"
} else {
var sv string
if len(e.Value) == 1 {
sv = fmt.Sprintf("%v", e.Value)
} else {
sv = fmt.Sprintf("(%d)%v", len(e.Value), e.Value)
}
if len(sv) > 1024 {
sv = sv[1:1024] + "(...)"
}
s += sv
}
return s
}
// Stringer
func (e *Element) String() string {
return elementString(e, 0)
}
// Read an Item object as raw bytes, w/o parsing them into DataElement. Used to
// parse pixel data.
func readRawItem(d *dicomio.Decoder) ([]byte, bool) {
tag := readTag(d)
// Item is always encoded implicit. PS3.6 7.5
vr, vl := readImplicit(d, tag)
if d.Error() != nil {
return nil, true
}
if tag == dicomtag.SequenceDelimitationItem {
if vl != 0 {
d.SetErrorf("SequenceDelimitationItem's VL != 0: %v", vl)
}
return nil, true
}
if tag != dicomtag.Item {
d.SetErrorf("Expect Item in pixeldata but found tag %v", dicomtag.DebugString(tag))
return nil, false
}
if vl == undefinedLength {
d.SetErrorf("Expect defined-length item in pixeldata")
return nil, false
}
if vr != "NA" {
d.SetErrorf("Expect NA item, but found %s", vr)
return nil, true
}
return d.ReadBytes(int(vl)), false
}
// PixelDataInfo is the Element.Value payload for PixelData element.
type PixelDataInfo struct {
Offsets []uint32 // BasicOffsetTable
Frames [][]byte // Parsed images
}
func (data PixelDataInfo) String() string {
s := fmt.Sprintf("image{offsets: %v, frames: [", data.Offsets)
for i := 0; i < len(data.Frames); i++ {
csum := sha256.Sum256(data.Frames[i])
s += fmt.Sprintf("%d:{size:%d, csum:%v} ",
i, len(data.Frames[i]),
base64.URLEncoding.EncodeToString(csum[:]))
}
return s + "]}"
}
// Read the basic offset table. This is the first Item object embedded inside
// PixelData element. P3.5 8.2. P3.5, A4 has a better example.
func readBasicOffsetTable(d *dicomio.Decoder) []uint32 {
data, endOfData := readRawItem(d)
if endOfData {
d.SetErrorf("basic offset table not found")
}
if len(data) == 0 {
return []uint32{0}
}
byteOrder, _ := d.TransferSyntax()
// The payload of the item is sequence of uint32s, each representing the
// byte size of an image that follows.
subdecoder := dicomio.NewBytesDecoder(data, byteOrder, dicomio.ImplicitVR)
var offsets []uint32
for subdecoder.Len() > 0 && subdecoder.Error() == nil {
offsets = append(offsets, subdecoder.ReadUInt32())
}
return offsets
}
// ParseFileHeader consumes the DICOM magic header and metadata elements (whose
// elements with tag group==2) from a Dicom file. Errors are reported through
// d.Error().
func ParseFileHeader(d *dicomio.Decoder) []*Element {
d.PushTransferSyntax(binary.LittleEndian, dicomio.ExplicitVR)
defer d.PopTransferSyntax()
d.Skip(128) // skip preamble
// check for magic word
if s := d.ReadString(4); s != "DICM" {
d.SetError(errors.New("Keyword 'DICM' not found in the header"))
return nil
}
// (0002,0000) MetaElementGroupLength
metaElem := ReadElement(d, ReadOptions{})
if d.Error() != nil {
return nil
}
if metaElem.Tag != dicomtag.FileMetaInformationGroupLength {
d.SetErrorf("MetaElementGroupLength not found; insteadfound %s", metaElem.Tag.String())
}
metaLength, err := metaElem.GetUInt32()
if err != nil {
d.SetErrorf("Failed to read uint32 in MetaElementGroupLength: %v", err)
return nil
}
if d.Len() <= 0 {
d.SetErrorf("No data element found")
return nil
}
metaElems := []*Element{metaElem}
// Read meta tags
d.PushLimit(int64(metaLength))
defer d.PopLimit()
for d.Len() > 0 {
elem := ReadElement(d, ReadOptions{})
if d.Error() != nil {
break
}
metaElems = append(metaElems, elem)
dicomlog.Vprintf(2, "dicom.ParseFileHeader: Meta elem: %v, len %v", elem.String(), d.Len())
}
return metaElems
}
// endElement is an pseudoelement to cause the caller to stop reading the input.
var endOfDataElement = &Element{Tag: dicomtag.Tag{Group: 0x7fff, Element: 0x7fff}}
// ReadElement reads one DICOM data element. It returns three kind of values.
//
// - On parse error, it returns nil and sets the error in d.Error().
//
// - It returns (endOfDataElement, nil) if options.DropPixelData=true and the
// element is a pixel data, or it sees an element defined by options.StopAtTag.
//
// - On successful parsing, it returns non-nil and non-endOfDataElement value.
func ReadElement(d *dicomio.Decoder, options ReadOptions) *Element {
tag := readTag(d)
if tag == dicomtag.PixelData && options.DropPixelData {
return endOfDataElement
}
// Return nil if the tag is greater than the StopAtTag if a StopAtTag is given
if options.StopAtTag != nil && tag.Compare(*options.StopAtTag) == 1 {
return endOfDataElement
}
// The elements for group 0xFFFE should be Encoded as Implicit VR.
// DICOM Standard 09. PS 3.6 - Section 7.5: "Nesting of Data Sets"
_, implicit := d.TransferSyntax()
if tag.Group == itemSeqGroup {
implicit = dicomio.ImplicitVR
}
var vr string // Value Representation
var vl uint32 // Value Length
if implicit == dicomio.ImplicitVR {
vr, vl = readImplicit(d, tag)
} else {
doassert(implicit == dicomio.ExplicitVR, implicit)
vr, vl = readExplicit(d, tag)
}
var data []interface{}
elem := &Element{
Tag: tag,
VR: vr,
UndefinedLength: (vl == undefinedLength),
}
if vr == "UN" && vl == undefinedLength {
// This combination appears in some file, but it's unclear what
// to do. The standard, as always, is unclear. The best guess is
// in PS3.5, 6.2.2, where it states that the combination of
// vr=UN and undefined length is allowed, it refers to a section
// of parsing "Data Elemets with Unknown Length". That reference
// is specifically about element of type SQ, so I'm just
// assuming <UN, undefinedlength> is the same as <SQ, undefined
// length>.
vr = "SQ"
}
if tag == dicomtag.PixelData {
// P3.5, A.4 describes the format. Currently we only support an encapsulated image format.
//
// PixelData is usually the last element in a DICOM file. When
// the file stores N images, the elements that follow PixelData
// are laid out in the following way:
//
// Item(BasicOffsetTable) Item(PixelDataInfo0) ... Item(PixelDataInfoM) SequenceDelimiterItem
//
// Item(BasicOffsetTable) is an Item element whose payload
// encodes N uint32 values. Kth uint32 is the bytesize of the
// Kth image. Item(PixelDataInfo*) are chunked sequences of bytes. I
// presume that single PixelDataInfo item doesn't cross a image
// boundary, but the spec isn't clear.
//
// The total byte size of Item(PixelDataInfo*) equal the total of
// the bytesizes found in BasicOffsetTable.
if vl == undefinedLength {
var image PixelDataInfo
image.Offsets = readBasicOffsetTable(d) // TODO(saito) Use the offset table.
if len(image.Offsets) > 1 {
dicomlog.Vprintf(1, "dicom.ReadElement: Multiple images not supported yet. Combining them into a byte sequence: %v", image.Offsets)
}
for d.Len() > 0 {
chunk, endOfItems := readRawItem(d)
if d.Error() != nil {
break
}
if endOfItems {
break
}
image.Frames = append(image.Frames, chunk)
}
data = append(data, image)
} else {
dicomlog.Vprintf(1, "dicom.ReadElement: Defined-length pixel data not supported: tag %v, VR=%v, VL=%v", tag.String(), vr, vl)
var image PixelDataInfo
image.Frames = append(image.Frames, d.ReadBytes(int(vl)))
data = append(data, image)
}
// TODO(saito) handle multi-frame image.
} else if vr == "SQ" {
// Note: when reading subitems inside sequence or item, we ignore
// DropPixelData and other shortcircuiting options. If we honored them, we'd
// be unable to read the rest of the file.
if vl == undefinedLength {
// Format:
// Sequence := ItemSet* SequenceDelimitationItem
// ItemSet := Item Any* ItemDelimitationItem (when Item.VL is undefined) or
// Item Any*N (when Item.VL has a defined value)
for {
// Makes sure to return all sub elements even if the tag is not in the return tags list of options or is greater than the Stop At Tag
item := ReadElement(d, ReadOptions{})
if d.Error() != nil {
break
}
if item.Tag == dicomtag.SequenceDelimitationItem {
break
}
if item.Tag != dicomtag.Item {
d.SetErrorf("dicom.ReadElement: Found non-Item element in seq w/ undefined length: %v", dicomtag.DebugString(item.Tag))
break
}
data = append(data, item)
}
} else {
// Format:
// Sequence := ItemSet*VL
// See the above comment for the definition of ItemSet.
d.PushLimit(int64(vl))
for d.Len() > 0 {
// Makes sure to return all sub elements even if the tag is not in the return tags list of options or is greater than the Stop At Tag
item := ReadElement(d, ReadOptions{})
if d.Error() != nil {
break
}
if item.Tag != dicomtag.Item {
d.SetErrorf("dicom.ReadElement: Found non-Item element in seq w/ undefined length: %v", dicomtag.DebugString(item.Tag))
break
}
data = append(data, item)
}
d.PopLimit()
}
} else if tag == dicomtag.Item { // Item (component of SQ)
if vl == undefinedLength {
// Format: Item Any* ItemDelimitationItem
for {
// Makes sure to return all sub elements even if the tag is not in the return tags list of options or is greater than the Stop At Tag
subelem := ReadElement(d, ReadOptions{})
if d.Error() != nil {
break
}
if subelem.Tag == dicomtag.ItemDelimitationItem {
break
}
data = append(data, subelem)
}
} else {
// Sequence of arbitary elements, for the total of "vl" bytes.
d.PushLimit(int64(vl))
for d.Len() > 0 {
// Makes sure to return all sub elements even if the tag is not in the return tags list of options or is greater than the Stop At Tag
subelem := ReadElement(d, ReadOptions{})
if d.Error() != nil {
break
}
data = append(data, subelem)
}
d.PopLimit()
}
} else { // List of scalar
if vl == undefinedLength {
d.SetErrorf("dicom.ReadElement: Undefined length disallowed for VR=%s, tag %s", vr, dicomtag.DebugString(tag))
return nil
}
d.PushLimit(int64(vl))
defer d.PopLimit()
if vr == "DA" {
// TODO(saito) Maybe we should validate the date.
date := strings.Trim(d.ReadString(int(vl)), " \000")
data = []interface{}{date}
} else if vr == "AT" {
// (2byte group, 2byte elem)
for d.Len() > 0 && d.Error() == nil {
tag := dicomtag.Tag{d.ReadUInt16(), d.ReadUInt16()}
data = append(data, tag)
}
} else if vr == "OW" {
if vl%2 != 0 {
d.SetErrorf("dicom.ReadElement: tag %v: OW requires even length, but found %v", dicomtag.DebugString(tag), vl)
} else {
n := int(vl / 2)
e := dicomio.NewBytesEncoder(dicomio.NativeByteOrder, dicomio.UnknownVR)
for i := 0; i < n; i++ {
v := d.ReadUInt16()
e.WriteUInt16(v)
}
doassert(e.Error() == nil, e.Error())
// TODO(saito) Check that size is even. Byte swap??
// TODO(saito) If OB's length is odd, is VL odd too? Need to check!
data = append(data, e.Bytes())
}
} else if vr == "OB" {
// TODO(saito) Check that size is even. Byte swap??
// TODO(saito) If OB's length is odd, is VL odd too? Need to check!
data = append(data, d.ReadBytes(int(vl)))
} else if vr == "LT" || vr == "UT" {
str := d.ReadString(int(vl))
data = append(data, str)
} else if vr == "UL" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadUInt32())
}
} else if vr == "SL" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadInt32())
}
} else if vr == "US" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadUInt16())
}
} else if vr == "SS" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadInt16())
}
} else if vr == "FL" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadFloat32())
}
} else if vr == "FD" {
for d.Len() > 0 && d.Error() == nil {
data = append(data, d.ReadFloat64())
}
} else {
// List of strings, each delimited by '\\'.
v := d.ReadString(int(vl))
// String may have '\0' suffix if its length is odd.
str := strings.Trim(v, " \000")
if len(str) > 0 {
for _, s := range strings.Split(str, "\\") {
data = append(data, s)
}
}
}
}
elem.Value = data
return elem
}
const undefinedLength uint32 = 0xffffffff
// Read a DICOM data element's tag value ie. (0002,0000) added Value
// Multiplicity PS 3.5 6.4
func readTag(buffer *dicomio.Decoder) dicomtag.Tag {
group := buffer.ReadUInt16() // group
element := buffer.ReadUInt16() // element
return dicomtag.Tag{group, element}
}
// Read the VR from the DICOM ditionary The VL is a 32-bit unsigned integer
func readImplicit(buffer *dicomio.Decoder, tag dicomtag.Tag) (string, uint32) {
vr := "UN"
if entry, err := dicomtag.Find(tag); err == nil {
vr = entry.VR
}
vl := buffer.ReadUInt32()
if vl != undefinedLength && vl%2 != 0 {
glog.V(2).Infof("Encountered odd length (vl=%v) when reading explicit VR %v for tag %s", vl, vr, dicomtag.DebugString(tag))
// buffer.SetErrorf("Encountered odd length (vl=%v) when reading implicit VR '%v' for tag %s", vl, vr, dicomtag.DebugString(tag))
// vl = 0
}
return vr, vl
}
// The VR is represented by the next two consecutive bytes
// The VL depends on the VR value
func readExplicit(buffer *dicomio.Decoder, tag dicomtag.Tag) (string, uint32) {
vr := buffer.ReadString(2)
var vl uint32
if vr == "US" {
vl = 2
}
// long value representations
switch vr {
case "NA", "OB", "OD", "OF", "OL", "OW", "SQ", "UN", "UC", "UR", "UT":
buffer.Skip(2) // ignore two bytes for "future use" (0000H)
vl = buffer.ReadUInt32()
if vl == undefinedLength && (vr == "UC" || vr == "UR" || vr == "UT") {
buffer.SetError(errors.New("UC, UR and UT may not have an Undefined Length, i.e.,a Value Length of FFFFFFFFH"))
vl = 0
}
default:
vl = uint32(buffer.ReadUInt16())
// Rectify Undefined Length VL
if vl == 0xffff {
vl = undefinedLength
}
}
if vl != undefinedLength && vl%2 != 0 {
glog.V(2).Infof("Encountered odd length (vl=%v) when reading explicit VR %v for tag %s", vl, vr, dicomtag.DebugString(tag))
// buffer.SetErrorf("Encountered odd length (vl=%v) when reading explicit VR %v for tag %s", vl, vr, dicomtag.DebugString(tag))
// vl = 0
}
return vr, vl
}
func tagInList(tag dicomtag.Tag, tags []dicomtag.Tag) bool {
for _, t := range tags {
if tag == t {
return true
}
}
return false
}
// FindElementByName finds an element with the given Element.Name in
// "elems" If not found, returns an error.
func FindElementByName(elems []*Element, name string) (*Element, error) {
t, err := dicomtag.FindByName(name)
if err != nil {
return nil, err
}
for _, elem := range elems {
if elem.Tag == t.Tag {
return elem, nil
}
}
return nil, fmt.Errorf("Could not find element named '%s' in dicom file", name)
}
// FindElementByTag finds an element with the given Element.Tag in
// "elems" If not found, returns an error.
func FindElementByTag(elems []*Element, tag dicomtag.Tag) (*Element, error) {
for _, elem := range elems {
if elem.Tag == tag {
return elem, nil
}
}
return nil, fmt.Errorf("%s: element not found", dicomtag.DebugString(tag))
}