9 #include <netinet/in.h>
11 #include <cctype> // for isalpha
14 #include "gdcmHeader.h"
16 #define HEADER_LENGTH_TO_READ 256 // on ne lit plus que le debut
17 #define _MaxSizeLoadElementValue_ 1024 // longueur au dela de laquelle on ne charge plus les valeurs
19 //FIXME: this looks dirty to me...
21 #define str2num(str, typeNum) *((typeNum *)(str))
23 // str est un pointeur dans un tableau de caractères, qui doit contenir,
24 // à cet endroit la, la représentation binaire d'un entier (16 ou 32 bits)
25 // je veux récupérer ça ... dans un entier.
26 // s'il y a une autre solution, évitant des cast et les indirections,
29 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
31 void gdcmHeader::Initialise(void) {
32 if (!gdcmHeader::dicom_vr)
34 Dicts = new gdcmDictSet();
35 RefPubDict = Dicts->GetDefaultPubDict();
36 RefShaDict = (gdcmDict*)0;
40 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error)
41 throw(gdcmFileError) {
42 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
43 filename = InFilename;
45 fp=fopen(InFilename,"rb");
46 if(exception_on_error) {
48 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
51 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
53 AddAndDefaultElements();
57 gdcmHeader::~gdcmHeader (void) {
62 void gdcmHeader::InitVRDict (void) {
64 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
68 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
69 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
70 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
71 (*vr)["CS"] = "Code String"; // At most 16 bytes
72 (*vr)["DA"] = "Date"; // Exactly 8 bytes
73 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
74 (*vr)["DT"] = "Date Time"; // At most 26 bytes
75 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
76 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
77 (*vr)["IS"] = "Integer String"; // At most 12 bytes
78 (*vr)["LO"] = "Long String"; // At most 64 chars
79 (*vr)["LT"] = "Long Text"; // At most 10240 chars
80 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
81 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
82 (*vr)["PN"] = "Person Name"; // At most 64 chars
83 (*vr)["SH"] = "Short String"; // At most 16 chars
84 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
85 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
86 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
87 (*vr)["ST"] = "Short Text"; // At most 1024 chars
88 (*vr)["TM"] = "Time"; // At most 16 bytes
89 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
90 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
91 (*vr)["UN"] = "Unknown"; // Any length of bytes
92 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
93 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
99 * \brief Discover what the swap code is (among little endian, big endian,
100 * bad little endian, bad big endian).
103 void gdcmHeader::CheckSwap()
105 // The only guaranted way of finding the swap code is to find a
106 // group tag since we know it's length has to be of four bytes i.e.
107 // 0x00000004. Finding the swap code in then straigthforward. Trouble
108 // occurs when we can't find such group...
110 guint32 x=4; // x : pour ntohs
111 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
115 char deb[HEADER_LENGTH_TO_READ];
117 // First, compare HostByteOrder and NetworkByteOrder in order to
118 // determine if we shall need to swap bytes (i.e. the Endian type).
124 // The easiest case is the one of a DICOM header, since it possesses a
125 // file preamble where it suffice to look for the string "DICM".
126 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
129 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
130 filetype = TrueDicom;
131 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
134 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
137 if(filetype == TrueDicom) {
138 // Next, determine the value representation (VR). Let's skip to the
139 // first element (0002, 0000) and check there if we find "UL", in
140 // which case we (almost) know it is explicit VR.
141 // WARNING: if it happens to be implicit VR then what we will read
142 // is the length of the group. If this ascii representation of this
143 // length happens to be "UL" then we shall believe it is explicit VR.
144 // FIXME: in order to fix the above warning, we could read the next
145 // element value (or a couple of elements values) in order to make
146 // sure we are not commiting a big mistake.
148 // * the 128 bytes of File Preamble (often padded with zeroes),
149 // * the 4 bytes of "DICM" string,
150 // * the 4 bytes of the first tag (0002, 0000),
151 // i.e. a total of 136 bytes.
153 if(memcmp(entCur, "UL", (size_t)2) == 0) {
154 filetype = ExplicitVR;
155 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
156 "explicit Value Representation");
158 filetype = ImplicitVR;
159 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
160 "not an explicit Value Representation");
165 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
166 "HostByteOrder != NetworkByteOrder");
169 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
170 "HostByteOrder = NetworkByteOrder");
173 // Position the file position indicator at first tag (i.e.
174 // after the file preamble and the "DICM" string).
176 fseek (fp, 132L, SEEK_SET);
178 } // End of TrueDicom
180 // Alas, this is not a DicomV3 file and whatever happens there is no file
181 // preamble. We can reset the file position indicator to where the data
182 // is (i.e. the beginning of the file).
185 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
186 // By clean we mean that the length of the first tag is written down.
187 // If this is the case and since the length of the first group HAS to be
188 // four (bytes), then determining the proper swap code is straightforward.
191 s = str2num(entCur, guint32);
211 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
212 "ACR/NEMA unfound swap info (time to raise bets)");
215 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
216 // It is time for despaired wild guesses. So, let's assume this file
217 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
218 // not present. Then the only info we have is the net2host one.
226 void gdcmHeader::SwitchSwapToBigEndian(void) {
227 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
228 "Switching to BigEndian mode.");
245 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
247 pixelsOffset = GetPixelOffset();
248 fseek(fp, pixelsOffset, SEEK_SET);
249 fread(_Pixels, 1, lgrTotale, fp);
255 * \ingroup gdcmHeader
256 * \brief Find the value representation of the current tag.
258 void gdcmHeader::FindVR( ElValue *ElVal) {
259 if (filetype != ExplicitVR)
265 long PositionOnEntry = ftell(fp);
266 // Warning: we believe this is explicit VR (Value Representation) because
267 // we used a heuristic that found "UL" in the first tag. Alas this
268 // doesn't guarantee that all the tags will be in explicit VR. In some
269 // cases (see e-film filtered files) one finds implicit VR tags mixed
270 // within an explicit VR file. Hence we make sure the present tag
271 // is in explicit VR and try to fix things if it happens not to be
273 bool RealExplicit = true;
275 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
279 // Assume we are reading a falsely explicit VR file i.e. we reached
280 // a tag where we expect reading a VR but are in fact we read the
281 // first to bytes of the length. Then we will interogate (through find)
282 // the dicom_vr dictionary with oddities like "\004\0" which crashes
283 // both GCC and VC++ implementations of the STL map. Hence when the
284 // expected VR read happens to be non-ascii characters we consider
285 // we hit falsely explicit VR tag.
287 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
288 RealExplicit = false;
290 // CLEANME searching the dicom_vr at each occurence is expensive.
291 // PostPone this test in an optional integrity check at the end
292 // of parsing or only in debug mode.
293 if ( RealExplicit && !dicom_vr->count(vr) )
294 RealExplicit = false;
296 if ( RealExplicit ) {
297 if ( ElVal->IsVrUnknown() ) {
298 // When not a dictionary entry, we can safely overwrite the vr.
302 if ( ElVal->GetVR() == vr ) {
303 // The vr we just read and the dictionary agree. Nothing to do.
306 // The vr present in the file and the dictionary disagree. We assume
307 // the file writer knew best and use the vr of the file. Since it would
308 // be unwise to overwrite the vr of a dictionary (since it would
309 // compromise it's next user), we need to clone the actual DictEntry
310 // and change the vr for the read one.
311 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
316 ElVal->SetDictEntry(NewTag);
320 // We thought this was explicit VR, but we end up with an
321 // implicit VR tag. Let's backtrack.
322 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
323 fseek(fp, PositionOnEntry, SEEK_SET);
324 // When this element is known in the dictionary we shall use, e.g. for
325 // the semantics (see the usage of IsAnInteger), the vr proposed by the
326 // dictionary entry. Still we have to flag the element as implicit since
327 // we know now our assumption on expliciteness is not furfilled.
329 if ( ElVal->IsVrUnknown() )
330 ElVal->SetVR("Implicit");
331 ElVal->SetImplicitVr();
335 * \ingroup gdcmHeader
336 * \brief Determines if the Transfer Syntax was allready encountered
337 * and if it corresponds to a ImplicitVRLittleEndian one.
339 * @return True when ImplicitVRLittleEndian found. False in all other cases.
341 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
342 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
345 LoadElementValueSafe(Element);
346 string Transfer = Element->GetValue();
347 if ( Transfer == "1.2.840.10008.1.2" )
353 * \ingroup gdcmHeader
354 * \brief Determines if the Transfer Syntax was allready encountered
355 * and if it corresponds to a ExplicitVRLittleEndian one.
357 * @return True when ExplicitVRLittleEndian found. False in all other cases.
359 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
360 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
363 LoadElementValueSafe(Element);
364 string Transfer = Element->GetValue();
365 if ( Transfer == "1.2.840.10008.1.2.1" )
371 * \ingroup gdcmHeader
372 * \brief Determines if the Transfer Syntax was allready encountered
373 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
375 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
377 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
378 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
381 LoadElementValueSafe(Element);
382 string Transfer = Element->GetValue();
383 if ( Transfer == "1.2.840.10008.1.2.1.99" )
390 * \ingroup gdcmHeader
391 * \brief Determines if the Transfer Syntax was allready encountered
392 * and if it corresponds to a Explicit VR Big Endian one.
394 * @return True when big endian found. False in all other cases.
396 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
397 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
400 LoadElementValueSafe(Element);
401 string Transfer = Element->GetValue();
402 if ( Transfer == "1.2.840.10008.1.2.2" )
409 * \ingroup gdcmHeader
410 * \brief Determines if the Transfer Syntax was allready encountered
411 * and if it corresponds to a JPEGBaseLineProcess1 one.
413 * @return True when JPEGBaseLineProcess1found. False in all other cases.
415 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
416 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
419 LoadElementValueSafe(Element);
420 string Transfer = Element->GetValue();
421 if ( Transfer == "1.2.840.10008.1.2.4.50" )
427 * \ingroup gdcmHeader
428 * \brief Determines if the Transfer Syntax was allready encountered
429 * and if it corresponds to a JPEGExtendedProcess2-4 one.
431 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
433 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
434 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
437 LoadElementValueSafe(Element);
438 string Transfer = Element->GetValue();
439 if ( Transfer == "1.2.840.10008.1.2.4.51" )
446 * \ingroup gdcmHeader
447 * \brief Determines if the Transfer Syntax was allready encountered
448 * and if it corresponds to a JPEGExtendeProcess3-5 one.
450 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
452 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
453 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
456 LoadElementValueSafe(Element);
457 string Transfer = Element->GetValue();
458 if ( Transfer == "1.2.840.10008.1.2.4.52" )
464 * \ingroup gdcmHeader
465 * \brief Determines if the Transfer Syntax was allready encountered
466 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
468 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
470 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
471 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
474 LoadElementValueSafe(Element);
475 string Transfer = Element->GetValue();
476 if ( Transfer == "1.2.840.10008.1.2.4.53" )
483 // Il y en a encore DIX-SEPT, comme ça.
484 // Il faudrait trouver qq chose + rusé ...
486 // --> probablement TOUS les supprimer (Eric dixit)
490 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
491 // Heuristic: a final fix.
492 if ( FoundLength == 0xffffffff)
494 ElVal->SetLength(FoundLength);
497 guint32 gdcmHeader::FindLengthOB(void) {
498 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
501 long PositionOnEntry = ftell(fp);
502 bool FoundSequenceDelimiter = false;
503 guint32 TotalLength = 0;
506 while ( ! FoundSequenceDelimiter) {
511 TotalLength += 4; // We even have to decount the group and element
513 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
514 "wrong group for an item sequence.");
519 FoundSequenceDelimiter = true;
520 else if ( n != 0xe000) {
521 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
522 "wrong element for an item sequence.");
526 ItemLength = ReadInt32();
527 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
528 // the ItemLength with ReadInt32
529 SkipBytes(ItemLength);
531 fseek(fp, PositionOnEntry, SEEK_SET);
535 void gdcmHeader::FindLength(ElValue * ElVal) {
536 guint16 element = ElVal->GetElement();
537 string vr = ElVal->GetVR();
540 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
542 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
543 // The following reserved two bytes (see PS 3.5-2001, section
544 // 7.1.2 Data element structure with explicit vr p27) must be
545 // skipped before proceeding on reading the length on 4 bytes.
546 fseek(fp, 2L, SEEK_CUR);
547 guint32 length32 = ReadInt32();
548 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
549 ElVal->SetLength(FindLengthOB());
552 FixFoundLength(ElVal, length32);
556 // Length is encoded on 2 bytes.
557 length16 = ReadInt16();
559 // We can tell the current file is encoded in big endian (like
560 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
561 // and it's value is the one of the encoding of a big endian file.
562 // In order to deal with such big endian encoded files, we have
563 // (at least) two strategies:
564 // * when we load the "Transfer Syntax" tag with value of big endian
565 // encoding, we raise the proper flags. Then we wait for the end
566 // of the META group (0x0002) among which is "Transfer Syntax",
567 // before switching the swap code to big endian. We have to postpone
568 // the switching of the swap code since the META group is fully encoded
569 // in little endian, and big endian coding only starts at the next
570 // group. The corresponding code can be hard to analyse and adds
571 // many additional unnecessary tests for regular tags.
572 // * the second strategy consists in waiting for trouble, that shall appear
573 // when we find the first group with big endian encoding. This is
574 // easy to detect since the length of a "Group Length" tag (the
575 // ones with zero as element number) has to be of 4 (0x0004). When we
576 // encouter 1024 (0x0400) chances are the encoding changed and we
577 // found a group with big endian encoding.
578 // We shall use this second strategy. In order make sure that we
579 // can interpret the presence of an apparently big endian encoded
580 // length of a "Group Length" without committing a big mistake, we
581 // add an additional check: we look in the allready parsed elements
582 // for the presence of a "Transfer Syntax" whose value has to be "big
583 // endian encoding". When this is the case, chances are we got our
584 // hands on a big endian encoded file: we switch the swap code to
585 // big endian and proceed...
586 if ( (element == 0x000) && (length16 == 0x0400) ) {
587 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
588 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
593 SwitchSwapToBigEndian();
594 // Restore the unproperly loaded values i.e. the group, the element
595 // and the dictionary entry depending on them.
596 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
597 guint16 CorrectElem = SwapShort(ElVal->GetElement());
598 gdcmDictEntry * NewTag = GetDictEntryByKey(CorrectGroup, CorrectElem);
600 // This correct tag is not in the dictionary. Create a new one.
601 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
603 // FIXME this can create a memory leaks on the old entry that be
604 // left unreferenced.
605 ElVal->SetDictEntry(NewTag);
608 // Heuristic: well some files are really ill-formed.
609 if ( length16 == 0xffff) {
611 dbg.Verbose(0, "gdcmHeader::FindLength",
612 "Erroneous element length fixed.");
614 FixFoundLength(ElVal, (guint32)length16);
618 // Either implicit VR or a non DICOM conformal (see not below) explicit
619 // VR that ommited the VR of (at least) this element. Farts happen.
620 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
621 // on Data elements "Implicit and Explicit VR Data Elements shall
622 // not coexist in a Data Set and Data Sets nested within it".]
623 // Length is on 4 bytes.
624 FixFoundLength(ElVal, ReadInt32());
628 * \ingroup gdcmHeader
629 * \brief Swaps back the bytes of 4-byte long integer accordingly to
632 * @return The suggested integer.
634 guint32 gdcmHeader::SwapLong(guint32 a) {
635 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
640 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
641 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
645 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
649 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
652 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
659 * \ingroup gdcmHeader
660 * \brief Swaps the bytes so they agree with the processor order
661 * @return The properly swaped 16 bits integer.
663 guint16 gdcmHeader::SwapShort(guint16 a) {
664 if ( (sw==4321) || (sw==2143) )
665 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
669 void gdcmHeader::SkipBytes(guint32 NBytes) {
670 //FIXME don't dump the returned value
671 (void)fseek(fp, (long)NBytes, SEEK_CUR);
674 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
675 SkipBytes(ElVal->GetLength());
678 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
681 if ((guint32)NewSize >= (guint32)0xffffffff) {
682 MaxSizeLoadElementValue = 0xffffffff;
685 MaxSizeLoadElementValue = NewSize;
689 * \ingroup gdcmHeader
690 * \brief Loads the element content if it's length is not bigger
691 * than the value specified with
692 * gdcmHeader::SetMaxSizeLoadElementValue()
694 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
696 guint16 group = ElVal->GetGroup();
697 guint16 elem = ElVal->GetElement();
698 string vr = ElVal->GetVR();
699 guint32 length = ElVal->GetLength();
700 bool SkipLoad = false;
702 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
704 // Sequences not treated yet !
706 // Ne faudrait-il pas au contraire trouver immediatement
707 // une maniere 'propre' de traiter les sequences (vr = SQ)
708 // car commencer par les ignorer risque de conduire a qq chose
709 // qui pourrait ne pas etre generalisable
714 // Heuristic : a sequence "contains" a set of tags (called items). It looks
715 // like the last tag of a sequence (the one that terminates the sequence)
716 // has a group of 0xfffe (with a dummy length).
717 if( group == 0xfffe )
720 // The group length doesn't represent data to be loaded in memory, since
721 // each element of the group shall be loaded individualy.
723 //SkipLoad = true; // modif sauvage JPR
724 // On charge la longueur du groupe
725 // quand l'element 0x0000 est présent !
728 // FIXME the following skip is not necessary
729 SkipElementValue(ElVal);
731 ElVal->SetValue("gdcm::Skipped");
735 // When the length is zero things are easy:
741 // The elements whose length is bigger than the specified upper bound
742 // are not loaded. Instead we leave a short notice of the offset of
743 // the element content and it's length.
744 if (length > MaxSizeLoadElementValue) {
746 s << "gdcm::NotLoaded.";
747 s << " Address:" << (long)ElVal->GetOffset();
748 s << " Length:" << ElVal->GetLength();
749 ElVal->SetValue(s.str());
753 // When an integer is expected, read and convert the following two or
754 // four bytes properly i.e. as an integer as opposed to a string.
755 if ( IsAnInteger(ElVal) ) {
758 NewInt = ReadInt16();
759 } else if( length == 4 ) {
760 NewInt = ReadInt32();
762 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
764 //FIXME: make the following an util fonction
767 ElVal->SetValue(s.str());
771 // FIXME The exact size should be length if we move to strings or whatever
772 char* NewValue = (char*)malloc(length+1);
774 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
779 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
780 if ( item_read != 1 ) {
782 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
783 ElVal->SetValue("gdcm::UnRead");
786 ElVal->SetValue(NewValue);
790 * \ingroup gdcmHeader
791 * \brief Loads the element while preserving the current
792 * underlying file position indicator as opposed to
793 * to LoadElementValue that modifies it.
794 * @param ElVal Element whose value shall be loaded.
797 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
798 long PositionOnEntry = ftell(fp);
799 LoadElementValue(ElVal);
800 fseek(fp, PositionOnEntry, SEEK_SET);
804 guint16 gdcmHeader::ReadInt16(void) {
807 item_read = fread (&g, (size_t)2,(size_t)1, fp);
809 if ( item_read != 1 ) {
810 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
818 guint32 gdcmHeader::ReadInt32(void) {
821 item_read = fread (&g, (size_t)4,(size_t)1, fp);
823 if ( item_read != 1 ) {
824 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
833 * \ingroup gdcmHeader
834 * \brief Build a new Element Value from all the low level arguments.
835 * Check for existence of dictionary entry, and build
836 * a default one when absent.
837 * @param Group group of the underlying DictEntry
838 * @param Elem element of the underlying DictEntry
840 ElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
841 // Find out if the tag we encountered is in the dictionaries:
842 gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
844 NewTag = new gdcmDictEntry(Group, Elem);
846 ElValue* NewElVal = new ElValue(NewTag);
848 dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
849 "failed to allocate ElValue");
856 * \ingroup gdcmHeader
857 * \brief Build a new Element Value from all the low level arguments.
858 * Check for existence of dictionary entry, and build
859 * a default one when absent.
860 * @param Name Name of the underlying DictEntry
862 ElValue* gdcmHeader::NewElValueByName(string Name) {
864 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
866 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
868 ElValue* NewElVal = new ElValue(NewTag);
870 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
871 "failed to allocate ElValue");
879 * \ingroup gdcmHeader
880 * \brief Read the next tag without loading it's value
881 * @return On succes the newly created ElValue, NULL on failure.
884 ElValue * gdcmHeader::ReadNextElement(void) {
892 // We reached the EOF (or an error occured) and header parsing
893 // has to be considered as finished.
896 NewElVal = NewElValueByKey(g, n);
898 FindLength(NewElVal);
902 NewElVal->SetOffset(ftell(fp));
906 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
907 guint16 group = ElVal->GetGroup();
908 guint16 element = ElVal->GetElement();
909 string vr = ElVal->GetVR();
910 guint32 length = ElVal->GetLength();
912 // When we have some semantics on the element we just read, and if we
913 // a priori know we are dealing with an integer, then we shall be
914 // able to swap it's element value properly.
915 if ( element == 0 ) { // This is the group length of the group
919 dbg.Error("gdcmHeader::IsAnInteger",
920 "Erroneous Group Length element length.");
923 if ( group % 2 != 0 )
924 // We only have some semantics on documented elements, which are
928 if ( (length != 4) && ( length != 2) )
929 // Swapping only make sense on integers which are 2 or 4 bytes long.
932 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
935 if ( (group == 0x0028) && (element == 0x0005) )
936 // The "Image Dimensions" tag is retained from ACR/NEMA and contains
937 // the number of dimensions of the contained object (1 for Signal,
938 // 2 for Image, 3 for Volume, 4 for Sequence).
941 if ( (group == 0x0028) && (element == 0x0200) )
942 // This tag is retained from ACR/NEMA
949 * \ingroup gdcmHeader
950 * \brief Recover the offset (from the beginning of the file) of the pixels.
952 size_t gdcmHeader::GetPixelOffset(void) {
953 // If this file complies with the norm we should encounter the
954 // "Image Location" tag (0x0028, 0x0200). This tag contains the
955 // the group that contains the pixel data (hence the "Pixel Data"
956 // is found by indirection through the "Image Location").
957 // Inside the group pointed by "Image Location" the searched element
958 // is conventionally the element 0x0010 (when the norm is respected).
959 // When the "Image Location" is absent we default to group 0x7fe0.
962 string ImageLocation = GetPubElValByName("Image Location");
963 if ( ImageLocation == "gdcm::Unfound" ) {
966 grPixel = (guint16) atoi( ImageLocation.c_str() );
968 if (grPixel != 0x7fe0)
969 // FIXME is this still necessary ?
970 // Now, this looks like an old dirty fix for Philips imager
974 ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
976 return PixelElement->GetOffset();
982 * \ingroup gdcmHeader
983 * \brief Searches both the public and the shadow dictionary (when they
984 * exist) for the presence of the DictEntry with given
985 * group and element. The public dictionary has precedence on the
987 * @param group group of the searched DictEntry
988 * @param element element of the searched DictEntry
989 * @return Corresponding DictEntry when it exists, NULL otherwise.
991 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
992 gdcmDictEntry * found = (gdcmDictEntry*)0;
993 if (!RefPubDict && !RefShaDict) {
994 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
995 "we SHOULD have a default dictionary");
998 found = RefPubDict->GetTagByKey(group, element);
1003 found = RefShaDict->GetTagByKey(group, element);
1011 * \ingroup gdcmHeader
1012 * \brief Searches both the public and the shadow dictionary (when they
1013 * exist) for the presence of the DictEntry with given name.
1014 * The public dictionary has precedence on the shadow one.
1015 * @earam Name name of the searched DictEntry
1016 * @return Corresponding DictEntry when it exists, NULL otherwise.
1018 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1019 gdcmDictEntry * found = (gdcmDictEntry*)0;
1020 if (!RefPubDict && !RefShaDict) {
1021 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1022 "we SHOULD have a default dictionary");
1025 found = RefPubDict->GetTagByName(Name);
1030 found = RefShaDict->GetTagByName(Name);
1037 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1038 return PubElVals.GetElValueByNumber(group, element);
1041 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1042 ElValue* elem = PubElVals.GetElementByNumber(group, element);
1044 return "gdcm::Unfound";
1045 return elem->GetVR();
1048 string gdcmHeader::GetPubElValByName(string TagName) {
1049 return PubElVals.GetElValueByName(TagName);
1052 string gdcmHeader::GetPubElValRepByName(string TagName) {
1053 ElValue* elem = PubElVals.GetElementByName(TagName);
1055 return "gdcm::Unfound";
1056 return elem->GetVR();
1059 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1060 return ShaElVals.GetElValueByNumber(group, element);
1063 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1064 ElValue* elem = ShaElVals.GetElementByNumber(group, element);
1066 return "gdcm::Unfound";
1067 return elem->GetVR();
1070 string gdcmHeader::GetShaElValByName(string TagName) {
1071 return ShaElVals.GetElValueByName(TagName);
1074 string gdcmHeader::GetShaElValRepByName(string TagName) {
1075 ElValue* elem = ShaElVals.GetElementByName(TagName);
1077 return "gdcm::Unfound";
1078 return elem->GetVR();
1081 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1082 string pub = GetPubElValByNumber(group, element);
1085 return GetShaElValByNumber(group, element);
1088 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1089 string pub = GetPubElValRepByNumber(group, element);
1092 return GetShaElValRepByNumber(group, element);
1095 string gdcmHeader::GetElValByName(string TagName) {
1096 string pub = GetPubElValByName(TagName);
1099 return GetShaElValByName(TagName);
1102 string gdcmHeader::GetElValRepByName(string TagName) {
1103 string pub = GetPubElValRepByName(TagName);
1106 return GetShaElValRepByName(TagName);
1110 * \ingroup gdcmHeader
1111 * \brief Accesses an existing ElValue in the PubElVals of this instance
1112 * through it's (group, element) and modifies it's content with
1114 * @param content new value to substitute with
1115 * @param group group of the ElVal to modify
1116 * @param element element of the ElVal to modify
1118 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1121 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1122 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1123 return ( PubElVals.SetElValueByNumber (content, group, element) );
1127 * \ingroup gdcmHeader
1128 * \brief Accesses an existing ElValue in the PubElVals of this instance
1129 * through tag name and modifies it's content with the given value.
1130 * @param content new value to substitute with
1131 * @param TagName name of the tag to be modified
1133 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1134 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1135 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1136 return ( PubElVals.SetElValueByName (content, TagName) );
1140 * \ingroup gdcmHeader
1141 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1142 * through it's (group, element) and modifies it's content with
1144 * @param content new value to substitute with
1145 * @param group group of the ElVal to modify
1146 * @param element element of the ElVal to modify
1148 int gdcmHeader::SetShaElValByNumber(string content,
1149 guint16 group, guint16 element)
1151 return ( ShaElVals.SetElValueByNumber (content, group, element) );
1155 * \ingroup gdcmHeader
1156 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1157 * through tag name and modifies it's content with the given value.
1158 * @param content new value to substitute with
1159 * @param TagName name of the tag to be modified
1161 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1162 return ( ShaElVals.SetElValueByName (content, TagName) );
1166 * \ingroup gdcmHeader
1167 * \brief Parses the header of the file but WITHOUT loading element values.
1169 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1170 ElValue * newElValue = (ElValue *)0;
1174 while ( (newElValue = ReadNextElement()) ) {
1175 SkipElementValue(newElValue);
1176 PubElVals.Add(newElValue);
1181 * \ingroup gdcmHeader
1182 * \brief Once the header is parsed add some gdcm convenience/helper elements
1183 * in the ElValSet. For example add:
1184 * - gdcmImageType which is an entry containing a short for the
1185 * type of image and whose value ranges in
1186 * I8 (unsigned 8 bit image)
1187 * I16 (unsigned 8 bit image)
1188 * IS16 (signed 8 bit image)
1189 * - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1190 * the ones of the official DICOM fields Rows, Columns and Planes.
1192 void gdcmHeader::AddAndDefaultElements(void) {
1193 ElValue* NewEntry = (ElValue*)0;
1195 NewEntry = NewElValueByName("gdcmXSize");
1196 NewEntry->SetValue(GetElValByName("Rows"));
1197 PubElVals.Add(NewEntry);
1199 NewEntry = NewElValueByName("gdcmYSize");
1200 NewEntry->SetValue(GetElValByName("Columns"));
1201 PubElVals.Add(NewEntry);
1203 NewEntry = NewElValueByName("gdcmZSize");
1204 NewEntry->SetValue(GetElValByName("Planes"));
1205 PubElVals.Add(NewEntry);
1209 * \ingroup gdcmHeader
1210 * \brief Loads the element values of all the elements present in the
1211 * public tag based hash table.
1213 void gdcmHeader::LoadElements(void) {
1215 TagElValueHT ht = PubElVals.GetTagHt();
1216 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1217 LoadElementValue(tag->second);
1221 void gdcmHeader::PrintPubElVal(ostream & os) {
1222 PubElVals.Print(os);
1225 void gdcmHeader::PrintPubDict(ostream & os) {
1226 RefPubDict->Print(os);