9 #include <netinet/in.h>
11 #include <cctype> // for isalpha
14 #include "gdcmHeader.h"
16 #include <iddcmjpeg.h>
18 // Refer to gdcmHeader::CheckSwap()
19 #define HEADER_LENGTH_TO_READ 256
20 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
21 #define _MaxSizeLoadElementValue_ 1024
23 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
25 void gdcmHeader::Initialise(void) {
26 if (!gdcmHeader::dicom_vr)
28 Dicts = new gdcmDictSet();
29 RefPubDict = Dicts->GetDefaultPubDict();
30 RefShaDict = (gdcmDict*)0;
33 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error)
34 throw(gdcmFileError) {
35 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
36 filename = InFilename;
38 fp=fopen(InFilename,"rb");
39 if(exception_on_error) {
41 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
44 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
47 AddAndDefaultElements();
51 gdcmHeader::~gdcmHeader (void) {
52 //FIXME obviously there is much to be done here !
57 void gdcmHeader::InitVRDict (void) {
59 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
63 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
64 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
65 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
66 (*vr)["CS"] = "Code String"; // At most 16 bytes
67 (*vr)["DA"] = "Date"; // Exactly 8 bytes
68 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
69 (*vr)["DT"] = "Date Time"; // At most 26 bytes
70 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
71 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
72 (*vr)["IS"] = "Integer String"; // At most 12 bytes
73 (*vr)["LO"] = "Long String"; // At most 64 chars
74 (*vr)["LT"] = "Long Text"; // At most 10240 chars
75 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
76 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
77 (*vr)["PN"] = "Person Name"; // At most 64 chars
78 (*vr)["SH"] = "Short String"; // At most 16 chars
79 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
80 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
81 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
82 (*vr)["ST"] = "Short Text"; // At most 1024 chars
83 (*vr)["TM"] = "Time"; // At most 16 bytes
84 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
85 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
86 (*vr)["UN"] = "Unknown"; // Any length of bytes
87 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
88 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
94 * \brief Discover what the swap code is (among little endian, big endian,
95 * bad little endian, bad big endian).
98 void gdcmHeader::CheckSwap()
100 // The only guaranted way of finding the swap code is to find a
101 // group tag since we know it's length has to be of four bytes i.e.
102 // 0x00000004. Finding the swap code in then straigthforward. Trouble
103 // occurs when we can't find such group...
105 guint32 x=4; // x : pour ntohs
106 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
110 char deb[HEADER_LENGTH_TO_READ];
112 // First, compare HostByteOrder and NetworkByteOrder in order to
113 // determine if we shall need to swap bytes (i.e. the Endian type).
119 // The easiest case is the one of a DICOM header, since it possesses a
120 // file preamble where it suffice to look for the string "DICM".
121 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
124 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
125 filetype = TrueDicom;
126 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
129 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
132 if(filetype == TrueDicom) {
133 // Next, determine the value representation (VR). Let's skip to the
134 // first element (0002, 0000) and check there if we find "UL"
135 // - or "OB" if the 1st one is (0002,0001) -,
136 // in which case we (almost) know it is explicit VR.
137 // WARNING: if it happens to be implicit VR then what we will read
138 // is the length of the group. If this ascii representation of this
139 // length happens to be "UL" then we shall believe it is explicit VR.
140 // FIXME: in order to fix the above warning, we could read the next
141 // element value (or a couple of elements values) in order to make
142 // sure we are not commiting a big mistake.
144 // * the 128 bytes of File Preamble (often padded with zeroes),
145 // * the 4 bytes of "DICM" string,
146 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
147 // i.e. a total of 136 bytes.
149 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
150 (memcmp(entCur, "OB", (size_t)2) == 0) )
152 filetype = ExplicitVR;
153 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
154 "explicit Value Representation");
156 filetype = ImplicitVR;
157 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
158 "not an explicit Value Representation");
163 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
164 "HostByteOrder != NetworkByteOrder");
167 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
168 "HostByteOrder = NetworkByteOrder");
171 // Position the file position indicator at first tag (i.e.
172 // after the file preamble and the "DICM" string).
174 fseek (fp, 132L, SEEK_SET);
176 } // End of TrueDicom
178 // Alas, this is not a DicomV3 file and whatever happens there is no file
179 // preamble. We can reset the file position indicator to where the data
180 // is (i.e. the beginning of the file).
183 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
184 // By clean we mean that the length of the first tag is written down.
185 // If this is the case and since the length of the first group HAS to be
186 // four (bytes), then determining the proper swap code is straightforward.
189 // We assume the array of char we are considering contains the binary
190 // representation of a 32 bits integer. Hence the following dirty
192 s = *((guint32 *)(entCur));
212 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
213 "ACR/NEMA unfound swap info (time to raise bets)");
216 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
217 // It is time for despaired wild guesses. So, let's assume this file
218 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
219 // not present. Then the only info we have is the net2host one.
227 void gdcmHeader::SwitchSwapToBigEndian(void) {
228 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
229 "Switching to BigEndian mode.");
246 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
248 pixelsOffset = GetPixelOffset();
249 fseek(fp, pixelsOffset, SEEK_SET);
250 if (IsJPEGLossless()) {
251 _Pixels=_IdDcmJpegRead(fp);
253 fread(_Pixels, 1, lgrTotale, fp);
260 * \ingroup gdcmHeader
261 * \brief Find the value representation of the current tag.
263 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
264 if (filetype != ExplicitVR)
270 long PositionOnEntry = ftell(fp);
271 // Warning: we believe this is explicit VR (Value Representation) because
272 // we used a heuristic that found "UL" in the first tag. Alas this
273 // doesn't guarantee that all the tags will be in explicit VR. In some
274 // cases (see e-film filtered files) one finds implicit VR tags mixed
275 // within an explicit VR file. Hence we make sure the present tag
276 // is in explicit VR and try to fix things if it happens not to be
278 bool RealExplicit = true;
280 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
284 // Assume we are reading a falsely explicit VR file i.e. we reached
285 // a tag where we expect reading a VR but are in fact we read the
286 // first to bytes of the length. Then we will interogate (through find)
287 // the dicom_vr dictionary with oddities like "\004\0" which crashes
288 // both GCC and VC++ implementations of the STL map. Hence when the
289 // expected VR read happens to be non-ascii characters we consider
290 // we hit falsely explicit VR tag.
292 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
293 RealExplicit = false;
295 // CLEANME searching the dicom_vr at each occurence is expensive.
296 // PostPone this test in an optional integrity check at the end
297 // of parsing or only in debug mode.
298 if ( RealExplicit && !dicom_vr->count(vr) )
301 if ( RealExplicit ) {
302 if ( ElVal->IsVrUnknown() ) {
303 // When not a dictionary entry, we can safely overwrite the vr.
307 if ( ElVal->GetVR() == vr ) {
308 // The vr we just read and the dictionary agree. Nothing to do.
311 // The vr present in the file and the dictionary disagree. We assume
312 // the file writer knew best and use the vr of the file. Since it would
313 // be unwise to overwrite the vr of a dictionary (since it would
314 // compromise it's next user), we need to clone the actual DictEntry
315 // and change the vr for the read one.
316 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
321 ElVal->SetDictEntry(NewTag);
325 // We thought this was explicit VR, but we end up with an
326 // implicit VR tag. Let's backtrack.
327 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
328 fseek(fp, PositionOnEntry, SEEK_SET);
329 // When this element is known in the dictionary we shall use, e.g. for
330 // the semantics (see the usage of IsAnInteger), the vr proposed by the
331 // dictionary entry. Still we have to flag the element as implicit since
332 // we know now our assumption on expliciteness is not furfilled.
334 if ( ElVal->IsVrUnknown() )
335 ElVal->SetVR("Implicit");
336 ElVal->SetImplicitVr();
340 * \ingroup gdcmHeader
341 * \brief Determines if the Transfer Syntax was allready encountered
342 * and if it corresponds to a ImplicitVRLittleEndian one.
344 * @return True when ImplicitVRLittleEndian found. False in all other cases.
346 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
347 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
350 LoadElementValueSafe(Element);
351 string Transfer = Element->GetValue();
352 if ( Transfer == "1.2.840.10008.1.2" )
358 * \ingroup gdcmHeader
359 * \brief Determines if the Transfer Syntax was allready encountered
360 * and if it corresponds to a ExplicitVRLittleEndian one.
362 * @return True when ExplicitVRLittleEndian found. False in all other cases.
364 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
365 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
368 LoadElementValueSafe(Element);
369 string Transfer = Element->GetValue();
370 if ( Transfer == "1.2.840.10008.1.2.1" )
376 * \ingroup gdcmHeader
377 * \brief Determines if the Transfer Syntax was allready encountered
378 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
380 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
382 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
383 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
386 LoadElementValueSafe(Element);
387 string Transfer = Element->GetValue();
388 if ( Transfer == "1.2.840.10008.1.2.1.99" )
394 * \ingroup gdcmHeader
395 * \brief Determines if the Transfer Syntax was allready encountered
396 * and if it corresponds to a Explicit VR Big Endian one.
398 * @return True when big endian found. False in all other cases.
400 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
401 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
404 LoadElementValueSafe(Element);
405 string Transfer = Element->GetValue();
406 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
412 * \ingroup gdcmHeader
413 * \brief Determines if the Transfer Syntax was allready encountered
414 * and if it corresponds to a JPEGBaseLineProcess1 one.
416 * @return True when JPEGBaseLineProcess1found. False in all other cases.
418 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
419 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
422 LoadElementValueSafe(Element);
423 string Transfer = Element->GetValue();
424 if ( Transfer == "1.2.840.10008.1.2.4.50" )
429 // faire qq chose d'intelligent a la place de ça
431 bool gdcmHeader::IsJPEGLossless(void) {
432 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
435 LoadElementValueSafe(Element);
436 const char * Transfert = Element->GetValue().c_str();
437 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
438 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
444 * \ingroup gdcmHeader
445 * \brief Determines if the Transfer Syntax was allready encountered
446 * and if it corresponds to a JPEGExtendedProcess2-4 one.
448 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
450 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
451 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
454 LoadElementValueSafe(Element);
455 string Transfer = Element->GetValue();
456 if ( Transfer == "1.2.840.10008.1.2.4.51" )
462 * \ingroup gdcmHeader
463 * \brief Determines if the Transfer Syntax was allready encountered
464 * and if it corresponds to a JPEGExtendeProcess3-5 one.
466 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
468 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
469 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
472 LoadElementValueSafe(Element);
473 string Transfer = Element->GetValue();
474 if ( Transfer == "1.2.840.10008.1.2.4.52" )
480 * \ingroup gdcmHeader
481 * \brief Determines if the Transfer Syntax was allready encountered
482 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
484 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
487 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
488 gdcmElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
491 LoadElementValueSafe(Element);
492 string Transfer = Element->GetValue();
493 if ( Transfer == "1.2.840.10008.1.2.4.53" )
499 * \ingroup gdcmHeader
500 * \brief When the length of an element value is obviously wrong (because
501 * the parser went Jabberwocky) one can hope improving things by
502 * applying this heuristic.
504 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
505 if ( FoundLength == 0xffffffff)
507 ElVal->SetLength(FoundLength);
510 guint32 gdcmHeader::FindLengthOB(void) {
511 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
514 long PositionOnEntry = ftell(fp);
515 bool FoundSequenceDelimiter = false;
516 guint32 TotalLength = 0;
519 while ( ! FoundSequenceDelimiter) {
524 TotalLength += 4; // We even have to decount the group and element
526 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
527 "wrong group for an item sequence.");
532 FoundSequenceDelimiter = true;
533 else if ( n != 0xe000) {
534 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
535 "wrong element for an item sequence.");
539 ItemLength = ReadInt32();
540 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
541 // the ItemLength with ReadInt32
542 SkipBytes(ItemLength);
544 fseek(fp, PositionOnEntry, SEEK_SET);
548 void gdcmHeader::FindLength(gdcmElValue * ElVal) {
549 guint16 element = ElVal->GetElement();
550 string vr = ElVal->GetVR();
553 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
555 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
556 // The following reserved two bytes (see PS 3.5-2001, section
557 // 7.1.2 Data element structure with explicit vr p27) must be
558 // skipped before proceeding on reading the length on 4 bytes.
559 fseek(fp, 2L, SEEK_CUR);
560 guint32 length32 = ReadInt32();
561 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
562 ElVal->SetLength(FindLengthOB());
565 FixFoundLength(ElVal, length32);
569 // Length is encoded on 2 bytes.
570 length16 = ReadInt16();
572 // We can tell the current file is encoded in big endian (like
573 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
574 // and it's value is the one of the encoding of a big endian file.
575 // In order to deal with such big endian encoded files, we have
576 // (at least) two strategies:
577 // * when we load the "Transfer Syntax" tag with value of big endian
578 // encoding, we raise the proper flags. Then we wait for the end
579 // of the META group (0x0002) among which is "Transfer Syntax",
580 // before switching the swap code to big endian. We have to postpone
581 // the switching of the swap code since the META group is fully encoded
582 // in little endian, and big endian coding only starts at the next
583 // group. The corresponding code can be hard to analyse and adds
584 // many additional unnecessary tests for regular tags.
585 // * the second strategy consists in waiting for trouble, that shall
586 // appear when we find the first group with big endian encoding. This
587 // is easy to detect since the length of a "Group Length" tag (the
588 // ones with zero as element number) has to be of 4 (0x0004). When we
589 // encouter 1024 (0x0400) chances are the encoding changed and we
590 // found a group with big endian encoding.
591 // We shall use this second strategy. In order to make sure that we
592 // can interpret the presence of an apparently big endian encoded
593 // length of a "Group Length" without committing a big mistake, we
594 // add an additional check: we look in the allready parsed elements
595 // for the presence of a "Transfer Syntax" whose value has to be "big
596 // endian encoding". When this is the case, chances are we have got our
597 // hands on a big endian encoded file: we switch the swap code to
598 // big endian and proceed...
599 if ( (element == 0x000) && (length16 == 0x0400) ) {
600 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
601 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
606 SwitchSwapToBigEndian();
607 // Restore the unproperly loaded values i.e. the group, the element
608 // and the dictionary entry depending on them.
609 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
610 guint16 CorrectElem = SwapShort(ElVal->GetElement());
611 gdcmDictEntry * NewTag = GetDictEntryByKey(CorrectGroup, CorrectElem);
613 // This correct tag is not in the dictionary. Create a new one.
614 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
616 // FIXME this can create a memory leaks on the old entry that be
617 // left unreferenced.
618 ElVal->SetDictEntry(NewTag);
621 // Heuristic: well some files are really ill-formed.
622 if ( length16 == 0xffff) {
624 dbg.Verbose(0, "gdcmHeader::FindLength",
625 "Erroneous element length fixed.");
627 FixFoundLength(ElVal, (guint32)length16);
631 // Either implicit VR or a non DICOM conformal (see not below) explicit
632 // VR that ommited the VR of (at least) this element. Farts happen.
633 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
634 // on Data elements "Implicit and Explicit VR Data Elements shall
635 // not coexist in a Data Set and Data Sets nested within it".]
636 // Length is on 4 bytes.
637 FixFoundLength(ElVal, ReadInt32());
641 * \ingroup gdcmHeader
642 * \brief Swaps back the bytes of 4-byte long integer accordingly to
645 * @return The suggested integer.
647 guint32 gdcmHeader::SwapLong(guint32 a) {
648 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
653 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
654 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
658 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
662 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
665 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
672 * \ingroup gdcmHeader
673 * \brief Swaps the bytes so they agree with the processor order
674 * @return The properly swaped 16 bits integer.
676 guint16 gdcmHeader::SwapShort(guint16 a) {
677 if ( (sw==4321) || (sw==2143) )
678 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
682 void gdcmHeader::SkipBytes(guint32 NBytes) {
683 //FIXME don't dump the returned value
684 (void)fseek(fp, (long)NBytes, SEEK_CUR);
687 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
688 SkipBytes(ElVal->GetLength());
691 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
694 if ((guint32)NewSize >= (guint32)0xffffffff) {
695 MaxSizeLoadElementValue = 0xffffffff;
698 MaxSizeLoadElementValue = NewSize;
702 * \ingroup gdcmHeader
703 * \brief Loads the element content if it's length is not bigger
704 * than the value specified with
705 * gdcmHeader::SetMaxSizeLoadElementValue()
707 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
709 guint16 group = ElVal->GetGroup();
710 guint16 elem = ElVal->GetElement();
711 string vr = ElVal->GetVR();
712 guint32 length = ElVal->GetLength();
713 bool SkipLoad = false;
715 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
717 // Sequences not treated yet !
719 // Ne faudrait-il pas au contraire trouver immediatement
720 // une maniere 'propre' de traiter les sequences (vr = SQ)
721 // car commencer par les ignorer risque de conduire a qq chose
722 // qui pourrait ne pas etre generalisable
727 // Heuristic : a sequence "contains" a set of tags (called items). It looks
728 // like the last tag of a sequence (the one that terminates the sequence)
729 // has a group of 0xfffe (with a dummy length).
730 if( group == 0xfffe )
733 // The group length doesn't represent data to be loaded in memory, since
734 // each element of the group shall be loaded individualy.
736 //SkipLoad = true; // modif sauvage JPR
737 // On charge la longueur du groupe
738 // quand l'element 0x0000 est présent !
741 // FIXME the following skip is not necessary
742 SkipElementValue(ElVal);
744 ElVal->SetValue("gdcm::Skipped");
748 // When the length is zero things are easy:
754 // The elements whose length is bigger than the specified upper bound
755 // are not loaded. Instead we leave a short notice of the offset of
756 // the element content and it's length.
757 if (length > MaxSizeLoadElementValue) {
759 s << "gdcm::NotLoaded.";
760 s << " Address:" << (long)ElVal->GetOffset();
761 s << " Length:" << ElVal->GetLength();
762 ElVal->SetValue(s.str());
766 // When an integer is expected, read and convert the following two or
767 // four bytes properly i.e. as an integer as opposed to a string.
769 // pour les elements de Value Multiplicity > 1
770 // on aura en fait une serie d'entiers
772 // on devrait pouvoir faire + compact (?)
774 if ( IsAnInteger(ElVal) ) {
778 if (vr == "US" || vr == "SS") {
780 NewInt = ReadInt16();
783 for (int i=1; i < nbInt; i++) {
785 NewInt = ReadInt16();
787 //printf("%s\n", s.str().c_str());
791 } else if (vr == "UL" || vr == "SL") {
793 NewInt = ReadInt32();
796 for (int i=1; i < nbInt; i++) {
798 NewInt = ReadInt32();
803 ElVal->SetValue(s.str());
807 // FIXME The exact size should be length if we move to strings or whatever
808 char* NewValue = (char*)malloc(length+1);
810 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
815 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
816 if ( item_read != 1 ) {
818 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
819 ElVal->SetValue("gdcm::UnRead");
822 ElVal->SetValue(NewValue);
826 * \ingroup gdcmHeader
827 * \brief Loads the element while preserving the current
828 * underlying file position indicator as opposed to
829 * to LoadElementValue that modifies it.
830 * @param ElVal Element whose value shall be loaded.
833 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
834 long PositionOnEntry = ftell(fp);
835 LoadElementValue(ElVal);
836 fseek(fp, PositionOnEntry, SEEK_SET);
840 guint16 gdcmHeader::ReadInt16(void) {
843 item_read = fread (&g, (size_t)2,(size_t)1, fp);
845 if ( item_read != 1 ) {
846 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
854 guint32 gdcmHeader::ReadInt32(void) {
857 item_read = fread (&g, (size_t)4,(size_t)1, fp);
859 if ( item_read != 1 ) {
860 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
869 * \ingroup gdcmHeader
870 * \brief Build a new Element Value from all the low level arguments.
871 * Check for existence of dictionary entry, and build
872 * a default one when absent.
873 * @param Group group of the underlying DictEntry
874 * @param Elem element of the underlying DictEntry
876 gdcmElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
877 // Find out if the tag we encountered is in the dictionaries:
878 gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
880 NewTag = new gdcmDictEntry(Group, Elem);
882 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
884 dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
885 "failed to allocate gdcmElValue");
886 return (gdcmElValue*)0;
892 * \ingroup gdcmHeader
893 * \brief Build a new Element Value from all the low level arguments.
894 * Check for existence of dictionary entry, and build
895 * a default one when absent.
896 * @param Name Name of the underlying DictEntry
898 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
900 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
902 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
904 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
906 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
907 "failed to allocate gdcmElValue");
908 return (gdcmElValue*)0;
914 * \ingroup gdcmHeader
915 * \brief Read the next tag but WITHOUT loading it's value
916 * @return On succes the newly created ElValue, NULL on failure.
918 gdcmElValue * gdcmHeader::ReadNextElement(void) {
921 gdcmElValue * NewElVal;
926 // We reached the EOF (or an error occured) and header parsing
927 // has to be considered as finished.
928 return (gdcmElValue *)0;
930 NewElVal = NewElValueByKey(g, n);
932 FindLength(NewElVal);
935 return (gdcmElValue *)0;
936 NewElVal->SetOffset(ftell(fp));
941 * \ingroup gdcmHeader
942 * \brief Apply some heuristics to predict wether the considered
943 * element value contains/represents an integer or not.
944 * @param ElVal The element value on which to apply the predicate.
945 * @return The result of the heuristical predicate.
947 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
948 guint16 group = ElVal->GetGroup();
949 guint16 element = ElVal->GetElement();
950 string vr = ElVal->GetVR();
951 guint32 length = ElVal->GetLength();
953 // When we have some semantics on the element we just read, and if we
954 // a priori know we are dealing with an integer, then we shall be
955 // able to swap it's element value properly.
956 if ( element == 0 ) { // This is the group length of the group
960 dbg.Error("gdcmHeader::IsAnInteger",
961 "Erroneous Group Length element length.");
965 // on le traite tt de même (VR peut donner l'info)
966 // faire qq chose + ruse (pas de test si pas de VR)
967 if ( group % 2 != 0 )
968 // We only have some semantics on documented elements, which are
974 if ( (length != 4) && ( length != 2) )
975 // Swapping only make sense on integers which are 2 or 4 bytes long.
977 // En fait, pour les entiers de 'Value Multiplicity' supérieur a 1
978 // la longueur n'est pas forcement 2 ou 4
979 // ET il faudra swapper.
983 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
987 // est-ce encore utile?
988 // mieux vaut modifier le source du Dicom Dictionnaty
989 // et remplacer pour ces 2 cas RET par US
991 if ( (group == 0x0028) && (element == 0x0005) )
992 // The "Image Dimensions" tag is retained from ACR/NEMA and contains
993 // the number of dimensions of the contained object (1 for Signal,
994 // 2 for Image, 3 for Volume, 4 for Sequence).
997 if ( (group == 0x0028) && (element == 0x0200) )
998 // This tag is retained from ACR/NEMA
1005 * \ingroup gdcmHeader
1006 * \brief Recover the offset (from the beginning of the file) of the pixels.
1008 size_t gdcmHeader::GetPixelOffset(void) {
1009 // If this file complies with the norm we should encounter the
1010 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1011 // the group that contains the pixel data (hence the "Pixel Data"
1012 // is found by indirection through the "Image Location").
1013 // Inside the group pointed by "Image Location" the searched element
1014 // is conventionally the element 0x0010 (when the norm is respected).
1015 // When the "Image Location" is absent we default to group 0x7fe0.
1018 string ImageLocation = GetPubElValByName("Image Location");
1019 if ( ImageLocation == "gdcm::Unfound" ) {
1022 grPixel = (guint16) atoi( ImageLocation.c_str() );
1024 if (grPixel != 0x7fe0)
1025 // FIXME is this still necessary ?
1026 // Now, this looks like an old dirty fix for Philips imager
1030 gdcmElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
1032 return PixelElement->GetOffset();
1038 * \ingroup gdcmHeader
1039 * \brief Searches both the public and the shadow dictionary (when they
1040 * exist) for the presence of the DictEntry with given
1041 * group and element. The public dictionary has precedence on the
1043 * @param group group of the searched DictEntry
1044 * @param element element of the searched DictEntry
1045 * @return Corresponding DictEntry when it exists, NULL otherwise.
1047 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
1048 gdcmDictEntry * found = (gdcmDictEntry*)0;
1049 if (!RefPubDict && !RefShaDict) {
1050 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1051 "we SHOULD have a default dictionary");
1054 found = RefPubDict->GetTagByKey(group, element);
1059 found = RefShaDict->GetTagByKey(group, element);
1067 * \ingroup gdcmHeader
1068 * \brief Searches both the public and the shadow dictionary (when they
1069 * exist) for the presence of the DictEntry with given name.
1070 * The public dictionary has precedence on the shadow one.
1071 * @param Name name of the searched DictEntry
1072 * @return Corresponding DictEntry when it exists, NULL otherwise.
1074 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1075 gdcmDictEntry * found = (gdcmDictEntry*)0;
1076 if (!RefPubDict && !RefShaDict) {
1077 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1078 "we SHOULD have a default dictionary");
1081 found = RefPubDict->GetTagByName(Name);
1086 found = RefShaDict->GetTagByName(Name);
1094 * \ingroup gdcmHeader
1095 * \brief Searches within the public dictionary for element value of
1097 * @param group Group of the researched tag.
1098 * @param element Element of the researched tag.
1099 * @return Corresponding element value when it exists, and the string
1100 * "gdcm::Unfound" otherwise.
1102 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1103 return PubElVals.GetElValueByNumber(group, element);
1107 * \ingroup gdcmHeader
1108 * \brief Searches within the public dictionary for element value
1109 * representation of a given tag.
1111 * Obtaining the VR (Value Representation) might be needed by caller
1112 * to convert the string typed content to caller's native type
1113 * (think of C++ vs Python). The VR is actually of a higher level
1114 * of semantics than just the native C++ type.
1115 * @param group Group of the researched tag.
1116 * @param element Element of the researched tag.
1117 * @return Corresponding element value representation when it exists,
1118 * and the string "gdcm::Unfound" otherwise.
1120 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1121 gdcmElValue* elem = PubElVals.GetElementByNumber(group, element);
1123 return "gdcm::Unfound";
1124 return elem->GetVR();
1128 * \ingroup gdcmHeader
1129 * \brief Searches within the public dictionary for element value of
1131 * @param TagName name of the researched element.
1132 * @return Corresponding element value when it exists, and the string
1133 * "gdcm::Unfound" otherwise.
1135 string gdcmHeader::GetPubElValByName(string TagName) {
1136 return PubElVals.GetElValueByName(TagName);
1140 * \ingroup gdcmHeader
1141 * \brief Searches within the elements parsed with the public dictionary for
1142 * the element value representation of a given tag.
1144 * Obtaining the VR (Value Representation) might be needed by caller
1145 * to convert the string typed content to caller's native type
1146 * (think of C++ vs Python). The VR is actually of a higher level
1147 * of semantics than just the native C++ type.
1148 * @param TagName name of the researched element.
1149 * @return Corresponding element value representation when it exists,
1150 * and the string "gdcm::Unfound" otherwise.
1152 string gdcmHeader::GetPubElValRepByName(string TagName) {
1153 gdcmElValue* elem = PubElVals.GetElementByName(TagName);
1155 return "gdcm::Unfound";
1156 return elem->GetVR();
1160 * \ingroup gdcmHeader
1161 * \brief Searches within elements parsed with the SHADOW dictionary
1162 * for the element value of a given tag.
1163 * @param group Group of the researched tag.
1164 * @param element Element of the researched tag.
1165 * @return Corresponding element value representation when it exists,
1166 * and the string "gdcm::Unfound" otherwise.
1168 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1169 return ShaElVals.GetElValueByNumber(group, element);
1173 * \ingroup gdcmHeader
1174 * \brief Searches within the elements parsed with the SHADOW dictionary
1175 * for the element value representation of a given tag.
1177 * Obtaining the VR (Value Representation) might be needed by caller
1178 * to convert the string typed content to caller's native type
1179 * (think of C++ vs Python). The VR is actually of a higher level
1180 * of semantics than just the native C++ type.
1181 * @param group Group of the researched tag.
1182 * @param element Element of the researched tag.
1183 * @return Corresponding element value representation when it exists,
1184 * and the string "gdcm::Unfound" otherwise.
1186 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1187 gdcmElValue* elem = ShaElVals.GetElementByNumber(group, element);
1189 return "gdcm::Unfound";
1190 return elem->GetVR();
1194 * \ingroup gdcmHeader
1195 * \brief Searches within the elements parsed with the shadow dictionary
1196 * for an element value of given tag.
1197 * @param TagName name of the researched element.
1198 * @return Corresponding element value when it exists, and the string
1199 * "gdcm::Unfound" otherwise.
1201 string gdcmHeader::GetShaElValByName(string TagName) {
1202 return ShaElVals.GetElValueByName(TagName);
1206 * \ingroup gdcmHeader
1207 * \brief Searches within the elements parsed with the shadow dictionary for
1208 * the element value representation of a given tag.
1210 * Obtaining the VR (Value Representation) might be needed by caller
1211 * to convert the string typed content to caller's native type
1212 * (think of C++ vs Python). The VR is actually of a higher level
1213 * of semantics than just the native C++ type.
1214 * @param TagName name of the researched element.
1215 * @return Corresponding element value representation when it exists,
1216 * and the string "gdcm::Unfound" otherwise.
1218 string gdcmHeader::GetShaElValRepByName(string TagName) {
1219 gdcmElValue* elem = ShaElVals.GetElementByName(TagName);
1221 return "gdcm::Unfound";
1222 return elem->GetVR();
1226 * \ingroup gdcmHeader
1227 * \brief Searches within elements parsed with the public dictionary
1228 * and then within the elements parsed with the shadow dictionary
1229 * for the element value of a given tag.
1230 * @param group Group of the researched tag.
1231 * @param element Element of the researched tag.
1232 * @return Corresponding element value representation when it exists,
1233 * and the string "gdcm::Unfound" otherwise.
1235 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1236 string pub = GetPubElValByNumber(group, element);
1239 return GetShaElValByNumber(group, element);
1243 * \ingroup gdcmHeader
1244 * \brief Searches within elements parsed with the public dictionary
1245 * and then within the elements parsed with the shadow dictionary
1246 * for the element value representation of a given tag.
1248 * Obtaining the VR (Value Representation) might be needed by caller
1249 * to convert the string typed content to caller's native type
1250 * (think of C++ vs Python). The VR is actually of a higher level
1251 * of semantics than just the native C++ type.
1252 * @param group Group of the researched tag.
1253 * @param element Element of the researched tag.
1254 * @return Corresponding element value representation when it exists,
1255 * and the string "gdcm::Unfound" otherwise.
1257 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1258 string pub = GetPubElValRepByNumber(group, element);
1261 return GetShaElValRepByNumber(group, element);
1265 * \ingroup gdcmHeader
1266 * \brief Searches within elements parsed with the public dictionary
1267 * and then within the elements parsed with the shadow dictionary
1268 * for the element value of a given tag.
1269 * @param TagName name of the researched element.
1270 * @return Corresponding element value when it exists,
1271 * and the string "gdcm::Unfound" otherwise.
1273 string gdcmHeader::GetElValByName(string TagName) {
1274 string pub = GetPubElValByName(TagName);
1277 return GetShaElValByName(TagName);
1281 * \ingroup gdcmHeader
1282 * \brief Searches within elements parsed with the public dictionary
1283 * and then within the elements parsed with the shadow dictionary
1284 * for the element value representation of a given tag.
1286 * Obtaining the VR (Value Representation) might be needed by caller
1287 * to convert the string typed content to caller's native type
1288 * (think of C++ vs Python). The VR is actually of a higher level
1289 * of semantics than just the native C++ type.
1290 * @param TagName name of the researched element.
1291 * @return Corresponding element value representation when it exists,
1292 * and the string "gdcm::Unfound" otherwise.
1294 string gdcmHeader::GetElValRepByName(string TagName) {
1295 string pub = GetPubElValRepByName(TagName);
1298 return GetShaElValRepByName(TagName);
1302 * \ingroup gdcmHeader
1303 * \brief Accesses an existing gdcmElValue in the PubElVals of this instance
1304 * through it's (group, element) and modifies it's content with
1306 * @param content new value to substitute with
1307 * @param group group of the ElVal to modify
1308 * @param element element of the ElVal to modify
1310 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1313 return ( PubElVals.SetElValueByNumber (content, group, element) );
1317 * \ingroup gdcmHeader
1318 * \brief Accesses an existing gdcmElValue in the PubElVals of this instance
1319 * through tag name and modifies it's content with the given value.
1320 * @param content new value to substitute with
1321 * @param TagName name of the tag to be modified
1323 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1324 return ( PubElVals.SetElValueByName (content, TagName) );
1328 * \ingroup gdcmHeader
1329 * \brief Accesses an existing gdcmElValue in the PubElVals of this instance
1330 * through it's (group, element) and modifies it's length with
1333 * @param contents new length to substitute with
1334 * @param group group of the ElVal to modify
1335 * @param element element of the ElVal to modify
1337 int gdcmHeader::SetPubElValLengthByNumber(guint32 lgr, guint16 group,
1340 return ( PubElVals.SetElValueLengthByNumber (lgr, group, element) );
1344 * \ingroup gdcmHeader
1345 * \brief Accesses an existing gdcmElValue in the ShaElVals of this instance
1346 * through it's (group, element) and modifies it's content with
1348 * @param content new value to substitute with
1349 * @param group group of the ElVal to modify
1350 * @param element element of the ElVal to modify
1352 int gdcmHeader::SetShaElValByNumber(string content,
1353 guint16 group, guint16 element)
1355 return ( ShaElVals.SetElValueByNumber (content, group, element) );
1359 * \ingroup gdcmHeader
1360 * \brief Accesses an existing gdcmElValue in the ShaElVals of this instance
1361 * through tag name and modifies it's content with the given value.
1362 * @param content new value to substitute with
1363 * @param TagName name of the tag to be modified
1365 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1366 return ( ShaElVals.SetElValueByName (content, TagName) );
1370 * \ingroup gdcmHeader
1371 * \brief Parses the header of the file but WITHOUT loading element values.
1373 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1374 gdcmElValue * newElValue = (gdcmElValue *)0;
1378 while ( (newElValue = ReadNextElement()) ) {
1379 SkipElementValue(newElValue);
1380 PubElVals.Add(newElValue);
1385 * \ingroup gdcmHeader
1386 * \brief Once the header is parsed add some gdcm convenience/helper elements
1387 * in the gdcmElValSet. For example add:
1388 * - gdcmImageType which is an entry containing a short for the
1389 * type of image and whose value ranges in
1390 * I8 (unsigned 8 bit image)
1391 * I16 (unsigned 8 bit image)
1392 * IS16 (signed 8 bit image)
1393 * - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1394 * the ones of the official DICOM fields Rows, Columns and Planes.
1396 void gdcmHeader::AddAndDefaultElements(void) {
1397 gdcmElValue* NewElVal = (gdcmElValue*)0;
1400 NewElVal = NewManualElValToPubDict("gdcmXSize", "US");
1401 if (!NewElVal) return;
1402 NewVal = GetElValByName("Rows");
1403 if (NewVal != "gdcm::Unfound")
1404 NewElVal->SetValue(NewVal);
1406 NewElVal->SetValue("0");
1409 NewElVal = NewManualElValToPubDict("gdcmYSize", "US");
1410 if (!NewElVal) return;
1411 NewVal = GetElValByName("Columns");
1412 if (NewVal != "gdcm::Unfound")
1413 NewElVal->SetValue(NewVal);
1415 NewElVal->SetValue("0");
1418 NewElVal = NewManualElValToPubDict("gdcmZSize", "US");
1419 if (!NewElVal) return;
1420 NewVal = GetElValByName("Planes");
1421 if (NewVal != "gdcm::Unfound")
1422 NewElVal->SetValue(NewVal);
1424 NewElVal->SetValue("0");
1428 * \ingroup gdcmHeader
1429 * \brief Small utility function that creates a new manually crafted
1430 * (as opposed as read from the file) gdcmElValue with user
1431 * specified name and adds it to the public tag hash table.
1432 * Refer to gdcmHeader::AddAndDefaultElements for a typical usage.
1433 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1434 * @param NewTagName The name to be given to this new tag.
1435 * @param VR The Value Representation to be given to this new tag.
1436 * @ return The newly hand crafted Element Value.
1438 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1439 gdcmElValue* NewElVal = (gdcmElValue*)0;
1440 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1441 guint32 FreeElem = 0;
1442 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1444 FreeElem = PubElVals.GenerateFreeTagKeyInGroup(StuffGroup);
1445 if (FreeElem == UINT32_MAX) {
1446 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1447 "Group 0xffff in Public Dict is full");
1448 return (gdcmElValue*)0;
1450 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1451 VR, "GDCM", NewTagName);
1452 NewElVal = new gdcmElValue(NewEntry);
1453 PubElVals.Add(NewElVal);
1458 * \ingroup gdcmHeader
1459 * \brief Loads the element values of all the elements present in the
1460 * public tag based hash table.
1462 void gdcmHeader::LoadElements(void) {
1464 TagElValueHT ht = PubElVals.GetTagHt();
1465 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1466 LoadElementValue(tag->second);
1470 void gdcmHeader::PrintPubElVal(ostream & os) {
1471 PubElVals.Print(os);
1474 void gdcmHeader::PrintPubDict(ostream & os) {
1475 RefPubDict->Print(os);