-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathvtkDICOMParser.cxx
2495 lines (2228 loc) · 71.8 KB
/
vtkDICOMParser.cxx
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
/*=========================================================================
Program: DICOM for VTK
Copyright (c) 2012-2024 David Gobbi
All rights reserved.
See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDICOMParser.h"
#include "vtkDICOMDictionary.h"
#include "vtkDICOMFile.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMSequence.h"
#include "vtkDICOMItem.h"
#include "vtkObjectFactory.h"
#include "vtkUnsignedShortArray.h"
#include "vtkErrorCode.h"
#include <ctype.h>
#include <assert.h>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
vtkStandardNewMacro(vtkDICOMParser);
vtkCxxSetObjectMacro(vtkDICOMParser, MetaData, vtkDICOMMetaData);
vtkCxxSetObjectMacro(vtkDICOMParser, Query, vtkDICOMMetaData);
vtkCxxSetObjectMacro(vtkDICOMParser, Groups, vtkUnsignedShortArray);
/*----------------------------------------------------------------------------
The top section of this file defines "Decoder" classes that parse the
DICOM tags and decode the values. The decoder class hierarchy is as
follows:
DecoderBase (the base class)
Decoder<LE> (template specialization for little-endian decoding)
DefaultDecoder (decoder for implicit little-endian syntax)
LittleEndianDecoder (decoder for explicit little-endian syntax)
Decoder<GE> (template specialization for big-endian decoding)
BigEndianDecoder (decoder for explicit big-endian syntax)
The vtkDICOMParser utilizes the DefaultDecoder, LittleEndianDecoder,
or the BigEndianDecoder depending on the transfer syntax.
----------------------------------------------------------------------------*/
class vtkDICOMParserInternalFriendship
{
public:
static bool FillBuffer(vtkDICOMParser *parser,
const unsigned char* &cp, const unsigned char* &ep)
{
return parser->FillBuffer(cp, ep);
}
static bool SeekBuffer(vtkDICOMParser *parser,
const unsigned char* &cp, const unsigned char* &ep,
vtkTypeInt64 offset)
{
return parser->SeekBuffer(cp, ep, offset);
}
static vtkTypeInt64 GetBytesRemaining(vtkDICOMParser *parser,
const unsigned char *cp, const unsigned char *ep)
{
return parser->GetBytesRemaining(cp, ep);
}
static vtkTypeInt64 GetBytesProcessed(vtkDICOMParser *parser,
const unsigned char *cp, const unsigned char *ep)
{
return parser->GetBytesProcessed(cp, ep);
}
static void ParseError(vtkDICOMParser *parser,
const unsigned char *cp, const unsigned char *ep, const char *message)
{
return parser->ParseError(cp, ep, message);
}
};
namespace {
// Useful constants to replace commonly-used literals.
const unsigned short HxFFFE = 0xFFFE; // sequence group
const unsigned short HxE000 = 0xE000; // item start
const unsigned short HxE00D = 0xE00D; // item end
const unsigned short HxE0DD = 0xE0DD; // sequence end
const unsigned int HxFFFFFFFF = 0xFFFFFFFF; // unknown length
// The decoder has two specializations: little-endian, big-endian.
const int LE = 0;
const int BE = 1;
// The decoder types that are available.
class DefaultDecoder;
class LittleEndianDecoder;
class BigEndianDecoder;
//----------------------------------------------------------------------------
// Class that caches info about the current sequence item
class DecoderContext
{
public:
// Construct the base info from the meta data.
DecoderContext(vtkDICOMMetaData *meta, int index,
vtkDICOMCharacterSet dcs, bool ocs) :
Prev(nullptr), Item(nullptr), MetaData(meta), Index(index),
CurrentTag(0,0), DefaultCharacterSet(dcs),
CharacterSet(ocs ? dcs :
vtkDICOMCharacterSet(vtkDICOMCharacterSet::Unknown)),
VRForXS(vtkDICOMVR::XX) {}
// Construct from the current item.
DecoderContext(vtkDICOMItem *item, vtkDICOMCharacterSet dcs, bool ocs) :
Prev(nullptr), Item(item), MetaData(nullptr), Index(0),
CurrentTag(0,0), DefaultCharacterSet(dcs),
CharacterSet(ocs ? dcs :
vtkDICOMCharacterSet(vtkDICOMCharacterSet::Unknown)),
VRForXS(vtkDICOMVR::XX) {}
// Find an element within the current context. This is used
// by FindDictVR() to disambiguate VRs that could be either US
// or SS, or that could be either OB or OW.
const vtkDICOMValue& Get(vtkDICOMTag tag);
// Get the dictionary VR (for implicit VR elements).
// If the tag is not found, UN (unknown) will be returned.
vtkDICOMVR FindDictVR(vtkDICOMTag tag);
// Get the character set that is currently active.
vtkDICOMCharacterSet GetCharacterSet();
// Get the VR to use for XS by checking PixelRepresentation.
vtkDICOMVR GetVRForXS();
// Set the previous context.
void SetPrev(DecoderContext *context) { this->Prev = context; }
DecoderContext *GetPrev() { return this->Prev; }
// Get the current item.
vtkDICOMItem *GetItem() { return this->Item; }
int GetIndex() { return this->Index; }
// Set the current tag position for the context.
void SetCurrentTag(vtkDICOMTag tag) { this->CurrentTag = tag; }
vtkDICOMTag GetCurrentTag() { return this->CurrentTag; }
private:
DecoderContext *Prev;
vtkDICOMItem *Item;
vtkDICOMMetaData *MetaData;
int Index;
vtkDICOMTag CurrentTag;
vtkDICOMCharacterSet DefaultCharacterSet;
vtkDICOMCharacterSet CharacterSet;
vtkDICOMVR VRForXS;
};
//----------------------------------------------------------------------------
const vtkDICOMValue& DecoderContext::Get(vtkDICOMTag tag)
{
if (this->Item)
{
return this->Item->Get(tag);
}
else
{
int idx = (this->Index == -1 ? 0 : this->Index);
return this->MetaData->Get(idx, tag);
}
}
//----------------------------------------------------------------------------
vtkDICOMCharacterSet DecoderContext::GetCharacterSet()
{
vtkDICOMCharacterSet cs = this->CharacterSet;
if (cs == vtkDICOMCharacterSet::Unknown)
{
const vtkDICOMValue& v = this->Get(DC::SpecificCharacterSet);
if (v.IsValid())
{
cs = vtkDICOMCharacterSet(v.GetCharData(), v.GetVL());
}
else if (this->Prev)
{
cs = this->Prev->GetCharacterSet();
}
else
{
cs = this->DefaultCharacterSet;
}
if (this->CurrentTag > DC::SpecificCharacterSet)
{
this->CharacterSet = cs;
}
}
return cs;
}
//----------------------------------------------------------------------------
vtkDICOMVR DecoderContext::GetVRForXS()
{
vtkDICOMVR vr = this->VRForXS;
if (vr == vtkDICOMVR::XX)
{
const vtkDICOMValue& v = this->Get(DC::PixelRepresentation);
if (v.IsValid())
{
vr = (v.AsUnsignedShort() == 0 ? vtkDICOMVR::US : vtkDICOMVR::SS);
}
else if (this->Prev)
{
vr = this->Prev->GetVRForXS();
}
else
{
vr = vtkDICOMVR::US;
}
if (this->CurrentTag > DC::PixelRepresentation)
{
this->VRForXS = vr;
}
}
return vr;
}
//----------------------------------------------------------------------------
vtkDICOMVR DecoderContext::FindDictVR(vtkDICOMTag tag)
{
vtkDICOMVR vr = vtkDICOMVR::UN;
if (tag.GetElement() == 0x0000)
{
// this is a group length element, which has VR of "UL"
vr = vtkDICOMVR::UL;
}
else if ((tag.GetGroup() & 0x1) != 0 &&
tag.GetElement() >= 0x0010 && tag.GetElement() < 0x0100)
{
// this is a private creator tag
vr = vtkDICOMVR::LO;
}
else
{
vtkDICOMDictEntry de;
if ((tag.GetGroup() & 0x1) == 0)
{
de = vtkDICOMDictionary::FindDictEntry(tag);
}
else if (this->Item)
{
de = this->Item->FindDictEntry(tag);
}
else if (this->MetaData)
{
de = this->MetaData->FindDictEntry(tag);
}
if (de.IsValid())
{
vr = de.GetVR();
if (vr == vtkDICOMVR::XS)
{
// disambiguate tags that may be either "US" or "SS"
this->CurrentTag = tag;
vr = this->GetVRForXS();
}
else if (vr == vtkDICOMVR::OX)
{
// disambiguate tags that may be either "OB" or "OW"
vr = vtkDICOMVR::OW;
vtkDICOMTag reftag = (tag.GetGroup() == 0x5400 ?
DC::WaveformBitsAllocated :
DC::BitsAllocated);
const vtkDICOMValue& v = this->Get(reftag);
if (v.IsValid() && v.AsUnsignedShort() <= 8)
{
vr = vtkDICOMVR::OB;
}
}
}
}
return vr;
}
//----------------------------------------------------------------------------
// The base class for the decoder classes.
class DecoderBase
{
public:
// Virtual destructor for completeness.
virtual ~DecoderBase() {}
// Whether to use implicit VRs (default: explicit VRs).
void SetImplicitVR(bool i) { this->ImplicitVR = i; }
// Set the current item context.
void PushContext(DecoderContext *context, vtkDICOMTag tag);
// Pop the current item context.
void PopContext();
// The query with which to filter the data.
void SetQuery(
const vtkDICOMDataElementIterator& iter,
const vtkDICOMDataElementIterator& iterEnd);
// Read l bytes of data, or until delimiter tag found.
// Set l to 0xffffffff to ignore length completely.
// If the delimiter is of the form (0xgggg,0x0000), ie. if the
// "element" part is zero, then the reading will stop before
// the first element that is not in the specified group.
virtual bool ReadElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter) = 0;
// Skip l bytes of data, or until delimiter tag found.
// Set l to 0xffffffff to ignore length completely.
// If the delimiter is of the form (0xgggg,0x0000), ie. if the
// "element" part is zero, then the skip will stop before
// the first element that is not in the specified group.
virtual bool SkipElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter) = 0;
// Peek ahead to see what the next element is.
virtual vtkDICOMTag Peek(
const unsigned char* &cp, const unsigned char* &ep) = 0;
// Copy bytes from sp to end marker cp into the value "v".
// If the parameter "v" is NULL, then it will be ignored.
void CopyBuffer(
vtkDICOMValue *v, const unsigned char *sp, const unsigned char *cp);
// If there are fewer than "n" bytes left in the buffer, then move
// any data that hasn't yet been parsed to the start of the buffer,
// and then read new data into the remainder of the buffer.
// A return value of "false" indicates that the check failed
// because the needed bytes could not be read from the file, either
// due to an IO error or the end of the file. If "false" is
// returned, "cp" will be advanced to the position of "ep".
bool CheckBuffer(
const unsigned char* &cp, const unsigned char* &ep, size_t n);
// This overload of CheckBuffer is used within SkipElements to
// automatically copy the skipped bytes into the value "v".
// If the parameter "v" is NULL, then it will be ignored.
bool CheckBuffer(
const unsigned char* &cp, const unsigned char* &ep, size_t n,
vtkDICOMValue *v, const unsigned char* &sp);
// Get the current byte offset from the start of the file.
size_t GetByteOffset(
const unsigned char *cp, const unsigned char *ep);
// Get the last tag that was read.
vtkDICOMTag GetLastTag() { return this->LastTag; }
// Get the VR of the last data element (invalid if implicit)
vtkDICOMVR GetLastVR() { return this->LastVR; }
// Get the VL of the last data element.
unsigned int GetLastVL() { return this->LastVL; }
// Check for attributes missing from this instance, that were present
// for instances in the series that were already parsed.
void HandleMissingAttributes(vtkDICOMTag tag);
// Advance the query iterator (this->Query) to the given tag,
// and set this->QueryMatched to false if any unmatched query keys
// were found, unless the keys support universal matching (i.e. the
// key has no value), or unless the keys are private
void AdvanceQueryIterator(vtkDICOMTag tag);
// Returns true if the query contains the given tag.
bool QueryContains(vtkDICOMTag tag);
// Returns true if the value matches the query.
bool QueryMatches(const vtkDICOMValue& v);
// Returns true if all queries have matched so far.
bool GetQueryMatched() { return this->QueryMatched; }
// Check whether the query is finished.
bool GetQueryFinished() { return this->Query == this->QueryEnd; }
// Finish the query (check for unused keys that must match).
bool FinishQuery();
// Report an error.
void ParseError(
const unsigned char *cp, const unsigned char *ep, const char *message);
protected:
// Constructor that initializes all of the members.
DecoderBase(vtkDICOMParser *parser, vtkDICOMMetaData *data, int idx) :
Parser(parser), BaseContext(data,idx,parser->GetDefaultCharacterSet(),
parser->GetOverrideCharacterSet()),
Item(nullptr), MetaData(data), Index(idx), ImplicitVR(false),
HasQuery(false), QueryMatched(false),
LastVL(0) { this->Context = &this->BaseContext; }
// an internal implicit little-endian decoder
DefaultDecoder *ImplicitLE;
// the vtkDICOMParser::FillBuffer method is used to refill the buffer
vtkDICOMParser *Parser;
// the current context (info about the current item being parsed)
DecoderContext *Context;
// the base context.
DecoderContext BaseContext;
// the sequence item to read the data into while parsing a sequence
vtkDICOMItem *Item;
// the metadata object to read the data into
vtkDICOMMetaData *MetaData;
// the instance index to use with the meta data
int Index;
// if this is set, then VRs are implicit
bool ImplicitVR;
// the query to apply while reading the data
bool HasQuery;
bool QueryMatched;
vtkDICOMDataElementIterator Query;
vtkDICOMDataElementIterator QueryEnd;
vtkDICOMDataElementIterator QuerySave;
// this is set to the last tag that was read.
vtkDICOMTag LastTag;
vtkDICOMVR LastVR;
unsigned int LastVL;
// this is set to the last tag written to this->MetaData
vtkDICOMTag LastWrittenTag;
};
//----------------------------------------------------------------------------
template<int E>
class Decoder : public DecoderBase
{
public:
// Decode two, four, or eight bytes as unsigned integers.
static unsigned short GetInt16(const unsigned char* ip);
static unsigned int GetInt32(const unsigned char* ip);
static unsigned long long GetInt64(const unsigned char* ip);
// Read from "ip" and write "n" decoded values into "v".
static void GetValues(const unsigned char *ip, char *v, size_t n);
static void GetValues(const unsigned char *ip, unsigned char *v, size_t n);
static void GetValues(const unsigned char *ip, short *v, size_t n);
static void GetValues(const unsigned char *ip, unsigned short *v, size_t n);
static void GetValues(const unsigned char *ip, int *v, size_t n);
static void GetValues(const unsigned char *ip, unsigned int *v, size_t n);
static void GetValues(const unsigned char *ip, long long *v, size_t n);
static void GetValues(
const unsigned char *ip, unsigned long long *v, size_t n);
static void GetValues(const unsigned char *ip, float *v, size_t n);
static void GetValues(const unsigned char *ip, double *v, size_t n);
static void GetValues(const unsigned char *ip, vtkDICOMTag *v, size_t n);
// Read "n" values from the buffer into the provided pointer.
// The number of bytes that were read from the buffer will be returned.
// The buffer will be refilled as necessary.
template<class T>
size_t ReadData(
const unsigned char* &cp, const unsigned char* &ep, T *ptr, size_t n);
// Skip forward by "n" bytes. The number of bytes skipped will be
// returned. If the end of the file is reached before the operation,
// is complete, then the return value will be less than "n".
size_t SkipData(
const unsigned char* &cp, const unsigned char* &ep, size_t n);
// Read l bytes of data, or until delimiter tag found.
// Set l to 0xffffffff to ignore length completely.
// If the delimiter is of the form (0xgggg,0x0000), ie. if the
// "element" part is zero, then the reading will stop before
// the first element that is not in the specified group.
bool ReadElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter) VTK_DICOM_OVERRIDE
{
size_t bytesRead;
return ReadElements(cp, ep, l, delimiter, bytesRead);
}
// Skip l bytes of data, or until delimiter tag found.
// Set l to 0xffffffff to ignore length completely.
// If the delimiter is of the form (0xgggg,0x0000), ie. if the
// "element" part is zero, then the skip will stop before
// the first element that is not in the specified group.
bool SkipElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter) VTK_DICOM_OVERRIDE
{
return SkipElements(cp, ep, l, delimiter, nullptr);
}
// A ReadElements that returns the number of bytes read.
bool ReadElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter, size_t &bytesRead);
// Query the elements of one item within a sequence.
bool QueryOneItem(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter, size_t &bytesRead);
// A SkipElements that copies skipped bytes into value "v".
// This method is used when parsing encapsulated data, it simply
// reads the encapsulated data into the value as raw bytes.
// If the parameter "v" is NULL, then it will be ignored.
bool SkipElements(
const unsigned char* &cp, const unsigned char* &ep,
unsigned int l, vtkDICOMTag delimiter, vtkDICOMValue *v);
// Read the vr and vl and return the number of bytes read
// (will return zero if an error occurred)
size_t ReadElementHead(
const unsigned char* &cp, const unsigned char* &ep,
vtkDICOMTag tag, vtkDICOMVR &vr, unsigned int &vl);
// Read a value, given the vr and vl, where vl can be 0xffffffff
// for SQ, UN, or OB to indicate tag-delimited data.
// The number of bytes that were read will be returned.
size_t ReadElementValue(
const unsigned char* &cp, const unsigned char* &ep,
vtkDICOMVR vr, unsigned int vl, vtkDICOMValue &v);
// Peek ahead to see what the next element is.
vtkDICOMTag Peek(
const unsigned char* &cp, const unsigned char* &ep) VTK_DICOM_OVERRIDE
{
unsigned short g = 0;
unsigned short e = 0;
if (this->CheckBuffer(cp, ep, 4))
{
g = Decoder<E>::GetInt16(cp);
e = Decoder<E>::GetInt16(cp + 2);
}
return vtkDICOMTag(g, e);
}
protected:
Decoder(vtkDICOMParser *parser, vtkDICOMMetaData *data, int idx) :
DecoderBase(parser, data, idx) {}
private:
Decoder() {};
};
//----------------------------------------------------------------------------
// The little-endian implicit-vr decoder.
class DefaultDecoder : public Decoder<LE>
{
public:
DefaultDecoder(vtkDICOMParser *parser, vtkDICOMMetaData *data, int idx) :
Decoder<LE>(parser, data, idx)
{
this->ImplicitVR = true;
this->ImplicitLE = this;
}
};
// The little-endian explicit-vr decoder.
class LittleEndianDecoder : public Decoder<LE>
{
public:
LittleEndianDecoder(vtkDICOMParser *parser, vtkDICOMMetaData *data, int idx) :
Decoder<LE>(parser, data, idx), ExtraDecoder(parser, data, idx)
{
this->ImplicitLE = &this->ExtraDecoder;
}
private:
// an internal implicit little-endian decoder.
DefaultDecoder ExtraDecoder;
};
// The big-endian explicit-vr decoder.
class BigEndianDecoder : public Decoder<BE>
{
public:
BigEndianDecoder(vtkDICOMParser *parser, vtkDICOMMetaData *data, int idx) :
Decoder<BE>(parser, data, idx), ExtraDecoder(parser, data, idx)
{
this->ImplicitLE = &this->ExtraDecoder;
}
private:
// an internal implicit little-endian decoder.
DefaultDecoder ExtraDecoder;
};
//----------------------------------------------------------------------------
inline void DecoderBase::PushContext(DecoderContext *context, vtkDICOMTag tag)
{
// ensure that "Item" is set for the ImplicitLE decoder, too
this->Item = context->GetItem();
this->ImplicitLE->Item = context->GetItem();
// save the current position in the current context
this->Context->SetCurrentTag(tag);
// push the new context
context->SetPrev(this->Context);
this->Context = context;
}
//----------------------------------------------------------------------------
inline void DecoderBase::PopContext()
{
this->Context = this->Context->GetPrev();
this->Item = this->Context->GetItem();
this->ImplicitLE->Item = this->Context->GetItem();
}
//----------------------------------------------------------------------------
void DecoderBase::SetQuery(
const vtkDICOMDataElementIterator& iter,
const vtkDICOMDataElementIterator& iterEnd)
{
if (iter != iterEnd)
{
this->HasQuery = true;
this->QueryMatched = true;
this->Query = iter;
this->QueryEnd = iterEnd;
this->QuerySave = iter;
}
else
{
this->HasQuery = false;
this->QueryMatched = false;
}
}
//----------------------------------------------------------------------------
inline void DecoderBase::CopyBuffer(
vtkDICOMValue *v, const unsigned char *sp, const unsigned char *cp)
{
// append bytes from sp to cp into the supplied value "v"
if (v && cp != sp)
{
size_t m = cp - sp;
size_t n = v->GetNumberOfValues();
unsigned char *ptr = v->ReallocateUnsignedCharData(n + m) + n;
do { *ptr++ = *sp++; } while (--m);
}
}
//----------------------------------------------------------------------------
inline bool DecoderBase::CheckBuffer(
const unsigned char* &cp, const unsigned char* &ep, size_t n)
{
bool r = true;
if (n > static_cast<size_t>(ep - cp))
{
r = vtkDICOMParserInternalFriendship::FillBuffer(this->Parser, cp, ep);
if (r && n > static_cast<size_t>(ep - cp))
{
cp = ep;
r = false;
}
}
return r;
}
inline bool DecoderBase::CheckBuffer(
const unsigned char* &cp, const unsigned char* &ep, size_t n,
vtkDICOMValue *v, const unsigned char* &sp)
{
bool r = true;
if (n > static_cast<size_t>(ep - cp))
{
this->CopyBuffer(v, sp, cp);
r = vtkDICOMParserInternalFriendship::FillBuffer(this->Parser, cp, ep);
if (r && n > static_cast<size_t>(ep - cp))
{
cp = ep;
r = false;
}
sp = cp;
}
return r;
}
//----------------------------------------------------------------------------
inline size_t DecoderBase::GetByteOffset(
const unsigned char *cp, const unsigned char *ep)
{
return vtkDICOMParserInternalFriendship::GetBytesProcessed(
this->Parser, cp, ep);
}
//----------------------------------------------------------------------------
void DecoderBase::HandleMissingAttributes(vtkDICOMTag tag)
{
// insert null values for any attributes that were present for other
// instances in this series but not present for this instance
vtkDICOMDataElementIterator iter = this->MetaData->Find(tag);
--iter;
if (iter->GetTag() != this->LastWrittenTag &&
iter->GetTag().GetGroup() != 0x0002)
{
int count = 0;
do
{
count++;
--iter;
}
while (iter->GetTag() != this->LastWrittenTag &&
iter->GetTag().GetGroup() != 0x0002);
vtkDICOMTag *missing = new vtkDICOMTag[count];
for (int i = 0; i < count; i++)
{
missing[i] = (++iter)->GetTag();
}
for (int i = 0; i < count; i++)
{
this->MetaData->Set(this->Index, missing[i], vtkDICOMValue());
}
delete [] missing;
}
this->LastWrittenTag = tag;
}
//----------------------------------------------------------------------------
void DecoderBase::AdvanceQueryIterator(vtkDICOMTag tag)
{
// advance the query iterator to the given tag
while (this->Query != this->QueryEnd && this->Query->GetTag() < tag)
{
// for query keys that weren't in the data set, only match if:
// 1) the key is SpecificCharacterSet (not used for matching), or
// 2) the key is a group length element (gggg,0000)
// 3) the key is a private creator tag, or
// 4) the key supports universal matching, i.e. will even match null
vtkDICOMTag qtag = this->Query->GetTag();
if (qtag != DC::SpecificCharacterSet && qtag.GetElement() != 0 &&
((qtag.GetGroup() & 1) == 0 || qtag.GetElement() > 0x00ff))
{
vtkDICOMValue nullValue;
bool matched = nullValue.Matches(this->Query->GetValue());
// if query tag is private, need additional checks
if (!matched && (qtag.GetGroup() & 1) != 0)
{
// compute creator tag, and search for it
vtkDICOMTag ctag =
vtkDICOMTag(qtag.GetGroup(), qtag.GetElement() >> 8);
vtkDICOMDataElementIterator iter = this->QuerySave;
while (iter != this->QueryEnd && iter->GetTag() < ctag)
{
++iter;
}
if (iter != this->QueryEnd && iter->GetTag() == ctag)
{
// if we already read the element, we already checked whether it
// but if we didn't read it, then it doesn't exist, so don't match
if (this->Item)
{
vtkDICOMTag ptag = this->Item->ResolvePrivateTag(
qtag, iter->GetValue().AsString());
matched = (ptag != vtkDICOMTag(0xffff,0xffff) &&
this->Item->Get(ptag).IsValid());
}
else if (this->Index < 0)
{
vtkDICOMTag ptag = this->MetaData->ResolvePrivateTag(
qtag, iter->GetValue().AsString());
matched = (ptag != vtkDICOMTag(0xffff,0xffff) &&
this->MetaData->Has(ptag));
}
else
{
vtkDICOMTag ptag = this->MetaData->ResolvePrivateTag(
this->Index, qtag, iter->GetValue().AsString());
matched = (ptag != vtkDICOMTag(0xffff,0xffff) &&
this->MetaData->Get(this->Index, ptag).IsValid());
}
}
else
{
// query has a private tag with no creator!
if (this->Item)
{
matched = this->Item->Get(qtag).Matches(
this->Query->GetValue());
}
else
{
matched = this->MetaData->Get(qtag).Matches(
this->Query->GetValue());
}
}
}
this->QueryMatched &= matched;
}
++this->Query;
}
}
//----------------------------------------------------------------------------
bool DecoderBase::QueryContains(vtkDICOMTag tag)
{
// if the tag isn't private
if ((tag.GetGroup() & 1) == 0)
{
// advance the query iterator until the tag is found in the query
this->AdvanceQueryIterator(tag);
// return true if the tag exists in the query
return (this->Query != this->QueryEnd && this->Query->GetTag() == tag);
}
// the remainder of this function handles private tags
unsigned short g = tag.GetGroup();
unsigned short e = tag.GetElement();
// first, make sure this private group is present in the query,
// and ignore any elements before (gggg,0010)
vtkDICOMTag gtag = vtkDICOMTag(g, 0x0010);
this->AdvanceQueryIterator(gtag);
// save the query iterator
if (this->QuerySave->GetTag() < gtag)
{
this->QuerySave = this->Query;
}
// if query doesn't contain any more keys in this group, return
vtkDICOMDataElementIterator iter = this->Query;
if (iter == this->QueryEnd || iter->GetTag().GetGroup() != g)
{
return false;
}
// if this is a creator element (e is 0x00XX), return true
if (e >= 0x0010 && e <= 0x00FF)
{
return true;
}
// search for the creator element within the query
vtkDICOMTag ctag = vtkDICOMTag(g, e >> 8);
vtkDICOMValue creator = this->Context->Get(ctag);
if (creator.IsValid())
{
// maximum possible creator element is (gggg,00FF)
gtag = vtkDICOMTag(g, 0x00FF);
while (iter != this->QueryEnd && iter->GetTag() <= gtag)
{
if (iter->GetValue().Matches(creator))
{
tag = vtkDICOMTag(
g, (iter->GetTag().GetElement() << 8) | (e & 0x00FF));
break;
}
++iter;
}
// if creator not found in query, tag obviously won't be found
if (iter == this->QueryEnd || iter->GetTag() > gtag)
{
return false;
}
}
// finally, look for the private tag at its resolved location
while (iter != this->QueryEnd && iter->GetTag() < tag)
{
++iter;
}
if (iter != this->QueryEnd && iter->GetTag() == tag)
{
this->Query = iter;
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool DecoderBase::QueryMatches(const vtkDICOMValue& v)
{
bool matched = true;
vtkDICOMTag tag = this->Query->GetTag();
if (v.GetVR() != vtkDICOMVR::SQ)
{
// a query match is always true for SpecificCharacterSet, because this
// element exists to describe the character encoding of the query, not
// because it is to be matched.
if (tag != DC::SpecificCharacterSet && tag.GetElement() != 0 &&
((tag.GetGroup() & 1) == 0 || tag.GetElement() > 0x00ff))
{
// if above conditions don't apply, check if the query key matches
matched = v.Matches(this->Query->GetValue());
}
}
else
{
// if VR is SQ, then the matching was done when the sequence items were
// parsed, and we just have to return the current value of QueryMatched
matched = this->QueryMatched;
}
if ((tag.GetGroup() & 1) == 0)
{
// advance the query iterator
++this->Query;
}
else
{
// if private, restore to the start of the private group
this->Query = this->QuerySave;
}
return matched;
}
//----------------------------------------------------------------------------
bool DecoderBase::FinishQuery()
{
if (this->HasQuery)
{
this->AdvanceQueryIterator(vtkDICOMTag(0xffff,0xffff));
}
return this->QueryMatched;
}
//----------------------------------------------------------------------------
void DecoderBase::ParseError(
const unsigned char *cp, const unsigned char *ep, const char *message)
{
vtkDICOMTag tag = this->LastTag;
const char *name = "Element";
vtkDICOMDictEntry de = vtkDICOMDictionary::FindDictEntry(tag);
if (de.IsValid())
{
name = de.GetName();
}
std::stringstream msg;
msg << "In " << name << " " << tag;
int idx = this->Context->GetIndex();
for (DecoderContext *context = this->Context->GetPrev();
context; context = context->GetPrev())
{
tag = context->GetCurrentTag();
name = "Sequence";
de = vtkDICOMDictionary::FindDictEntry(tag);
if (de.IsValid())
{
name = de.GetName();
}
msg << ", in " << name << " " << tag;
if (idx >= 0)
{
msg << " [Item " << (idx + 1) << "]";
}
idx = context->GetIndex();
}
msg << ": " << message;
vtkDICOMParserInternalFriendship::ParseError(
this->Parser, cp, ep, msg.str().c_str());
}
//----------------------------------------------------------------------------
template<>
inline unsigned short Decoder<LE>::GetInt16(const unsigned char *ip)
{
return ip[0] + (ip[1] << 8);
}
template<>
inline unsigned int Decoder<LE>::GetInt32(const unsigned char *ip)
{
return ip[0] + (ip[1] << 8) + ((ip[2] + (ip[3] << 8)) << 16);
}
template<>
inline unsigned long long Decoder<LE>::GetInt64(const unsigned char *ip)
{
unsigned int a = ip[0] + (ip[1] << 8) + ((ip[2] + (ip[3] << 8)) << 16);
unsigned int b = ip[4] + (ip[5] << 8) + ((ip[6] + (ip[7] << 8)) << 16);
return (static_cast<unsigned long long>(b) << 32) + a;