1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/17 13:11:16 $
7 Version: $Revision: 1.81 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.htm for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
34 #include <netinet/in.h>
39 // Implicit VR Little Endian
40 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
41 // Explicit VR Little Endian
42 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
43 // Deflated Explicit VR Little Endian
44 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
45 // Explicit VR Big Endian
46 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
47 // JPEG Baseline (Process 1)
48 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
49 // JPEG Extended (Process 2 & 4)
50 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
51 // JPEG Extended (Process 3 & 5)
52 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
53 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
54 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
55 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
56 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
57 // JPEG Lossless, Non-Hierarchical (Process 14)
58 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
59 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
60 // [Selection Value 1])
61 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
63 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
65 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
67 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
68 // UI1_1_2_840_10008_1_2_5
69 #define str2num(str, typeNum) *((typeNum *)(str))
71 //-----------------------------------------------------------------------------
72 // Refer to gdcmDocument::CheckSwap()
73 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
75 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
76 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
77 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
79 //-----------------------------------------------------------------------------
80 // Constructor / Destructor
84 * @param filename file to be opened for parsing
86 gdcmDocument::gdcmDocument( std::string const & filename )
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 fseek(Fp,0L,SEEK_END);
103 long lgt = ftell(Fp);
107 long beg = ftell(Fp);
110 (void)ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
114 // Load 'non string' values
116 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
117 if( PhotometricInterpretation == "PALETTE COLOR " )
119 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
120 /// FIXME FIXME FIXME
121 /// The tags refered by the three following lines used to be CORRECTLY
122 /// defined as having an US Value Representation in the public
123 /// dictionnary. BUT the semantics implied by the three following
124 /// lines state that the corresponding tag contents are in fact
125 /// the ones of a gdcmBinEntry.
126 /// In order to fix things "Quick and Dirty" the dictionnary was
127 /// altered on PURPOUS but now contains a WRONG value.
128 /// In order to fix things and restore the dictionary to its
129 /// correct value, one needs to decided of the semantics by deciding
130 /// wether the following tags are either:
131 /// - multivaluated US, and hence loaded as gdcmValEntry, but afterwards
132 /// also used as gdcmBinEntry, which requires the proper conversion,
133 /// - OW, and hence loaded as gdcmBinEntry, but afterwards also used
134 /// as gdcmValEntry, which requires the proper conversion.
135 LoadEntryVoidArea(0x0028,0x1201); // R LUT
136 LoadEntryVoidArea(0x0028,0x1202); // G LUT
137 LoadEntryVoidArea(0x0028,0x1203); // B LUT
139 // Segmented Red Palette Color LUT Data
140 LoadEntryVoidArea(0x0028,0x1221);
141 // Segmented Green Palette Color LUT Data
142 LoadEntryVoidArea(0x0028,0x1222);
143 // Segmented Blue Palette Color LUT Data
144 LoadEntryVoidArea(0x0028,0x1223);
146 //FIXME later : how to use it?
147 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
151 // --------------------------------------------------------------
152 // Specific code to allow gdcm to read ACR-LibIDO formated images
153 // Note: ACR-LibIDO is an extension of the ACR standard that was
154 // used at CREATIS. For the time being (say a couple years)
155 // we keep this kludge to allow a smooth move to gdcm for
156 // CREATIS developpers (sorry folks).
158 // if recognition code tells us we deal with a LibIDO image
159 // we switch lineNumber and columnNumber
162 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
163 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
164 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
165 // with "little-endian strings"
167 Filetype = gdcmACR_LIBIDO;
168 std::string rows = GetEntryByNumber(0x0028, 0x0010);
169 std::string columns = GetEntryByNumber(0x0028, 0x0011);
170 SetEntryByNumber(columns, 0x0028, 0x0010);
171 SetEntryByNumber(rows , 0x0028, 0x0011);
173 // ----------------- End of ACR-LibIDO kludge ------------------
175 PrintLevel = 1; // 'Medium' print level by default
179 * \brief This default constructor doesn't parse the file. You should
180 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
182 gdcmDocument::gdcmDocument()
185 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
187 PrintLevel = 1; // 'Medium' print level by default
191 * \brief Canonical destructor.
193 gdcmDocument::~gdcmDocument ()
198 // Recursive clean up of sequences
199 for (TagDocEntryHT::const_iterator it = TagHT.begin();
200 it != TagHT.end(); ++it )
202 //delete it->second; //temp remove
207 //-----------------------------------------------------------------------------
211 * \brief Prints The Dict Entries of THE public Dicom Dictionary
214 void gdcmDocument::PrintPubDict(std::ostream & os)
216 RefPubDict->Print(os);
220 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
223 void gdcmDocument::PrintShaDict(std::ostream & os)
225 RefShaDict->Print(os);
228 //-----------------------------------------------------------------------------
231 * \brief Get the public dictionary used
233 gdcmDict *gdcmDocument::GetPubDict()
239 * \brief Get the shadow dictionary used
241 gdcmDict *gdcmDocument::GetShaDict()
247 * \brief Set the shadow dictionary used
248 * \param dict dictionary to use in shadow
250 bool gdcmDocument::SetShaDict(gdcmDict *dict)
257 * \brief Set the shadow dictionary used
258 * \param dictName name of the dictionary to use in shadow
260 bool gdcmDocument::SetShaDict(DictKey const & dictName)
262 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
267 * \brief This predicate, based on hopefully reasonable heuristics,
268 * decides whether or not the current gdcmDocument was properly parsed
269 * and contains the mandatory information for being considered as
270 * a well formed and usable Dicom/Acr File.
271 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
274 bool gdcmDocument::IsReadable()
276 if( Filetype == gdcmUnknown)
278 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
284 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
294 * \brief Internal function that checks whether the Transfer Syntax given
295 * as argument is the one present in the current document.
296 * @param syntaxToCheck The transfert syntax we need to check against.
297 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
298 * the current document. False either when the document contains
299 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
301 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
303 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
309 // The entry might be present but not loaded (parsing and loading
310 // happen at different stages): try loading and proceed with check...
311 LoadDocEntrySafe(entry);
312 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
314 std::string transfer = valEntry->GetValue();
315 // The actual transfer (as read from disk) might be padded. We
316 // first need to remove the potential padding. We can make the
317 // weak assumption that padding was not executed with digits...
318 if ( transfer.length() == 0 ) { // for brain damaged headers
321 while ( ! isdigit(transfer[transfer.length()-1]) )
323 transfer.erase(transfer.length()-1, 1);
325 if ( transfer == syntaxToCheck )
334 * \brief Determines if the Transfer Syntax of the present document
335 * corresponds to a Implicit Value Representation of
337 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
338 * @return True when ImplicitVRLittleEndian found. False in all other cases.
340 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
342 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
346 * \brief Determines if the Transfer Syntax was already encountered
347 * and if it corresponds to a ExplicitVRLittleEndian one.
348 * @return True when ExplicitVRLittleEndian found. False in all other cases.
350 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
352 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
356 * \brief Determines if the Transfer Syntax was already encountered
357 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
358 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
360 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
362 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
366 * \brief Determines if the Transfer Syntax was already encountered
367 * and if it corresponds to a Explicit VR Big Endian one.
368 * @return True when big endian found. False in all other cases.
370 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
372 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
376 * \brief Determines if the Transfer Syntax was already encountered
377 * and if it corresponds to a JPEGBaseLineProcess1 one.
378 * @return True when JPEGBaseLineProcess1found. False in all other cases.
380 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
382 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
386 * \brief Determines if the Transfer Syntax was already encountered
387 * and if it corresponds to a JPEGExtendedProcess2-4 one.
388 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
390 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
392 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
396 * \brief Determines if the Transfer Syntax was already encountered
397 * and if it corresponds to a JPEGExtendeProcess3-5 one.
398 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
400 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
402 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
406 * \brief Determines if the Transfer Syntax was already encountered
407 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
408 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
411 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
413 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
417 * \brief Determines if the Transfer Syntax was already encountered
418 * and if it corresponds to a RLE Lossless one.
419 * @return True when RLE Lossless found. False in all
422 bool gdcmDocument::IsRLELossLessTransferSyntax()
424 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
428 * \brief Determines if Transfer Syntax was already encountered
429 * and if it corresponds to a JPEG Lossless one.
430 * @return True when RLE Lossless found. False in all
434 bool gdcmDocument::IsJPEGLossless()
436 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
437 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
438 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
442 * \brief Determines if the Transfer Syntax was already encountered
443 * and if it corresponds to a JPEG2000 one
444 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
447 bool gdcmDocument::IsJPEG2000()
449 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
450 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
454 * \brief Predicate for dicom version 3 file.
455 * @return True when the file is a dicom version 3.
457 bool gdcmDocument::IsDicomV3()
459 // Checking if Transfert Syntax exists is enough
460 // Anyway, it's to late check if the 'Preamble' was found ...
461 // And ... would it be a rich idea to check ?
462 // (some 'no Preamble' DICOM images exist !)
463 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
467 * \brief returns the File Type
468 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
469 * @return the FileType code
471 FileType gdcmDocument::GetFileType()
477 * \brief Tries to open the file \ref gdcmDocument::Filename and
478 * checks the preamble when existing.
479 * @return The FILE pointer on success.
481 FILE* gdcmDocument::OpenFile()
483 Fp = fopen(Filename.c_str(),"rb");
488 "gdcmDocument::OpenFile cannot open file: ",
494 fread(&zero, (size_t)2, (size_t)1, Fp);
496 //ACR -- or DICOM with no Preamble --
497 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
503 fseek(Fp, 126L, SEEK_CUR);
505 fread(dicm, (size_t)4, (size_t)1, Fp);
506 if( memcmp(dicm, "DICM", 4) == 0 )
513 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
520 * \brief closes the file
521 * @return TRUE if the close was successfull
523 bool gdcmDocument::CloseFile()
525 int closed = fclose(Fp);
532 * \brief Writes in a file all the Header Entries (Dicom Elements)
533 * @param fp file pointer on an already open file
534 * @param filetype Type of the File to be written
535 * (ACR-NEMA, ExplicitVR, ImplicitVR)
536 * \return Always true.
538 void gdcmDocument::Write(FILE* fp,FileType filetype)
540 /// \todo move the following lines (and a lot of others, to be written)
541 /// to a future function CheckAndCorrectHeader
543 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
544 /// no way (check : FileType est un champ de gdcmDocument ...)
545 /// a moins de se livrer a un tres complique ajout des champs manquants.
546 /// faire un CheckAndCorrectHeader (?)
548 if (filetype == gdcmImplicitVR)
550 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
551 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
553 /// \todo Refer to standards on page 21, chapter 6.2
554 /// "Value representation": values with a VR of UI shall be
555 /// padded with a single trailing null
556 /// in the following case we have to padd manually with a 0
558 SetEntryLengthByNumber(18, 0x0002, 0x0010);
561 if (filetype == gdcmExplicitVR)
563 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
564 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
566 /// \todo Refer to standards on page 21, chapter 6.2
567 /// "Value representation": values with a VR of UI shall be
568 /// padded with a single trailing null
569 /// Dans le cas suivant on doit pader manuellement avec un 0
571 SetEntryLengthByNumber(20, 0x0002, 0x0010);
575 * \todo rewrite later, if really usefull
576 * - 'Group Length' element is optional in DICOM
577 * - but un-updated odd groups lengthes can causes pb
580 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
581 * UpdateGroupLength(false,filetype);
582 * if ( filetype == ACR)
583 * UpdateGroupLength(true,ACR);
586 gdcmElementSet::Write(fp, filetype); // This one is recursive
591 * \brief Modifies the value of a given Header Entry (Dicom Element)
592 * when it exists. Create it with the given value when unexistant.
593 * @param value (string) Value to be set
594 * @param group Group number of the Entry
595 * @param elem Element number of the Entry
596 * \return pointer to the modified/created Header Entry (NULL when creation
601 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
602 std::string const & value,
606 gdcmValEntry* valEntry = 0;
607 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
611 // The entry wasn't present and we simply create the required ValEntry:
612 currentEntry = NewDocEntryByNumber(group, elem);
615 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
616 " NewDocEntryByNumber failed.");
619 valEntry = new gdcmValEntry(currentEntry);
620 if ( !AddEntry(valEntry))
622 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
623 " failed allthough this is a creation.");
628 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
629 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
630 // then we change it to a ValEntry ?
631 // Shouldn't it be considered as an error ?
633 // We need to promote the gdcmDocEntry to a gdcmValEntry:
634 valEntry = new gdcmValEntry(currentEntry);
635 if (!RemoveEntry(currentEntry))
637 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
638 " of previous DocEntry failed.");
641 if ( !AddEntry(valEntry))
643 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
644 " promoted ValEntry failed.");
650 SetEntryByNumber(value, group, elem);
657 * \brief Modifies the value of a given Header Entry (Dicom Element)
658 * when it exists. Create it with the given value when unexistant.
659 * @param value (string) Value to be set
660 * @param group Group number of the Entry
661 * @param elem Element number of the Entry
662 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
663 * \return pointer to the modified/created Header Entry (NULL when creation
667 // TODO : write something clever, using default value for VR
668 // to avoid code duplication
669 // (I don't know how to tell NewDocEntryByNumber
670 // that ReplaceOrCreateByNumber was called with a default value)
672 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
673 std::string const & value,
676 std::string const & VR )
678 gdcmValEntry* valEntry = 0;
679 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
683 // check if (group,element) DictEntry exists
684 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
687 // Find out if the tag we received is in the dictionaries:
688 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
689 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
692 currentEntry = NewDocEntryByNumber(group, elem,VR);
696 currentEntry = NewDocEntryByNumber(group, elem);
701 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
702 " NewDocEntryByNumber failed.");
705 valEntry = new gdcmValEntry(currentEntry);
706 if ( !AddEntry(valEntry))
708 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
709 " failed allthough this is a creation.");
714 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
715 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
716 // then we change it to a ValEntry ?
717 // Shouldn't it be considered as an error ?
719 // We need to promote the gdcmDocEntry to a gdcmValEntry:
720 valEntry = new gdcmValEntry(currentEntry);
721 if (!RemoveEntry(currentEntry))
723 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
724 " of previous DocEntry failed.");
727 if ( !AddEntry(valEntry))
729 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
730 " promoted ValEntry failed.");
736 SetEntryByNumber(value, group, elem);
742 * \brief Modifies the value of a given Header Entry (Dicom Element)
743 * when it exists. Create it with the given value when unexistant.
744 * @param voidArea (binary) value to be set
745 * @param Group Group number of the Entry
746 * @param Elem Element number of the Entry
747 * \return pointer to the modified/created Header Entry (NULL when creation
750 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
755 std::string const & VR )
757 gdcmBinEntry* binEntry = 0;
758 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
762 // check if (group,element) DictEntry exists
763 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
766 // Find out if the tag we received is in the dictionaries:
767 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
768 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
772 currentEntry = NewDocEntryByNumber(group, elem,VR);
776 currentEntry = NewDocEntryByNumber(group, elem);
780 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
781 " NewDocEntryByNumber failed.");
784 binEntry = new gdcmBinEntry(currentEntry);
785 if ( !AddEntry(binEntry))
787 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
788 " failed allthough this is a creation.");
793 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
794 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
795 // then we change it to a BinEntry ?
796 // Shouldn't it be considered as an error ?
798 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
799 binEntry = new gdcmBinEntry(currentEntry);
800 if (!RemoveEntry(currentEntry))
802 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
803 " of previous DocEntry failed.");
806 if ( !AddEntry(binEntry))
808 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
809 " promoted BinEntry failed.");
815 SetEntryByNumber(voidArea, lgth, group, elem);
822 * \brief Modifies the value of a given Header Entry (Dicom Element)
823 * when it exists. Create it when unexistant.
824 * @param Group Group number of the Entry
825 * @param Elem Element number of the Entry
826 * \return pointer to the modified/created SeqEntry (NULL when creation
829 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
834 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
837 a = NewSeqEntryByNumber(group, elem);
843 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
850 * \brief Set a new value if the invoked element exists
851 * Seems to be useless !!!
852 * @param value new element value
853 * @param group group number of the Entry
854 * @param elem element number of the Entry
857 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
858 uint16_t group, uint16_t elem )
860 SetEntryByNumber(value, group, elem);
865 //-----------------------------------------------------------------------------
869 * \brief Checks if a given Dicom Element exists within the H table
870 * @param group Group number of the searched Dicom Element
871 * @param element Element number of the searched Dicom Element
872 * @return true is found
874 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
876 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
877 return TagHT.count(key);
881 * \brief Searches within Header Entries (Dicom Elements) parsed with
882 * the public and private dictionaries
883 * for the element value of a given tag.
884 * \warning Don't use any longer : use GetPubEntryByName
885 * @param tagName name of the searched element.
886 * @return Corresponding element value when it exists,
887 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
889 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
891 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
897 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
901 * \brief Searches within Header Entries (Dicom Elements) parsed with
902 * the public and private dictionaries
903 * for the element value representation of a given tag.
905 * Obtaining the VR (Value Representation) might be needed by caller
906 * to convert the string typed content to caller's native type
907 * (think of C++ vs Python). The VR is actually of a higher level
908 * of semantics than just the native C++ type.
909 * @param tagName name of the searched element.
910 * @return Corresponding element value representation when it exists,
911 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
913 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
915 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
916 if( dictEntry == NULL)
921 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
922 dictEntry->GetElement());
923 return elem->GetVR();
928 * \brief Searches within Header Entries (Dicom Elements) parsed with
929 * the public and private dictionaries
930 * for the element value representation of a given tag.
931 * @param group Group number of the searched tag.
932 * @param element Element number of the searched tag.
933 * @return Corresponding element value representation when it exists,
934 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
936 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
938 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
939 /// \todo use map methods, instead of multimap JPR
940 if ( !TagHT.count(key))
945 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
949 * \brief Searches within Header Entries (Dicom Elements) parsed with
950 * the public and private dictionaries
951 * for the element value representation of a given tag..
953 * Obtaining the VR (Value Representation) might be needed by caller
954 * to convert the string typed content to caller's native type
955 * (think of C++ vs Python). The VR is actually of a higher level
956 * of semantics than just the native C++ type.
957 * @param group Group number of the searched tag.
958 * @param element Element number of the searched tag.
959 * @return Corresponding element value representation when it exists,
960 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
962 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
964 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
969 return elem->GetVR();
973 * \brief Searches within Header Entries (Dicom Elements) parsed with
974 * the public and private dictionaries
975 * for the value length of a given tag..
976 * @param group Group number of the searched tag.
977 * @param element Element number of the searched tag.
978 * @return Corresponding element length; -2 if not found
980 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
982 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
985 return -2; //magic number
987 return elem->GetLength();
990 * \brief Sets the value (string) of the Header Entry (Dicom Element)
991 * @param content string value of the Dicom Element
992 * @param tagName name of the searched Dicom Element.
993 * @return true when found
995 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
997 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1003 return SetEntryByNumber(content,dictEntry->GetGroup(),
1004 dictEntry->GetElement());
1008 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1009 * through it's (group, element) and modifies it's content with
1011 * @param content new value (string) to substitute with
1012 * @param group group number of the Dicom Element to modify
1013 * @param element element number of the Dicom Element to modify
1015 bool gdcmDocument::SetEntryByNumber(std::string const & content,
1022 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
1025 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
1026 " ValEntry (try promotion first).");
1029 // Non even content must be padded with a space (020H)...
1030 std::string finalContent = content;
1031 if( finalContent.length() % 2 )
1033 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
1035 valEntry->SetValue(finalContent);
1037 // Integers have a special treatement for their length:
1039 l = finalContent.length();
1040 if ( l != 0) // To avoid to be cheated by 'zero length' integers
1042 gdcmVRKey vr = valEntry->GetVR();
1043 if( vr == "US" || vr == "SS" )
1045 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1048 else if( vr == "UL" || vr == "SL" )
1050 c = CountSubstring(content, "\\") + 1; // for multivaluated items
1054 valEntry->SetLength(l);
1059 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1060 * through it's (group, element) and modifies it's content with
1062 * @param content new value (void *) to substitute with
1063 * @param lgth new value length
1064 * @param group group number of the Dicom Element to modify
1065 * @param element element number of the Dicom Element to modify
1067 bool gdcmDocument::SetEntryByNumber(void *content,
1072 (void)lgth; //not used
1073 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1074 if ( !TagHT.count(key))
1079 /* Hope Binary field length is *never* wrong
1080 if(lgth%2) // Non even length are padded with a space (020H).
1083 //content = content + '\0'; // fing a trick to enlarge a binary field?
1086 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1087 a->SetVoidArea(content);
1094 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1095 * in the PubDocEntrySet of this instance
1096 * through it's (group, element) and modifies it's length with
1098 * \warning Use with extreme caution.
1099 * @param l new length to substitute with
1100 * @param group group number of the Entry to modify
1101 * @param element element number of the Entry to modify
1102 * @return true on success, false otherwise.
1104 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1108 /// \todo use map methods, instead of multimap JPR
1109 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1110 if ( !TagHT.count(key) )
1116 l++; // length must be even
1118 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1124 * \brief Gets (from Header) the offset of a 'non string' element value
1125 * (LoadElementValues has already be executed)
1126 * @param group group number of the Entry
1127 * @param elem element number of the Entry
1128 * @return File Offset of the Element Value
1130 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1132 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1135 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1138 return entry->GetOffset();
1142 * \brief Gets (from Header) a 'non string' element value
1143 * (LoadElementValues has already be executed)
1144 * @param group group number of the Entry
1145 * @param elem element number of the Entry
1146 * @return Pointer to the 'non string' area
1148 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1150 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1153 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1156 return ((gdcmBinEntry *)entry)->GetVoidArea();
1160 * \brief Loads (from disk) the element content
1161 * when a string is not suitable
1162 * @param group group number of the Entry
1163 * @param elem element number of the Entry
1165 void* gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1167 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1172 size_t o =(size_t)docElement->GetOffset();
1173 fseek(Fp, o, SEEK_SET);
1174 size_t l = docElement->GetLength();
1175 char* a = new char[l];
1178 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1181 size_t l2 = fread(a, 1, l , Fp);
1187 /// \todo Drop any already existing void area! JPR
1188 if( !SetEntryVoidAreaByNumber( a, group, elem ) );
1190 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea setting failed.");
1196 * \brief Loads (from disk) the element content
1197 * when a string is not suitable
1198 * @param element Entry whose voidArea is going to be loaded
1200 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1202 size_t o =(size_t)element->GetOffset();
1203 fseek(Fp, o, SEEK_SET);
1204 size_t l = element->GetLength();
1205 char* a = new char[l];
1208 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1211 element->SetVoidArea((void *)a);
1212 /// \todo check the result
1213 size_t l2 = fread(a, 1, l , Fp);
1224 * \brief Sets a 'non string' value to a given Dicom Element
1225 * @param area area containing the 'non string' value
1226 * @param group Group number of the searched Dicom Element
1227 * @param element Element number of the searched Dicom Element
1230 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1234 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1235 if ( !currentEntry )
1239 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1241 binEntry->SetVoidArea( area );
1248 * \brief Update the entries with the shadow dictionary.
1249 * Only non even entries are analyzed
1251 void gdcmDocument::UpdateShaEntries()
1253 //gdcmDictEntry *entry;
1256 /// \todo TODO : still any use to explore recursively the whole structure?
1258 for(ListTag::iterator it=listEntries.begin();
1259 it!=listEntries.end();
1262 // Odd group => from public dictionary
1263 if((*it)->GetGroup()%2==0)
1266 // Peer group => search the corresponding dict entry
1268 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1272 if((*it)->IsImplicitVR())
1277 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1279 // Set the new entry and the new value
1280 (*it)->SetDictEntry(entry);
1281 CheckDocEntryVR(*it,vr);
1283 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1288 // Remove precedent value transformation
1289 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1296 * \brief Searches within the Header Entries for a Dicom Element of
1298 * @param tagName name of the searched Dicom Element.
1299 * @return Corresponding Dicom Element when it exists, and NULL
1302 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1304 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1310 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1314 * \brief retrieves a Dicom Element (the first one) using (group, element)
1315 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1316 * if you think it's NOT UNIQUE, check the count number
1317 * and use iterators to retrieve ALL the Dicoms Elements within
1318 * a given couple (group, element)
1319 * @param group Group number of the searched Dicom Element
1320 * @param element Element number of the searched Dicom Element
1323 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1326 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1327 if ( !TagHT.count(key))
1331 return TagHT.find(key)->second;
1335 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1336 * returns a result when the corresponding entry is of type
1338 * @return When present, the corresponding ValEntry.
1340 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1343 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1344 if ( !currentEntry )
1348 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1352 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1358 * \brief Loads the element while preserving the current
1359 * underlying file position indicator as opposed to
1360 * to LoadDocEntry that modifies it.
1361 * @param entry Header Entry whose value shall be loaded.
1364 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1366 long PositionOnEntry = ftell(Fp);
1367 LoadDocEntry(entry);
1368 fseek(Fp, PositionOnEntry, SEEK_SET);
1372 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1374 * @return The properly swaped 32 bits integer.
1376 uint32_t gdcmDocument::SwapLong(uint32_t a)
1383 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1384 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1388 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1392 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1395 //std::cout << "swapCode= " << SwapCode << std::endl;
1396 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1403 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1405 * @return The properly unswaped 32 bits integer.
1407 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1413 * \brief Swaps the bytes so they agree with the processor order
1414 * @return The properly swaped 16 bits integer.
1416 uint16_t gdcmDocument::SwapShort(uint16_t a)
1418 if ( SwapCode == 4321 || SwapCode == 2143 )
1420 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1426 * \brief Unswaps the bytes so they agree with the processor order
1427 * @return The properly unswaped 16 bits integer.
1429 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1431 return SwapShort(a);
1434 //-----------------------------------------------------------------------------
1438 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1439 * @return length of the parsed set.
1442 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1447 gdcmDocEntry *newDocEntry = 0;
1448 unsigned long l = 0;
1452 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1456 newDocEntry = ReadNextDocEntry( );
1462 gdcmVRKey vr = newDocEntry->GetVR();
1466 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1468 /////////////////////// ValEntry
1469 gdcmValEntry* newValEntry =
1470 new gdcmValEntry( newDocEntry->GetDictEntry() );
1471 newValEntry->Copy( newDocEntry );
1473 // When "set" is a gdcmDocument, then we are at the top of the
1474 // hierarchy and the Key is simply of the form ( group, elem )...
1475 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1477 newValEntry->SetKey( newValEntry->GetKey() );
1479 // ...but when "set" is a gdcmSQItem, we are inserting this new
1480 // valEntry in a sequence item. Hence the key has the
1481 // generalized form (refer to \ref gdcmBaseTagKey):
1482 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1484 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1485 + newValEntry->GetKey() );
1488 set->AddEntry( newValEntry );
1489 LoadDocEntry( newValEntry );
1490 if (newValEntry->IsItemDelimitor())
1494 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1501 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1503 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1504 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1505 "nor BinEntry. Probably unknown VR.");
1508 //////////////////// BinEntry or UNKOWN VR:
1509 gdcmBinEntry* newBinEntry =
1510 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1511 newBinEntry->Copy( newDocEntry );
1513 // When "this" is a gdcmDocument the Key is simply of the
1514 // form ( group, elem )...
1515 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1517 newBinEntry->SetKey( newBinEntry->GetKey() );
1519 // but when "this" is a SQItem, we are inserting this new
1520 // valEntry in a sequence item, and the kay has the
1521 // generalized form (refer to \ref gdcmBaseTagKey):
1522 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1524 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1525 + newBinEntry->GetKey() );
1528 set->AddEntry( newBinEntry );
1529 LoadDocEntry( newBinEntry );
1532 if (newDocEntry->GetGroup() == 0x7fe0 &&
1533 newDocEntry->GetElement() == 0x0010 )
1535 if (newDocEntry->GetReadLength()==0xffffffff)
1537 // Broken US.3405.1.dcm
1538 Parse7FE0(); // to skip the pixels
1539 // (multipart JPEG/RLE are trouble makers)
1543 SkipToNextDocEntry(newDocEntry);
1544 l = newDocEntry->GetFullLength();
1549 // to be sure we are at the beginning
1550 SkipToNextDocEntry(newDocEntry);
1551 l = newDocEntry->GetFullLength();
1557 l = newDocEntry->GetReadLength();
1558 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1560 if ( l == 0xffffffff )
1569 // no other way to create it ...
1570 gdcmSeqEntry* newSeqEntry =
1571 new gdcmSeqEntry( newDocEntry->GetDictEntry() );
1572 newSeqEntry->Copy( newDocEntry );
1573 newSeqEntry->SetDelimitorMode( delim_mode );
1575 // At the top of the hierarchy, stands a gdcmDocument. When "set"
1576 // is a gdcmDocument, then we are building the first depth level.
1577 // Hence the gdcmSeqEntry we are building simply has a depth
1579 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1581 newSeqEntry->SetDepthLevel( 1 );
1582 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1584 // But when "set" is allready a SQItem, we are building a nested
1585 // sequence, and hence the depth level of the new gdcmSeqEntry
1586 // we are building, is one level deeper:
1587 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1589 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1590 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1591 + newSeqEntry->GetKey() );
1595 { // Don't try to parse zero-length sequences
1596 (void)ParseSQ( newSeqEntry,
1597 newDocEntry->GetOffset(),
1600 set->AddEntry( newSeqEntry );
1601 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1608 return l; // Probably useless
1612 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1613 * @return parsed length for this level
1615 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1616 long offset, long l_max, bool delim_mode)
1618 int SQItemNumber = 0;
1623 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1626 // FIXME Should warn user
1631 if ( newDocEntry->IsSequenceDelimitor() )
1633 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1637 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1642 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1643 std::ostringstream newBase;
1644 newBase << seqEntry->GetKey()
1648 itemSQ->SetBaseTagKey( newBase.str() );
1649 unsigned int l = newDocEntry->GetReadLength();
1651 if ( l == 0xffffffff )
1660 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1662 seqEntry->AddEntry( itemSQ, SQItemNumber );
1664 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1670 int lgth = ftell(Fp) - offset;
1675 * \brief Loads the element content if its length doesn't exceed
1676 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1677 * @param entry Header Entry (Dicom Element) to be dealt with
1679 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1682 uint16_t group = entry->GetGroup();
1683 std::string vr = entry->GetVR();
1684 uint32_t length = entry->GetLength();
1686 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1688 // A SeQuence "contains" a set of Elements.
1689 // (fffe e000) tells us an Element is beginning
1690 // (fffe e00d) tells us an Element just ended
1691 // (fffe e0dd) tells us the current SeQuence just ended
1692 if( group == 0xfffe )
1694 // NO more value field for SQ !
1698 // When the length is zero things are easy:
1701 ((gdcmValEntry *)entry)->SetValue("");
1705 // The elements whose length is bigger than the specified upper bound
1706 // are not loaded. Instead we leave a short notice of the offset of
1707 // the element content and it's length.
1709 std::ostringstream s;
1710 if (length > MaxSizeLoadEntry)
1712 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1714 //s << "gdcm::NotLoaded (BinEntry)";
1715 s << GDCM_NOTLOADED;
1716 s << " Address:" << (long)entry->GetOffset();
1717 s << " Length:" << entry->GetLength();
1718 s << " x(" << std::hex << entry->GetLength() << ")";
1719 binEntryPtr->SetValue(s.str());
1721 // Be carefull : a BinEntry IS_A ValEntry ...
1722 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1724 // s << "gdcm::NotLoaded. (ValEntry)";
1725 s << GDCM_NOTLOADED;
1726 s << " Address:" << (long)entry->GetOffset();
1727 s << " Length:" << entry->GetLength();
1728 s << " x(" << std::hex << entry->GetLength() << ")";
1729 valEntryPtr->SetValue(s.str());
1734 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1735 << "nor a ValEntry ?! Should never print that !" << std::endl;
1738 // to be sure we are at the end of the value ...
1739 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1743 // When we find a BinEntry not very much can be done :
1744 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1746 s << "gdcm::Loaded (BinEntry)";
1747 binEntryPtr->SetValue(s.str());
1748 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1752 /// \todo Any compacter code suggested (?)
1753 if ( IsDocEntryAnInteger(entry) )
1757 // When short integer(s) are expected, read and convert the following
1758 // n *two characters properly i.e. consider them as short integers as
1759 // opposed to strings.
1760 // Elements with Value Multiplicity > 1
1761 // contain a set of integers (not a single one)
1762 if (vr == "US" || vr == "SS")
1765 NewInt = ReadInt16();
1769 for (int i=1; i < nbInt; i++)
1772 NewInt = ReadInt16();
1777 // See above comment on multiple integers (mutatis mutandis).
1778 else if (vr == "UL" || vr == "SL")
1781 NewInt = ReadInt32();
1785 for (int i=1; i < nbInt; i++)
1788 NewInt = ReadInt32();
1793 #ifdef GDCM_NO_ANSI_STRING_STREAM
1794 s << std::ends; // to avoid oddities on Solaris
1795 #endif //GDCM_NO_ANSI_STRING_STREAM
1797 ((gdcmValEntry *)entry)->SetValue(s.str());
1801 // We need an additional byte for storing \0 that is not on disk
1802 //std::string newValue(length,0);
1803 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1804 //rah !! I can't believe it could work, normally this is a const char* !!!
1805 char *str = new char[length+1];
1806 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1808 std::string newValue = str;
1810 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1812 if ( item_read != 1 )
1814 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1815 "unread element value");
1816 valEntry->SetValue(GDCM_UNREAD);
1822 // Because of correspondance with the VR dic
1823 valEntry->SetValue(newValue);
1827 valEntry->SetValue(newValue);
1832 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1833 "Should have a ValEntry, here !");
1839 * \brief Find the value Length of the passed Header Entry
1840 * @param entry Header Entry whose length of the value shall be loaded.
1842 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1843 throw ( gdcmFormatError )
1845 uint16_t element = entry->GetElement();
1846 std::string vr = entry->GetVR();
1849 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1851 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1853 // The following reserved two bytes (see PS 3.5-2001, section
1854 // 7.1.2 Data element structure with explicit vr p27) must be
1855 // skipped before proceeding on reading the length on 4 bytes.
1856 fseek(Fp, 2L, SEEK_CUR);
1857 uint32_t length32 = ReadInt32();
1859 if ( vr == "OB" && length32 == 0xffffffff )
1864 lengthOB = FindDocEntryLengthOB();
1866 catch ( gdcmFormatUnexpected )
1868 // Computing the length failed (this happens with broken
1869 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1870 // chance to get the pixels by deciding the element goes
1871 // until the end of the file. Hence we artificially fix the
1872 // the length and proceed.
1873 long currentPosition = ftell(Fp);
1874 fseek(Fp,0L,SEEK_END);
1875 long lengthUntilEOF = ftell(Fp) - currentPosition;
1876 fseek(Fp, currentPosition, SEEK_SET);
1877 entry->SetLength(lengthUntilEOF);
1880 entry->SetLength(lengthOB);
1883 FixDocEntryFoundLength(entry, length32);
1887 // Length is encoded on 2 bytes.
1888 length16 = ReadInt16();
1890 // We can tell the current file is encoded in big endian (like
1891 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1892 // and it's value is the one of the encoding of a big endian file.
1893 // In order to deal with such big endian encoded files, we have
1894 // (at least) two strategies:
1895 // * when we load the "Transfer Syntax" tag with value of big endian
1896 // encoding, we raise the proper flags. Then we wait for the end
1897 // of the META group (0x0002) among which is "Transfer Syntax",
1898 // before switching the swap code to big endian. We have to postpone
1899 // the switching of the swap code since the META group is fully encoded
1900 // in little endian, and big endian coding only starts at the next
1901 // group. The corresponding code can be hard to analyse and adds
1902 // many additional unnecessary tests for regular tags.
1903 // * the second strategy consists in waiting for trouble, that shall
1904 // appear when we find the first group with big endian encoding. This
1905 // is easy to detect since the length of a "Group Length" tag (the
1906 // ones with zero as element number) has to be of 4 (0x0004). When we
1907 // encounter 1024 (0x0400) chances are the encoding changed and we
1908 // found a group with big endian encoding.
1909 // We shall use this second strategy. In order to make sure that we
1910 // can interpret the presence of an apparently big endian encoded
1911 // length of a "Group Length" without committing a big mistake, we
1912 // add an additional check: we look in the already parsed elements
1913 // for the presence of a "Transfer Syntax" whose value has to be "big
1914 // endian encoding". When this is the case, chances are we have got our
1915 // hands on a big endian encoded file: we switch the swap code to
1916 // big endian and proceed...
1917 if ( element == 0x0000 && length16 == 0x0400 )
1919 if ( !IsExplicitVRBigEndianTransferSyntax() )
1921 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1922 " not explicit VR." );
1926 SwitchSwapToBigEndian();
1927 // Restore the unproperly loaded values i.e. the group, the element
1928 // and the dictionary entry depending on them.
1929 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1930 uint16_t correctElem = SwapShort( entry->GetElement() );
1931 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1935 // This correct tag is not in the dictionary. Create a new one.
1936 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1938 // FIXME this can create a memory leaks on the old entry that be
1939 // left unreferenced.
1940 entry->SetDictEntry( newTag );
1943 // Heuristic: well, some files are really ill-formed.
1944 if ( length16 == 0xffff)
1946 // 0xffff means that we deal with 'Unknown Length' Sequence
1949 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1954 // Either implicit VR or a non DICOM conformal (see note below) explicit
1955 // VR that ommited the VR of (at least) this element. Farts happen.
1956 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1957 // on Data elements "Implicit and Explicit VR Data Elements shall
1958 // not coexist in a Data Set and Data Sets nested within it".]
1959 // Length is on 4 bytes.
1961 FixDocEntryFoundLength( entry, ReadInt32() );
1967 * \brief Find the Value Representation of the current Dicom Element.
1970 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1972 if ( Filetype != gdcmExplicitVR )
1979 long positionOnEntry = ftell(Fp);
1980 // Warning: we believe this is explicit VR (Value Representation) because
1981 // we used a heuristic that found "UL" in the first tag. Alas this
1982 // doesn't guarantee that all the tags will be in explicit VR. In some
1983 // cases (see e-film filtered files) one finds implicit VR tags mixed
1984 // within an explicit VR file. Hence we make sure the present tag
1985 // is in explicit VR and try to fix things if it happens not to be
1988 fread (vr, (size_t)2,(size_t)1, Fp);
1991 if( !CheckDocEntryVR(entry, vr) )
1993 fseek(Fp, positionOnEntry, SEEK_SET);
1994 // When this element is known in the dictionary we shall use, e.g. for
1995 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1996 // dictionary entry. Still we have to flag the element as implicit since
1997 // we know now our assumption on expliciteness is not furfilled.
1999 if ( entry->IsVRUnknown() )
2001 entry->SetVR("Implicit");
2003 entry->SetImplicitVR();
2008 * \brief Check the correspondance between the VR of the header entry
2009 * and the taken VR. If they are different, the header entry is
2010 * updated with the new VR.
2011 * @param entry Header Entry to check
2012 * @param vr Dicom Value Representation
2013 * @return false if the VR is incorrect of if the VR isn't referenced
2014 * otherwise, it returns true
2016 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
2018 char msg[100]; // for sprintf
2019 bool realExplicit = true;
2021 // Assume we are reading a falsely explicit VR file i.e. we reached
2022 // a tag where we expect reading a VR but are in fact we read the
2023 // first to bytes of the length. Then we will interogate (through find)
2024 // the dicom_vr dictionary with oddities like "\004\0" which crashes
2025 // both GCC and VC++ implementations of the STL map. Hence when the
2026 // expected VR read happens to be non-ascii characters we consider
2027 // we hit falsely explicit VR tag.
2029 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
2031 realExplicit = false;
2034 // CLEANME searching the dicom_vr at each occurence is expensive.
2035 // PostPone this test in an optional integrity check at the end
2036 // of parsing or only in debug mode.
2037 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
2039 realExplicit = false;
2042 if ( !realExplicit )
2044 // We thought this was explicit VR, but we end up with an
2045 // implicit VR tag. Let's backtrack.
2046 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
2047 entry->GetGroup(), entry->GetElement());
2048 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
2050 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2052 // Group length is UL !
2053 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2054 entry->GetGroup(), entry->GetElement(),
2055 "UL", "FIXME", "Group Length");
2056 entry->SetDictEntry( newEntry );
2061 if ( entry->IsVRUnknown() )
2063 // When not a dictionary entry, we can safely overwrite the VR.
2064 if( entry->GetElement() == 0x0000 )
2066 // Group length is UL !
2074 else if ( entry->GetVR() != vr )
2076 // The VR present in the file and the dictionary disagree. We assume
2077 // the file writer knew best and use the VR of the file. Since it would
2078 // be unwise to overwrite the VR of a dictionary (since it would
2079 // compromise it's next user), we need to clone the actual DictEntry
2080 // and change the VR for the read one.
2081 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2082 entry->GetGroup(), entry->GetElement(),
2083 vr, "FIXME", entry->GetName());
2084 entry->SetDictEntry(newEntry);
2091 * \brief Get the transformed value of the header entry. The VR value
2092 * is used to define the transformation to operate on the value
2093 * \warning NOT end user intended method !
2094 * @param entry entry to tranform
2095 * @return Transformed entry value
2097 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2099 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2101 std::string val = ((gdcmValEntry *)entry)->GetValue();
2102 std::string vr = entry->GetVR();
2103 uint32_t length = entry->GetLength();
2104 std::ostringstream s;
2107 // When short integer(s) are expected, read and convert the following
2108 // n * 2 bytes properly i.e. as a multivaluated strings
2109 // (each single value is separated fromthe next one by '\'
2110 // as usual for standard multivaluated filels
2111 // Elements with Value Multiplicity > 1
2112 // contain a set of short integers (not a single one)
2114 if( vr == "US" || vr == "SS" )
2119 for (int i=0; i < nbInt; i++)
2125 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2126 newInt16 = SwapShort( newInt16 );
2131 // When integer(s) are expected, read and convert the following
2132 // n * 4 bytes properly i.e. as a multivaluated strings
2133 // (each single value is separated fromthe next one by '\'
2134 // as usual for standard multivaluated filels
2135 // Elements with Value Multiplicity > 1
2136 // contain a set of integers (not a single one)
2137 else if( vr == "UL" || vr == "SL" )
2142 for (int i=0; i < nbInt; i++)
2148 newInt32 = ( val[4*i+0] & 0xFF )
2149 + (( val[4*i+1] & 0xFF ) << 8 )
2150 + (( val[4*i+2] & 0xFF ) << 16 )
2151 + (( val[4*i+3] & 0xFF ) << 24 );
2152 newInt32 = SwapLong( newInt32 );
2156 #ifdef GDCM_NO_ANSI_STRING_STREAM
2157 s << std::ends; // to avoid oddities on Solaris
2158 #endif //GDCM_NO_ANSI_STRING_STREAM
2162 return ((gdcmValEntry *)entry)->GetValue();
2166 * \brief Get the reverse transformed value of the header entry. The VR
2167 * value is used to define the reverse transformation to operate on
2169 * \warning NOT end user intended method !
2170 * @param entry Entry to reverse transform
2171 * @return Reverse transformed entry value
2173 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2175 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2177 std::string vr = entry->GetVR();
2178 std::vector<std::string> tokens;
2179 std::ostringstream s;
2181 if ( vr == "US" || vr == "SS" )
2185 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2186 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2187 for (unsigned int i=0; i<tokens.size(); i++)
2189 newInt16 = atoi(tokens[i].c_str());
2190 s << ( newInt16 & 0xFF )
2191 << (( newInt16 >> 8 ) & 0xFF );
2195 if ( vr == "UL" || vr == "SL")
2199 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2200 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2201 for (unsigned int i=0; i<tokens.size();i++)
2203 newInt32 = atoi(tokens[i].c_str());
2204 s << (char)( newInt32 & 0xFF )
2205 << (char)(( newInt32 >> 8 ) & 0xFF )
2206 << (char)(( newInt32 >> 16 ) & 0xFF )
2207 << (char)(( newInt32 >> 24 ) & 0xFF );
2212 #ifdef GDCM_NO_ANSI_STRING_STREAM
2213 s << std::ends; // to avoid oddities on Solaris
2214 #endif //GDCM_NO_ANSI_STRING_STREAM
2218 return ((gdcmValEntry *)entry)->GetValue();
2222 * \brief Skip a given Header Entry
2223 * \warning NOT end user intended method !
2224 * @param entry entry to skip
2226 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2228 SkipBytes(entry->GetLength());
2232 * \brief Skips to the begining of the next Header Entry
2233 * \warning NOT end user intended method !
2234 * @param entry entry to skip
2236 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2238 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2239 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2243 * \brief When the length of an element value is obviously wrong (because
2244 * the parser went Jabberwocky) one can hope improving things by
2245 * applying some heuristics.
2246 * @param entry entry to check
2247 * @param foundLength fist assumption about length
2249 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2250 uint32_t foundLength)
2252 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2253 if ( foundLength == 0xffffffff)
2258 uint16_t gr = entry->GetGroup();
2259 uint16_t el = entry->GetElement();
2261 if ( foundLength % 2)
2263 std::ostringstream s;
2264 s << "Warning : Tag with uneven length "
2266 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2267 dbg.Verbose(0, s.str().c_str());
2270 //////// Fix for some naughty General Electric images.
2271 // Allthough not recent many such GE corrupted images are still present
2272 // on Creatis hard disks. Hence this fix shall remain when such images
2273 // are no longer in user (we are talking a few years, here)...
2274 // Note: XMedCom probably uses such a trick since it is able to read
2275 // those pesky GE images ...
2276 if ( foundLength == 13)
2278 // Only happens for this length !
2279 if ( entry->GetGroup() != 0x0008
2280 || ( entry->GetElement() != 0x0070
2281 && entry->GetElement() != 0x0080 ) )
2284 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2288 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2289 // Occurence of such images is quite low (unless one leaves close to a
2290 // 'Leonardo' source. Hence, one might consider commenting out the
2291 // following fix on efficiency reasons.
2292 else if ( entry->GetGroup() == 0x0009
2293 && ( entry->GetElement() == 0x1113
2294 || entry->GetElement() == 0x1114 ) )
2297 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2300 else if ( entry->GetVR() == "SQ" )
2302 foundLength = 0; // ReadLength is unchanged
2305 //////// We encountered a 'delimiter' element i.e. a tag of the form
2306 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2307 // taken into account.
2308 else if( entry->GetGroup() == 0xfffe )
2310 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2311 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2312 // causes extra troubles...
2313 if( entry->GetElement() != 0x0000 )
2319 entry->SetUsableLength(foundLength);
2323 * \brief Apply some heuristics to predict whether the considered
2324 * element value contains/represents an integer or not.
2325 * @param entry The element value on which to apply the predicate.
2326 * @return The result of the heuristical predicate.
2328 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2330 uint16_t element = entry->GetElement();
2331 uint16_t group = entry->GetGroup();
2332 std::string vr = entry->GetVR();
2333 uint32_t length = entry->GetLength();
2335 // When we have some semantics on the element we just read, and if we
2336 // a priori know we are dealing with an integer, then we shall be
2337 // able to swap it's element value properly.
2338 if ( element == 0 ) // This is the group length of the group
2346 // Allthough this should never happen, still some images have a
2347 // corrupted group length [e.g. have a glance at offset x(8336) of
2348 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2349 // Since for dicom compliant and well behaved headers, the present
2350 // test is useless (and might even look a bit paranoid), when we
2351 // encounter such an ill-formed image, we simply display a warning
2352 // message and proceed on parsing (while crossing fingers).
2353 std::ostringstream s;
2354 int filePosition = ftell(Fp);
2355 s << "Erroneous Group Length element length on : (" \
2356 << std::hex << group << " , " << element
2357 << ") -before- position x(" << filePosition << ")"
2358 << "lgt : " << length;
2359 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2363 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2372 * \brief Find the Length till the next sequence delimiter
2373 * \warning NOT end user intended method !
2377 uint32_t gdcmDocument::FindDocEntryLengthOB()
2378 throw( gdcmFormatUnexpected )
2380 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2381 long positionOnEntry = ftell(Fp);
2382 bool foundSequenceDelimiter = false;
2383 uint32_t totalLength = 0;
2385 while ( !foundSequenceDelimiter )
2391 group = ReadInt16();
2394 catch ( gdcmFormatError )
2396 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2397 " group or element not present.");
2400 // We have to decount the group and element we just read
2403 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2405 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2406 "tag nor a Sequence delimiter tag.");
2407 fseek(Fp, positionOnEntry, SEEK_SET);
2408 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2409 "Neither an Item tag nor a Sequence "
2413 if ( elem == 0xe0dd )
2415 foundSequenceDelimiter = true;
2418 uint32_t itemLength = ReadInt32();
2419 // We add 4 bytes since we just read the ItemLength with ReadInt32
2420 totalLength += itemLength + 4;
2421 SkipBytes(itemLength);
2423 if ( foundSequenceDelimiter )
2428 fseek(Fp, positionOnEntry, SEEK_SET);
2433 * \brief Reads a supposed to be 16 Bits integer
2434 * (swaps it depending on processor endianity)
2435 * @return read value
2437 uint16_t gdcmDocument::ReadInt16()
2438 throw( gdcmFormatError )
2441 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2442 if ( item_read != 1 )
2446 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2448 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2455 * \brief Reads a supposed to be 32 Bits integer
2456 * (swaps it depending on processor endianity)
2457 * @return read value
2459 uint32_t gdcmDocument::ReadInt32()
2460 throw( gdcmFormatError )
2463 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2464 if ( item_read != 1 )
2468 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2470 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2477 * \brief skips bytes inside the source file
2478 * \warning NOT end user intended method !
2481 void gdcmDocument::SkipBytes(uint32_t nBytes)
2483 //FIXME don't dump the returned value
2484 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2488 * \brief Loads all the needed Dictionaries
2489 * \warning NOT end user intended method !
2491 void gdcmDocument::Initialise()
2493 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2498 * \brief Discover what the swap code is (among little endian, big endian,
2499 * bad little endian, bad big endian).
2501 * @return false when we are absolutely sure
2502 * it's neither ACR-NEMA nor DICOM
2503 * true when we hope ours assuptions are OK
2505 bool gdcmDocument::CheckSwap()
2507 // The only guaranted way of finding the swap code is to find a
2508 // group tag since we know it's length has to be of four bytes i.e.
2509 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2510 // occurs when we can't find such group...
2512 uint32_t x = 4; // x : for ntohs
2513 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2517 char deb[HEADER_LENGTH_TO_READ];
2519 // First, compare HostByteOrder and NetworkByteOrder in order to
2520 // determine if we shall need to swap bytes (i.e. the Endian type).
2521 if ( x == ntohs(x) )
2530 // The easiest case is the one of a DICOM header, since it possesses a
2531 // file preamble where it suffice to look for the string "DICM".
2532 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2533 (void)lgrLue; //FIXME not used
2535 char *entCur = deb + 128;
2536 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2538 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2540 // Next, determine the value representation (VR). Let's skip to the
2541 // first element (0002, 0000) and check there if we find "UL"
2542 // - or "OB" if the 1st one is (0002,0001) -,
2543 // in which case we (almost) know it is explicit VR.
2544 // WARNING: if it happens to be implicit VR then what we will read
2545 // is the length of the group. If this ascii representation of this
2546 // length happens to be "UL" then we shall believe it is explicit VR.
2547 // FIXME: in order to fix the above warning, we could read the next
2548 // element value (or a couple of elements values) in order to make
2549 // sure we are not commiting a big mistake.
2550 // We need to skip :
2551 // * the 128 bytes of File Preamble (often padded with zeroes),
2552 // * the 4 bytes of "DICM" string,
2553 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2554 // i.e. a total of 136 bytes.
2558 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2559 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2560 // *Implicit* VR. -and it is !-
2562 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2563 memcmp(entCur, "OB", (size_t)2) == 0 ||
2564 memcmp(entCur, "UI", (size_t)2) == 0 ||
2565 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2566 // when Write DCM *adds*
2568 // Use gdcmDocument::dicom_vr to test all the possibilities
2569 // instead of just checking for UL, OB and UI !? group 0000
2571 Filetype = gdcmExplicitVR;
2572 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2573 "explicit Value Representation");
2577 Filetype = gdcmImplicitVR;
2578 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2579 "not an explicit Value Representation");
2585 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2586 "HostByteOrder != NetworkByteOrder");
2591 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2592 "HostByteOrder = NetworkByteOrder");
2595 // Position the file position indicator at first tag (i.e.
2596 // after the file preamble and the "DICM" string).
2598 fseek (Fp, 132L, SEEK_SET);
2602 // Alas, this is not a DicomV3 file and whatever happens there is no file
2603 // preamble. We can reset the file position indicator to where the data
2604 // is (i.e. the beginning of the file).
2605 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2608 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2609 // By clean we mean that the length of the first tag is written down.
2610 // If this is the case and since the length of the first group HAS to be
2611 // four (bytes), then determining the proper swap code is straightforward.
2614 // We assume the array of char we are considering contains the binary
2615 // representation of a 32 bits integer. Hence the following dirty
2617 s32 = *((uint32_t *)(entCur));
2638 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2639 // It is time for despaired wild guesses.
2640 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2641 // i.e. the 'group length' element is not present :
2643 // check the supposed to be 'group number'
2644 // 0x0002 or 0x0004 or 0x0008
2645 // to determine ' SwapCode' value .
2646 // Only 0 or 4321 will be possible
2647 // (no oportunity to check for the formerly well known
2648 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2649 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2650 // the file IS NOT ACR-NEMA nor DICOM V3
2651 // Find a trick to tell it the caller...
2653 s16 = *((uint16_t *)(deb));
2670 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2671 "ACR/NEMA unfound swap info (Really hopeless !)");
2672 Filetype = gdcmUnknown;
2675 // Then the only info we have is the net2host one.
2685 * \brief Restore the unproperly loaded values i.e. the group, the element
2686 * and the dictionary entry depending on them.
2688 void gdcmDocument::SwitchSwapToBigEndian()
2690 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2691 "Switching to BigEndian mode.");
2692 if ( SwapCode == 0 )
2696 else if ( SwapCode == 4321 )
2700 else if ( SwapCode == 3412 )
2704 else if ( SwapCode == 2143 )
2711 * \brief during parsing, Header Elements too long are not loaded in memory
2714 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2720 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2722 MaxSizeLoadEntry = 0xffffffff;
2725 MaxSizeLoadEntry = newSize;
2730 * \brief Header Elements too long will not be printed
2731 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2734 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2736 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2741 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2743 MaxSizePrintEntry = 0xffffffff;
2746 MaxSizePrintEntry = newSize;
2752 * \brief Read the next tag but WITHOUT loading it's value
2753 * (read the 'Group Number', the 'Element Number',
2754 * gets the Dict Entry
2755 * gets the VR, gets the length, gets the offset value)
2756 * @return On succes the newly created DocEntry, NULL on failure.
2758 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2765 group = ReadInt16();
2768 catch ( gdcmFormatError e )
2770 // We reached the EOF (or an error occured) therefore
2771 // header parsing has to be considered as finished.
2776 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2777 FindDocEntryVR(newEntry);
2781 FindDocEntryLength(newEntry);
2783 catch ( gdcmFormatError e )
2791 newEntry->SetOffset(ftell(Fp));
2798 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2799 * in the TagHt dictionary.
2800 * @param group The generated tag must belong to this group.
2801 * @return The element of tag with given group which is fee.
2803 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2805 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2807 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2808 if (TagHT.count(key) == 0)
2817 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2818 * is placed at the beginning of a tag check whether this
2819 * tag is (TestGroup, TestElement).
2820 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2821 * is modified to point after the tag.
2822 * On failure (i.e. when the tag wasn't the expected tag
2823 * (TestGroup, TestElement) the internal file pointer
2824 * \ref gdcmDocument::Fp is restored to it's original position.
2825 * @param testGroup The expected group of the tag.
2826 * @param testElement The expected Element of the tag.
2827 * @return True on success, false otherwise.
2829 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2831 long positionOnEntry = ftell(Fp);
2832 long currentPosition = ftell(Fp); // On debugging purposes
2834 //// Read the Item Tag group and element, and make
2835 // sure they are what we expected:
2836 uint16_t itemTagGroup = ReadInt16();
2837 uint16_t itemTagElement = ReadInt16();
2838 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2840 std::ostringstream s;
2841 s << " We should have found tag (";
2842 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2843 s << " but instead we encountered tag (";
2844 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2846 s << " at address: " << (unsigned)currentPosition << std::endl;
2847 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2848 dbg.Verbose(0, s.str().c_str());
2849 fseek(Fp, positionOnEntry, SEEK_SET);
2857 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2858 * is placed at the beginning of a tag (TestGroup, TestElement),
2859 * read the length associated to the Tag.
2860 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2861 * is modified to point after the tag and it's length.
2862 * On failure (i.e. when the tag wasn't the expected tag
2863 * (TestGroup, TestElement) the internal file pointer
2864 * \ref gdcmDocument::Fp is restored to it's original position.
2865 * @param testGroup The expected group of the tag.
2866 * @param testElement The expected Element of the tag.
2867 * @return On success returns the length associated to the tag. On failure
2870 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2872 long positionOnEntry = ftell(Fp);
2873 (void)positionOnEntry;
2875 if ( !ReadTag(testGroup, testElement) )
2880 //// Then read the associated Item Length
2881 long currentPosition = ftell(Fp);
2882 uint32_t itemLength = ReadInt32();
2884 std::ostringstream s;
2885 s << "Basic Item Length is: "
2886 << itemLength << std::endl;
2887 s << " at address: " << (unsigned)currentPosition << std::endl;
2888 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2894 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2895 * No other way so 'skip' the Data
2897 void gdcmDocument::Parse7FE0 ()
2899 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2902 // Should warn user FIXME
2906 if ( IsImplicitVRLittleEndianTransferSyntax()
2907 || IsExplicitVRLittleEndianTransferSyntax()
2908 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2909 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2914 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2916 //// Read the Basic Offset Table Item Tag length...
2917 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2919 //// ... and then read length[s] itself[themselves]. We don't use
2920 // the values read (BTW what is the purpous of those lengths ?)
2921 if ( itemLength != 0 )
2923 // BTW, what is the purpous of those length anyhow !?
2924 char* basicOffsetTableItemValue = new char[itemLength + 1];
2925 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2927 for (unsigned int i=0; i < itemLength; i += 4 )
2929 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2930 std::ostringstream s;
2931 s << " Read one length: ";
2932 s << std::hex << individualLength << std::endl;
2933 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2935 delete[] basicOffsetTableItemValue;
2938 if ( ! IsRLELossLessTransferSyntax() )
2942 //// We then skip (not reading them) all the fragments of images:
2943 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2945 SkipBytes(itemLength);
2952 long rleSegmentLength[15], fragmentLength;
2954 // While we find some items:
2955 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2957 // Parse fragments of the current Fragment (Frame)
2958 //------------------ scanning (not reading) fragment pixels
2959 uint32_t nbRleSegments = ReadInt32();
2961 //// Reading RLE Segments Offset Table
2962 uint32_t rleSegmentOffsetTable[15];
2963 for(int k=1; k<=15; k++)
2965 ftellRes = ftell(Fp);
2966 rleSegmentOffsetTable[k] = ReadInt32();
2969 // skipping (not reading) RLE Segments
2970 if ( nbRleSegments > 1)
2972 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2974 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2975 - rleSegmentOffsetTable[k];
2976 ftellRes = ftell(Fp);
2977 SkipBytes(rleSegmentLength[k]);
2981 rleSegmentLength[nbRleSegments] = fragmentLength
2982 - rleSegmentOffsetTable[nbRleSegments];
2983 ftellRes = ftell(Fp);
2984 SkipBytes(rleSegmentLength[nbRleSegments]);
2987 // Make sure that at the end of the item we encounter a 'Sequence
2989 if ( !ReadTag(0xfffe, 0xe0dd) )
2991 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2992 dbg.Verbose(0, " at end of RLE item sequence");
2998 * \brief Walk recursively the given \ref gdcmDocEntrySet, and feed
2999 * the given hash table (\ref TagDocEntryHT) with all the
3000 * \ref gdcmDocEntry (Dicom entries) encountered.
3001 * This method does the job for \ref BuildFlatHashTable.
3002 * @param builtHT Where to collect all the \ref gdcmDocEntry encountered
3003 * when recursively walking the given set.
3004 * @param set The structure to be traversed (recursively).
3006 void gdcmDocument::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3007 gdcmDocEntrySet* set )
3009 if (gdcmElementSet* elementSet = dynamic_cast< gdcmElementSet* > ( set ) )
3011 TagDocEntryHT* currentHT = elementSet->GetTagHT();
3012 for( TagDocEntryHT::const_iterator i = currentHT->begin();
3013 i != currentHT->end();
3016 gdcmDocEntry* entry = i->second;
3017 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
3019 ListSQItem& items = seqEntry->GetSQItems();
3020 for( ListSQItem::const_iterator item = items.begin();
3021 item != items.end();
3024 BuildFlatHashTableRecurse( builtHT, *item );
3028 builtHT[entry->GetKey()] = entry;
3033 if (gdcmSQItem* SQItemSet = dynamic_cast< gdcmSQItem* > ( set ) )
3035 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3036 for (ListDocEntry::iterator i = currentList.begin();
3037 i != currentList.end();
3040 gdcmDocEntry* entry = *i;
3041 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
3043 ListSQItem& items = seqEntry->GetSQItems();
3044 for( ListSQItem::const_iterator item = items.begin();
3045 item != items.end();
3048 BuildFlatHashTableRecurse( builtHT, *item );
3052 builtHT[entry->GetKey()] = entry;
3059 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3062 * The structure used by a gdcmDocument (through \ref gdcmElementSet),
3063 * in order to old the parsed entries of a Dicom header, is a recursive
3064 * one. This is due to the fact that the sequences (when present)
3065 * can be nested. Additionaly, the sequence items (represented in
3066 * gdcm as \ref gdcmSQItem) add an extra complexity to the data
3067 * structure. Hence, a gdcm user whishing to visit all the entries of
3068 * a Dicom header will need to dig in the gdcm internals (which
3069 * implies exposing all the internal data structures to the API).
3070 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3071 * recursively builds a temporary hash table, which olds all the
3072 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3074 * \warning Of course there is NO integrity constrain between the
3075 * returned \ref TagDocEntryHT and the \ref gdcmElemenSet used
3076 * to build it. Hence if the underlying \ref gdcmElemenSet is
3077 * altered, then it is the caller responsability to invoke
3078 * \ref BuildFlatHashTable again...
3079 * @return The flat std::map<> we juste build.
3081 TagDocEntryHT* gdcmDocument::BuildFlatHashTable()
3083 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3084 BuildFlatHashTableRecurse( *FlatHT, this );
3091 * \brief Compares two documents, according to \ref gdcmDicomDir rules
3092 * \warning Does NOT work with ACR-NEMA files
3093 * \todo Find a trick to solve the pb (use RET fields ?)
3095 * @return true if 'smaller'
3097 bool gdcmDocument::operator<(gdcmDocument &document)
3100 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3101 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3113 s1 = GetEntryByNumber(0x0010,0x0020);
3114 s2 = document.GetEntryByNumber(0x0010,0x0020);
3125 // Study Instance UID
3126 s1 = GetEntryByNumber(0x0020,0x000d);
3127 s2 = document.GetEntryByNumber(0x0020,0x000d);
3138 // Serie Instance UID
3139 s1 = GetEntryByNumber(0x0020,0x000e);
3140 s2 = document.GetEntryByNumber(0x0020,0x000e);
3156 //-----------------------------------------------------------------------------