-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
parse.go
350 lines (310 loc) · 11.9 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
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
// Package dicom provides a set of tools to read, write, and generally
// work with DICOM (https://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"
"bytes"
"encoding/binary"
"errors"
"fmt"
"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")
// ErrorMismatchPixelDataLength indicates that the size calculated from DICOM mismatch the VL.
ErrorMismatchPixelDataLength = errors.New("the size calculated from DICOM elements and the PixelData element's VL are mismatched")
)
func Parse(in io.Reader, bytesToRead int64, frameChan chan *frame.Frame, opts ...ParseOption) (Dataset, error) {
return parseInternal(in, bytesToRead, frameChan, opts...)
}
func ParseUntilEOF(in io.Reader, frameChan chan *frame.Frame, opts ...ParseOption) (Dataset, error) {
return parseInternal(in, dicomio.LimitReadUntilEOF, frameChan, opts...)
}
// 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 parseInternal(in io.Reader, bytesToRead int64, frameChan chan *frame.Frame, opts ...ParseOption) (Dataset, error) {
p, err := NewParser(in, bytesToRead, frameChan, opts...)
if err != nil {
return Dataset{}, err
}
for !p.reader.rawReader.IsLimitExhausted() {
_, err := p.Next()
if err != nil {
if errors.Is(err, io.EOF) {
// exiting on EOF
err = nil
break
}
// exit on error
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, opts ...ParseOption) (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, opts...)
}
// 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 *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...)
p := Parser{
reader: &reader{
rawReader: dicomio.NewReader(bufio.NewReader(in), binary.LittleEndian, bytesToRead),
opts: optSet,
},
frameChannel: frameChannel,
}
elems := []*Element{}
var err error
if !optSet.skipMetadataReadOnNewParserInit {
debug.Log("NewParser: readHeader")
elems, err = p.reader.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 {
// If we found the transfer syntax, apply it.
tsStr := MustGetStrings(ts.Value)[0]
bo, implicit, err = uid.ParseTransferSyntaxUID(tsStr)
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")
}
if tsStr == uid.DeflatedExplicitVRLittleEndian {
p.reader.rawReader.SetDeflate()
}
p.SetTransferSyntax(bo, implicit)
return &p, nil
}
// No transfer syntax found, so let's try to infer the transfer syntax by
// trying to read the next element under various transfer syntaxes.
next100, err := p.reader.rawReader.Peek(100)
if errors.Is(err, io.EOF) {
// DICOM is shorter than 100 bytes.
return nil, fmt.Errorf("dicom with missing transfer syntax metadata is shorter than 100 bytes, so cannot infer transfer syntax")
}
syntaxes := []struct {
name string
bo binary.ByteOrder
implicit bool
}{
{
name: "Little Endian Implicit",
bo: binary.LittleEndian,
implicit: true,
},
{
name: "Big Endian Explicit",
bo: binary.BigEndian,
implicit: false,
},
{
name: "Little Endian Explicit",
bo: binary.LittleEndian,
implicit: false,
},
}
for _, syntax := range syntaxes {
if canReadElementFromBytes(next100, optSet, syntax.bo, syntax.implicit) {
debug.Logf("WARN: could not find transfer syntax uid in metadata, proceeding with %v", syntax.name)
p.SetTransferSyntax(syntax.bo, syntax.implicit)
return &p, nil
}
}
// TODO(https://github.com/suyashkumar/dicom/issues/329): consider trying
// deflated parsing as a fallback as well.
return &p, errors.New("dicom missing transfer syntax uid in metadata, and it was not possible to successfully infer it using the next 100 bytes of the dicom")
}
func canReadElementFromBytes(buf []byte, optSet parseOptSet, bo binary.ByteOrder, implicit bool) bool {
next100Reader := bytes.NewReader(buf)
subR := &reader{
rawReader: dicomio.NewReader(bufio.NewReader(next100Reader), bo, int64(len(buf))),
opts: optSet,
}
subR.rawReader.SetTransferSyntax(bo, implicit)
_, err := subR.readElement(nil, nil)
if err == nil {
return true
}
return false
}
// 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.moreToRead() {
// Close the frameChannel if needed
if p.frameChannel != nil {
close(p.frameChannel)
}
return nil, ErrorEndOfDICOM
}
elem, err := p.reader.readElement(&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.rawReader.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.rawReader.SetTransferSyntax(bo, implicit)
}
// 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
allowMismatchPixelDataLength bool
skipPixelData bool
skipProcessingPixelDataValue bool
allowMissingMetaElementGroupLength bool
}
func toParseOptSet(opts ...ParseOption) parseOptSet {
optSet := parseOptSet{}
for _, opt := range opts {
opt(&optSet)
}
return optSet
}
// AllowMismatchPixelDataLength allows parser to ignore an error when the length calculated from elements do not match with value length.
func AllowMismatchPixelDataLength() ParseOption {
return func(set *parseOptSet) {
set.allowMismatchPixelDataLength = true
}
}
// AllowMissingMetaElementGroupLength allows parser to work around missing metaelement group length tag (0x0002,0x0000) by reading elements only
// in group 2.
func AllowMissingMetaElementGroupLength() ParseOption {
return func(set *parseOptSet) {
set.allowMissingMetaElementGroupLength = true
}
}
// 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
}
}
// SkipPixelData skips reading data from the PixelData tag, wherever it appears
// (e.g. even if within an IconSequence). A PixelDataInfo will be added to the
// Dataset with the IntentionallySkipped property set to true, and no other
// data. Use this option if you don't need the PixelData value to be in the
// Dataset at all, and want to save both CPU and Memory. If you need the
// PixelData value in the Dataset (e.g. so it can be written out identically
// later) but _don't_ want to process/parse the value, see the
// SkipProcessingPixelDataValue option below.
func SkipPixelData() ParseOption {
return func(set *parseOptSet) {
set.skipPixelData = true
}
}
// SkipProcessingPixelDataValue will attempt to skip processing the _value_
// of any PixelData elements. Unlike SkipPixelData(), this means the PixelData
// bytes will still be read into the Dataset, and can be written back out via
// this library's write functionality. Specifically, if this option is set,
// a PixelData element will be added to the dataset with the
// PixelDataInfo.IntentionallyUnprocessed = true, and the raw bytes of the
// entire PixelData element stored in PixelDataInfo.UnprocessedValueData.
//
// In the future, we may be able to extend this functionality to support
// on-demand processing of elements elsewhere in the library.
func SkipProcessingPixelDataValue() ParseOption {
return func(set *parseOptSet) {
set.skipProcessingPixelDataValue = true
}
}