10 #include <netinet/in.h>
12 #include <cctype> // for isalpha
17 #define HEADER_LENGTH_TO_READ 256 // on ne lit plus que le debut
18 #define _MaxSizeLoadElementValue_ 1024 // longueur au dela de laquelle on ne charge plus les valeurs
20 //FIXME: this looks dirty to me...
22 #define str2num(str, typeNum) *((typeNum *)(str))
24 // str est un pointeur dans un tableau de caractères, qui doit contenir,
25 // à cet endroit la, la représentation binaire d'un entier (16 ou 32 bits)
26 // je veux récupérer ça ... dans un entier.
27 // s'il y a une autre solution, évitant des cast et les indirections,
30 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
31 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
33 void gdcmHeader::Initialise(void) {
34 if (!gdcmHeader::dicom_vr)
36 RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
37 RefShaDict = (gdcmDict*)0;
40 gdcmHeader::gdcmHeader (const char* InFilename) {
41 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
42 filename = InFilename;
44 fp=fopen(InFilename,"rw");
45 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
47 AddAndDefaultElements();
50 gdcmHeader::~gdcmHeader (void) {
55 void gdcmHeader::InitVRDict (void) {
57 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
61 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
62 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
63 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
64 (*vr)["CS"] = "Code String"; // At most 16 bytes
65 (*vr)["DA"] = "Date"; // Exactly 8 bytes
66 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
67 (*vr)["DT"] = "Date Time"; // At most 26 bytes
68 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
69 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
70 (*vr)["IS"] = "Integer String"; // At most 12 bytes
71 (*vr)["LO"] = "Long String"; // At most 64 chars
72 (*vr)["LT"] = "Long Text"; // At most 10240 chars
73 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
74 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
75 (*vr)["PN"] = "Person Name"; // At most 64 chars
76 (*vr)["SH"] = "Short String"; // At most 16 chars
77 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
78 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
79 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
80 (*vr)["ST"] = "Short Text"; // At most 1024 chars
81 (*vr)["TM"] = "Time"; // At most 16 bytes
82 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
83 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
84 (*vr)["UN"] = "Unknown"; // Any length of bytes
85 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
86 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
92 * \brief Discover what the swap code is (among little endian, big endian,
93 * bad little endian, bad big endian).
96 void gdcmHeader::CheckSwap()
98 // The only guaranted way of finding the swap code is to find a
99 // group tag since we know it's length has to be of four bytes i.e.
100 // 0x00000004. Finding the swap code in then straigthforward. Trouble
101 // occurs when we can't find such group...
103 guint32 x=4; // x : pour ntohs
104 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
108 char deb[HEADER_LENGTH_TO_READ];
110 // First, compare HostByteOrder and NetworkByteOrder in order to
111 // determine if we shall need to swap bytes (i.e. the Endian type).
117 // The easiest case is the one of a DICOM header, since it possesses a
118 // file preamble where it suffice to look for the string "DICM".
119 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
122 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
123 filetype = TrueDicom;
124 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
127 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
130 if(filetype == TrueDicom) {
131 // Next, determine the value representation (VR). Let's skip to the
132 // first element (0002, 0000) and check there if we find "UL", in
133 // which case we (almost) know it is explicit VR.
134 // WARNING: if it happens to be implicit VR then what we will read
135 // is the length of the group. If this ascii representation of this
136 // length happens to be "UL" then we shall believe it is explicit VR.
137 // FIXME: in order to fix the above warning, we could read the next
138 // element value (or a couple of elements values) in order to make
139 // sure we are not commiting a big mistake.
141 // * the 128 bytes of File Preamble (often padded with zeroes),
142 // * the 4 bytes of "DICM" string,
143 // * the 4 bytes of the first tag (0002, 0000),
144 // i.e. a total of 136 bytes.
146 if(memcmp(entCur, "UL", (size_t)2) == 0) {
147 filetype = ExplicitVR;
148 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
149 "explicit Value Representation");
151 filetype = ImplicitVR;
152 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
153 "not an explicit Value Representation");
158 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
159 "HostByteOrder != NetworkByteOrder");
162 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
163 "HostByteOrder = NetworkByteOrder");
166 // Position the file position indicator at first tag (i.e.
167 // after the file preamble and the "DICM" string).
169 fseek (fp, 132L, SEEK_SET);
171 } // End of TrueDicom
173 // Alas, this is not a DicomV3 file and whatever happens there is no file
174 // preamble. We can reset the file position indicator to where the data
175 // is (i.e. the beginning of the file).
178 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
179 // By clean we mean that the length of the first tag is written down.
180 // If this is the case and since the length of the first group HAS to be
181 // four (bytes), then determining the proper swap code is straightforward.
184 s = str2num(entCur, guint32);
204 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
205 "ACR/NEMA unfound swap info (time to raise bets)");
208 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
209 // It is time for despaired wild guesses. So, let's assume this file
210 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
211 // not present. Then the only info we have is the net2host one.
219 void gdcmHeader::SwitchSwapToBigEndian(void) {
220 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
221 "Switching to BigEndian mode.");
238 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
240 pixelsOffset = GetPixelOffset();
241 fseek(fp, pixelsOffset, SEEK_SET);
242 fread(_Pixels, 1, lgrTotale, fp);
248 * \ingroup gdcmHeader
249 * \brief Find the value representation of the current tag.
251 * @param sw code swap
252 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
253 * la lecture est finie
254 * @param longueurLue pointeur sur longueur (en nombre d'octets)
256 * @return longueur retenue pour le champ
261 // --> C'etait la description de quoi, ca?
264 void gdcmHeader::FindVR( ElValue *ElVal) {
265 if (filetype != ExplicitVR)
271 long PositionOnEntry = ftell(fp);
272 // Warning: we believe this is explicit VR (Value Representation) because
273 // we used a heuristic that found "UL" in the first tag. Alas this
274 // doesn't guarantee that all the tags will be in explicit VR. In some
275 // cases (see e-film filtered files) one finds implicit VR tags mixed
276 // within an explicit VR file. Hence we make sure the present tag
277 // is in explicit VR and try to fix things if it happens not to be
279 bool RealExplicit = true;
281 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
285 // Assume we are reading a falsely explicit VR file i.e. we reached
286 // a tag where we expect reading a VR but are in fact we read the
287 // first to bytes of the length. Then we will interogate (through find)
288 // the dicom_vr dictionary with oddities like "\004\0" which crashes
289 // both GCC and VC++ implementations of the STL map. Hence when the
290 // expected VR read happens to be non-ascii characters we consider
291 // we hit falsely explicit VR tag.
293 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
294 RealExplicit = false;
296 // CLEANME searching the dicom_vr at each occurence is expensive.
297 // PostPone this test in an optional integrity check at the end
298 // of parsing or only in debug mode.
299 if ( RealExplicit && !dicom_vr->count(vr) )
300 RealExplicit = false;
302 if ( RealExplicit ) {
303 if ( ElVal->IsVrUnknown() ) {
304 // When not a dictionary entry, we can safely overwrite the vr.
308 if ( ElVal->GetVR() == vr ) {
309 // The vr we just read and the dictionary agree. Nothing to do.
312 // The vr present in the file and the dictionary disagree. We assume
313 // the file writer knew best and use the vr of the file. Since it would
314 // be unwise to overwrite the vr of a dictionary (since it would
315 // compromise it's next user), we need to clone the actual DictEntry
316 // and change the vr for the read one.
317 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
322 ElVal->SetDictEntry(NewTag);
326 // We thought this was explicit VR, but we end up with an
327 // implicit VR tag. Let's backtrack.
328 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
329 fseek(fp, PositionOnEntry, SEEK_SET);
330 // When this element is known in the dictionary we shall use, e.g. for
331 // the semantics (see the usage of IsAnInteger), the vr proposed by the
332 // dictionary entry. Still we have to flag the element as implicit since
333 // we know now our assumption on expliciteness is not furfilled.
335 if ( ElVal->IsVrUnknown() )
336 ElVal->SetVR("Implicit");
337 ElVal->SetImplicitVr();
341 * \ingroup gdcmHeader
342 * \brief Determines if the Transfer Syntax was allready encountered
343 * and if it corresponds to a ImplicitVRLittleEndian one.
345 * @return True when ImplicitVRLittleEndian found. False in all other cases.
347 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
348 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
351 LoadElementValueSafe(Element);
352 string Transfer = Element->GetValue();
353 if ( Transfer == "1.2.840.10008.1.2" )
359 * \ingroup gdcmHeader
360 * \brief Determines if the Transfer Syntax was allready encountered
361 * and if it corresponds to a ExplicitVRLittleEndian one.
363 * @return True when ExplicitVRLittleEndian found. False in all other cases.
365 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
366 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
369 LoadElementValueSafe(Element);
370 string Transfer = Element->GetValue();
371 if ( Transfer == "1.2.840.10008.1.2.1" )
377 * \ingroup gdcmHeader
378 * \brief Determines if the Transfer Syntax was allready encountered
379 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
381 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
383 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
384 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
387 LoadElementValueSafe(Element);
388 string Transfer = Element->GetValue();
389 if ( Transfer == "1.2.840.10008.1.2.1.99" )
396 * \ingroup gdcmHeader
397 * \brief Determines if the Transfer Syntax was allready encountered
398 * and if it corresponds to a Explicit VR Big Endian one.
400 * @return True when big endian found. False in all other cases.
402 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
403 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
406 LoadElementValueSafe(Element);
407 string Transfer = Element->GetValue();
408 if ( Transfer == "1.2.840.10008.1.2.2" )
415 * \ingroup gdcmHeader
416 * \brief Determines if the Transfer Syntax was allready encountered
417 * and if it corresponds to a JPEGBaseLineProcess1 one.
419 * @return True when JPEGBaseLineProcess1found. False in all other cases.
421 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
422 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
425 LoadElementValueSafe(Element);
426 string Transfer = Element->GetValue();
427 if ( Transfer == "1.2.840.10008.1.2.4.50" )
433 * \ingroup gdcmHeader
434 * \brief Determines if the Transfer Syntax was allready encountered
435 * and if it corresponds to a JPEGExtendedProcess2-4 one.
437 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
439 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
440 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
443 LoadElementValueSafe(Element);
444 string Transfer = Element->GetValue();
445 if ( Transfer == "1.2.840.10008.1.2.4.51" )
452 * \ingroup gdcmHeader
453 * \brief Determines if the Transfer Syntax was allready encountered
454 * and if it corresponds to a JPEGExtendeProcess3-5 one.
456 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
458 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
459 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
462 LoadElementValueSafe(Element);
463 string Transfer = Element->GetValue();
464 if ( Transfer == "1.2.840.10008.1.2.4.52" )
470 * \ingroup gdcmHeader
471 * \brief Determines if the Transfer Syntax was allready encountered
472 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
474 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
476 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
477 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
480 LoadElementValueSafe(Element);
481 string Transfer = Element->GetValue();
482 if ( Transfer == "1.2.840.10008.1.2.4.53" )
489 // Il y en a encore DIX-SEPT, comme ça.
490 // Il faudrait trouver qq chose + rusé ...
492 // --> probablement TOUS les supprimer (Eric dixit)
496 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
497 // Heuristic: a final fix.
498 if ( FoundLength == 0xffffffff)
500 ElVal->SetLength(FoundLength);
503 guint32 gdcmHeader::FindLengthOB(void) {
504 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
507 long PositionOnEntry = ftell(fp);
508 bool FoundSequenceDelimiter = false;
509 guint32 TotalLength = 0;
512 while ( ! FoundSequenceDelimiter) {
517 TotalLength += 4; // We even have to decount the group and element
519 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
520 "wrong group for an item sequence.");
525 FoundSequenceDelimiter = true;
526 else if ( n != 0xe000) {
527 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
528 "wrong element for an item sequence.");
532 ItemLength = ReadInt32();
533 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
534 // the ItemLength with ReadInt32
535 SkipBytes(ItemLength);
537 fseek(fp, PositionOnEntry, SEEK_SET);
541 void gdcmHeader::FindLength(ElValue * ElVal) {
542 guint16 element = ElVal->GetElement();
543 string vr = ElVal->GetVR();
546 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
548 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
549 // The following reserved two bytes (see PS 3.5-2001, section
550 // 7.1.2 Data element structure with explicit vr p27) must be
551 // skipped before proceeding on reading the length on 4 bytes.
552 fseek(fp, 2L, SEEK_CUR);
553 guint32 length32 = ReadInt32();
554 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
555 ElVal->SetLength(FindLengthOB());
558 FixFoundLength(ElVal, length32);
562 // Length is encoded on 2 bytes.
563 length16 = ReadInt16();
565 // We can tell the current file is encoded in big endian (like
566 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
567 // and it's value is the one of the encoding of a big endian file.
568 // In order to deal with such big endian encoded files, we have
569 // (at least) two strategies:
570 // * when we load the "Transfer Syntax" tag with value of big endian
571 // encoding, we raise the proper flags. Then we wait for the end
572 // of the META group (0x0002) among which is "Transfer Syntax",
573 // before switching the swap code to big endian. We have to postpone
574 // the switching of the swap code since the META group is fully encoded
575 // in little endian, and big endian coding only starts at the next
576 // group. The corresponding code can be hard to analyse and adds
577 // many additional unnecessary tests for regular tags.
578 // * the second strategy consists in waiting for trouble, that shall appear
579 // when we find the first group with big endian encoding. This is
580 // easy to detect since the length of a "Group Length" tag (the
581 // ones with zero as element number) has to be of 4 (0x0004). When we
582 // encouter 1024 (0x0400) chances are the encoding changed and we
583 // found a group with big endian encoding.
584 // We shall use this second strategy. In order make sure that we
585 // can interpret the presence of an apparently big endian encoded
586 // length of a "Group Length" without committing a big mistake, we
587 // add an additional check: we look in the allready parsed elements
588 // for the presence of a "Transfer Syntax" whose value has to be "big
589 // endian encoding". When this is the case, chances are we got our
590 // hands on a big endian encoded file: we switch the swap code to
591 // big endian and proceed...
592 if ( (element == 0x000) && (length16 == 0x0400) ) {
593 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
594 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
599 SwitchSwapToBigEndian();
600 // Restore the unproperly loaded values i.e. the group, the element
601 // and the dictionary entry depending on them.
602 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
603 guint16 CorrectElem = SwapShort(ElVal->GetElement());
604 gdcmDictEntry * NewTag = GetDictEntryByKey(CorrectGroup, CorrectElem);
606 // This correct tag is not in the dictionary. Create a new one.
607 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
609 // FIXME this can create a memory leaks on the old entry that be
610 // left unreferenced.
611 ElVal->SetDictEntry(NewTag);
614 // Heuristic: well some files are really ill-formed.
615 if ( length16 == 0xffff) {
617 dbg.Verbose(0, "gdcmHeader::FindLength",
618 "Erroneous element length fixed.");
620 FixFoundLength(ElVal, (guint32)length16);
624 // Either implicit VR or a non DICOM conformal (see not below) explicit
625 // VR that ommited the VR of (at least) this element. Farts happen.
626 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
627 // on Data elements "Implicit and Explicit VR Data Elements shall
628 // not coexist in a Data Set and Data Sets nested within it".]
629 // Length is on 4 bytes.
630 FixFoundLength(ElVal, ReadInt32());
634 * \ingroup gdcmHeader
635 * \brief Swaps back the bytes of 4-byte long integer accordingly to
638 * @return The suggested integer.
640 guint32 gdcmHeader::SwapLong(guint32 a) {
641 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
646 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
647 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
651 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
655 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
658 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
665 * \ingroup gdcmHeader
666 * \brief Swaps the bytes so they agree with the processor order
667 * @return The properly swaped 16 bits integer.
669 guint16 gdcmHeader::SwapShort(guint16 a) {
670 if ( (sw==4321) || (sw==2143) )
671 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
675 void gdcmHeader::SkipBytes(guint32 NBytes) {
676 //FIXME don't dump the returned value
677 (void)fseek(fp, (long)NBytes, SEEK_CUR);
680 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
681 SkipBytes(ElVal->GetLength());
684 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
687 if ((guint32)NewSize >= (guint32)0xffffffff) {
688 MaxSizeLoadElementValue = 0xffffffff;
691 MaxSizeLoadElementValue = NewSize;
695 * \ingroup gdcmHeader
696 * \brief Loads the element if it's size is not to big.
697 * @param ElVal Element whose value shall be loaded.
698 * @param MaxSize Size treshold above which the element value is not
699 * loaded in memory. The element value is allways loaded
700 * when MaxSize is equal to UINT32_MAX.
703 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
705 guint16 group = ElVal->GetGroup();
706 guint16 elem = ElVal->GetElement();
707 string vr = ElVal->GetVR();
708 guint32 length = ElVal->GetLength();
709 bool SkipLoad = false;
711 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
713 // Sequences not treated yet !
715 // Ne faudrait-il pas au contraire trouver immediatement
716 // une maniere 'propre' de traiter les sequences (vr = SQ)
717 // car commencer par les ignorer risque de conduire a qq chose
718 // qui pourrait ne pas etre generalisable
723 // Heuristic : a sequence "contains" a set of tags (called items). It looks
724 // like the last tag of a sequence (the one that terminates the sequence)
725 // has a group of 0xfffe (with a dummy length).
726 if( group == 0xfffe )
729 // The group length doesn't represent data to be loaded in memory, since
730 // each element of the group shall be loaded individualy.
732 //SkipLoad = true; // modif sauvage JPR
733 // On charge la longueur du groupe
734 // quand l'element 0x0000 est présent !
737 // FIXME the following skip is not necessary
738 SkipElementValue(ElVal);
740 ElVal->SetValue("gdcm::Skipped");
744 // When the length is zero things are easy:
750 // Values bigger than specified are not loaded.
752 // En fait, c'est les elements dont la longueur est superieure
753 // a celle fixee qui ne sont pas charges
755 if (length > MaxSizeLoadElementValue) {
757 s << "gdcm::NotLoaded.";
758 s << " Address:" << (long)ElVal->GetOffset();
759 s << " Length:" << ElVal->GetLength();
760 //mesg += " Length:" + ElVal->GetLength();
761 ElVal->SetValue(s.str());
765 // When an integer is expected, read and convert the following two or
766 // four bytes properly i.e. as an integer as opposed to a string.
767 if ( IsAnInteger(ElVal) ) {
770 NewInt = ReadInt16();
771 } else if( length == 4 ) {
772 NewInt = ReadInt32();
774 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
776 //FIXME: make the following an util fonction
779 ElVal->SetValue(s.str());
783 // FIXME The exact size should be length if we move to strings or whatever
784 char* NewValue = (char*)malloc(length+1);
786 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
791 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
792 if ( item_read != 1 ) {
794 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
795 ElVal->SetValue("gdcm::UnRead");
798 ElVal->SetValue(NewValue);
802 * \ingroup gdcmHeader
803 * \brief Loads the element while preserving the current
804 * underlying file position indicator as opposed to
805 * to LoadElementValue that modifies it.
806 * @param ElVal Element whose value shall be loaded.
809 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
810 long PositionOnEntry = ftell(fp);
811 LoadElementValue(ElVal);
812 fseek(fp, PositionOnEntry, SEEK_SET);
816 guint16 gdcmHeader::ReadInt16(void) {
819 item_read = fread (&g, (size_t)2,(size_t)1, fp);
821 if ( item_read != 1 ) {
822 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
830 guint32 gdcmHeader::ReadInt32(void) {
833 item_read = fread (&g, (size_t)4,(size_t)1, fp);
835 if ( item_read != 1 ) {
836 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
845 * \ingroup gdcmHeader
846 * \brief Build a new Element Value from all the low level arguments.
847 * Check for existence of dictionary entry, and build
848 * a default one when absent.
849 * @param Group group of the underlying DictEntry
850 * @param Elem element of the underlying DictEntry
852 ElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
853 // Find out if the tag we encountered is in the dictionaries:
854 gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
856 NewTag = new gdcmDictEntry(Group, Elem);
858 ElValue* NewElVal = new ElValue(NewTag);
860 dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
861 "failed to allocate ElValue");
868 * \ingroup gdcmHeader
869 * \brief Build a new Element Value from all the low level arguments.
870 * Check for existence of dictionary entry, and build
871 * a default one when absent.
872 * @param Name Name of the underlying DictEntry
874 ElValue* gdcmHeader::NewElValueByName(string Name) {
876 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
878 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
880 ElValue* NewElVal = new ElValue(NewTag);
882 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
883 "failed to allocate ElValue");
891 * \ingroup gdcmHeader
892 * \brief Read the next tag without loading it's value
893 * @return On succes the newly created ElValue, NULL on failure.
896 ElValue * gdcmHeader::ReadNextElement(void) {
904 // We reached the EOF (or an error occured) and header parsing
905 // has to be considered as finished.
908 NewElVal = NewElValueByKey(g, n);
910 FindLength(NewElVal);
914 NewElVal->SetOffset(ftell(fp));
918 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
919 guint16 group = ElVal->GetGroup();
920 guint16 element = ElVal->GetElement();
921 string vr = ElVal->GetVR();
922 guint32 length = ElVal->GetLength();
924 // When we have some semantics on the element we just read, and if we
925 // a priori know we are dealing with an integer, then we shall be
926 // able to swap it's element value properly.
927 if ( element == 0 ) { // This is the group length of the group
931 dbg.Error("gdcmHeader::IsAnInteger",
932 "Erroneous Group Length element length.");
935 if ( group % 2 != 0 )
936 // We only have some semantics on documented elements, which are
940 if ( (length != 4) && ( length != 2) )
941 // Swapping only make sense on integers which are 2 or 4 bytes long.
944 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
947 if ( (group == 0x0028) && (element == 0x0005) )
948 // The "Image Dimensions" tag is retained from ACR/NEMA and contains
949 // the number of dimensions of the contained object (1 for Signal,
950 // 2 for Image, 3 for Volume, 4 for Sequence).
953 if ( (group == 0x0028) && (element == 0x0200) )
954 // This tag is retained from ACR/NEMA
961 * \ingroup gdcmHeader
962 * \brief Recover the offset (from the beginning of the file) of the pixels.
964 size_t gdcmHeader::GetPixelOffset(void) {
965 // If this file complies with the norm we should encounter the
966 // "Image Location" tag (0x0028, 0x0200). This tag contains the
967 // the group that contains the pixel data (hence the "Pixel Data"
968 // is found by indirection through the "Image Location").
969 // Inside the group pointed by "Image Location" the searched element
970 // is conventionally the element 0x0010 (when the norm is respected).
971 // When the "Image Location" is absent we default to group 0x7fe0.
974 string ImageLocation = GetPubElValByName("Image Location");
975 if ( ImageLocation == "gdcm::Unfound" ) {
978 grPixel = (guint16) atoi( ImageLocation.c_str() );
980 if (grPixel != 0x7fe0)
981 // FIXME is this still necessary ?
982 // Now, this looks like an old dirty fix for Philips imager
986 ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
988 return PixelElement->GetOffset();
994 * \ingroup gdcmHeader
995 * \brief Searches both the public and the shadow dictionary (when they
996 * exist) for the presence of the DictEntry with given
997 * group and element. The public dictionary has precedence on the
999 * @param group group of the searched DictEntry
1000 * @earam element element of the searched DictEntry
1001 * @return Corresponding DictEntry when it exists, NULL otherwise.
1003 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
1004 gdcmDictEntry * found = (gdcmDictEntry*)0;
1005 if (!RefPubDict && !RefShaDict) {
1006 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1007 "we SHOULD have a default dictionary");
1010 found = RefPubDict->GetTagByKey(group, element);
1015 found = RefShaDict->GetTagByKey(group, element);
1023 * \ingroup gdcmHeader
1024 * \brief Searches both the public and the shadow dictionary (when they
1025 * exist) for the presence of the DictEntry with given name.
1026 * The public dictionary has precedence on the shadow one.
1027 * @earam Name name of the searched DictEntry
1028 * @return Corresponding DictEntry when it exists, NULL otherwise.
1030 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1031 gdcmDictEntry * found = (gdcmDictEntry*)0;
1032 if (!RefPubDict && !RefShaDict) {
1033 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1034 "we SHOULD have a default dictionary");
1037 found = RefPubDict->GetTagByName(Name);
1042 found = RefShaDict->GetTagByName(Name);
1049 list<string> * gdcmHeader::GetPubTagNames(void) {
1050 list<string> * Result = new list<string>;
1051 TagKeyHT entries = RefPubDict->GetEntries();
1053 for (TagKeyHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1054 Result->push_back( tag->second->GetName() );
1059 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
1060 map<string, list<string> > * Result = new map<string, list<string> >;
1061 TagKeyHT entries = RefPubDict->GetEntries();
1063 for (TagKeyHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1064 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
1069 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1070 return PubElVals.GetElValueByNumber(group, element);
1073 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1074 ElValue* elem = PubElVals.GetElementByNumber(group, element);
1076 return "gdcm::Unfound";
1077 return elem->GetVR();
1080 string gdcmHeader::GetPubElValByName(string TagName) {
1081 return PubElVals.GetElValueByName(TagName);
1084 string gdcmHeader::GetPubElValRepByName(string TagName) {
1085 ElValue* elem = PubElVals.GetElementByName(TagName);
1087 return "gdcm::Unfound";
1088 return elem->GetVR();
1091 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1092 return ShaElVals.GetElValueByNumber(group, element);
1095 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1096 ElValue* elem = ShaElVals.GetElementByNumber(group, element);
1098 return "gdcm::Unfound";
1099 return elem->GetVR();
1102 string gdcmHeader::GetShaElValByName(string TagName) {
1103 return ShaElVals.GetElValueByName(TagName);
1106 string gdcmHeader::GetShaElValRepByName(string TagName) {
1107 ElValue* elem = ShaElVals.GetElementByName(TagName);
1109 return "gdcm::Unfound";
1110 return elem->GetVR();
1113 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1114 string pub = GetPubElValByNumber(group, element);
1117 return GetShaElValByNumber(group, element);
1120 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1121 string pub = GetPubElValRepByNumber(group, element);
1124 return GetShaElValRepByNumber(group, element);
1127 string gdcmHeader::GetElValByName(string TagName) {
1128 string pub = GetPubElValByName(TagName);
1131 return GetShaElValByName(TagName);
1134 string gdcmHeader::GetElValRepByName(string TagName) {
1135 string pub = GetPubElValRepByName(TagName);
1138 return GetShaElValRepByName(TagName);
1142 * \ingroup gdcmHeader
1143 * \brief Accesses an existing ElValue in the PubElVals of this instance
1144 * through it's (group, element) and modifies it's content with
1146 * @param content new value to substitute with
1147 * @param group group of the ElVal to modify
1148 * @param element element of the ElVal to modify
1150 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1153 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1154 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1155 return ( PubElVals.SetElValueByNumber (content, group, element) );
1159 * \ingroup gdcmHeader
1160 * \brief Accesses an existing ElValue in the PubElVals of this instance
1161 * through tag name and modifies it's content with the given value.
1162 * @param content new value to substitute with
1163 * @param TagName name of the tag to be modified
1165 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1166 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1167 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1168 return ( PubElVals.SetElValueByName (content, TagName) );
1172 * \ingroup gdcmHeader
1173 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1174 * through it's (group, element) and modifies it's content with
1176 * @param content new value to substitute with
1177 * @param group group of the ElVal to modify
1178 * @param element element of the ElVal to modify
1180 int gdcmHeader::SetShaElValByNumber(string content,
1181 guint16 group, guint16 element)
1183 return ( ShaElVals.SetElValueByNumber (content, group, element) );
1187 * \ingroup gdcmHeader
1188 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1189 * through tag name and modifies it's content with the given value.
1190 * @param content new value to substitute with
1191 * @param TagName name of the tag to be modified
1193 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1194 return ( ShaElVals.SetElValueByName (content, TagName) );
1198 * \ingroup gdcmHeader
1199 * \brief Parses the header of the file but WITHOUT loading element values.
1201 void gdcmHeader::ParseHeader(void) {
1202 ElValue * newElValue = (ElValue *)0;
1206 while ( (newElValue = ReadNextElement()) ) {
1207 SkipElementValue(newElValue);
1208 PubElVals.Add(newElValue);
1213 * \ingroup gdcmHeader
1214 * \brief Once the header is parsed add some gdcm convenience/helper elements
1215 * in the ElValSet. For example add:
1216 * - gdcmImageType which is an entry containing a short for the
1217 * type of image and whose value ranges in
1218 * I8 (unsigned 8 bit image)
1219 * I16 (unsigned 8 bit image)
1220 * IS16 (signed 8 bit image)
1221 * - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1222 * the ones of the official DICOM fields Rows, Columns and Planes.
1224 void gdcmHeader::AddAndDefaultElements(void) {
1225 ElValue* NewEntry = (ElValue*)0;
1227 NewEntry = NewElValueByName("gdcmXSize");
1228 NewEntry->SetValue(GetElValByName("Rows"));
1229 PubElVals.Add(NewEntry);
1231 NewEntry = NewElValueByName("gdcmYSize");
1232 NewEntry->SetValue(GetElValByName("Columns"));
1233 PubElVals.Add(NewEntry);
1235 NewEntry = NewElValueByName("gdcmZSize");
1236 NewEntry->SetValue(GetElValByName("Planes"));
1237 PubElVals.Add(NewEntry);
1241 * \ingroup gdcmHeader
1242 * \brief Loads the element values of all the elements present in the
1243 * public tag based hash table.
1245 void gdcmHeader::LoadElements(void) {
1247 TagElValueHT ht = PubElVals.GetTagHt();
1248 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1249 LoadElementValue(tag->second);
1253 void gdcmHeader::PrintPubElVal(ostream & os) {
1254 PubElVals.Print(os);
1257 void gdcmHeader::PrintPubDict(ostream & os) {
1258 RefPubDict->Print(os);