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;
41 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error)
42 throw(gdcmFileError) {
43 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
44 filename = InFilename;
46 fp=fopen(InFilename,"rw");
47 if(exception_on_error) {
49 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
52 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
54 AddAndDefaultElements();
58 gdcmHeader::~gdcmHeader (void) {
63 void gdcmHeader::InitVRDict (void) {
65 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
69 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
70 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
71 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
72 (*vr)["CS"] = "Code String"; // At most 16 bytes
73 (*vr)["DA"] = "Date"; // Exactly 8 bytes
74 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
75 (*vr)["DT"] = "Date Time"; // At most 26 bytes
76 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
77 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
78 (*vr)["IS"] = "Integer String"; // At most 12 bytes
79 (*vr)["LO"] = "Long String"; // At most 64 chars
80 (*vr)["LT"] = "Long Text"; // At most 10240 chars
81 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
82 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
83 (*vr)["PN"] = "Person Name"; // At most 64 chars
84 (*vr)["SH"] = "Short String"; // At most 16 chars
85 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
86 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
87 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
88 (*vr)["ST"] = "Short Text"; // At most 1024 chars
89 (*vr)["TM"] = "Time"; // At most 16 bytes
90 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
91 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
92 (*vr)["UN"] = "Unknown"; // Any length of bytes
93 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
94 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
100 * \brief Discover what the swap code is (among little endian, big endian,
101 * bad little endian, bad big endian).
104 void gdcmHeader::CheckSwap()
106 // The only guaranted way of finding the swap code is to find a
107 // group tag since we know it's length has to be of four bytes i.e.
108 // 0x00000004. Finding the swap code in then straigthforward. Trouble
109 // occurs when we can't find such group...
111 guint32 x=4; // x : pour ntohs
112 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
116 char deb[HEADER_LENGTH_TO_READ];
118 // First, compare HostByteOrder and NetworkByteOrder in order to
119 // determine if we shall need to swap bytes (i.e. the Endian type).
125 // The easiest case is the one of a DICOM header, since it possesses a
126 // file preamble where it suffice to look for the string "DICM".
127 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
130 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
131 filetype = TrueDicom;
132 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
135 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
138 if(filetype == TrueDicom) {
139 // Next, determine the value representation (VR). Let's skip to the
140 // first element (0002, 0000) and check there if we find "UL", in
141 // which case we (almost) know it is explicit VR.
142 // WARNING: if it happens to be implicit VR then what we will read
143 // is the length of the group. If this ascii representation of this
144 // length happens to be "UL" then we shall believe it is explicit VR.
145 // FIXME: in order to fix the above warning, we could read the next
146 // element value (or a couple of elements values) in order to make
147 // sure we are not commiting a big mistake.
149 // * the 128 bytes of File Preamble (often padded with zeroes),
150 // * the 4 bytes of "DICM" string,
151 // * the 4 bytes of the first tag (0002, 0000),
152 // i.e. a total of 136 bytes.
154 if(memcmp(entCur, "UL", (size_t)2) == 0) {
155 filetype = ExplicitVR;
156 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
157 "explicit Value Representation");
159 filetype = ImplicitVR;
160 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
161 "not an explicit Value Representation");
166 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
167 "HostByteOrder != NetworkByteOrder");
170 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
171 "HostByteOrder = NetworkByteOrder");
174 // Position the file position indicator at first tag (i.e.
175 // after the file preamble and the "DICM" string).
177 fseek (fp, 132L, SEEK_SET);
179 } // End of TrueDicom
181 // Alas, this is not a DicomV3 file and whatever happens there is no file
182 // preamble. We can reset the file position indicator to where the data
183 // is (i.e. the beginning of the file).
186 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
187 // By clean we mean that the length of the first tag is written down.
188 // If this is the case and since the length of the first group HAS to be
189 // four (bytes), then determining the proper swap code is straightforward.
192 s = str2num(entCur, guint32);
212 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
213 "ACR/NEMA unfound swap info (time to raise bets)");
216 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
217 // It is time for despaired wild guesses. So, let's assume this file
218 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
219 // not present. Then the only info we have is the net2host one.
227 void gdcmHeader::SwitchSwapToBigEndian(void) {
228 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
229 "Switching to BigEndian mode.");
246 void gdcmHeader::GetPixels(size_t lgrTotale, void* _Pixels) {
248 pixelsOffset = GetPixelOffset();
249 fseek(fp, pixelsOffset, SEEK_SET);
250 fread(_Pixels, 1, lgrTotale, fp);
256 * \ingroup gdcmHeader
257 * \brief Find the value representation of the current tag.
259 * @param sw code swap
260 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
261 * la lecture est finie
262 * @param longueurLue pointeur sur longueur (en nombre d'octets)
264 * @return longueur retenue pour le champ
269 // --> C'etait la description de quoi, ca?
272 void gdcmHeader::FindVR( ElValue *ElVal) {
273 if (filetype != ExplicitVR)
279 long PositionOnEntry = ftell(fp);
280 // Warning: we believe this is explicit VR (Value Representation) because
281 // we used a heuristic that found "UL" in the first tag. Alas this
282 // doesn't guarantee that all the tags will be in explicit VR. In some
283 // cases (see e-film filtered files) one finds implicit VR tags mixed
284 // within an explicit VR file. Hence we make sure the present tag
285 // is in explicit VR and try to fix things if it happens not to be
287 bool RealExplicit = true;
289 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
293 // Assume we are reading a falsely explicit VR file i.e. we reached
294 // a tag where we expect reading a VR but are in fact we read the
295 // first to bytes of the length. Then we will interogate (through find)
296 // the dicom_vr dictionary with oddities like "\004\0" which crashes
297 // both GCC and VC++ implementations of the STL map. Hence when the
298 // expected VR read happens to be non-ascii characters we consider
299 // we hit falsely explicit VR tag.
301 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
302 RealExplicit = false;
304 // CLEANME searching the dicom_vr at each occurence is expensive.
305 // PostPone this test in an optional integrity check at the end
306 // of parsing or only in debug mode.
307 if ( RealExplicit && !dicom_vr->count(vr) )
308 RealExplicit = false;
310 if ( RealExplicit ) {
311 if ( ElVal->IsVrUnknown() ) {
312 // When not a dictionary entry, we can safely overwrite the vr.
316 if ( ElVal->GetVR() == vr ) {
317 // The vr we just read and the dictionary agree. Nothing to do.
320 // The vr present in the file and the dictionary disagree. We assume
321 // the file writer knew best and use the vr of the file. Since it would
322 // be unwise to overwrite the vr of a dictionary (since it would
323 // compromise it's next user), we need to clone the actual DictEntry
324 // and change the vr for the read one.
325 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
330 ElVal->SetDictEntry(NewTag);
334 // We thought this was explicit VR, but we end up with an
335 // implicit VR tag. Let's backtrack.
336 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
337 fseek(fp, PositionOnEntry, SEEK_SET);
338 // When this element is known in the dictionary we shall use, e.g. for
339 // the semantics (see the usage of IsAnInteger), the vr proposed by the
340 // dictionary entry. Still we have to flag the element as implicit since
341 // we know now our assumption on expliciteness is not furfilled.
343 if ( ElVal->IsVrUnknown() )
344 ElVal->SetVR("Implicit");
345 ElVal->SetImplicitVr();
349 * \ingroup gdcmHeader
350 * \brief Determines if the Transfer Syntax was allready encountered
351 * and if it corresponds to a ImplicitVRLittleEndian one.
353 * @return True when ImplicitVRLittleEndian found. False in all other cases.
355 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
356 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
359 LoadElementValueSafe(Element);
360 string Transfer = Element->GetValue();
361 if ( Transfer == "1.2.840.10008.1.2" )
367 * \ingroup gdcmHeader
368 * \brief Determines if the Transfer Syntax was allready encountered
369 * and if it corresponds to a ExplicitVRLittleEndian one.
371 * @return True when ExplicitVRLittleEndian found. False in all other cases.
373 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
374 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
377 LoadElementValueSafe(Element);
378 string Transfer = Element->GetValue();
379 if ( Transfer == "1.2.840.10008.1.2.1" )
385 * \ingroup gdcmHeader
386 * \brief Determines if the Transfer Syntax was allready encountered
387 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
389 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
391 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
392 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
395 LoadElementValueSafe(Element);
396 string Transfer = Element->GetValue();
397 if ( Transfer == "1.2.840.10008.1.2.1.99" )
404 * \ingroup gdcmHeader
405 * \brief Determines if the Transfer Syntax was allready encountered
406 * and if it corresponds to a Explicit VR Big Endian one.
408 * @return True when big endian found. False in all other cases.
410 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
411 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
414 LoadElementValueSafe(Element);
415 string Transfer = Element->GetValue();
416 if ( Transfer == "1.2.840.10008.1.2.2" )
423 * \ingroup gdcmHeader
424 * \brief Determines if the Transfer Syntax was allready encountered
425 * and if it corresponds to a JPEGBaseLineProcess1 one.
427 * @return True when JPEGBaseLineProcess1found. False in all other cases.
429 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
430 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
433 LoadElementValueSafe(Element);
434 string Transfer = Element->GetValue();
435 if ( Transfer == "1.2.840.10008.1.2.4.50" )
441 * \ingroup gdcmHeader
442 * \brief Determines if the Transfer Syntax was allready encountered
443 * and if it corresponds to a JPEGExtendedProcess2-4 one.
445 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
447 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
448 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
451 LoadElementValueSafe(Element);
452 string Transfer = Element->GetValue();
453 if ( Transfer == "1.2.840.10008.1.2.4.51" )
460 * \ingroup gdcmHeader
461 * \brief Determines if the Transfer Syntax was allready encountered
462 * and if it corresponds to a JPEGExtendeProcess3-5 one.
464 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
466 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
467 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
470 LoadElementValueSafe(Element);
471 string Transfer = Element->GetValue();
472 if ( Transfer == "1.2.840.10008.1.2.4.52" )
478 * \ingroup gdcmHeader
479 * \brief Determines if the Transfer Syntax was allready encountered
480 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
482 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
484 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
485 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
488 LoadElementValueSafe(Element);
489 string Transfer = Element->GetValue();
490 if ( Transfer == "1.2.840.10008.1.2.4.53" )
497 // Il y en a encore DIX-SEPT, comme ça.
498 // Il faudrait trouver qq chose + rusé ...
500 // --> probablement TOUS les supprimer (Eric dixit)
504 void gdcmHeader::FixFoundLength(ElValue * ElVal, guint32 FoundLength) {
505 // Heuristic: a final fix.
506 if ( FoundLength == 0xffffffff)
508 ElVal->SetLength(FoundLength);
511 guint32 gdcmHeader::FindLengthOB(void) {
512 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
515 long PositionOnEntry = ftell(fp);
516 bool FoundSequenceDelimiter = false;
517 guint32 TotalLength = 0;
520 while ( ! FoundSequenceDelimiter) {
525 TotalLength += 4; // We even have to decount the group and element
527 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
528 "wrong group for an item sequence.");
533 FoundSequenceDelimiter = true;
534 else if ( n != 0xe000) {
535 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
536 "wrong element for an item sequence.");
540 ItemLength = ReadInt32();
541 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
542 // the ItemLength with ReadInt32
543 SkipBytes(ItemLength);
545 fseek(fp, PositionOnEntry, SEEK_SET);
549 void gdcmHeader::FindLength(ElValue * ElVal) {
550 guint16 element = ElVal->GetElement();
551 string vr = ElVal->GetVR();
554 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
556 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
557 // The following reserved two bytes (see PS 3.5-2001, section
558 // 7.1.2 Data element structure with explicit vr p27) must be
559 // skipped before proceeding on reading the length on 4 bytes.
560 fseek(fp, 2L, SEEK_CUR);
561 guint32 length32 = ReadInt32();
562 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
563 ElVal->SetLength(FindLengthOB());
566 FixFoundLength(ElVal, length32);
570 // Length is encoded on 2 bytes.
571 length16 = ReadInt16();
573 // We can tell the current file is encoded in big endian (like
574 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
575 // and it's value is the one of the encoding of a big endian file.
576 // In order to deal with such big endian encoded files, we have
577 // (at least) two strategies:
578 // * when we load the "Transfer Syntax" tag with value of big endian
579 // encoding, we raise the proper flags. Then we wait for the end
580 // of the META group (0x0002) among which is "Transfer Syntax",
581 // before switching the swap code to big endian. We have to postpone
582 // the switching of the swap code since the META group is fully encoded
583 // in little endian, and big endian coding only starts at the next
584 // group. The corresponding code can be hard to analyse and adds
585 // many additional unnecessary tests for regular tags.
586 // * the second strategy consists in waiting for trouble, that shall appear
587 // when we find the first group with big endian encoding. This is
588 // easy to detect since the length of a "Group Length" tag (the
589 // ones with zero as element number) has to be of 4 (0x0004). When we
590 // encouter 1024 (0x0400) chances are the encoding changed and we
591 // found a group with big endian encoding.
592 // We shall use this second strategy. In order make sure that we
593 // can interpret the presence of an apparently big endian encoded
594 // length of a "Group Length" without committing a big mistake, we
595 // add an additional check: we look in the allready parsed elements
596 // for the presence of a "Transfer Syntax" whose value has to be "big
597 // endian encoding". When this is the case, chances are we got our
598 // hands on a big endian encoded file: we switch the swap code to
599 // big endian and proceed...
600 if ( (element == 0x000) && (length16 == 0x0400) ) {
601 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
602 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
607 SwitchSwapToBigEndian();
608 // Restore the unproperly loaded values i.e. the group, the element
609 // and the dictionary entry depending on them.
610 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
611 guint16 CorrectElem = SwapShort(ElVal->GetElement());
612 gdcmDictEntry * NewTag = GetDictEntryByKey(CorrectGroup, CorrectElem);
614 // This correct tag is not in the dictionary. Create a new one.
615 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
617 // FIXME this can create a memory leaks on the old entry that be
618 // left unreferenced.
619 ElVal->SetDictEntry(NewTag);
622 // Heuristic: well some files are really ill-formed.
623 if ( length16 == 0xffff) {
625 dbg.Verbose(0, "gdcmHeader::FindLength",
626 "Erroneous element length fixed.");
628 FixFoundLength(ElVal, (guint32)length16);
632 // Either implicit VR or a non DICOM conformal (see not below) explicit
633 // VR that ommited the VR of (at least) this element. Farts happen.
634 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
635 // on Data elements "Implicit and Explicit VR Data Elements shall
636 // not coexist in a Data Set and Data Sets nested within it".]
637 // Length is on 4 bytes.
638 FixFoundLength(ElVal, ReadInt32());
642 * \ingroup gdcmHeader
643 * \brief Swaps back the bytes of 4-byte long integer accordingly to
646 * @return The suggested integer.
648 guint32 gdcmHeader::SwapLong(guint32 a) {
649 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
654 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
655 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
659 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
663 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
666 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
673 * \ingroup gdcmHeader
674 * \brief Swaps the bytes so they agree with the processor order
675 * @return The properly swaped 16 bits integer.
677 guint16 gdcmHeader::SwapShort(guint16 a) {
678 if ( (sw==4321) || (sw==2143) )
679 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
683 void gdcmHeader::SkipBytes(guint32 NBytes) {
684 //FIXME don't dump the returned value
685 (void)fseek(fp, (long)NBytes, SEEK_CUR);
688 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
689 SkipBytes(ElVal->GetLength());
692 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
695 if ((guint32)NewSize >= (guint32)0xffffffff) {
696 MaxSizeLoadElementValue = 0xffffffff;
699 MaxSizeLoadElementValue = NewSize;
703 * \ingroup gdcmHeader
704 * \brief Loads the element if it's size is not to big.
705 * @param ElVal Element whose value shall be loaded.
706 * @param MaxSize Size treshold above which the element value is not
707 * loaded in memory. The element value is allways loaded
708 * when MaxSize is equal to UINT32_MAX.
711 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
713 guint16 group = ElVal->GetGroup();
714 guint16 elem = ElVal->GetElement();
715 string vr = ElVal->GetVR();
716 guint32 length = ElVal->GetLength();
717 bool SkipLoad = false;
719 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
721 // Sequences not treated yet !
723 // Ne faudrait-il pas au contraire trouver immediatement
724 // une maniere 'propre' de traiter les sequences (vr = SQ)
725 // car commencer par les ignorer risque de conduire a qq chose
726 // qui pourrait ne pas etre generalisable
731 // Heuristic : a sequence "contains" a set of tags (called items). It looks
732 // like the last tag of a sequence (the one that terminates the sequence)
733 // has a group of 0xfffe (with a dummy length).
734 if( group == 0xfffe )
737 // The group length doesn't represent data to be loaded in memory, since
738 // each element of the group shall be loaded individualy.
740 //SkipLoad = true; // modif sauvage JPR
741 // On charge la longueur du groupe
742 // quand l'element 0x0000 est présent !
745 // FIXME the following skip is not necessary
746 SkipElementValue(ElVal);
748 ElVal->SetValue("gdcm::Skipped");
752 // When the length is zero things are easy:
758 // Values bigger than specified are not loaded.
760 // En fait, c'est les elements dont la longueur est superieure
761 // a celle fixee qui ne sont pas charges
763 if (length > MaxSizeLoadElementValue) {
765 s << "gdcm::NotLoaded.";
766 s << " Address:" << (long)ElVal->GetOffset();
767 s << " Length:" << ElVal->GetLength();
768 //mesg += " Length:" + ElVal->GetLength();
769 ElVal->SetValue(s.str());
773 // When an integer is expected, read and convert the following two or
774 // four bytes properly i.e. as an integer as opposed to a string.
775 if ( IsAnInteger(ElVal) ) {
778 NewInt = ReadInt16();
779 } else if( length == 4 ) {
780 NewInt = ReadInt32();
782 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
784 //FIXME: make the following an util fonction
787 ElVal->SetValue(s.str());
791 // FIXME The exact size should be length if we move to strings or whatever
792 char* NewValue = (char*)malloc(length+1);
794 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
799 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
800 if ( item_read != 1 ) {
802 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
803 ElVal->SetValue("gdcm::UnRead");
806 ElVal->SetValue(NewValue);
810 * \ingroup gdcmHeader
811 * \brief Loads the element while preserving the current
812 * underlying file position indicator as opposed to
813 * to LoadElementValue that modifies it.
814 * @param ElVal Element whose value shall be loaded.
817 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
818 long PositionOnEntry = ftell(fp);
819 LoadElementValue(ElVal);
820 fseek(fp, PositionOnEntry, SEEK_SET);
824 guint16 gdcmHeader::ReadInt16(void) {
827 item_read = fread (&g, (size_t)2,(size_t)1, fp);
829 if ( item_read != 1 ) {
830 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File read error");
838 guint32 gdcmHeader::ReadInt32(void) {
841 item_read = fread (&g, (size_t)4,(size_t)1, fp);
843 if ( item_read != 1 ) {
844 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File read error");
853 * \ingroup gdcmHeader
854 * \brief Build a new Element Value from all the low level arguments.
855 * Check for existence of dictionary entry, and build
856 * a default one when absent.
857 * @param Group group of the underlying DictEntry
858 * @param Elem element of the underlying DictEntry
860 ElValue* gdcmHeader::NewElValueByKey(guint16 Group, guint16 Elem) {
861 // Find out if the tag we encountered is in the dictionaries:
862 gdcmDictEntry * NewTag = GetDictEntryByKey(Group, Elem);
864 NewTag = new gdcmDictEntry(Group, Elem);
866 ElValue* NewElVal = new ElValue(NewTag);
868 dbg.Verbose(1, "gdcmHeader::NewElValueByKey",
869 "failed to allocate ElValue");
876 * \ingroup gdcmHeader
877 * \brief Build a new Element Value from all the low level arguments.
878 * Check for existence of dictionary entry, and build
879 * a default one when absent.
880 * @param Name Name of the underlying DictEntry
882 ElValue* gdcmHeader::NewElValueByName(string Name) {
884 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
886 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
888 ElValue* NewElVal = new ElValue(NewTag);
890 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
891 "failed to allocate ElValue");
899 * \ingroup gdcmHeader
900 * \brief Read the next tag without loading it's value
901 * @return On succes the newly created ElValue, NULL on failure.
904 ElValue * gdcmHeader::ReadNextElement(void) {
912 // We reached the EOF (or an error occured) and header parsing
913 // has to be considered as finished.
916 NewElVal = NewElValueByKey(g, n);
918 FindLength(NewElVal);
922 NewElVal->SetOffset(ftell(fp));
926 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
927 guint16 group = ElVal->GetGroup();
928 guint16 element = ElVal->GetElement();
929 string vr = ElVal->GetVR();
930 guint32 length = ElVal->GetLength();
932 // When we have some semantics on the element we just read, and if we
933 // a priori know we are dealing with an integer, then we shall be
934 // able to swap it's element value properly.
935 if ( element == 0 ) { // This is the group length of the group
939 dbg.Error("gdcmHeader::IsAnInteger",
940 "Erroneous Group Length element length.");
943 if ( group % 2 != 0 )
944 // We only have some semantics on documented elements, which are
948 if ( (length != 4) && ( length != 2) )
949 // Swapping only make sense on integers which are 2 or 4 bytes long.
952 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
955 if ( (group == 0x0028) && (element == 0x0005) )
956 // The "Image Dimensions" tag is retained from ACR/NEMA and contains
957 // the number of dimensions of the contained object (1 for Signal,
958 // 2 for Image, 3 for Volume, 4 for Sequence).
961 if ( (group == 0x0028) && (element == 0x0200) )
962 // This tag is retained from ACR/NEMA
969 * \ingroup gdcmHeader
970 * \brief Recover the offset (from the beginning of the file) of the pixels.
972 size_t gdcmHeader::GetPixelOffset(void) {
973 // If this file complies with the norm we should encounter the
974 // "Image Location" tag (0x0028, 0x0200). This tag contains the
975 // the group that contains the pixel data (hence the "Pixel Data"
976 // is found by indirection through the "Image Location").
977 // Inside the group pointed by "Image Location" the searched element
978 // is conventionally the element 0x0010 (when the norm is respected).
979 // When the "Image Location" is absent we default to group 0x7fe0.
982 string ImageLocation = GetPubElValByName("Image Location");
983 if ( ImageLocation == "gdcm::Unfound" ) {
986 grPixel = (guint16) atoi( ImageLocation.c_str() );
988 if (grPixel != 0x7fe0)
989 // FIXME is this still necessary ?
990 // Now, this looks like an old dirty fix for Philips imager
994 ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
996 return PixelElement->GetOffset();
1002 * \ingroup gdcmHeader
1003 * \brief Searches both the public and the shadow dictionary (when they
1004 * exist) for the presence of the DictEntry with given
1005 * group and element. The public dictionary has precedence on the
1007 * @param group group of the searched DictEntry
1008 * @earam element element of the searched DictEntry
1009 * @return Corresponding DictEntry when it exists, NULL otherwise.
1011 gdcmDictEntry * gdcmHeader::GetDictEntryByKey(guint16 group, guint16 element) {
1012 gdcmDictEntry * found = (gdcmDictEntry*)0;
1013 if (!RefPubDict && !RefShaDict) {
1014 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1015 "we SHOULD have a default dictionary");
1018 found = RefPubDict->GetTagByKey(group, element);
1023 found = RefShaDict->GetTagByKey(group, element);
1031 * \ingroup gdcmHeader
1032 * \brief Searches both the public and the shadow dictionary (when they
1033 * exist) for the presence of the DictEntry with given name.
1034 * The public dictionary has precedence on the shadow one.
1035 * @earam Name name of the searched DictEntry
1036 * @return Corresponding DictEntry when it exists, NULL otherwise.
1038 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1039 gdcmDictEntry * found = (gdcmDictEntry*)0;
1040 if (!RefPubDict && !RefShaDict) {
1041 dbg.Verbose(0, "FIXME in gdcmHeader::GetDictEntry",
1042 "we SHOULD have a default dictionary");
1045 found = RefPubDict->GetTagByName(Name);
1050 found = RefShaDict->GetTagByName(Name);
1057 list<string> * gdcmHeader::GetPubTagNames(void) {
1058 list<string> * Result = new list<string>;
1059 TagKeyHT entries = RefPubDict->GetEntries();
1061 for (TagKeyHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1062 Result->push_back( tag->second->GetName() );
1067 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
1068 map<string, list<string> > * Result = new map<string, list<string> >;
1069 TagKeyHT entries = RefPubDict->GetEntries();
1071 for (TagKeyHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1072 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
1077 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1078 return PubElVals.GetElValueByNumber(group, element);
1081 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1082 ElValue* elem = PubElVals.GetElementByNumber(group, element);
1084 return "gdcm::Unfound";
1085 return elem->GetVR();
1088 string gdcmHeader::GetPubElValByName(string TagName) {
1089 return PubElVals.GetElValueByName(TagName);
1092 string gdcmHeader::GetPubElValRepByName(string TagName) {
1093 ElValue* elem = PubElVals.GetElementByName(TagName);
1095 return "gdcm::Unfound";
1096 return elem->GetVR();
1099 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1100 return ShaElVals.GetElValueByNumber(group, element);
1103 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1104 ElValue* elem = ShaElVals.GetElementByNumber(group, element);
1106 return "gdcm::Unfound";
1107 return elem->GetVR();
1110 string gdcmHeader::GetShaElValByName(string TagName) {
1111 return ShaElVals.GetElValueByName(TagName);
1114 string gdcmHeader::GetShaElValRepByName(string TagName) {
1115 ElValue* elem = ShaElVals.GetElementByName(TagName);
1117 return "gdcm::Unfound";
1118 return elem->GetVR();
1121 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1122 string pub = GetPubElValByNumber(group, element);
1125 return GetShaElValByNumber(group, element);
1128 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1129 string pub = GetPubElValRepByNumber(group, element);
1132 return GetShaElValRepByNumber(group, element);
1135 string gdcmHeader::GetElValByName(string TagName) {
1136 string pub = GetPubElValByName(TagName);
1139 return GetShaElValByName(TagName);
1142 string gdcmHeader::GetElValRepByName(string TagName) {
1143 string pub = GetPubElValRepByName(TagName);
1146 return GetShaElValRepByName(TagName);
1150 * \ingroup gdcmHeader
1151 * \brief Accesses an existing ElValue in the PubElVals of this instance
1152 * through it's (group, element) and modifies it's content with
1154 * @param content new value to substitute with
1155 * @param group group of the ElVal to modify
1156 * @param element element of the ElVal to modify
1158 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1161 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1162 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1163 return ( PubElVals.SetElValueByNumber (content, group, element) );
1167 * \ingroup gdcmHeader
1168 * \brief Accesses an existing ElValue in the PubElVals of this instance
1169 * through tag name and modifies it's content with the given value.
1170 * @param content new value to substitute with
1171 * @param TagName name of the tag to be modified
1173 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1174 //CLEANME TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1175 //CLEANME PubElVals.tagHt[key]->SetValue(content);
1176 return ( PubElVals.SetElValueByName (content, TagName) );
1180 * \ingroup gdcmHeader
1181 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1182 * through it's (group, element) and modifies it's content with
1184 * @param content new value to substitute with
1185 * @param group group of the ElVal to modify
1186 * @param element element of the ElVal to modify
1188 int gdcmHeader::SetShaElValByNumber(string content,
1189 guint16 group, guint16 element)
1191 return ( ShaElVals.SetElValueByNumber (content, group, element) );
1195 * \ingroup gdcmHeader
1196 * \brief Accesses an existing ElValue in the ShaElVals of this instance
1197 * through tag name and modifies it's content with the given value.
1198 * @param content new value to substitute with
1199 * @param TagName name of the tag to be modified
1201 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1202 return ( ShaElVals.SetElValueByName (content, TagName) );
1206 * \ingroup gdcmHeader
1207 * \brief Parses the header of the file but WITHOUT loading element values.
1209 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1210 ElValue * newElValue = (ElValue *)0;
1214 while ( (newElValue = ReadNextElement()) ) {
1215 SkipElementValue(newElValue);
1216 PubElVals.Add(newElValue);
1221 * \ingroup gdcmHeader
1222 * \brief Once the header is parsed add some gdcm convenience/helper elements
1223 * in the ElValSet. For example add:
1224 * - gdcmImageType which is an entry containing a short for the
1225 * type of image and whose value ranges in
1226 * I8 (unsigned 8 bit image)
1227 * I16 (unsigned 8 bit image)
1228 * IS16 (signed 8 bit image)
1229 * - gdcmXsize, gdcmYsize, gdcmZsize whose values are respectively
1230 * the ones of the official DICOM fields Rows, Columns and Planes.
1232 void gdcmHeader::AddAndDefaultElements(void) {
1233 ElValue* NewEntry = (ElValue*)0;
1235 NewEntry = NewElValueByName("gdcmXSize");
1236 NewEntry->SetValue(GetElValByName("Rows"));
1237 PubElVals.Add(NewEntry);
1239 NewEntry = NewElValueByName("gdcmYSize");
1240 NewEntry->SetValue(GetElValByName("Columns"));
1241 PubElVals.Add(NewEntry);
1243 NewEntry = NewElValueByName("gdcmZSize");
1244 NewEntry->SetValue(GetElValByName("Planes"));
1245 PubElVals.Add(NewEntry);
1249 * \ingroup gdcmHeader
1250 * \brief Loads the element values of all the elements present in the
1251 * public tag based hash table.
1253 void gdcmHeader::LoadElements(void) {
1255 TagElValueHT ht = PubElVals.GetTagHt();
1256 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1257 LoadElementValue(tag->second);
1261 void gdcmHeader::PrintPubElVal(ostream & os) {
1262 PubElVals.Print(os);
1265 void gdcmHeader::PrintPubDict(ostream & os) {
1266 RefPubDict->Print(os);