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);
49 gdcmHeader::~gdcmHeader (void) {
54 void gdcmHeader::InitVRDict (void) {
56 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
60 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
61 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
62 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
63 (*vr)["CS"] = "Code String"; // At most 16 bytes
64 (*vr)["DA"] = "Date"; // Exactly 8 bytes
65 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
66 (*vr)["DT"] = "Date Time"; // At most 26 bytes
67 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
68 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
69 (*vr)["IS"] = "Integer String"; // At most 12 bytes
70 (*vr)["LO"] = "Long String"; // At most 64 chars
71 (*vr)["LT"] = "Long Text"; // At most 10240 chars
72 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
73 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
74 (*vr)["PN"] = "Person Name"; // At most 64 chars
75 (*vr)["SH"] = "Short String"; // At most 16 chars
76 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
77 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
78 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
79 (*vr)["ST"] = "Short Text"; // At most 1024 chars
80 (*vr)["TM"] = "Time"; // At most 16 bytes
81 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
82 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
83 (*vr)["UN"] = "Unknown"; // Any length of bytes
84 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
85 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
91 * \brief Discover what the swap code is (among little endian, big endian,
92 * bad little endian, bad big endian).
95 void gdcmHeader::CheckSwap()
97 // The only guaranted way of finding the swap code is to find a
98 // group tag since we know it's length has to be of four bytes i.e.
99 // 0x00000004. Finding the swap code in then straigthforward. Trouble
100 // occurs when we can't find such group...
102 guint32 x=4; // x : pour ntohs
103 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
107 char deb[HEADER_LENGTH_TO_READ];
109 // First, compare HostByteOrder and NetworkByteOrder in order to
110 // determine if we shall need to swap bytes (i.e. the Endian type).
116 // The easiest case is the one of a DICOM header, since it possesses a
117 // file preamble where it suffice to look for the string "DICM".
118 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
121 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
122 filetype = TrueDicom;
123 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
126 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
129 if(filetype == TrueDicom) {
130 // Next, determine the value representation (VR). Let's skip to the
131 // first element (0002, 0000) and check there if we find "UL", in
132 // which case we (almost) know it is explicit VR.
133 // WARNING: if it happens to be implicit VR then what we will read
134 // is the length of the group. If this ascii representation of this
135 // length happens to be "UL" then we shall believe it is explicit VR.
136 // FIXME: in order to fix the above warning, we could read the next
137 // element value (or a couple of elements values) in order to make
138 // sure we are not commiting a big mistake.
140 // * the 128 bytes of File Preamble (often padded with zeroes),
141 // * the 4 bytes of "DICM" string,
142 // * the 4 bytes of the first tag (0002, 0000),
143 // i.e. a total of 136 bytes.
145 if(memcmp(entCur, "UL", (size_t)2) == 0) {
146 filetype = ExplicitVR;
147 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
148 "explicit Value Representation");
150 filetype = ImplicitVR;
151 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
152 "not an explicit Value Representation");
157 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
158 "HostByteOrder != NetworkByteOrder");
161 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
162 "HostByteOrder = NetworkByteOrder");
165 // Position the file position indicator at first tag (i.e.
166 // after the file preamble and the "DICM" string).
168 fseek (fp, 132L, SEEK_SET);
170 } // End of TrueDicom
172 // Alas, this is not a DicomV3 file and whatever happens there is no file
173 // preamble. We can reset the file position indicator to where the data
174 // is (i.e. the beginning of the file).
177 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
178 // By clean we mean that the length of the first tag is written down.
179 // If this is the case and since the length of the first group HAS to be
180 // four (bytes), then determining the proper swap code is straightforward.
183 s = str2num(entCur, guint32);
203 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
204 "ACR/NEMA unfound swap info (time to raise bets)");
207 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
208 // It is time for despaired wild guesses. So, let's assume this file
209 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
210 // not present. Then the only info we have is the net2host one.
218 void gdcmHeader::SwitchSwapToBigEndian(void) {
219 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
220 "Switching to BigEndian mode.");
237 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
239 pixelsOffset = GetPixelOffset();
240 fseek(fp, pixelsOffset, SEEK_SET);
241 fread(_Pixels, 1, lgrTotale, fp);
247 * \ingroup gdcmHeader
248 * \brief Find the value representation of the current tag.
250 * @param sw code swap
251 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
252 * la lecture est finie
253 * @param longueurLue pointeur sur longueur (en nombre d'octets)
255 * @return longueur retenue pour le champ
260 // --> C'etait la description de quoi, ca?
263 void gdcmHeader::FindVR( ElValue *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) )
299 RealExplicit = false;
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 ElValue* 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 ElValue* 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 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
386 LoadElementValueSafe(Element);
387 string Transfer = Element->GetValue();
388 if ( Transfer == "1.2.840.10008.1.2.1.99" )
395 * \ingroup gdcmHeader
396 * \brief Determines if the Transfer Syntax was allready encountered
397 * and if it corresponds to a Explicit VR Big Endian one.
399 * @return True when big endian found. False in all other cases.
401 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
402 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
405 LoadElementValueSafe(Element);
406 string Transfer = Element->GetValue();
407 if ( Transfer == "1.2.840.10008.1.2.2" )
414 * \ingroup gdcmHeader
415 * \brief Determines if the Transfer Syntax was allready encountered
416 * and if it corresponds to a JPEGBaseLineProcess1 one.
418 * @return True when JPEGBaseLineProcess1found. False in all other cases.
420 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
421 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
424 LoadElementValueSafe(Element);
425 string Transfer = Element->GetValue();
426 if ( Transfer == "1.2.840.10008.1.2.4.50" )
432 * \ingroup gdcmHeader
433 * \brief Determines if the Transfer Syntax was allready encountered
434 * and if it corresponds to a JPEGExtendedProcess2-4 one.
436 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
438 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
439 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
442 LoadElementValueSafe(Element);
443 string Transfer = Element->GetValue();
444 if ( Transfer == "1.2.840.10008.1.2.4.51" )
451 * \ingroup gdcmHeader
452 * \brief Determines if the Transfer Syntax was allready encountered
453 * and if it corresponds to a JPEGExtendeProcess3-5 one.
455 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
457 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
458 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
461 LoadElementValueSafe(Element);
462 string Transfer = Element->GetValue();
463 if ( Transfer == "1.2.840.10008.1.2.4.52" )
469 * \ingroup gdcmHeader
470 * \brief Determines if the Transfer Syntax was allready encountered
471 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
473 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
475 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
476 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
479 LoadElementValueSafe(Element);
480 string Transfer = Element->GetValue();
481 if ( Transfer == "1.2.840.10008.1.2.4.53" )
488 // Il y en a encore DIX-SEPT, comme ça.
489 // Il faudrait trouver qq chose + rusé ...
491 // --> probablement TOUS les supprimer (Eric dixit)
495 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
496 // Heuristic: a final fix.
497 if ( FoundLength == 0xffffffff)
499 ElVal->SetLength(FoundLength);
502 guint32 gdcmHeader::FindLengthOB(void) {
503 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
506 long PositionOnEntry = ftell(fp);
507 bool FoundSequenceDelimiter = false;
508 guint32 TotalLength = 0;
511 while ( ! FoundSequenceDelimiter) {
516 TotalLength += 4; // We even have to decount the group and element
518 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
519 "wrong group for an item sequence.");
524 FoundSequenceDelimiter = true;
525 else if ( n != 0xe000) {
526 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
527 "wrong element for an item sequence.");
531 ItemLength = ReadInt32();
532 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
533 // the ItemLength with ReadInt32
534 SkipBytes(ItemLength);
536 fseek(fp, PositionOnEntry, SEEK_SET);
540 void gdcmHeader::FindLength(ElValue * ElVal) {
541 guint16 element = ElVal->GetElement();
542 string vr = ElVal->GetVR();
545 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
547 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
548 // The following reserved two bytes (see PS 3.5-2001, section
549 // 7.1.2 Data element structure with explicit vr p27) must be
550 // skipped before proceeding on reading the length on 4 bytes.
551 fseek(fp, 2L, SEEK_CUR);
552 guint32 length32 = ReadInt32();
553 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
554 ElVal->SetLength(FindLengthOB());
557 FixFoundLength(ElVal, length32);
561 // Length is encoded on 2 bytes.
562 length16 = ReadInt16();
564 // We can tell the current file is encoded in big endian (like
565 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
566 // and it's value is the one of the encoding of a big endian file.
567 // In order to deal with such big endian encoded files, we have
568 // (at least) two strategies:
569 // * when we load the "Transfer Syntax" tag with value of big endian
570 // encoding, we raise the proper flags. Then we wait for the end
571 // of the META group (0x0002) among which is "Transfer Syntax",
572 // before switching the swap code to big endian. We have to postpone
573 // the switching of the swap code since the META group is fully encoded
574 // in little endian, and big endian coding only starts at the next
575 // group. The corresponding code can be hard to analyse and adds
576 // many additional unnecessary tests for regular tags.
577 // * the second strategy consists in waiting for trouble, that shall appear
578 // when we find the first group with big endian encoding. This is
579 // easy to detect since the length of a "Group Length" tag (the
580 // ones with zero as element number) has to be of 4 (0x0004). When we
581 // encouter 1024 (0x0400) chances are the encoding changed and we
582 // found a group with big endian encoding.
583 // We shall use this second strategy. In order make sure that we
584 // can interpret the presence of an apparently big endian encoded
585 // length of a "Group Length" without committing a big mistake, we
586 // add an additional check: we look in the allready parsed elements
587 // for the presence of a "Transfer Syntax" whose value has to be "big
588 // endian encoding". When this is the case, chances are we got our
589 // hands on a big endian encoded file: we switch the swap code to
590 // big endian and proceed...
591 if ( (element == 0x000) && (length16 == 0x0400) ) {
592 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
593 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
598 SwitchSwapToBigEndian();
599 // Restore the unproperly loaded values i.e. the group, the element
600 // and the dictionary entry depending on them.
601 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
602 guint16 CorrectElem = SwapShort(ElVal->GetElement());
603 gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
605 // This correct tag is not in the dictionary. Create a new one.
606 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
608 // FIXME this can create a memory leaks on the old entry that be
609 // left unreferenced.
610 ElVal->SetDictEntry(NewTag);
613 // Heuristic: well some files are really ill-formed.
614 if ( length16 == 0xffff) {
616 dbg.Verbose(0, "gdcmHeader::FindLength",
617 "Erroneous element length fixed.");
619 FixFoundLength(ElVal, (guint32)length16);
623 // Either implicit VR or a non DICOM conformal (see not below) explicit
624 // VR that ommited the VR of (at least) this element. Farts happen.
625 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
626 // on Data elements "Implicit and Explicit VR Data Elements shall
627 // not coexist in a Data Set and Data Sets nested within it".]
628 // Length is on 4 bytes.
629 FixFoundLength(ElVal, ReadInt32());
633 * \ingroup gdcmHeader
634 * \brief Swaps back the bytes of 4-byte long integer accordingly to
637 * @return The suggested integer.
639 guint32 gdcmHeader::SwapLong(guint32 a) {
640 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
645 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
646 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
650 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
654 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
657 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
664 * \ingroup gdcmHeader
665 * \brief Swaps the bytes so they agree with the processor order
666 * @return The properly swaped 16 bits integer.
668 guint16 gdcmHeader::SwapShort(guint16 a) {
669 if ( (sw==4321) || (sw==2143) )
670 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
674 void gdcmHeader::SkipBytes(guint32 NBytes) {
675 //FIXME don't dump the returned value
676 (void)fseek(fp, (long)NBytes, SEEK_CUR);
679 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
680 SkipBytes(ElVal->GetLength());
683 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
686 if ((guint32)NewSize >= (guint32)0xffffffff) {
687 MaxSizeLoadElementValue = 0xffffffff;
690 MaxSizeLoadElementValue = NewSize;
694 * \ingroup gdcmHeader
695 * \brief Loads the element if it's size is not to big.
696 * @param ElVal Element whose value shall be loaded.
697 * @param MaxSize Size treshold above which the element value is not
698 * loaded in memory. The element value is allways loaded
699 * when MaxSize is equal to UINT32_MAX.
702 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
704 guint16 group = ElVal->GetGroup();
705 guint16 elem = ElVal->GetElement();
706 string vr = ElVal->GetVR();
707 guint32 length = ElVal->GetLength();
708 bool SkipLoad = false;
710 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
712 // Sequences not treated yet !
714 // Ne faudrait-il pas au contraire trouver immediatement
715 // une maniere 'propre' de traiter les sequences (vr = SQ)
716 // car commencer par les ignorer risque de conduire a qq chose
717 // qui pourrait ne pas etre generalisable
722 // Heuristic : a sequence "contains" a set of tags (called items). It looks
723 // like the last tag of a sequence (the one that terminates the sequence)
724 // has a group of 0xfffe (with a dummy length).
725 if( group == 0xfffe )
728 // The group length doesn't represent data to be loaded in memory, since
729 // each element of the group shall be loaded individualy.
731 //SkipLoad = true; // modif sauvage JPR
732 // On charge la longueur du groupe
733 // quand l'element 0x0000 est présent !
736 // FIXME the following skip is not necessary
737 SkipElementValue(ElVal);
739 ElVal->SetValue("gdcm::Skipped");
743 // When the length is zero things are easy:
749 // Values bigger than specified are not loaded.
751 // En fait, c'est les elements dont la longueur est superieure
752 // a celle fixee qui ne sont pas charges
754 if (length > MaxSizeLoadElementValue) {
756 s << "gdcm::NotLoaded.";
757 s << " Address:" << (long)ElVal->GetOffset();
758 s << " Length:" << ElVal->GetLength();
759 //mesg += " Length:" + ElVal->GetLength();
760 ElVal->SetValue(s.str());
764 // When an integer is expected, read and convert the following two or
765 // four bytes properly i.e. as an integer as opposed to a string.
766 if ( IsAnInteger(ElVal) ) {
769 NewInt = ReadInt16();
770 } else if( length == 4 ) {
771 NewInt = ReadInt32();
773 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
775 //FIXME: make the following an util fonction
778 ElVal->SetValue(s.str());
782 // FIXME The exact size should be length if we move to strings or whatever
783 char* NewValue = (char*)malloc(length+1);
785 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
790 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
791 if ( item_read != 1 ) {
793 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
794 ElVal->SetValue("gdcm::UnRead");
797 ElVal->SetValue(NewValue);
801 * \ingroup gdcmHeader
802 * \brief Loads the element while preserving the current
803 * underlying file position indicator as opposed to
804 * to LoadElementValue that modifies it.
805 * @param ElVal Element whose value shall be loaded.
808 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
809 long PositionOnEntry = ftell(fp);
810 LoadElementValue(ElVal);
811 fseek(fp, PositionOnEntry, SEEK_SET);
815 guint16 gdcmHeader::ReadInt16(void) {
818 item_read = fread (&g, (size_t)2,(size_t)1, fp);
820 if ( item_read != 1 ) {
821 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
829 guint32 gdcmHeader::ReadInt32(void) {
832 item_read = fread (&g, (size_t)4,(size_t)1, fp);
834 if ( item_read != 1 ) {
835 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
844 * \ingroup gdcmHeader
845 * \brief Read the next tag without loading it's value
846 * @return On succes the newly created ElValue, NULL on failure.
849 ElValue * gdcmHeader::ReadNextElement(void) {
857 // We reached the EOF (or an error occured) and header parsing
858 // has to be considered as finished.
861 // Find out if the tag we encountered is in the dictionaries:
862 gdcmDictEntry * NewTag = IsInDicts(g, n);
864 NewTag = new gdcmDictEntry(g, n);
866 NewElVal = new ElValue(NewTag);
868 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
873 FindLength(NewElVal);
877 NewElVal->SetOffset(ftell(fp));
881 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
882 guint16 group = ElVal->GetGroup();
883 guint16 element = ElVal->GetElement();
884 string vr = ElVal->GetVR();
885 guint32 length = ElVal->GetLength();
887 // When we have some semantics on the element we just read, and if we
888 // a priori know we are dealing with an integer, then we shall be
889 // able to swap it's element value properly.
890 if ( element == 0 ) { // This is the group length of the group
894 dbg.Error("gdcmHeader::IsAnInteger",
895 "Erroneous Group Length element length.");
898 if ( group % 2 != 0 )
899 // We only have some semantics on documented elements, which are
903 if ( (length != 4) && ( length != 2) )
904 // Swapping only make sense on integers which are 2 or 4 bytes long.
907 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
910 if ( (group == 0x0028) && (element == 0x0005) )
911 // This tag is retained from ACR/NEMA
912 // CHECKME Why should "Image Dimensions" be a single integer ?
914 // "Image Dimensions", c'est en fait le 'nombre de dimensions'
915 // de l'objet ACR-NEMA stocké
921 // DICOM V3 ne retient pas cette information
922 // Par defaut, tout est 'Image',
923 // C'est a l'utilisateur d'explorer l'ensemble des entetes
924 // pour savoir à quoi il a a faire
926 // Le Dicom Multiframe peut etre utilise pour stocker,
927 // dans un seul fichier, une serie temporelle (cardio vasculaire GE, p.ex)
928 // ou un volume (medecine Nucleaire, p.ex)
932 if ( (group == 0x0028) && (element == 0x0200) )
933 // This tag is retained from ACR/NEMA
940 * \ingroup gdcmHeader
941 * \brief Recover the offset (from the beginning of the file) of the pixels.
943 size_t gdcmHeader::GetPixelOffset(void) {
944 // If this file complies with the norm we should encounter the
945 // "Image Location" tag (0x0028, 0x0200). This tag contains the
946 // the group that contains the pixel data (hence the "Pixel Data"
947 // is found by indirection through the "Image Location").
948 // Inside the group pointed by "Image Location" the searched element
949 // is conventionally the element 0x0010 (when the norm is respected).
950 // When the "Image Location" is absent we default to group 0x7fe0.
953 string ImageLocation = GetPubElValByName("Image Location");
954 if ( ImageLocation == "gdcm::Unfound" ) {
957 grPixel = (guint16) atoi( ImageLocation.c_str() );
959 if (grPixel != 0x7fe0)
960 // FIXME is this still necessary ?
961 // Now, this looks like an old dirty fix for Philips imager
965 ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
967 return PixelElement->GetOffset();
972 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
974 // Y a-t-il une raison de lui passer des guint32
975 // alors que group et element sont des guint16?
977 gdcmDictEntry * found = (gdcmDictEntry*)0;
978 if (!RefPubDict && !RefShaDict) {
979 //FIXME build a default dictionary !
980 printf("FIXME in gdcmHeader::IsInDicts\n");
983 found = RefPubDict->GetTag(group, element);
988 found = RefShaDict->GetTag(group, element);
995 list<string> * gdcmHeader::GetPubTagNames(void) {
996 list<string> * Result = new list<string>;
997 TagHT entries = RefPubDict->GetEntries();
999 for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1000 Result->push_back( tag->second->GetName() );
1005 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
1006 map<string, list<string> > * Result = new map<string, list<string> >;
1007 TagHT entries = RefPubDict->GetEntries();
1009 for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1010 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
1015 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1016 return PubElVals.GetElValueByNumber(group, element);
1019 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1020 ElValue* elem = PubElVals.GetElementByNumber(group, element);
1022 return "gdcm::Unfound";
1023 return elem->GetVR();
1026 string gdcmHeader::GetPubElValByName(string TagName) {
1027 return PubElVals.GetElValueByName(TagName);
1030 string gdcmHeader::GetPubElValRepByName(string TagName) {
1031 ElValue* elem = PubElVals.GetElementByName(TagName);
1033 return "gdcm::Unfound";
1034 return elem->GetVR();
1037 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1038 return ShaElVals.GetElValueByNumber(group, element);
1041 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1042 ElValue* elem = ShaElVals.GetElementByNumber(group, element);
1044 return "gdcm::Unfound";
1045 return elem->GetVR();
1048 string gdcmHeader::GetShaElValByName(string TagName) {
1049 return ShaElVals.GetElValueByName(TagName);
1052 string gdcmHeader::GetShaElValRepByName(string TagName) {
1053 ElValue* elem = ShaElVals.GetElementByName(TagName);
1055 return "gdcm::Unfound";
1056 return elem->GetVR();
1060 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1061 string pub = GetPubElValByNumber(group, element);
1064 return GetShaElValByNumber(group, element);
1067 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1068 string pub = GetPubElValRepByNumber(group, element);
1071 return GetShaElValRepByNumber(group, element);
1074 string gdcmHeader::GetElValByName(string TagName) {
1075 string pub = GetPubElValByName(TagName);
1078 return GetShaElValByName(TagName);
1081 string gdcmHeader::GetElValRepByName(string TagName) {
1082 string pub = GetPubElValRepByName(TagName);
1085 return GetShaElValRepByName(TagName);
1089 * \ingroup gdcmHeader
1090 * \brief Modifie la valeur d'un ElValue déja existant
1091 * \ dans le PubElVals du gdcmHeader,
1092 * \ accédé par ses numero de groupe et d'element.
1094 int gdcmHeader::SetPubElValByNumber(string content, guint16 group, guint16 element) {
1095 //TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1096 //PubElVals.tagHt[key]->SetValue(content);
1098 return ( PubElVals.SetElValueByNumber (content, group, element) );
1103 * \ingroup gdcmHeader
1104 * \brief Modifie la valeur d'un ElValue déja existant
1105 * \ dans le PubElVals du gdcmHeader,
1106 * \ accédé par son nom
1108 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1109 //TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1110 //PubElVals.tagHt[key]->SetValue(content);
1112 return ( PubElVals.SetElValueByName (content, TagName) );
1117 * \ingroup gdcmHeader
1118 * \brief Modifie la valeur d'un ElValue déja existant
1119 * \ dans le ShaElVals du gdcmHeader,
1120 * \ accédé par ses numero de groupe et d'element.
1122 int gdcmHeader::SetShaElValByNumber(string content, guint16 group, guint16 element) {
1124 return ( ShaElVals.SetElValueByNumber (content, group, element) );
1129 * \ingroup gdcmHeader
1130 * \brief Modifie la valeur d'un ElValue déja existant
1131 * \ dans le ShaElVals du gdcmHeader,
1132 * \ accédé par son nom
1134 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1136 return ( ShaElVals.SetElValueByName (content, TagName) );
1139 * \ingroup gdcmHeader
1140 * \brief Parses the header of the file but does NOT load element values.
1142 void gdcmHeader::ParseHeader(void) {
1143 ElValue * newElValue = (ElValue *)0;
1147 while ( (newElValue = ReadNextElement()) ) {
1148 SkipElementValue(newElValue);
1149 PubElVals.Add(newElValue);
1154 * \ingroup gdcmHeader
1155 * \brief Loads the element values of all the elements present in the
1156 * public tag based hash table.
1158 void gdcmHeader::LoadElements(void) {
1162 TagElValueHT ht = PubElVals.GetTagHt();
1164 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1165 LoadElementValue(tag->second);
1169 void gdcmHeader::PrintPubElVal(ostream & os) {
1170 PubElVals.Print(os);
1173 void gdcmHeader::PrintPubDict(ostream & os) {
1174 RefPubDict->Print(os);