forked from suyashkumar/dicom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
277 lines (240 loc) · 8.85 KB
/
parse.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
// Package dicom provides a set of tools to read, write, and generally
// work with DICOM (http://dicom.nema.org/) medical image files in Go.
//
// dicom.Parse and dicom.Write provide the core functionality to read and write
// DICOM Datasets. This package provides Go data structures that represent
// DICOM concepts (for example, dicom.Dataset and dicom.Element). These
// structures will pretty-print by default and are JSON serializable out of the
// box.
//
// This package provides some advanced functionality as well, including:
// streaming image frames to an output channel, reading elements one-by-one
// (like an iterator pattern), flat iteration over nested elements in a Dataset,
// and more.
//
// General usage is simple.
// Check out the package examples below and some function specific examples.
//
// It may also be helpful to take a look at the example cmd/dicomutil program,
// which is a CLI built around this library to save out image frames from DICOMs
// and print out metadata to STDOUT.
package dicom
import (
"bufio"
"encoding/binary"
"errors"
"io"
"os"
"github.com/suyashkumar/dicom/pkg/charset"
"github.com/suyashkumar/dicom/pkg/debug"
"github.com/suyashkumar/dicom/pkg/dicomio"
"github.com/suyashkumar/dicom/pkg/frame"
"github.com/suyashkumar/dicom/pkg/tag"
"github.com/suyashkumar/dicom/pkg/uid"
)
const (
magicWord = "DICM"
)
var (
// ErrorMagicWord indicates that the magic word was not found in the correct
// location in the DICOM.
ErrorMagicWord = errors.New("error, DICM magic word not found in correct location")
// ErrorMetaElementGroupLength indicates that the MetaElementGroupLength
// was not found where expected in the metadata.
ErrorMetaElementGroupLength = errors.New("MetaElementGroupLength tag not found where expected")
// ErrorEndOfDICOM indicates to the callers of Parser.Next() that the DICOM
// has been fully parsed. Users using one of the other Parse APIs should not
// need to use this.
ErrorEndOfDICOM = errors.New("this indicates to the caller of Next() that the DICOM has been fully parsed")
)
// Parse parses the entire DICOM at the input io.Reader into a Dataset of DICOM Elements. Use this if you are
// looking to parse the DICOM all at once, instead of element-by-element.
func Parse(in io.Reader, bytesToRead int64, frameChan chan *frame.Frame) (Dataset, error) {
p, err := NewParser(in, bytesToRead, frameChan)
if err != nil {
return Dataset{}, err
}
for !p.reader.IsLimitExhausted() {
_, err := p.Next()
if err != nil {
return p.dataset, err
}
}
// Close the frameChannel if needed
if p.frameChannel != nil {
close(p.frameChannel)
}
return p.dataset, nil
}
// ParseFile parses the entire DICOM at the given filepath. See dicom.Parse as
// well for a more generic io.Reader based API.
func ParseFile(filepath string, frameChan chan *frame.Frame) (Dataset, error) {
f, err := os.Open(filepath)
if err != nil {
return Dataset{}, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return Dataset{}, err
}
return Parse(f, info.Size(), frameChan)
}
// Parser is a struct that allows a user to parse Elements from a DICOM element-by-element using Next(), which may be
// useful for some streaming processing applications. If you instead just want to parse the whole input DICOM at once,
// just use the dicom.Parse(...) method.
type Parser struct {
reader dicomio.Reader
dataset Dataset
metadata Dataset
// file is optional, might be populated if reading from an underlying file
file *os.File
frameChannel chan *frame.Frame
}
// NewParser returns a new Parser that points to the provided io.Reader, with bytesToRead bytes left to read. NewParser
// will read the DICOM header and metadata as part of initialization.
//
// frameChannel is an optional channel (can be nil) upon which DICOM image frames will be sent as they are parsed (if
// provided).
func NewParser(in io.Reader, bytesToRead int64, frameChannel chan *frame.Frame, opts ...ParseOption) (*Parser, error) {
optSet := toParseOptSet(opts...)
reader, err := dicomio.NewReader(bufio.NewReader(in), binary.LittleEndian, bytesToRead)
if err != nil {
return nil, err
}
p := Parser{
reader: reader,
frameChannel: frameChannel,
}
elems := []*Element{}
if !optSet.skipMetadataReadOnNewParserInit {
debug.Log("NewParser: readHeader")
elems, err = p.readHeader()
if err != nil {
return nil, err
}
debug.Log("NewParser: readHeader complete")
}
p.dataset = Dataset{Elements: elems}
// TODO(suyashkumar): avoid storing the metadata pointers twice (though not that expensive)
p.metadata = Dataset{Elements: elems}
// Determine and set the transfer syntax based on the metadata elements parsed so far.
// The default will be LittleEndian Implicit.
var bo binary.ByteOrder = binary.LittleEndian
implicit := true
ts, err := p.dataset.FindElementByTag(tag.TransferSyntaxUID)
if err != nil {
debug.Log("WARN: could not find transfer syntax uid in metadata, proceeding with little endian implicit")
} else {
bo, implicit, err = uid.ParseTransferSyntaxUID(MustGetStrings(ts.Value)[0])
if err != nil {
// TODO(suyashkumar): should we attempt to parse with LittleEndian
// Implicit here?
debug.Log("WARN: could not parse transfer syntax uid in metadata")
}
}
p.reader.SetTransferSyntax(bo, implicit)
return &p, nil
}
// Next parses and returns the next top-level element from the DICOM this Parser points to.
func (p *Parser) Next() (*Element, error) {
if p.reader.IsLimitExhausted() {
// Close the frameChannel if needed
if p.frameChannel != nil {
close(p.frameChannel)
}
return nil, ErrorEndOfDICOM
}
elem, err := readElement(p.reader, &p.dataset, p.frameChannel)
if err != nil {
// TODO: tolerate some kinds of errors and continue parsing
return nil, err
}
// TODO: add dicom options to only keep track of certain tags
if elem.Tag == tag.SpecificCharacterSet {
encodingNames := MustGetStrings(elem.Value)
cs, err := charset.ParseSpecificCharacterSet(encodingNames)
if err != nil {
// unable to parse character set, hard error
// TODO: add option continue, even if unable to parse
return nil, err
}
p.reader.SetCodingSystem(cs)
}
p.dataset.Elements = append(p.dataset.Elements, elem)
return elem, nil
}
// GetMetadata returns just the set of metadata elements that have been parsed
// so far.
func (p *Parser) GetMetadata() Dataset {
return p.metadata
}
// SetTransferSyntax sets the transfer syntax for the underlying dicomio.Reader.
func (p *Parser) SetTransferSyntax(bo binary.ByteOrder, implicit bool) {
p.reader.SetTransferSyntax(bo, implicit)
}
// readHeader reads the DICOM magic header and group two metadata elements.
func (p *Parser) readHeader() ([]*Element, error) {
// Check to see if magic word is at byte offset 128. If not, 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).
data, err := p.reader.Peek(128 + 4)
if err != nil {
return nil, err
}
if string(data[128:]) != magicWord {
return nil, nil
}
err = p.reader.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 := readElement(p.reader, nil, nil)
if err != nil {
return nil, err
}
if maybeMetaLen.Tag != tag.FileMetaInformationGroupLength || maybeMetaLen.Value.ValueType() != Ints {
return nil, ErrorMetaElementGroupLength
}
metaLen := maybeMetaLen.Value.GetValue().([]int)[0]
metaElems := []*Element{maybeMetaLen} // TODO: maybe set capacity to a reasonable initial size
// Read the metadata elements
err = p.reader.PushLimit(int64(metaLen))
if err != nil {
return nil, err
}
defer p.reader.PopLimit()
for !p.reader.IsLimitExhausted() {
elem, err := readElement(p.reader, nil, nil)
if err != nil {
// TODO: see if we can skip over malformed elements somehow
return nil, err
}
// log.Printf("Metadata Element: %s\n", elem)
metaElems = append(metaElems, elem)
}
return metaElems, nil
}
// ParseOption represents an option that can be passed to NewParser.
type ParseOption func(*parseOptSet)
// parseOptSet represents the flattened option set after all ParseOptions have been applied.
type parseOptSet struct {
skipMetadataReadOnNewParserInit bool
}
func toParseOptSet(opts ...ParseOption) *parseOptSet {
optSet := &parseOptSet{}
for _, opt := range opts {
opt(optSet)
}
return optSet
}
// SkipMetadataReadOnNewParserInit makes NewParser skip trying to parse metadata. This will make the Parser default to implicit little endian byte order.
// Any metatata tags found in the dataset will still be available when parsing.
func SkipMetadataReadOnNewParserInit() ParseOption {
return func(set *parseOptSet) {
set.skipMetadataReadOnNewParserInit = true
}
}