9 #include <netinet/in.h>
11 #include <cctype> // for isalpha
16 #define HEADER_LENGTH_TO_READ 256 // on ne lit plus que le debut
19 struct FileReadError {
20 FileReadError(FILE* fp, const char* Mesg) {
22 dbg.Verbose(1, "EOF encountered :", Mesg);
24 dbg.Verbose(1, "Error on reading :", Mesg);
29 //FIXME: this looks dirty to me...
30 #define str2num(str, typeNum) *((typeNum *)(str))
32 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
33 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
35 void gdcmHeader::Initialise(void) {
36 if (!gdcmHeader::dicom_vr)
38 RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
39 RefShaDict = (gdcmDict*)0;
42 gdcmHeader::gdcmHeader (const char* InFilename) {
43 SetMaxSizeLoadElementValue(1024);
44 filename = InFilename;
46 fp=fopen(InFilename,"rw");
47 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
51 gdcmHeader::~gdcmHeader (void) {
56 void gdcmHeader::InitVRDict (void) {
58 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
62 (*vr)["AE"] = "Application Entity"; // At most 16 bytes
63 (*vr)["AS"] = "Age String"; // Exactly 4 bytes
64 (*vr)["AT"] = "Attribute Tag"; // 2 16-bit unsigned short integers
65 (*vr)["CS"] = "Code String"; // At most 16 bytes
66 (*vr)["DA"] = "Date"; // Exactly 8 bytes
67 (*vr)["DS"] = "Decimal String"; // At most 16 bytes
68 (*vr)["DT"] = "Date Time"; // At most 26 bytes
69 (*vr)["FL"] = "Floating Point Single"; // 32-bit IEEE 754:1985 float
70 (*vr)["FD"] = "Floating Point Double"; // 64-bit IEEE 754:1985 double
71 (*vr)["IS"] = "Integer String"; // At most 12 bytes
72 (*vr)["LO"] = "Long String"; // At most 64 chars
73 (*vr)["LT"] = "Long Text"; // At most 10240 chars
74 (*vr)["OB"] = "Other Byte String"; // String of bytes (vr independant)
75 (*vr)["OW"] = "Other Word String"; // String of 16-bit words (vr dep)
76 (*vr)["PN"] = "Person Name"; // At most 64 chars
77 (*vr)["SH"] = "Short String"; // At most 16 chars
78 (*vr)["SL"] = "Signed Long"; // Exactly 4 bytes
79 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
80 (*vr)["SS"] = "Signed Short"; // Exactly 2 bytes
81 (*vr)["ST"] = "Short Text"; // At most 1024 chars
82 (*vr)["TM"] = "Time"; // At most 16 bytes
83 (*vr)["UI"] = "Unique Identifier"; // At most 64 bytes
84 (*vr)["UL"] = "Unsigned Long "; // Exactly 4 bytes
85 (*vr)["UN"] = "Unknown"; // Any length of bytes
86 (*vr)["US"] = "Unsigned Short "; // Exactly 2 bytes
87 (*vr)["UT"] = "Unlimited Text"; // At most 2^32 -1 chars
93 * \brief Discover what the swap code is (among little endian, big endian,
94 * bad little endian, bad big endian).
97 void gdcmHeader::CheckSwap()
99 // The only guaranted way of finding the swap code is to find a
100 // group tag since we know it's length has to be of four bytes i.e.
101 // 0x00000004. Finding the swap code in then straigthforward. Trouble
102 // occurs when we can't find such group...
104 guint32 x=4; // x : pour ntohs
105 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
109 char deb[HEADER_LENGTH_TO_READ];
111 // First, compare HostByteOrder and NetworkByteOrder in order to
112 // determine if we shall need to swap bytes (i.e. the Endian type).
118 // The easiest case is the one of a DICOM header, since it possesses a
119 // file preamble where it suffice to look for the sting "DICM".
120 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
123 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
124 filetype = TrueDicom;
125 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
128 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
131 if(filetype == TrueDicom) {
132 // Next, determine the value representation (VR). Let's skip to the
133 // first element (0002, 0000) and check there if we find "UL", in
134 // which case we (almost) know it is explicit VR.
135 // WARNING: if it happens to be implicit VR then what we will read
136 // is the length of the group. If this ascii representation of this
137 // length happens to be "UL" then we shall believe it is explicit VR.
138 // FIXME: in order to fix the above warning, we could read the next
139 // element value (or a couple of elements values) in order to make
140 // sure we are not commiting a big mistake.
142 // * the 128 bytes of File Preamble (often padded with zeroes),
143 // * the 4 bytes of "DICM" string,
144 // * the 4 bytes of the first tag (0002, 0000),
145 // i.e. a total of 136 bytes.
147 if(memcmp(entCur, "UL", (size_t)2) == 0) {
148 filetype = ExplicitVR;
149 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
150 "explicit Value Representation");
152 filetype = ImplicitVR;
153 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
154 "not an explicit Value Representation");
159 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
160 "HostByteOrder != NetworkByteOrder");
163 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
164 "HostByteOrder = NetworkByteOrder");
167 // Position the file position indicator at first tag (i.e.
168 // after the file preamble and the "DICM" string).
170 fseek (fp, 132L, SEEK_SET);
172 } // End of TrueDicom
174 // Alas, this is not a DicomV3 file and whatever happens there is no file
175 // preamble. We can reset the file position indicator to where the data
176 // is (i.e. the beginning of the file).
179 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
180 // By clean we mean that the length of the first tag is written down.
181 // If this is the case and since the length of the first group HAS to be
182 // four (bytes), then determining the proper swap code is straightforward.
185 s = str2num(entCur, guint32);
205 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
206 "ACR/NEMA unfound swap info (time to raise bets)");
209 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
210 // It is time for despaired wild guesses. So, let's assume this file
211 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
212 // not present. Then the only info we have is the net2host one.
220 void gdcmHeader::SwitchSwapToBigEndian(void) {
221 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
222 "Switching to BigEndian mode.");
239 void gdcmHeader::GetPixels(size_t lgrTotale, void* Pixels) {
241 pixelsOffset = GetPixelOffset();
242 fseek(fp, pixelsOffset, SEEK_SET);
243 fread(Pixels, 1, lgrTotale, fp);
249 * \ingroup gdcmHeader
250 * \brief Find the value representation of the current tag.
252 * @param sw code swap
253 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
254 * la lecture est finie
255 * @param longueurLue pointeur sur longueur (en nombre d'octets)
257 * @return longueur retenue pour le champ
262 // --> C'etait la description de quoi, ca?
265 void gdcmHeader::FindVR( ElValue *ElVal) {
266 if (filetype != ExplicitVR)
272 long PositionOnEntry = ftell(fp);
273 // Warning: we believe this is explicit VR (Value Representation) because
274 // we used a heuristic that found "UL" in the first tag. Alas this
275 // doesn't guarantee that all the tags will be in explicit VR. In some
276 // cases (see e-film filtered files) one finds implicit VR tags mixed
277 // within an explicit VR file. Hence we make sure the present tag
278 // is in explicit VR and try to fix things if it happens not to be
280 bool RealExplicit = true;
282 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
286 // Assume we are reading a falsely explicit VR file i.e. we reached
287 // a tag where we expect reading a VR but are in fact we read the
288 // first to bytes of the length. Then we will interogate (through find)
289 // the dicom_vr dictionary with oddities like "\004\0" which crashes
290 // both GCC and VC++ implementations of the STL map. Hence when the
291 // expected VR read happens to be non-ascii characters we consider
292 // we hit falsely explicit VR tag.
294 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
295 RealExplicit = false;
297 // CLEANME searching the dicom_vr at each occurence is expensive.
298 // PostPone this test in an optional integrity check at the end
299 // of parsing or only in debug mode.
300 if ( RealExplicit && !dicom_vr->count(vr) )
301 RealExplicit = false;
303 if ( RealExplicit ) {
304 if ( ElVal->IsVrUnknown() ) {
305 // When not a dictionary entry, we can safely overwrite the vr.
309 if ( ElVal->GetVR() == vr ) {
310 // The vr we just read and the dictionary agree. Nothing to do.
313 // The vr present in the file and the dictionary disagree. We assume
314 // the file writer knew best and use the vr of the file. Since it would
315 // be unwise to overwrite the vr of a dictionary (since it would
316 // compromise it's next user), we need to clone the actual DictEntry
317 // and change the vr for the read one.
318 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
323 ElVal->SetDictEntry(NewTag);
327 // We thought this was explicit VR, but we end up with an
328 // implicit VR tag. Let's backtrack.
329 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
330 fseek(fp, PositionOnEntry, SEEK_SET);
331 // When this element is known in the dictionary we shall use, e.g. for
332 // the semantics (see the usage of IsAnInteger), the vr proposed by the
333 // dictionary entry. Still we have to flag the element as implicit since
334 // we know now our assumption on expliciteness is not furfilled.
336 if ( ElVal->IsVrUnknown() )
337 ElVal->SetVR("Implicit");
338 ElVal->SetImplicitVr();
342 * \ingroup gdcmHeader
343 * \brief Determines if the Transfer Syntax was allready encountered
344 * and if it corresponds to a ImplicitVRLittleEndian one.
346 * @return True when ImplicitVRLittleEndian found. False in all other cases.
348 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
349 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
352 LoadElementValueSafe(Element);
353 string Transfer = Element->GetValue();
354 if ( Transfer == "1.2.840.10008.1.2" )
360 * \ingroup gdcmHeader
361 * \brief Determines if the Transfer Syntax was allready encountered
362 * and if it corresponds to a ExplicitVRLittleEndian one.
364 * @return True when ExplicitVRLittleEndian found. False in all other cases.
366 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
367 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
370 LoadElementValueSafe(Element);
371 string Transfer = Element->GetValue();
372 if ( Transfer == "1.2.840.10008.1.2.1" )
378 * \ingroup gdcmHeader
379 * \brief Determines if the Transfer Syntax was allready encountered
380 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
382 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
384 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
385 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
388 LoadElementValueSafe(Element);
389 string Transfer = Element->GetValue();
390 if ( Transfer == "1.2.840.10008.1.2.1.99" )
397 * \ingroup gdcmHeader
398 * \brief Determines if the Transfer Syntax was allready encountered
399 * and if it corresponds to a Explicit VR Big Endian one.
401 * @return True when big endian found. False in all other cases.
403 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
404 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
407 LoadElementValueSafe(Element);
408 string Transfer = Element->GetValue();
409 if ( Transfer == "1.2.840.10008.1.2.2" )
416 * \ingroup gdcmHeader
417 * \brief Determines if the Transfer Syntax was allready encountered
418 * and if it corresponds to a JPEGBaseLineProcess1 one.
420 * @return True when JPEGBaseLineProcess1found. False in all other cases.
422 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
423 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
426 LoadElementValueSafe(Element);
427 string Transfer = Element->GetValue();
428 if ( Transfer == "1.2.840.10008.1.2.4.50" )
434 * \ingroup gdcmHeader
435 * \brief Determines if the Transfer Syntax was allready encountered
436 * and if it corresponds to a JPEGExtendedProcess2-4 one.
438 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
440 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
441 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
444 LoadElementValueSafe(Element);
445 string Transfer = Element->GetValue();
446 if ( Transfer == "1.2.840.10008.1.2.4.51" )
453 * \ingroup gdcmHeader
454 * \brief Determines if the Transfer Syntax was allready encountered
455 * and if it corresponds to a JPEGExtendeProcess3-5 one.
457 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
459 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
460 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
463 LoadElementValueSafe(Element);
464 string Transfer = Element->GetValue();
465 if ( Transfer == "1.2.840.10008.1.2.4.52" )
471 * \ingroup gdcmHeader
472 * \brief Determines if the Transfer Syntax was allready encountered
473 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
475 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all other cases.
477 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
478 ElValue* Element = PubElVals.GetElementByNumber(0x0002, 0x0010);
481 LoadElementValueSafe(Element);
482 string Transfer = Element->GetValue();
483 if ( Transfer == "1.2.840.10008.1.2.4.53" )
490 // Il y en a encore DIX-SEPT, comme ça.
491 // Il faudrait trouver qq chose + rusé ...
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) {
514 TotalLength += 4; // We even have to decount the group and element
516 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
517 "wrong group for an item sequence.");
518 throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
521 FoundSequenceDelimiter = true;
522 else if ( n != 0xe000) {
523 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",
524 "wrong element for an item sequence.");
525 throw Error::FileReadError(fp, "gdcmHeader::FindLengthOB");
527 ItemLength = ReadInt32();
528 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
529 // the ItemLength with ReadInt32
530 SkipBytes(ItemLength);
532 fseek(fp, PositionOnEntry, SEEK_SET);
536 void gdcmHeader::FindLength(ElValue * ElVal) {
537 guint16 element = ElVal->GetElement();
538 string vr = ElVal->GetVR();
541 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
543 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
544 // The following reserved two bytes (see PS 3.5-2001, section
545 // 7.1.2 Data element structure with explicit vr p27) must be
546 // skipped before proceeding on reading the length on 4 bytes.
547 fseek(fp, 2L, SEEK_CUR);
548 guint32 length32 = ReadInt32();
549 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
550 ElVal->SetLength(FindLengthOB());
553 FixFoundLength(ElVal, length32);
557 // Length is encoded on 2 bytes.
558 length16 = ReadInt16();
560 // We can tell the current file is encoded in big endian (like
561 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
562 // and it's value is the one of the encoding of a big endian file.
563 // In order to deal with such big endian encoded files, we have
564 // (at least) two strategies:
565 // * when we load the "Transfer Syntax" tag with value of big endian
566 // encoding, we raise the proper flags. Then we wait for the end
567 // of the META group (0x0002) among which is "Transfer Syntax",
568 // before switching the swap code to big endian. We have to postpone
569 // the switching of the swap code since the META group is fully encoded
570 // in little endian, and big endian coding only starts at the next
571 // group. The corresponding code can be hard to analyse and adds
572 // many additional unnecessary tests for regular tags.
573 // * the second strategy consist in waiting for trouble, that shall appear
574 // when we find the first group with big endian encoding. This is
575 // easy to detect since the length of a "Group Length" tag (the
576 // ones with zero as element number) has to be of 4 (0x0004). When we
577 // encouter 1024 (0x0400) chances are the encoding changed and we
578 // found a group with big endian encoding.
579 // We shall use this second strategy. In order make sure that we
580 // can interpret the presence of an apparently big endian encoded
581 // length of a "Group Length" without committing a big mistake, we
582 // add an additional check: we look in the allready parsed elements
583 // for the presence of a "Transfer Syntax" whose value has to be "big
584 // endian encoding". When this is the case, chances are we got our
585 // hands on a big endian encoded file: we switch the swap code to
586 // big endian and proceed...
587 if ( (element == 0x000) && (length16 == 0x0400) ) {
588 if ( ! IsExplicitVRBigEndianTransferSyntax() )
589 throw Error::FileReadError(fp, "gdcmHeader::FindLength");
591 SwitchSwapToBigEndian();
592 // Restore the unproperly loaded values i.e. the group, the element
593 // and the dictionary entry depending on them.
594 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
595 guint16 CorrectElem = SwapShort(ElVal->GetElement());
596 gdcmDictEntry * NewTag = IsInDicts(CorrectGroup, CorrectElem);
598 // This correct tag is not in the dictionary. Create a new one.
599 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
601 // FIXME this can create a memory leaks on the old entry that be
602 // left unreferenced.
603 ElVal->SetDictEntry(NewTag);
606 // Heuristic: well some files are really ill-formed.
607 if ( length16 == 0xffff) {
609 dbg.Verbose(0, "gdcmHeader::FindLength",
610 "Erroneous element length fixed.");
612 FixFoundLength(ElVal, (guint32)length16);
616 // Either implicit VR or a non DICOM conformal (see not below) explicit
617 // VR that ommited the VR of (at least) this element. Farts happen.
618 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
619 // on Data elements "Implicit and Explicit VR Data Elements shall
620 // not coexist in a Data Set and Data Sets nested within it".]
621 // Length is on 4 bytes.
622 FixFoundLength(ElVal, ReadInt32());
626 * \ingroup gdcmHeader
627 * \brief Swaps back the bytes of 4-byte long integer accordingly to
630 * @return The suggested integer.
632 guint32 gdcmHeader::SwapLong(guint32 a) {
633 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
638 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
639 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
643 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
647 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
650 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
657 * \ingroup gdcmHeader
658 * \brief Swaps the bytes so they agree with the processor order
659 * @return The properly swaped 16 bits integer.
661 guint16 gdcmHeader::SwapShort(guint16 a) {
662 if ( (sw==4321) || (sw==2143) )
663 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
667 void gdcmHeader::SkipBytes(guint32 NBytes) {
668 //FIXME don't dump the returned value
669 (void)fseek(fp, (long)NBytes, SEEK_CUR);
672 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
673 SkipBytes(ElVal->GetLength());
676 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
679 if ((guint32)NewSize >= (guint32)0xffffffff) {
680 MaxSizeLoadElementValue = 0xffffffff;
683 MaxSizeLoadElementValue = NewSize;
687 * \ingroup gdcmHeader
688 * \brief Loads the element if it's size is not to big.
689 * @param ElVal Element whose value shall be loaded.
690 * @param MaxSize Size treshold above which the element value is not
691 * loaded in memory. The element value is allways loaded
692 * when MaxSize is equal to UINT32_MAX.
695 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
697 guint16 group = ElVal->GetGroup();
698 guint16 elem = ElVal->GetElement();
699 string vr = ElVal->GetVR();
700 guint32 length = ElVal->GetLength();
701 bool SkipLoad = false;
703 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
705 // Sequences not treated yet !
707 // Ne faudrait-il pas au contraire trouver immediatement
708 // une maniere 'propre' de traiter les sequences (vr = SQ)
709 // car commencer par les ignorer risque de conduire a qq chose
710 // qui pourrait ne pas etre generalisable
715 // Heuristic : a sequence "contains" a set of tags (called items). It looks
716 // like the last tag of a sequence (the one that terminates the sequence)
717 // has a group of 0xfffe (with a dummy length).
718 if( group == 0xfffe )
721 // The group length doesn't represent data to be loaded in memory, since
722 // each element of the group shall be loaded individualy.
727 // FIXME the following skip is not necessary
728 SkipElementValue(ElVal);
730 ElVal->SetValue("gdcm::Skipped");
734 // When the length is zero things are easy:
740 // Values bigger than specified are not loaded.
742 // En fait, c'est les elements dont la longueur est superieure
743 // a celle fixee qui ne sont pas charges
745 if (length > MaxSizeLoadElementValue) {
747 s << "gdcm::NotLoaded.";
748 s << " Address:" << (long)ElVal->GetOffset();
749 s << " Length:" << ElVal->GetLength();
750 //mesg += " Length:" + ElVal->GetLength();
751 ElVal->SetValue(s.str());
755 // When an integer is expected, read and convert the following two or
756 // four bytes properly i.e. as an integer as opposed to a string.
757 if ( IsAnInteger(ElVal) ) {
760 NewInt = ReadInt16();
761 } else if( length == 4 ) {
762 NewInt = ReadInt32();
764 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
766 //FIXME: make the following an util fonction
769 ElVal->SetValue(s.str());
773 // FIXME The exact size should be length if we move to strings or whatever
776 // QUESTION : y a-t-il une raison pour ne pas utiliser g_malloc ici ?
779 char* NewValue = (char*)malloc(length+1);
781 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
786 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
787 if ( item_read != 1 ) {
789 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
790 ElVal->SetValue("gdcm::UnRead");
793 ElVal->SetValue(NewValue);
797 * \ingroup gdcmHeader
798 * \brief Loads the element while preserving the current
799 * underlying file position indicator as opposed to
800 * to LoadElementValue that modifies it.
801 * @param ElVal Element whose value shall be loaded.
804 void gdcmHeader::LoadElementValueSafe(ElValue * ElVal) {
805 long PositionOnEntry = ftell(fp);
806 LoadElementValue(ElVal);
807 fseek(fp, PositionOnEntry, SEEK_SET);
811 guint16 gdcmHeader::ReadInt16(void) {
814 item_read = fread (&g, (size_t)2,(size_t)1, fp);
815 if ( item_read != 1 )
816 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
821 guint32 gdcmHeader::ReadInt32(void) {
824 item_read = fread (&g, (size_t)4,(size_t)1, fp);
825 if ( item_read != 1 )
826 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
832 * \ingroup gdcmHeader
833 * \brief Read the next tag without loading it's value
834 * @return On succes the newly created ElValue, NULL on failure.
837 ElValue * gdcmHeader::ReadNextElement(void) {
846 catch ( Error::FileReadError ) {
847 // We reached the EOF (or an error occured) and header parsing
848 // has to be considered as finished.
852 // Find out if the tag we encountered is in the dictionaries:
853 gdcmDictEntry * NewTag = IsInDicts(g, n);
855 NewTag = new gdcmDictEntry(g, n);
857 NewElVal = new ElValue(NewTag);
859 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
864 try { FindLength(NewElVal); }
865 catch ( Error::FileReadError ) { // Call it quits
868 NewElVal->SetOffset(ftell(fp));
872 bool gdcmHeader::IsAnInteger(ElValue * ElVal) {
873 guint16 group = ElVal->GetGroup();
874 guint16 element = ElVal->GetElement();
875 string vr = ElVal->GetVR();
876 guint32 length = ElVal->GetLength();
878 // When we have some semantics on the element we just read, and if we
879 // a priori know we are dealing with an integer, then we shall be
880 // able to swap it's element value properly.
881 if ( element == 0 ) { // This is the group length of the group
885 dbg.Error("gdcmHeader::IsAnInteger",
886 "Erroneous Group Length element length.");
889 if ( group % 2 != 0 )
890 // We only have some semantics on documented elements, which are
894 if ( (length != 4) && ( length != 2) )
895 // Swapping only make sense on integers which are 2 or 4 bytes long.
898 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
901 if ( (group == 0x0028) && (element == 0x0005) )
902 // This tag is retained from ACR/NEMA
903 // CHECKME Why should "Image Dimensions" be a single integer ?
905 // "Image Dimensions", c'est en fait le 'nombre de dimensions'
906 // de l'objet ACR-NEMA stocké
912 // DICOM V3 ne retient pas cette information
913 // Par defaut, tout est 'Image',
914 // C'est a l'utilisateur d'explorer l'ensemble des entetes
915 // pour savoir à quoi il a a faire
917 // Le Dicom Multiframe peut etre utilise pour stocker,
918 // dans un seul fichier, une serie temporelle (cardio vasculaire GE, p.ex)
919 // ou un volume (medecine Nucleaire, p.ex)
923 if ( (group == 0x0028) && (element == 0x0200) )
924 // This tag is retained from ACR/NEMA
931 * \ingroup gdcmHeader
932 * \brief Recover the offset (from the beginning of the file) of the pixels.
934 size_t gdcmHeader::GetPixelOffset(void) {
935 // If this file complies with the norm we should encounter the
936 // "Image Location" tag (0x0028, 0x0200). This tag contains the
937 // the group that contains the pixel data (hence the "Pixel Data"
938 // is found by indirection through the "Image Location").
939 // Inside the group pointed by "Image Location" the searched element
940 // is conventionally the element 0x0010 (when the norm is respected).
941 // When the "Image Location" is absent we default to group 0x7fe0.
944 string ImageLocation = GetPubElValByName("Image Location");
945 if ( ImageLocation == "UNFOUND" ) {
948 grPixel = (guint16) atoi( ImageLocation.c_str() );
950 if (grPixel != 0x7fe0)
951 // FIXME is this still necessary ?
952 // Now, this looks like an old dirty fix for Philips imager
956 ElValue* PixelElement = PubElVals.GetElementByNumber(grPixel, numPixel);
958 return PixelElement->GetOffset();
963 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
965 // Y a-t-il une raison de lui passer des guint32
966 // alors que group et element sont des guint16?
968 gdcmDictEntry * found = (gdcmDictEntry*)0;
969 if (!RefPubDict && !RefShaDict) {
970 //FIXME build a default dictionary !
971 printf("FIXME in gdcmHeader::IsInDicts\n");
974 found = RefPubDict->GetTag(group, element);
979 found = RefShaDict->GetTag(group, element);
986 list<string> * gdcmHeader::GetPubTagNames(void) {
987 list<string> * Result = new list<string>;
988 TagHT entries = RefPubDict->GetEntries();
990 for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
991 Result->push_back( tag->second->GetName() );
996 map<string, list<string> > * gdcmHeader::GetPubTagNamesByCategory(void) {
997 map<string, list<string> > * Result = new map<string, list<string> >;
998 TagHT entries = RefPubDict->GetEntries();
1000 for (TagHT::iterator tag = entries.begin(); tag != entries.end(); ++tag){
1001 (*Result)[tag->second->GetFourth()].push_back(tag->second->GetName());
1006 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1007 return PubElVals.GetElValueByNumber(group, element);
1010 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1011 ElValue* elem = PubElVals.GetElementByNumber(group, element);
1013 return "gdcm::Unfound";
1014 return elem->GetVR();
1017 string gdcmHeader::GetPubElValByName(string TagName) {
1018 return PubElVals.GetElValueByName(TagName);
1021 string gdcmHeader::GetPubElValRepByName(string TagName) {
1022 ElValue* elem = PubElVals.GetElementByName(TagName);
1024 return "gdcm::Unfound";
1025 return elem->GetVR();
1028 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1029 return ShaElVals.GetElValueByNumber(group, element);
1032 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1033 ElValue* elem = ShaElVals.GetElementByNumber(group, element);
1035 return "gdcm::Unfound";
1036 return elem->GetVR();
1039 string gdcmHeader::GetShaElValByName(string TagName) {
1040 return ShaElVals.GetElValueByName(TagName);
1043 string gdcmHeader::GetShaElValRepByName(string TagName) {
1044 ElValue* elem = ShaElVals.GetElementByName(TagName);
1046 return "gdcm::Unfound";
1047 return elem->GetVR();
1051 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1052 string pub = GetPubElValByNumber(group, element);
1055 return GetShaElValByNumber(group, element);
1058 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1059 string pub = GetPubElValRepByNumber(group, element);
1062 return GetShaElValRepByNumber(group, element);
1065 string gdcmHeader::GetElValByName(string TagName) {
1066 string pub = GetPubElValByName(TagName);
1069 return GetShaElValByName(TagName);
1072 string gdcmHeader::GetElValRepByName(string TagName) {
1073 string pub = GetPubElValRepByName(TagName);
1076 return GetShaElValRepByName(TagName);
1080 * \ingroup gdcmHeader
1081 * \brief Parses the header of the file but does NOT load element values.
1083 void gdcmHeader::ParseHeader(void) {
1084 ElValue * newElValue = (ElValue *)0;
1088 while ( (newElValue = ReadNextElement()) ) {
1089 SkipElementValue(newElValue);
1090 PubElVals.Add(newElValue);
1095 * \ingroup gdcmHeader
1096 * \brief Loads the element values of all the elements present in the
1097 * public tag based hash table.
1099 void gdcmHeader::LoadElements(void) {
1101 TagElValueHT ht = PubElVals.GetTagHt();
1102 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
1103 LoadElementValue(tag->second);
1106 void gdcmHeader::PrintPubElVal(ostream & os) {
1107 PubElVals.Print(os);
1110 void gdcmHeader::PrintPubDict(ostream & os) {
1111 RefPubDict->Print(os);