1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/22 21:01:55 $
7 Version: $Revision: 1.87 $
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 ()
199 //-----------------------------------------------------------------------------
203 * \brief Prints The Dict Entries of THE public Dicom Dictionary
206 void gdcmDocument::PrintPubDict(std::ostream & os)
208 RefPubDict->Print(os);
212 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
215 void gdcmDocument::PrintShaDict(std::ostream & os)
217 RefShaDict->Print(os);
220 //-----------------------------------------------------------------------------
223 * \brief Get the public dictionary used
225 gdcmDict *gdcmDocument::GetPubDict()
231 * \brief Get the shadow dictionary used
233 gdcmDict *gdcmDocument::GetShaDict()
239 * \brief Set the shadow dictionary used
240 * \param dict dictionary to use in shadow
242 bool gdcmDocument::SetShaDict(gdcmDict *dict)
249 * \brief Set the shadow dictionary used
250 * \param dictName name of the dictionary to use in shadow
252 bool gdcmDocument::SetShaDict(DictKey const & dictName)
254 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
259 * \brief This predicate, based on hopefully reasonable heuristics,
260 * decides whether or not the current gdcmDocument was properly parsed
261 * and contains the mandatory information for being considered as
262 * a well formed and usable Dicom/Acr File.
263 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
266 bool gdcmDocument::IsReadable()
268 if( Filetype == gdcmUnknown)
270 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
276 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
286 * \brief Internal function that checks whether the Transfer Syntax given
287 * as argument is the one present in the current document.
288 * @param syntaxToCheck The transfert syntax we need to check against.
289 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
290 * the current document. False either when the document contains
291 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
293 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
295 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
301 // The entry might be present but not loaded (parsing and loading
302 // happen at different stages): try loading and proceed with check...
303 LoadDocEntrySafe(entry);
304 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
306 std::string transfer = valEntry->GetValue();
307 // The actual transfer (as read from disk) might be padded. We
308 // first need to remove the potential padding. We can make the
309 // weak assumption that padding was not executed with digits...
310 if ( transfer.length() == 0 ) { // for brain damaged headers
313 while ( ! isdigit(transfer[transfer.length()-1]) )
315 transfer.erase(transfer.length()-1, 1);
317 if ( transfer == syntaxToCheck )
326 * \brief Determines if the Transfer Syntax of the present document
327 * corresponds to a Implicit Value Representation of
329 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
330 * @return True when ImplicitVRLittleEndian found. False in all other cases.
332 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
334 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
338 * \brief Determines if the Transfer Syntax was already encountered
339 * and if it corresponds to a ExplicitVRLittleEndian one.
340 * @return True when ExplicitVRLittleEndian found. False in all other cases.
342 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
344 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
348 * \brief Determines if the Transfer Syntax was already encountered
349 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
350 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
352 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
354 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
358 * \brief Determines if the Transfer Syntax was already encountered
359 * and if it corresponds to a Explicit VR Big Endian one.
360 * @return True when big endian found. False in all other cases.
362 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
364 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
368 * \brief Determines if the Transfer Syntax was already encountered
369 * and if it corresponds to a JPEGBaseLineProcess1 one.
370 * @return True when JPEGBaseLineProcess1found. False in all other cases.
372 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
374 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
378 * \brief Determines if the Transfer Syntax was already encountered
379 * and if it corresponds to a JPEGExtendedProcess2-4 one.
380 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
382 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
384 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
388 * \brief Determines if the Transfer Syntax was already encountered
389 * and if it corresponds to a JPEGExtendeProcess3-5 one.
390 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
392 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
394 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
398 * \brief Determines if the Transfer Syntax was already encountered
399 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
400 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
403 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
405 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
409 * \brief Determines if the Transfer Syntax was already encountered
410 * and if it corresponds to a RLE Lossless one.
411 * @return True when RLE Lossless found. False in all
414 bool gdcmDocument::IsRLELossLessTransferSyntax()
416 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
420 * \brief Determines if Transfer Syntax was already encountered
421 * and if it corresponds to a JPEG Lossless one.
422 * @return True when RLE Lossless found. False in all
426 bool gdcmDocument::IsJPEGLossless()
428 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
429 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
430 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
434 * \brief Determines if the Transfer Syntax was already encountered
435 * and if it corresponds to a JPEG2000 one
436 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
439 bool gdcmDocument::IsJPEG2000()
441 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
442 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
446 * \brief Predicate for dicom version 3 file.
447 * @return True when the file is a dicom version 3.
449 bool gdcmDocument::IsDicomV3()
451 // Checking if Transfert Syntax exists is enough
452 // Anyway, it's to late check if the 'Preamble' was found ...
453 // And ... would it be a rich idea to check ?
454 // (some 'no Preamble' DICOM images exist !)
455 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
459 * \brief returns the File Type
460 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
461 * @return the FileType code
463 FileType gdcmDocument::GetFileType()
469 * \brief Tries to open the file \ref gdcmDocument::Filename and
470 * checks the preamble when existing.
471 * @return The FILE pointer on success.
473 FILE* gdcmDocument::OpenFile()
475 Fp = fopen(Filename.c_str(),"rb");
480 "gdcmDocument::OpenFile cannot open file: ",
486 fread(&zero, (size_t)2, (size_t)1, Fp);
488 //ACR -- or DICOM with no Preamble --
489 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
495 fseek(Fp, 126L, SEEK_CUR);
497 fread(dicm, (size_t)4, (size_t)1, Fp);
498 if( memcmp(dicm, "DICM", 4) == 0 )
505 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
512 * \brief closes the file
513 * @return TRUE if the close was successfull
515 bool gdcmDocument::CloseFile()
517 int closed = fclose(Fp);
524 * \brief Writes in a file all the Header Entries (Dicom Elements)
525 * @param fp file pointer on an already open file
526 * @param filetype Type of the File to be written
527 * (ACR-NEMA, ExplicitVR, ImplicitVR)
528 * \return Always true.
530 void gdcmDocument::Write(FILE* fp,FileType filetype)
532 /// \todo move the following lines (and a lot of others, to be written)
533 /// to a future function CheckAndCorrectHeader
534 /// (necessary if user wants to write a DICOM V3 file
535 /// starting from an ACR-NEMA (V2) gdcmHeader
537 if (filetype == gdcmImplicitVR)
539 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
540 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
542 /// \todo Refer to standards on page 21, chapter 6.2
543 /// "Value representation": values with a VR of UI shall be
544 /// padded with a single trailing null
545 /// in the following case we have to padd manually with a 0
547 SetEntryLengthByNumber(18, 0x0002, 0x0010);
550 if (filetype == gdcmExplicitVR)
552 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
553 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
555 /// \todo Refer to standards on page 21, chapter 6.2
556 /// "Value representation": values with a VR of UI shall be
557 /// padded with a single trailing null
558 /// Dans le cas suivant on doit pader manuellement avec un 0
560 SetEntryLengthByNumber(20, 0x0002, 0x0010);
564 * \todo rewrite later, if really usefull
565 * - 'Group Length' element is optional in DICOM
566 * - but un-updated odd groups lengthes can causes pb
569 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
570 * UpdateGroupLength(false,filetype);
571 * if ( filetype == ACR)
572 * UpdateGroupLength(true,ACR);
575 gdcmElementSet::Write(fp, filetype); // This one is recursive
580 * \brief Modifies the value of a given Header Entry (Dicom Element)
581 * when it exists. Create it with the given value when unexistant.
582 * @param value (string) Value to be set
583 * @param group Group number of the Entry
584 * @param elem Element number of the Entry
585 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
586 * \return pointer to the modified/created Header Entry (NULL when creation
589 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
590 std::string const & value,
593 std::string const & VR )
595 gdcmValEntry* valEntry = 0;
596 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
600 // check if (group,element) DictEntry exists
601 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
604 // Find out if the tag we received is in the dictionaries:
605 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
606 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
609 currentEntry = NewDocEntryByNumber(group, elem,VR);
613 currentEntry = NewDocEntryByNumber(group, elem);
618 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
619 " NewDocEntryByNumber failed.");
622 valEntry = new gdcmValEntry(currentEntry);
623 if ( !AddEntry(valEntry))
625 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
626 " failed allthough this is a creation.");
631 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
632 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
633 // then we change it to a ValEntry ?
634 // Shouldn't it be considered as an error ?
636 // We need to promote the gdcmDocEntry to a gdcmValEntry:
637 valEntry = new gdcmValEntry(currentEntry);
638 if (!RemoveEntry(currentEntry))
640 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
641 " of previous DocEntry failed.");
644 if ( !AddEntry(valEntry))
646 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
647 " promoted ValEntry failed.");
653 SetEntryByNumber(value, group, elem);
659 * \brief Modifies the value of a given Header Entry (Dicom Element)
660 * when it exists. Create it with the given value when unexistant.
661 * @param voidArea (binary) value to be set
662 * @param Group Group number of the Entry
663 * @param Elem Element number of the Entry
664 * \return pointer to the modified/created Header Entry (NULL when creation
667 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
672 std::string const & VR )
674 gdcmBinEntry* binEntry = 0;
675 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
679 // check if (group,element) DictEntry exists
680 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
683 // Find out if the tag we received is in the dictionaries:
684 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
685 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
689 currentEntry = NewDocEntryByNumber(group, elem, VR);
693 currentEntry = NewDocEntryByNumber(group, elem);
697 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
698 " NewDocEntryByNumber failed.");
701 binEntry = new gdcmBinEntry(currentEntry);
702 if ( !AddEntry(binEntry))
704 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
705 " failed allthough this is a creation.");
710 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
711 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
712 // then we change it to a BinEntry ?
713 // Shouldn't it be considered as an error ?
715 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
716 binEntry = new gdcmBinEntry(currentEntry);
717 if (!RemoveEntry(currentEntry))
719 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
720 " of previous DocEntry failed.");
723 if ( !AddEntry(binEntry))
725 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
726 " promoted BinEntry failed.");
732 SetEntryByNumber(voidArea, lgth, group, elem);
739 * \brief Modifies the value of a given Header Entry (Dicom Element)
740 * when it exists. Create it when unexistant.
741 * @param Group Group number of the Entry
742 * @param Elem Element number of the Entry
743 * \return pointer to the modified/created SeqEntry (NULL when creation
746 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
751 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
754 a = NewSeqEntryByNumber(group, elem);
760 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
767 * \brief Set a new value if the invoked element exists
768 * Seems to be useless !!!
769 * @param value new element value
770 * @param group group number of the Entry
771 * @param elem element number of the Entry
774 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
775 uint16_t group, uint16_t elem )
777 SetEntryByNumber(value, group, elem);
782 //-----------------------------------------------------------------------------
786 * \brief Checks if a given Dicom Element exists within the H table
787 * @param group Group number of the searched Dicom Element
788 * @param element Element number of the searched Dicom Element
789 * @return true is found
791 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
793 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
794 return TagHT.count(key);
798 * \brief Searches within Header Entries (Dicom Elements) parsed with
799 * the public and private dictionaries
800 * for the element value of a given tag.
801 * \warning Don't use any longer : use GetPubEntryByName
802 * @param tagName name of the searched element.
803 * @return Corresponding element value when it exists,
804 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
806 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
808 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
814 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
818 * \brief Searches within Header Entries (Dicom Elements) parsed with
819 * the public and private dictionaries
820 * for the element value representation of a given tag.
822 * Obtaining the VR (Value Representation) might be needed by caller
823 * to convert the string typed content to caller's native type
824 * (think of C++ vs Python). The VR is actually of a higher level
825 * of semantics than just the native C++ type.
826 * @param tagName name of the searched element.
827 * @return Corresponding element value representation when it exists,
828 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
830 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
832 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
833 if( dictEntry == NULL)
838 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
839 dictEntry->GetElement());
840 return elem->GetVR();
844 * \brief Searches within Header Entries (Dicom Elements) parsed with
845 * the public and private dictionaries
846 * for the element value representation of a given tag.
847 * @param group Group number of the searched tag.
848 * @param element Element number of the searched tag.
849 * @return Corresponding element value representation when it exists,
850 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
852 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
854 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
855 /// \todo use map methods, instead of multimap JPR
856 if ( !TagHT.count(key))
861 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
865 * \brief Searches within Header Entries (Dicom Elements) parsed with
866 * the public and private dictionaries
867 * for the element value representation of a given tag..
869 * Obtaining the VR (Value Representation) might be needed by caller
870 * to convert the string typed content to caller's native type
871 * (think of C++ vs Python). The VR is actually of a higher level
872 * of semantics than just the native C++ type.
873 * @param group Group number of the searched tag.
874 * @param element Element number of the searched tag.
875 * @return Corresponding element value representation when it exists,
876 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
878 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
880 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
885 return elem->GetVR();
889 * \brief Searches within Header Entries (Dicom Elements) parsed with
890 * the public and private dictionaries
891 * for the value length of a given tag..
892 * @param group Group number of the searched tag.
893 * @param element Element number of the searched tag.
894 * @return Corresponding element length; -2 if not found
896 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
898 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
901 return -2; //magic number
903 return elem->GetLength();
906 * \brief Sets the value (string) of the Header Entry (Dicom Element)
907 * @param content string value of the Dicom Element
908 * @param tagName name of the searched Dicom Element.
909 * @return true when found
911 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
913 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
919 return SetEntryByNumber(content,dictEntry->GetGroup(),
920 dictEntry->GetElement());
924 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
925 * through it's (group, element) and modifies it's content with
927 * @param content new value (string) to substitute with
928 * @param group group number of the Dicom Element to modify
929 * @param element element number of the Dicom Element to modify
931 bool gdcmDocument::SetEntryByNumber(std::string const & content,
938 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
941 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
942 " ValEntry (try promotion first).");
945 // Non even content must be padded with a space (020H)...
946 std::string finalContent = content;
947 if( finalContent.length() % 2 )
949 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
951 valEntry->SetValue(finalContent);
953 // Integers have a special treatement for their length:
955 l = finalContent.length();
956 if ( l != 0) // To avoid to be cheated by 'zero length' integers
958 gdcmVRKey vr = valEntry->GetVR();
959 if( vr == "US" || vr == "SS" )
961 c = CountSubstring(content, "\\") + 1; // for multivaluated items
964 else if( vr == "UL" || vr == "SL" )
966 c = CountSubstring(content, "\\") + 1; // for multivaluated items
970 valEntry->SetLength(l);
975 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
976 * through it's (group, element) and modifies it's content with
978 * @param content new value (void *) to substitute with
979 * @param lgth new value length
980 * @param group group number of the Dicom Element to modify
981 * @param element element number of the Dicom Element to modify
983 bool gdcmDocument::SetEntryByNumber(void *content,
988 (void)lgth; //not used
989 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
990 if ( !TagHT.count(key))
995 /* Hope Binary field length is *never* wrong
996 if(lgth%2) // Non even length are padded with a space (020H).
999 //content = content + '\0'; // fing a trick to enlarge a binary field?
1002 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1003 a->SetVoidArea(content);
1005 a->SetValue(GDCM_BINLOADED);
1011 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1012 * in the PubDocEntrySet of this instance
1013 * through it's (group, element) and modifies it's length with
1015 * \warning Use with extreme caution.
1016 * @param l new length to substitute with
1017 * @param group group number of the Entry to modify
1018 * @param element element number of the Entry to modify
1019 * @return true on success, false otherwise.
1021 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1025 /// \todo use map methods, instead of multimap JPR
1026 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1027 if ( !TagHT.count(key) )
1033 l++; // length must be even
1035 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1041 * \brief Gets (from Header) the offset of a 'non string' element value
1042 * (LoadElementValues has already be executed)
1043 * @param group group number of the Entry
1044 * @param elem element number of the Entry
1045 * @return File Offset of the Element Value
1047 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1049 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1052 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1055 return entry->GetOffset();
1059 * \brief Gets (from Header) a 'non string' element value
1060 * (LoadElementValues has already be executed)
1061 * @param group group number of the Entry
1062 * @param elem element number of the Entry
1063 * @return Pointer to the 'non string' area
1065 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1067 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1070 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1073 return ((gdcmBinEntry *)entry)->GetVoidArea();
1077 * \brief Loads (from disk) the element content
1078 * when a string is not suitable
1079 * @param group group number of the Entry
1080 * @param elem element number of the Entry
1082 void* gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1084 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1089 size_t o =(size_t)docElement->GetOffset();
1090 fseek(Fp, o, SEEK_SET);
1091 size_t l = docElement->GetLength();
1092 char* a = new char[l];
1095 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1098 size_t l2 = fread(a, 1, l , Fp);
1104 /// \todo Drop any already existing void area! JPR
1105 if( !SetEntryVoidAreaByNumber( a, group, elem ) );
1107 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea setting failed.");
1112 * \brief Loads (from disk) the element content
1113 * when a string is not suitable
1114 * @param element Entry whose voidArea is going to be loaded
1116 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1118 size_t o =(size_t)element->GetOffset();
1119 fseek(Fp, o, SEEK_SET);
1120 size_t l = element->GetLength();
1121 char* a = new char[l];
1124 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1127 element->SetVoidArea((void *)a);
1128 /// \todo check the result
1129 size_t l2 = fread(a, 1, l , Fp);
1140 * \brief Sets a 'non string' value to a given Dicom Element
1141 * @param area area containing the 'non string' value
1142 * @param group Group number of the searched Dicom Element
1143 * @param element Element number of the searched Dicom Element
1146 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1150 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1151 if ( !currentEntry )
1155 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1157 binEntry->SetVoidArea( area );
1164 * \brief Update the entries with the shadow dictionary.
1165 * Only non even entries are analyzed
1167 void gdcmDocument::UpdateShaEntries()
1169 //gdcmDictEntry *entry;
1172 /// \todo TODO : still any use to explore recursively the whole structure?
1174 for(ListTag::iterator it=listEntries.begin();
1175 it!=listEntries.end();
1178 // Odd group => from public dictionary
1179 if((*it)->GetGroup()%2==0)
1182 // Peer group => search the corresponding dict entry
1184 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1188 if((*it)->IsImplicitVR())
1193 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1195 // Set the new entry and the new value
1196 (*it)->SetDictEntry(entry);
1197 CheckDocEntryVR(*it,vr);
1199 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1204 // Remove precedent value transformation
1205 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1212 * \brief Searches within the Header Entries for a Dicom Element of
1214 * @param tagName name of the searched Dicom Element.
1215 * @return Corresponding Dicom Element when it exists, and NULL
1218 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1220 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1226 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1230 * \brief retrieves a Dicom Element (the first one) using (group, element)
1231 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1232 * if you think it's NOT UNIQUE, check the count number
1233 * and use iterators to retrieve ALL the Dicoms Elements within
1234 * a given couple (group, element)
1235 * @param group Group number of the searched Dicom Element
1236 * @param element Element number of the searched Dicom Element
1239 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1242 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1243 if ( !TagHT.count(key))
1247 return TagHT.find(key)->second;
1251 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1252 * returns a result when the corresponding entry is of type
1254 * @return When present, the corresponding ValEntry.
1256 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1259 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1260 if ( !currentEntry )
1264 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1268 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1274 * \brief Loads the element while preserving the current
1275 * underlying file position indicator as opposed to
1276 * to LoadDocEntry that modifies it.
1277 * @param entry Header Entry whose value shall be loaded.
1280 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1282 long PositionOnEntry = ftell(Fp);
1283 LoadDocEntry(entry);
1284 fseek(Fp, PositionOnEntry, SEEK_SET);
1288 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1290 * @return The properly swaped 32 bits integer.
1292 uint32_t gdcmDocument::SwapLong(uint32_t a)
1299 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1300 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1304 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1308 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1311 //std::cout << "swapCode= " << SwapCode << std::endl;
1312 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1319 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1321 * @return The properly unswaped 32 bits integer.
1323 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1329 * \brief Swaps the bytes so they agree with the processor order
1330 * @return The properly swaped 16 bits integer.
1332 uint16_t gdcmDocument::SwapShort(uint16_t a)
1334 if ( SwapCode == 4321 || SwapCode == 2143 )
1336 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1342 * \brief Unswaps the bytes so they agree with the processor order
1343 * @return The properly unswaped 16 bits integer.
1345 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1347 return SwapShort(a);
1350 //-----------------------------------------------------------------------------
1354 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1355 * @return length of the parsed set.
1358 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1363 gdcmDocEntry *newDocEntry = 0;
1364 unsigned long l = 0;
1368 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1372 newDocEntry = ReadNextDocEntry( );
1378 gdcmVRKey vr = newDocEntry->GetVR();
1382 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1384 /////////////////////// ValEntry
1385 gdcmValEntry* newValEntry =
1386 new gdcmValEntry( newDocEntry->GetDictEntry() );
1387 newValEntry->Copy( newDocEntry );
1389 // When "set" is a gdcmDocument, then we are at the top of the
1390 // hierarchy and the Key is simply of the form ( group, elem )...
1391 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1394 newValEntry->SetKey( newValEntry->GetKey() );
1396 // ...but when "set" is a gdcmSQItem, we are inserting this new
1397 // valEntry in a sequence item. Hence the key has the
1398 // generalized form (refer to \ref gdcmBaseTagKey):
1399 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1401 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1402 + newValEntry->GetKey() );
1405 set->AddEntry( newValEntry );
1406 LoadDocEntry( newValEntry );
1407 if (newValEntry->IsItemDelimitor())
1411 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1418 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1420 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1421 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1422 "nor BinEntry. Probably unknown VR.");
1425 //////////////////// BinEntry or UNKOWN VR:
1426 gdcmBinEntry* newBinEntry =
1427 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1428 newBinEntry->Copy( newDocEntry );
1430 // When "this" is a gdcmDocument the Key is simply of the
1431 // form ( group, elem )...
1432 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1435 newBinEntry->SetKey( newBinEntry->GetKey() );
1437 // but when "this" is a SQItem, we are inserting this new
1438 // valEntry in a sequence item, and the kay has the
1439 // generalized form (refer to \ref gdcmBaseTagKey):
1440 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1442 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1443 + newBinEntry->GetKey() );
1446 set->AddEntry( newBinEntry );
1447 LoadDocEntry( newBinEntry );
1450 if (newDocEntry->GetGroup() == 0x7fe0 &&
1451 newDocEntry->GetElement() == 0x0010 )
1453 if (newDocEntry->GetReadLength()==0xffffffff)
1455 // Broken US.3405.1.dcm
1456 Parse7FE0(); // to skip the pixels
1457 // (multipart JPEG/RLE are trouble makers)
1461 SkipToNextDocEntry(newDocEntry);
1462 l = newDocEntry->GetFullLength();
1467 // to be sure we are at the beginning
1468 SkipToNextDocEntry(newDocEntry);
1469 l = newDocEntry->GetFullLength();
1475 l = newDocEntry->GetReadLength();
1476 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1478 if ( l == 0xffffffff )
1487 // no other way to create it ...
1488 gdcmSeqEntry* newSeqEntry =
1489 new gdcmSeqEntry( newDocEntry->GetDictEntry() );
1490 newSeqEntry->Copy( newDocEntry );
1491 newSeqEntry->SetDelimitorMode( delim_mode );
1493 // At the top of the hierarchy, stands a gdcmDocument. When "set"
1494 // is a gdcmDocument, then we are building the first depth level.
1495 // Hence the gdcmSeqEntry we are building simply has a depth
1497 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1500 newSeqEntry->SetDepthLevel( 1 );
1501 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1503 // But when "set" is allready a SQItem, we are building a nested
1504 // sequence, and hence the depth level of the new gdcmSeqEntry
1505 // we are building, is one level deeper:
1506 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1508 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1509 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1510 + newSeqEntry->GetKey() );
1514 { // Don't try to parse zero-length sequences
1515 (void)ParseSQ( newSeqEntry,
1516 newDocEntry->GetOffset(),
1519 set->AddEntry( newSeqEntry );
1520 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1527 return l; // Probably useless
1531 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1532 * @return parsed length for this level
1534 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1535 long offset, long l_max, bool delim_mode)
1537 int SQItemNumber = 0;
1542 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1545 // FIXME Should warn user
1550 if ( newDocEntry->IsSequenceDelimitor() )
1552 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1556 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1561 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1562 std::ostringstream newBase;
1563 newBase << seqEntry->GetKey()
1567 itemSQ->SetBaseTagKey( newBase.str() );
1568 unsigned int l = newDocEntry->GetReadLength();
1570 if ( l == 0xffffffff )
1579 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1581 seqEntry->AddEntry( itemSQ, SQItemNumber );
1583 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1589 int lgth = ftell(Fp) - offset;
1594 * \brief Loads the element content if its length doesn't exceed
1595 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1596 * @param entry Header Entry (Dicom Element) to be dealt with
1598 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1601 uint16_t group = entry->GetGroup();
1602 std::string vr = entry->GetVR();
1603 uint32_t length = entry->GetLength();
1605 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1607 // A SeQuence "contains" a set of Elements.
1608 // (fffe e000) tells us an Element is beginning
1609 // (fffe e00d) tells us an Element just ended
1610 // (fffe e0dd) tells us the current SeQuence just ended
1611 if( group == 0xfffe )
1613 // NO more value field for SQ !
1617 // When the length is zero things are easy:
1620 ((gdcmValEntry *)entry)->SetValue("");
1624 // The elements whose length is bigger than the specified upper bound
1625 // are not loaded. Instead we leave a short notice of the offset of
1626 // the element content and it's length.
1628 std::ostringstream s;
1629 if (length > MaxSizeLoadEntry)
1631 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1633 //s << "gdcm::NotLoaded (BinEntry)";
1634 s << GDCM_NOTLOADED;
1635 s << " Address:" << (long)entry->GetOffset();
1636 s << " Length:" << entry->GetLength();
1637 s << " x(" << std::hex << entry->GetLength() << ")";
1638 binEntryPtr->SetValue(s.str());
1640 // Be carefull : a BinEntry IS_A ValEntry ...
1641 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1643 // s << "gdcm::NotLoaded. (ValEntry)";
1644 s << GDCM_NOTLOADED;
1645 s << " Address:" << (long)entry->GetOffset();
1646 s << " Length:" << entry->GetLength();
1647 s << " x(" << std::hex << entry->GetLength() << ")";
1648 valEntryPtr->SetValue(s.str());
1653 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1654 << "nor a ValEntry ?! Should never print that !" << std::endl;
1657 // to be sure we are at the end of the value ...
1658 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1662 // When we find a BinEntry not very much can be done :
1663 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1665 s << GDCM_BINLOADED;
1666 binEntryPtr->SetValue(s.str());
1667 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1671 /// \todo Any compacter code suggested (?)
1672 if ( IsDocEntryAnInteger(entry) )
1676 // When short integer(s) are expected, read and convert the following
1677 // n *two characters properly i.e. consider them as short integers as
1678 // opposed to strings.
1679 // Elements with Value Multiplicity > 1
1680 // contain a set of integers (not a single one)
1681 if (vr == "US" || vr == "SS")
1684 NewInt = ReadInt16();
1688 for (int i=1; i < nbInt; i++)
1691 NewInt = ReadInt16();
1696 // See above comment on multiple integers (mutatis mutandis).
1697 else if (vr == "UL" || vr == "SL")
1700 NewInt = ReadInt32();
1704 for (int i=1; i < nbInt; i++)
1707 NewInt = ReadInt32();
1712 #ifdef GDCM_NO_ANSI_STRING_STREAM
1713 s << std::ends; // to avoid oddities on Solaris
1714 #endif //GDCM_NO_ANSI_STRING_STREAM
1716 ((gdcmValEntry *)entry)->SetValue(s.str());
1720 // We need an additional byte for storing \0 that is not on disk
1721 //std::string newValue(length,0);
1722 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1723 //rah !! I can't believe it could work, normally this is a const char* !!!
1724 char *str = new char[length+1];
1725 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1727 std::string newValue = str;
1729 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1731 if ( item_read != 1 )
1733 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1734 "unread element value");
1735 valEntry->SetValue(GDCM_UNREAD);
1741 // Because of correspondance with the VR dic
1742 valEntry->SetValue(newValue);
1746 valEntry->SetValue(newValue);
1751 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1752 "Should have a ValEntry, here !");
1758 * \brief Find the value Length of the passed Header Entry
1759 * @param entry Header Entry whose length of the value shall be loaded.
1761 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1762 throw ( gdcmFormatError )
1764 uint16_t element = entry->GetElement();
1765 std::string vr = entry->GetVR();
1768 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1770 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1772 // The following reserved two bytes (see PS 3.5-2001, section
1773 // 7.1.2 Data element structure with explicit vr p27) must be
1774 // skipped before proceeding on reading the length on 4 bytes.
1775 fseek(Fp, 2L, SEEK_CUR);
1776 uint32_t length32 = ReadInt32();
1778 if ( vr == "OB" && length32 == 0xffffffff )
1783 lengthOB = FindDocEntryLengthOB();
1785 catch ( gdcmFormatUnexpected )
1787 // Computing the length failed (this happens with broken
1788 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1789 // chance to get the pixels by deciding the element goes
1790 // until the end of the file. Hence we artificially fix the
1791 // the length and proceed.
1792 long currentPosition = ftell(Fp);
1793 fseek(Fp,0L,SEEK_END);
1794 long lengthUntilEOF = ftell(Fp) - currentPosition;
1795 fseek(Fp, currentPosition, SEEK_SET);
1796 entry->SetLength(lengthUntilEOF);
1799 entry->SetLength(lengthOB);
1802 FixDocEntryFoundLength(entry, length32);
1806 // Length is encoded on 2 bytes.
1807 length16 = ReadInt16();
1809 // We can tell the current file is encoded in big endian (like
1810 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1811 // and it's value is the one of the encoding of a big endian file.
1812 // In order to deal with such big endian encoded files, we have
1813 // (at least) two strategies:
1814 // * when we load the "Transfer Syntax" tag with value of big endian
1815 // encoding, we raise the proper flags. Then we wait for the end
1816 // of the META group (0x0002) among which is "Transfer Syntax",
1817 // before switching the swap code to big endian. We have to postpone
1818 // the switching of the swap code since the META group is fully encoded
1819 // in little endian, and big endian coding only starts at the next
1820 // group. The corresponding code can be hard to analyse and adds
1821 // many additional unnecessary tests for regular tags.
1822 // * the second strategy consists in waiting for trouble, that shall
1823 // appear when we find the first group with big endian encoding. This
1824 // is easy to detect since the length of a "Group Length" tag (the
1825 // ones with zero as element number) has to be of 4 (0x0004). When we
1826 // encounter 1024 (0x0400) chances are the encoding changed and we
1827 // found a group with big endian encoding.
1828 // We shall use this second strategy. In order to make sure that we
1829 // can interpret the presence of an apparently big endian encoded
1830 // length of a "Group Length" without committing a big mistake, we
1831 // add an additional check: we look in the already parsed elements
1832 // for the presence of a "Transfer Syntax" whose value has to be "big
1833 // endian encoding". When this is the case, chances are we have got our
1834 // hands on a big endian encoded file: we switch the swap code to
1835 // big endian and proceed...
1836 if ( element == 0x0000 && length16 == 0x0400 )
1838 if ( !IsExplicitVRBigEndianTransferSyntax() )
1840 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1841 " not explicit VR." );
1845 SwitchSwapToBigEndian();
1846 // Restore the unproperly loaded values i.e. the group, the element
1847 // and the dictionary entry depending on them.
1848 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1849 uint16_t correctElem = SwapShort( entry->GetElement() );
1850 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1854 // This correct tag is not in the dictionary. Create a new one.
1855 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1857 // FIXME this can create a memory leaks on the old entry that be
1858 // left unreferenced.
1859 entry->SetDictEntry( newTag );
1862 // Heuristic: well, some files are really ill-formed.
1863 if ( length16 == 0xffff)
1865 // 0xffff means that we deal with 'Unknown Length' Sequence
1868 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1873 // Either implicit VR or a non DICOM conformal (see note below) explicit
1874 // VR that ommited the VR of (at least) this element. Farts happen.
1875 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1876 // on Data elements "Implicit and Explicit VR Data Elements shall
1877 // not coexist in a Data Set and Data Sets nested within it".]
1878 // Length is on 4 bytes.
1880 FixDocEntryFoundLength( entry, ReadInt32() );
1886 * \brief Find the Value Representation of the current Dicom Element.
1889 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1891 if ( Filetype != gdcmExplicitVR )
1898 long positionOnEntry = ftell(Fp);
1899 // Warning: we believe this is explicit VR (Value Representation) because
1900 // we used a heuristic that found "UL" in the first tag. Alas this
1901 // doesn't guarantee that all the tags will be in explicit VR. In some
1902 // cases (see e-film filtered files) one finds implicit VR tags mixed
1903 // within an explicit VR file. Hence we make sure the present tag
1904 // is in explicit VR and try to fix things if it happens not to be
1907 fread (vr, (size_t)2,(size_t)1, Fp);
1910 if( !CheckDocEntryVR(entry, vr) )
1912 fseek(Fp, positionOnEntry, SEEK_SET);
1913 // When this element is known in the dictionary we shall use, e.g. for
1914 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1915 // dictionary entry. Still we have to flag the element as implicit since
1916 // we know now our assumption on expliciteness is not furfilled.
1918 if ( entry->IsVRUnknown() )
1920 entry->SetVR("Implicit");
1922 entry->SetImplicitVR();
1927 * \brief Check the correspondance between the VR of the header entry
1928 * and the taken VR. If they are different, the header entry is
1929 * updated with the new VR.
1930 * @param entry Header Entry to check
1931 * @param vr Dicom Value Representation
1932 * @return false if the VR is incorrect of if the VR isn't referenced
1933 * otherwise, it returns true
1935 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1937 char msg[100]; // for sprintf
1938 bool realExplicit = true;
1940 // Assume we are reading a falsely explicit VR file i.e. we reached
1941 // a tag where we expect reading a VR but are in fact we read the
1942 // first to bytes of the length. Then we will interogate (through find)
1943 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1944 // both GCC and VC++ implementations of the STL map. Hence when the
1945 // expected VR read happens to be non-ascii characters we consider
1946 // we hit falsely explicit VR tag.
1948 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1950 realExplicit = false;
1953 // CLEANME searching the dicom_vr at each occurence is expensive.
1954 // PostPone this test in an optional integrity check at the end
1955 // of parsing or only in debug mode.
1956 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1958 realExplicit = false;
1961 if ( !realExplicit )
1963 // We thought this was explicit VR, but we end up with an
1964 // implicit VR tag. Let's backtrack.
1965 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1966 entry->GetGroup(), entry->GetElement());
1967 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1969 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1971 // Group length is UL !
1972 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1973 entry->GetGroup(), entry->GetElement(),
1974 "UL", "FIXME", "Group Length");
1975 entry->SetDictEntry( newEntry );
1980 if ( entry->IsVRUnknown() )
1982 // When not a dictionary entry, we can safely overwrite the VR.
1983 if( entry->GetElement() == 0x0000 )
1985 // Group length is UL !
1993 else if ( entry->GetVR() != vr )
1995 // The VR present in the file and the dictionary disagree. We assume
1996 // the file writer knew best and use the VR of the file. Since it would
1997 // be unwise to overwrite the VR of a dictionary (since it would
1998 // compromise it's next user), we need to clone the actual DictEntry
1999 // and change the VR for the read one.
2000 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2001 entry->GetGroup(), entry->GetElement(),
2002 vr, "FIXME", entry->GetName());
2003 entry->SetDictEntry(newEntry);
2010 * \brief Get the transformed value of the header entry. The VR value
2011 * is used to define the transformation to operate on the value
2012 * \warning NOT end user intended method !
2013 * @param entry entry to tranform
2014 * @return Transformed entry value
2016 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2018 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2020 std::string val = ((gdcmValEntry *)entry)->GetValue();
2021 std::string vr = entry->GetVR();
2022 uint32_t length = entry->GetLength();
2023 std::ostringstream s;
2026 // When short integer(s) are expected, read and convert the following
2027 // n * 2 bytes properly i.e. as a multivaluated strings
2028 // (each single value is separated fromthe next one by '\'
2029 // as usual for standard multivaluated filels
2030 // Elements with Value Multiplicity > 1
2031 // contain a set of short integers (not a single one)
2033 if( vr == "US" || vr == "SS" )
2038 for (int i=0; i < nbInt; i++)
2044 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2045 newInt16 = SwapShort( newInt16 );
2050 // When integer(s) are expected, read and convert the following
2051 // n * 4 bytes properly i.e. as a multivaluated strings
2052 // (each single value is separated fromthe next one by '\'
2053 // as usual for standard multivaluated filels
2054 // Elements with Value Multiplicity > 1
2055 // contain a set of integers (not a single one)
2056 else if( vr == "UL" || vr == "SL" )
2061 for (int i=0; i < nbInt; i++)
2067 newInt32 = ( val[4*i+0] & 0xFF )
2068 + (( val[4*i+1] & 0xFF ) << 8 )
2069 + (( val[4*i+2] & 0xFF ) << 16 )
2070 + (( val[4*i+3] & 0xFF ) << 24 );
2071 newInt32 = SwapLong( newInt32 );
2075 #ifdef GDCM_NO_ANSI_STRING_STREAM
2076 s << std::ends; // to avoid oddities on Solaris
2077 #endif //GDCM_NO_ANSI_STRING_STREAM
2081 return ((gdcmValEntry *)entry)->GetValue();
2085 * \brief Get the reverse transformed value of the header entry. The VR
2086 * value is used to define the reverse transformation to operate on
2088 * \warning NOT end user intended method !
2089 * @param entry Entry to reverse transform
2090 * @return Reverse transformed entry value
2092 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2094 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2096 std::string vr = entry->GetVR();
2097 std::vector<std::string> tokens;
2098 std::ostringstream s;
2100 if ( vr == "US" || vr == "SS" )
2104 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2105 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2106 for (unsigned int i=0; i<tokens.size(); i++)
2108 newInt16 = atoi(tokens[i].c_str());
2109 s << ( newInt16 & 0xFF )
2110 << (( newInt16 >> 8 ) & 0xFF );
2114 if ( vr == "UL" || vr == "SL")
2118 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2119 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2120 for (unsigned int i=0; i<tokens.size();i++)
2122 newInt32 = atoi(tokens[i].c_str());
2123 s << (char)( newInt32 & 0xFF )
2124 << (char)(( newInt32 >> 8 ) & 0xFF )
2125 << (char)(( newInt32 >> 16 ) & 0xFF )
2126 << (char)(( newInt32 >> 24 ) & 0xFF );
2131 #ifdef GDCM_NO_ANSI_STRING_STREAM
2132 s << std::ends; // to avoid oddities on Solaris
2133 #endif //GDCM_NO_ANSI_STRING_STREAM
2137 return ((gdcmValEntry *)entry)->GetValue();
2141 * \brief Skip a given Header Entry
2142 * \warning NOT end user intended method !
2143 * @param entry entry to skip
2145 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2147 SkipBytes(entry->GetLength());
2151 * \brief Skips to the begining of the next Header Entry
2152 * \warning NOT end user intended method !
2153 * @param entry entry to skip
2155 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2157 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2158 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2162 * \brief When the length of an element value is obviously wrong (because
2163 * the parser went Jabberwocky) one can hope improving things by
2164 * applying some heuristics.
2165 * @param entry entry to check
2166 * @param foundLength fist assumption about length
2168 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2169 uint32_t foundLength)
2171 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2172 if ( foundLength == 0xffffffff)
2177 uint16_t gr = entry->GetGroup();
2178 uint16_t el = entry->GetElement();
2180 if ( foundLength % 2)
2182 std::ostringstream s;
2183 s << "Warning : Tag with uneven length "
2185 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2186 dbg.Verbose(0, s.str().c_str());
2189 //////// Fix for some naughty General Electric images.
2190 // Allthough not recent many such GE corrupted images are still present
2191 // on Creatis hard disks. Hence this fix shall remain when such images
2192 // are no longer in user (we are talking a few years, here)...
2193 // Note: XMedCom probably uses such a trick since it is able to read
2194 // those pesky GE images ...
2195 if ( foundLength == 13)
2197 // Only happens for this length !
2198 if ( entry->GetGroup() != 0x0008
2199 || ( entry->GetElement() != 0x0070
2200 && entry->GetElement() != 0x0080 ) )
2203 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2207 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2208 // Occurence of such images is quite low (unless one leaves close to a
2209 // 'Leonardo' source. Hence, one might consider commenting out the
2210 // following fix on efficiency reasons.
2211 else if ( entry->GetGroup() == 0x0009
2212 && ( entry->GetElement() == 0x1113
2213 || entry->GetElement() == 0x1114 ) )
2216 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2219 else if ( entry->GetVR() == "SQ" )
2221 foundLength = 0; // ReadLength is unchanged
2224 //////// We encountered a 'delimiter' element i.e. a tag of the form
2225 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2226 // taken into account.
2227 else if( entry->GetGroup() == 0xfffe )
2229 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2230 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2231 // causes extra troubles...
2232 if( entry->GetElement() != 0x0000 )
2238 entry->SetUsableLength(foundLength);
2242 * \brief Apply some heuristics to predict whether the considered
2243 * element value contains/represents an integer or not.
2244 * @param entry The element value on which to apply the predicate.
2245 * @return The result of the heuristical predicate.
2247 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2249 uint16_t element = entry->GetElement();
2250 uint16_t group = entry->GetGroup();
2251 std::string vr = entry->GetVR();
2252 uint32_t length = entry->GetLength();
2254 // When we have some semantics on the element we just read, and if we
2255 // a priori know we are dealing with an integer, then we shall be
2256 // able to swap it's element value properly.
2257 if ( element == 0 ) // This is the group length of the group
2265 // Allthough this should never happen, still some images have a
2266 // corrupted group length [e.g. have a glance at offset x(8336) of
2267 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2268 // Since for dicom compliant and well behaved headers, the present
2269 // test is useless (and might even look a bit paranoid), when we
2270 // encounter such an ill-formed image, we simply display a warning
2271 // message and proceed on parsing (while crossing fingers).
2272 std::ostringstream s;
2273 int filePosition = ftell(Fp);
2274 s << "Erroneous Group Length element length on : (" \
2275 << std::hex << group << " , " << element
2276 << ") -before- position x(" << filePosition << ")"
2277 << "lgt : " << length;
2278 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2282 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2291 * \brief Find the Length till the next sequence delimiter
2292 * \warning NOT end user intended method !
2296 uint32_t gdcmDocument::FindDocEntryLengthOB()
2297 throw( gdcmFormatUnexpected )
2299 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2300 long positionOnEntry = ftell(Fp);
2301 bool foundSequenceDelimiter = false;
2302 uint32_t totalLength = 0;
2304 while ( !foundSequenceDelimiter )
2310 group = ReadInt16();
2313 catch ( gdcmFormatError )
2315 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2316 " group or element not present.");
2319 // We have to decount the group and element we just read
2322 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2324 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2325 "tag nor a Sequence delimiter tag.");
2326 fseek(Fp, positionOnEntry, SEEK_SET);
2327 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2328 "Neither an Item tag nor a Sequence "
2332 if ( elem == 0xe0dd )
2334 foundSequenceDelimiter = true;
2337 uint32_t itemLength = ReadInt32();
2338 // We add 4 bytes since we just read the ItemLength with ReadInt32
2339 totalLength += itemLength + 4;
2340 SkipBytes(itemLength);
2342 if ( foundSequenceDelimiter )
2347 fseek(Fp, positionOnEntry, SEEK_SET);
2352 * \brief Reads a supposed to be 16 Bits integer
2353 * (swaps it depending on processor endianity)
2354 * @return read value
2356 uint16_t gdcmDocument::ReadInt16()
2357 throw( gdcmFormatError )
2360 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2361 if ( item_read != 1 )
2365 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2367 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2374 * \brief Reads a supposed to be 32 Bits integer
2375 * (swaps it depending on processor endianity)
2376 * @return read value
2378 uint32_t gdcmDocument::ReadInt32()
2379 throw( gdcmFormatError )
2382 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2383 if ( item_read != 1 )
2387 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2389 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2396 * \brief skips bytes inside the source file
2397 * \warning NOT end user intended method !
2400 void gdcmDocument::SkipBytes(uint32_t nBytes)
2402 //FIXME don't dump the returned value
2403 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2407 * \brief Loads all the needed Dictionaries
2408 * \warning NOT end user intended method !
2410 void gdcmDocument::Initialise()
2412 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2417 * \brief Discover what the swap code is (among little endian, big endian,
2418 * bad little endian, bad big endian).
2420 * @return false when we are absolutely sure
2421 * it's neither ACR-NEMA nor DICOM
2422 * true when we hope ours assuptions are OK
2424 bool gdcmDocument::CheckSwap()
2426 // The only guaranted way of finding the swap code is to find a
2427 // group tag since we know it's length has to be of four bytes i.e.
2428 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2429 // occurs when we can't find such group...
2431 uint32_t x = 4; // x : for ntohs
2432 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2436 char deb[HEADER_LENGTH_TO_READ];
2438 // First, compare HostByteOrder and NetworkByteOrder in order to
2439 // determine if we shall need to swap bytes (i.e. the Endian type).
2440 if ( x == ntohs(x) )
2449 // The easiest case is the one of a DICOM header, since it possesses a
2450 // file preamble where it suffice to look for the string "DICM".
2451 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2452 (void)lgrLue; //FIXME not used
2454 char *entCur = deb + 128;
2455 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2457 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2459 // Next, determine the value representation (VR). Let's skip to the
2460 // first element (0002, 0000) and check there if we find "UL"
2461 // - or "OB" if the 1st one is (0002,0001) -,
2462 // in which case we (almost) know it is explicit VR.
2463 // WARNING: if it happens to be implicit VR then what we will read
2464 // is the length of the group. If this ascii representation of this
2465 // length happens to be "UL" then we shall believe it is explicit VR.
2466 // FIXME: in order to fix the above warning, we could read the next
2467 // element value (or a couple of elements values) in order to make
2468 // sure we are not commiting a big mistake.
2469 // We need to skip :
2470 // * the 128 bytes of File Preamble (often padded with zeroes),
2471 // * the 4 bytes of "DICM" string,
2472 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2473 // i.e. a total of 136 bytes.
2477 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2478 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2479 // *Implicit* VR. -and it is !-
2481 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2482 memcmp(entCur, "OB", (size_t)2) == 0 ||
2483 memcmp(entCur, "UI", (size_t)2) == 0 ||
2484 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2485 // when Write DCM *adds*
2487 // Use gdcmDocument::dicom_vr to test all the possibilities
2488 // instead of just checking for UL, OB and UI !? group 0000
2490 Filetype = gdcmExplicitVR;
2491 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2492 "explicit Value Representation");
2496 Filetype = gdcmImplicitVR;
2497 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2498 "not an explicit Value Representation");
2504 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2505 "HostByteOrder != NetworkByteOrder");
2510 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2511 "HostByteOrder = NetworkByteOrder");
2514 // Position the file position indicator at first tag (i.e.
2515 // after the file preamble and the "DICM" string).
2517 fseek (Fp, 132L, SEEK_SET);
2521 // Alas, this is not a DicomV3 file and whatever happens there is no file
2522 // preamble. We can reset the file position indicator to where the data
2523 // is (i.e. the beginning of the file).
2524 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2527 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2528 // By clean we mean that the length of the first tag is written down.
2529 // If this is the case and since the length of the first group HAS to be
2530 // four (bytes), then determining the proper swap code is straightforward.
2533 // We assume the array of char we are considering contains the binary
2534 // representation of a 32 bits integer. Hence the following dirty
2536 s32 = *((uint32_t *)(entCur));
2557 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2558 // It is time for despaired wild guesses.
2559 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2560 // i.e. the 'group length' element is not present :
2562 // check the supposed to be 'group number'
2563 // 0x0002 or 0x0004 or 0x0008
2564 // to determine ' SwapCode' value .
2565 // Only 0 or 4321 will be possible
2566 // (no oportunity to check for the formerly well known
2567 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2568 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2569 // the file IS NOT ACR-NEMA nor DICOM V3
2570 // Find a trick to tell it the caller...
2572 s16 = *((uint16_t *)(deb));
2589 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2590 "ACR/NEMA unfound swap info (Really hopeless !)");
2591 Filetype = gdcmUnknown;
2594 // Then the only info we have is the net2host one.
2604 * \brief Restore the unproperly loaded values i.e. the group, the element
2605 * and the dictionary entry depending on them.
2607 void gdcmDocument::SwitchSwapToBigEndian()
2609 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2610 "Switching to BigEndian mode.");
2611 if ( SwapCode == 0 )
2615 else if ( SwapCode == 4321 )
2619 else if ( SwapCode == 3412 )
2623 else if ( SwapCode == 2143 )
2630 * \brief during parsing, Header Elements too long are not loaded in memory
2633 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2639 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2641 MaxSizeLoadEntry = 0xffffffff;
2644 MaxSizeLoadEntry = newSize;
2649 * \brief Header Elements too long will not be printed
2650 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2653 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2655 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2660 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2662 MaxSizePrintEntry = 0xffffffff;
2665 MaxSizePrintEntry = newSize;
2671 * \brief Read the next tag but WITHOUT loading it's value
2672 * (read the 'Group Number', the 'Element Number',
2673 * gets the Dict Entry
2674 * gets the VR, gets the length, gets the offset value)
2675 * @return On succes the newly created DocEntry, NULL on failure.
2677 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2684 group = ReadInt16();
2687 catch ( gdcmFormatError e )
2689 // We reached the EOF (or an error occured) therefore
2690 // header parsing has to be considered as finished.
2695 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2696 FindDocEntryVR(newEntry);
2700 FindDocEntryLength(newEntry);
2702 catch ( gdcmFormatError e )
2710 newEntry->SetOffset(ftell(Fp));
2717 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2718 * in the TagHt dictionary.
2719 * @param group The generated tag must belong to this group.
2720 * @return The element of tag with given group which is fee.
2722 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2724 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2726 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2727 if (TagHT.count(key) == 0)
2736 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2737 * is placed at the beginning of a tag check whether this
2738 * tag is (TestGroup, TestElement).
2739 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2740 * is modified to point after the tag.
2741 * On failure (i.e. when the tag wasn't the expected tag
2742 * (TestGroup, TestElement) the internal file pointer
2743 * \ref gdcmDocument::Fp is restored to it's original position.
2744 * @param testGroup The expected group of the tag.
2745 * @param testElement The expected Element of the tag.
2746 * @return True on success, false otherwise.
2748 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2750 long positionOnEntry = ftell(Fp);
2751 long currentPosition = ftell(Fp); // On debugging purposes
2753 //// Read the Item Tag group and element, and make
2754 // sure they are what we expected:
2755 uint16_t itemTagGroup = ReadInt16();
2756 uint16_t itemTagElement = ReadInt16();
2757 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2759 std::ostringstream s;
2760 s << " We should have found tag (";
2761 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2762 s << " but instead we encountered tag (";
2763 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2765 s << " at address: " << (unsigned)currentPosition << std::endl;
2766 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2767 dbg.Verbose(0, s.str().c_str());
2768 fseek(Fp, positionOnEntry, SEEK_SET);
2776 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2777 * is placed at the beginning of a tag (TestGroup, TestElement),
2778 * read the length associated to the Tag.
2779 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2780 * is modified to point after the tag and it's length.
2781 * On failure (i.e. when the tag wasn't the expected tag
2782 * (TestGroup, TestElement) the internal file pointer
2783 * \ref gdcmDocument::Fp is restored to it's original position.
2784 * @param testGroup The expected group of the tag.
2785 * @param testElement The expected Element of the tag.
2786 * @return On success returns the length associated to the tag. On failure
2789 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2791 long positionOnEntry = ftell(Fp);
2792 (void)positionOnEntry;
2794 if ( !ReadTag(testGroup, testElement) )
2799 //// Then read the associated Item Length
2800 long currentPosition = ftell(Fp);
2801 uint32_t itemLength = ReadInt32();
2803 std::ostringstream s;
2804 s << "Basic Item Length is: "
2805 << itemLength << std::endl;
2806 s << " at address: " << (unsigned)currentPosition << std::endl;
2807 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2813 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2814 * No other way so 'skip' the Data
2816 void gdcmDocument::Parse7FE0 ()
2818 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2821 // Should warn user FIXME
2825 if ( IsImplicitVRLittleEndianTransferSyntax()
2826 || IsExplicitVRLittleEndianTransferSyntax()
2827 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2828 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2833 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2835 //// Read the Basic Offset Table Item Tag length...
2836 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2838 //// ... and then read length[s] itself[themselves]. We don't use
2839 // the values read (BTW what is the purpous of those lengths ?)
2840 if ( itemLength != 0 )
2842 // BTW, what is the purpous of those length anyhow !?
2843 char* basicOffsetTableItemValue = new char[itemLength + 1];
2844 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2846 for (unsigned int i=0; i < itemLength; i += 4 )
2848 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2849 std::ostringstream s;
2850 s << " Read one length: ";
2851 s << std::hex << individualLength << std::endl;
2852 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2854 delete[] basicOffsetTableItemValue;
2857 if ( ! IsRLELossLessTransferSyntax() )
2861 //// We then skip (not reading them) all the fragments of images:
2862 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2864 SkipBytes(itemLength);
2871 long rleSegmentLength[15], fragmentLength;
2873 // While we find some items:
2874 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2876 // Parse fragments of the current Fragment (Frame)
2877 //------------------ scanning (not reading) fragment pixels
2878 uint32_t nbRleSegments = ReadInt32();
2880 //// Reading RLE Segments Offset Table
2881 uint32_t rleSegmentOffsetTable[15];
2882 for(int k=1; k<=15; k++)
2884 ftellRes = ftell(Fp);
2885 rleSegmentOffsetTable[k] = ReadInt32();
2888 // skipping (not reading) RLE Segments
2889 if ( nbRleSegments > 1)
2891 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2893 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2894 - rleSegmentOffsetTable[k];
2895 ftellRes = ftell(Fp);
2896 SkipBytes(rleSegmentLength[k]);
2900 rleSegmentLength[nbRleSegments] = fragmentLength
2901 - rleSegmentOffsetTable[nbRleSegments];
2902 ftellRes = ftell(Fp);
2903 SkipBytes(rleSegmentLength[nbRleSegments]);
2906 // Make sure that at the end of the item we encounter a 'Sequence
2908 if ( !ReadTag(0xfffe, 0xe0dd) )
2910 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2911 dbg.Verbose(0, " at end of RLE item sequence");
2917 * \brief Walk recursively the given \ref gdcmDocEntrySet, and feed
2918 * the given hash table (\ref TagDocEntryHT) with all the
2919 * \ref gdcmDocEntry (Dicom entries) encountered.
2920 * This method does the job for \ref BuildFlatHashTable.
2921 * @param builtHT Where to collect all the \ref gdcmDocEntry encountered
2922 * when recursively walking the given set.
2923 * @param set The structure to be traversed (recursively).
2925 void gdcmDocument::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2926 gdcmDocEntrySet* set )
2928 if (gdcmElementSet* elementSet = dynamic_cast< gdcmElementSet* > ( set ) )
2930 TagDocEntryHT* currentHT = elementSet->GetTagHT();
2931 for( TagDocEntryHT::const_iterator i = currentHT->begin();
2932 i != currentHT->end();
2935 gdcmDocEntry* entry = i->second;
2936 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
2938 ListSQItem& items = seqEntry->GetSQItems();
2939 for( ListSQItem::const_iterator item = items.begin();
2940 item != items.end();
2943 BuildFlatHashTableRecurse( builtHT, *item );
2947 builtHT[entry->GetKey()] = entry;
2952 if (gdcmSQItem* SQItemSet = dynamic_cast< gdcmSQItem* > ( set ) )
2954 ListDocEntry& currentList = SQItemSet->GetDocEntries();
2955 for (ListDocEntry::iterator i = currentList.begin();
2956 i != currentList.end();
2959 gdcmDocEntry* entry = *i;
2960 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
2962 ListSQItem& items = seqEntry->GetSQItems();
2963 for( ListSQItem::const_iterator item = items.begin();
2964 item != items.end();
2967 BuildFlatHashTableRecurse( builtHT, *item );
2971 builtHT[entry->GetKey()] = entry;
2978 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2981 * The structure used by a gdcmDocument (through \ref gdcmElementSet),
2982 * in order to old the parsed entries of a Dicom header, is a recursive
2983 * one. This is due to the fact that the sequences (when present)
2984 * can be nested. Additionaly, the sequence items (represented in
2985 * gdcm as \ref gdcmSQItem) add an extra complexity to the data
2986 * structure. Hence, a gdcm user whishing to visit all the entries of
2987 * a Dicom header will need to dig in the gdcm internals (which
2988 * implies exposing all the internal data structures to the API).
2989 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2990 * recursively builds a temporary hash table, which holds all the
2991 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2993 * \warning Of course there is NO integrity constrain between the
2994 * returned \ref TagDocEntryHT and the \ref gdcmElementSet used
2995 * to build it. Hence if the underlying \ref gdcmElementSet is
2996 * altered, then it is the caller responsability to invoke
2997 * \ref BuildFlatHashTable again...
2998 * @return The flat std::map<> we juste build.
3000 TagDocEntryHT* gdcmDocument::BuildFlatHashTable()
3002 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3003 BuildFlatHashTableRecurse( *FlatHT, this );
3010 * \brief Compares two documents, according to \ref gdcmDicomDir rules
3011 * \warning Does NOT work with ACR-NEMA files
3012 * \todo Find a trick to solve the pb (use RET fields ?)
3014 * @return true if 'smaller'
3016 bool gdcmDocument::operator<(gdcmDocument &document)
3019 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3020 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3032 s1 = GetEntryByNumber(0x0010,0x0020);
3033 s2 = document.GetEntryByNumber(0x0010,0x0020);
3044 // Study Instance UID
3045 s1 = GetEntryByNumber(0x0020,0x000d);
3046 s2 = document.GetEntryByNumber(0x0020,0x000d);
3057 // Serie Instance UID
3058 s1 = GetEntryByNumber(0x0020,0x000e);
3059 s2 = document.GetEntryByNumber(0x0020,0x000e);
3075 //-----------------------------------------------------------------------------