1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/10/06 09:58:08 $
7 Version: $Revision: 1.93 $
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.html 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"
23 #include "gdcmGlobal.h"
25 #include "gdcmDebug.h"
33 #include <netinet/in.h>
38 // Implicit VR Little Endian
39 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
40 // Explicit VR Little Endian
41 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
42 // Deflated Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
44 // Explicit VR Big Endian
45 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
46 // JPEG Baseline (Process 1)
47 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
48 // JPEG Extended (Process 2 & 4)
49 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
50 // JPEG Extended (Process 3 & 5)
51 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
52 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
53 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
54 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
55 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
56 // JPEG Lossless, Non-Hierarchical (Process 14)
57 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
58 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
59 // [Selection Value 1])
60 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
62 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
64 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
66 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
67 // UI1_1_2_840_10008_1_2_5
68 #define str2num(str, typeNum) *((typeNum *)(str))
70 //-----------------------------------------------------------------------------
71 // Refer to gdcmDocument::CheckSwap()
72 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
74 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
75 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
76 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
78 //-----------------------------------------------------------------------------
79 // Constructor / Destructor
83 * @param filename file to be opened for parsing
85 gdcmDocument::gdcmDocument( std::string const & filename )
88 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
97 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
101 fseek(Fp,0L,SEEK_END);
102 long lgt = ftell(Fp);
106 long beg = ftell(Fp);
109 (void)ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 // Load 'non string' values
115 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
116 if( PhotometricInterpretation == "PALETTE COLOR " )
118 LoadEntryBinArea(0x0028,0x1200); // gray LUT
119 /// FIXME FIXME FIXME
120 /// The tags refered by the three following lines used to be CORRECTLY
121 /// defined as having an US Value Representation in the public
122 /// dictionnary. BUT the semantics implied by the three following
123 /// lines state that the corresponding tag contents are in fact
124 /// the ones of a gdcmBinEntry.
125 /// In order to fix things "Quick and Dirty" the dictionnary was
126 /// altered on PURPOUS but now contains a WRONG value.
127 /// In order to fix things and restore the dictionary to its
128 /// correct value, one needs to decided of the semantics by deciding
129 /// wether the following tags are either:
130 /// - multivaluated US, and hence loaded as gdcmValEntry, but afterwards
131 /// also used as gdcmBinEntry, which requires the proper conversion,
132 /// - OW, and hence loaded as gdcmBinEntry, but afterwards also used
133 /// as gdcmValEntry, which requires the proper conversion.
134 LoadEntryBinArea(0x0028,0x1201); // R LUT
135 LoadEntryBinArea(0x0028,0x1202); // G LUT
136 LoadEntryBinArea(0x0028,0x1203); // B LUT
138 // Segmented Red Palette Color LUT Data
139 LoadEntryBinArea(0x0028,0x1221);
140 // Segmented Green Palette Color LUT Data
141 LoadEntryBinArea(0x0028,0x1222);
142 // Segmented Blue Palette Color LUT Data
143 LoadEntryBinArea(0x0028,0x1223);
145 //FIXME later : how to use it?
146 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
150 // --------------------------------------------------------------
151 // Specific code to allow gdcm to read ACR-LibIDO formated images
152 // Note: ACR-LibIDO is an extension of the ACR standard that was
153 // used at CREATIS. For the time being (say a couple years)
154 // we keep this kludge to allow a smooth move to gdcm for
155 // CREATIS developpers (sorry folks).
157 // if recognition code tells us we deal with a LibIDO image
158 // we switch lineNumber and columnNumber
161 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
162 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
163 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
164 // with "little-endian strings"
166 Filetype = gdcmACR_LIBIDO;
167 std::string rows = GetEntryByNumber(0x0028, 0x0010);
168 std::string columns = GetEntryByNumber(0x0028, 0x0011);
169 SetEntryByNumber(columns, 0x0028, 0x0010);
170 SetEntryByNumber(rows , 0x0028, 0x0011);
172 // ----------------- End of ACR-LibIDO kludge ------------------
174 PrintLevel = 1; // 'Medium' print level by default
178 * \brief This default constructor doesn't parse the file. You should
179 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
181 gdcmDocument::gdcmDocument()
184 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
186 PrintLevel = 1; // 'Medium' print level by default
190 * \brief Canonical destructor.
192 gdcmDocument::~gdcmDocument ()
197 // Recursive clean up of sequences
198 for (TagDocEntryHT::const_iterator it = TagHT.begin();
199 it != TagHT.end(); ++it )
201 //delete it->second; //temp remove
206 //-----------------------------------------------------------------------------
210 * \brief Prints The Dict Entries of THE public Dicom Dictionary
213 void gdcmDocument::PrintPubDict(std::ostream & os)
215 RefPubDict->Print(os);
219 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
222 void gdcmDocument::PrintShaDict(std::ostream & os)
224 RefShaDict->Print(os);
227 //-----------------------------------------------------------------------------
230 * \brief Get the public dictionary used
232 gdcmDict* gdcmDocument::GetPubDict()
238 * \brief Get the shadow dictionary used
240 gdcmDict* gdcmDocument::GetShaDict()
246 * \brief Set the shadow dictionary used
247 * \param dict dictionary to use in shadow
249 bool gdcmDocument::SetShaDict(gdcmDict *dict)
256 * \brief Set the shadow dictionary used
257 * \param dictName name of the dictionary to use in shadow
259 bool gdcmDocument::SetShaDict(DictKey const & dictName)
261 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
266 * \brief This predicate, based on hopefully reasonable heuristics,
267 * decides whether or not the current gdcmDocument was properly parsed
268 * and contains the mandatory information for being considered as
269 * a well formed and usable Dicom/Acr File.
270 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
273 bool gdcmDocument::IsReadable()
275 if( Filetype == gdcmUnknown)
277 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
283 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
293 * \brief Internal function that checks whether the Transfer Syntax given
294 * as argument is the one present in the current document.
295 * @param syntaxToCheck The transfert syntax we need to check against.
296 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
297 * the current document. False either when the document contains
298 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
300 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
302 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
308 // The entry might be present but not loaded (parsing and loading
309 // happen at different stages): try loading and proceed with check...
310 LoadDocEntrySafe(entry);
311 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
313 std::string transfer = valEntry->GetValue();
314 // The actual transfer (as read from disk) might be padded. We
315 // first need to remove the potential padding. We can make the
316 // weak assumption that padding was not executed with digits...
317 if ( transfer.length() == 0 ) { // for brain damaged headers
320 while ( ! isdigit(transfer[transfer.length()-1]) )
322 transfer.erase(transfer.length()-1, 1);
324 if ( transfer == syntaxToCheck )
333 * \brief Determines if the Transfer Syntax of the present document
334 * corresponds to a Implicit Value Representation of
336 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
337 * @return True when ImplicitVRLittleEndian found. False in all other cases.
339 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
341 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a ExplicitVRLittleEndian one.
347 * @return True when ExplicitVRLittleEndian found. False in all other cases.
349 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
351 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
355 * \brief Determines if the Transfer Syntax was already encountered
356 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
357 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
359 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
361 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
365 * \brief Determines if the Transfer Syntax was already encountered
366 * and if it corresponds to a Explicit VR Big Endian one.
367 * @return True when big endian found. False in all other cases.
369 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
371 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
375 * \brief Determines if the Transfer Syntax was already encountered
376 * and if it corresponds to a JPEGBaseLineProcess1 one.
377 * @return True when JPEGBaseLineProcess1found. False in all other cases.
379 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
381 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
385 * \brief Determines if the Transfer Syntax was already encountered
386 * and if it corresponds to a JPEGExtendedProcess2-4 one.
387 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
389 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
391 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
395 * \brief Determines if the Transfer Syntax was already encountered
396 * and if it corresponds to a JPEGExtendeProcess3-5 one.
397 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
399 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
401 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
405 * \brief Determines if the Transfer Syntax was already encountered
406 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
407 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
410 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
412 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
416 * \brief Determines if the Transfer Syntax was already encountered
417 * and if it corresponds to a RLE Lossless one.
418 * @return True when RLE Lossless found. False in all
421 bool gdcmDocument::IsRLELossLessTransferSyntax()
423 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
427 * \brief Determines if Transfer Syntax was already encountered
428 * and if it corresponds to a JPEG Lossless one.
429 * @return True when RLE Lossless found. False in all
433 bool gdcmDocument::IsJPEGLossless()
435 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
436 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
437 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
441 * \brief Determines if the Transfer Syntax was already encountered
442 * and if it corresponds to a JPEG2000 one
443 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
446 bool gdcmDocument::IsJPEG2000()
448 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
449 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
453 * \brief Predicate for dicom version 3 file.
454 * @return True when the file is a dicom version 3.
456 bool gdcmDocument::IsDicomV3()
458 // Checking if Transfert Syntax exists is enough
459 // Anyway, it's to late check if the 'Preamble' was found ...
460 // And ... would it be a rich idea to check ?
461 // (some 'no Preamble' DICOM images exist !)
462 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
466 * \brief returns the File Type
467 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
468 * @return the FileType code
470 FileType gdcmDocument::GetFileType()
476 * \brief Tries to open the file \ref gdcmDocument::Filename and
477 * checks the preamble when existing.
478 * @return The FILE pointer on success.
480 FILE* gdcmDocument::OpenFile()
482 Fp = fopen(Filename.c_str(),"rb");
487 "gdcmDocument::OpenFile cannot open file: ",
493 fread(&zero, (size_t)2, (size_t)1, Fp);
495 //ACR -- or DICOM with no Preamble --
496 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
502 fseek(Fp, 126L, SEEK_CUR);
504 fread(dicm, (size_t)4, (size_t)1, Fp);
505 if( memcmp(dicm, "DICM", 4) == 0 )
512 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
519 * \brief closes the file
520 * @return TRUE if the close was successfull
522 bool gdcmDocument::CloseFile()
524 int closed = fclose(Fp);
531 * \brief Writes in a file all the Header Entries (Dicom Elements)
532 * @param fp file pointer on an already open file
533 * @param filetype Type of the File to be written
534 * (ACR-NEMA, ExplicitVR, ImplicitVR)
535 * \return Always true.
537 void gdcmDocument::Write(FILE* fp,FileType filetype)
539 /// \todo move the following lines (and a lot of others, to be written)
540 /// to a future function CheckAndCorrectHeader
541 /// (necessary if user wants to write a DICOM V3 file
542 /// starting from an ACR-NEMA (V2) gdcmHeader
544 if (filetype == gdcmImplicitVR)
546 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
547 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
549 /// \todo Refer to standards on page 21, chapter 6.2
550 /// "Value representation": values with a VR of UI shall be
551 /// padded with a single trailing null
552 /// in the following case we have to padd manually with a 0
554 SetEntryLengthByNumber(18, 0x0002, 0x0010);
557 if (filetype == gdcmExplicitVR)
559 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
560 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
562 /// \todo Refer to standards on page 21, chapter 6.2
563 /// "Value representation": values with a VR of UI shall be
564 /// padded with a single trailing null
565 /// Dans le cas suivant on doit pader manuellement avec un 0
567 SetEntryLengthByNumber(20, 0x0002, 0x0010);
571 * \todo rewrite later, if really usefull
572 * - 'Group Length' element is optional in DICOM
573 * - but un-updated odd groups lengthes can causes pb
576 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
577 * UpdateGroupLength(false,filetype);
578 * if ( filetype == ACR)
579 * UpdateGroupLength(true,ACR);
582 gdcmElementSet::Write(fp, filetype); // This one is recursive
587 * \brief Modifies the value of a given Header Entry (Dicom Element)
588 * when it exists. Create it with the given value when unexistant.
589 * @param value (string) Value to be set
590 * @param group Group number of the Entry
591 * @param elem Element number of the Entry
592 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
593 * \return pointer to the modified/created Header Entry (NULL when creation
596 gdcmValEntry* gdcmDocument::ReplaceOrCreateByNumber(
597 std::string const & value,
600 std::string const & VR )
602 gdcmValEntry* valEntry = 0;
603 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
607 // check if (group,element) DictEntry exists
608 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
611 // Find out if the tag we received is in the dictionaries:
612 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
613 gdcmDictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
616 currentEntry = NewDocEntryByNumber(group, elem,VR);
620 currentEntry = NewDocEntryByNumber(group, elem);
625 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
626 " NewDocEntryByNumber failed.");
629 valEntry = new gdcmValEntry(currentEntry);
630 if ( !AddEntry(valEntry))
632 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
633 " failed allthough this is a creation.");
638 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
639 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
640 // then we change it to a ValEntry ?
641 // Shouldn't it be considered as an error ?
643 // We need to promote the gdcmDocEntry to a gdcmValEntry:
644 valEntry = new gdcmValEntry(currentEntry);
645 if (!RemoveEntry(currentEntry))
647 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
648 " of previous DocEntry failed.");
651 if ( !AddEntry(valEntry))
653 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
654 " promoted ValEntry failed.");
660 SetEntryByNumber(value, group, elem);
666 * \brief Modifies the value of a given Header Entry (Dicom Element)
667 * when it exists. Create it with the given value when unexistant.
668 * @param binArea (binary) value to be set
669 * @param Group Group number of the Entry
670 * @param Elem Element number of the Entry
671 * \return pointer to the modified/created Header Entry (NULL when creation
674 gdcmBinEntry* gdcmDocument::ReplaceOrCreateByNumber(
679 std::string const& VR )
681 gdcmBinEntry* binEntry = 0;
682 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
686 // check if (group,element) DictEntry exists
687 // if it doesn't, create an entry in gdcmDictSet::VirtualEntry
690 // Find out if the tag we received is in the dictionaries:
691 gdcmDict *pubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
692 gdcmDictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
696 currentEntry = NewDocEntryByNumber(group, elem, VR);
700 currentEntry = NewDocEntryByNumber(group, elem);
704 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
705 " NewDocEntryByNumber failed.");
708 binEntry = new gdcmBinEntry(currentEntry);
709 if ( !AddEntry(binEntry))
711 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
712 " failed allthough this is a creation.");
717 binEntry = dynamic_cast< gdcmBinEntry* >(currentEntry);
718 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
719 // then we change it to a BinEntry ?
720 // Shouldn't it be considered as an error ?
722 // We need to promote the gdcmDocEntry to a gdcmBinEntry:
723 binEntry = new gdcmBinEntry(currentEntry);
724 if (!RemoveEntry(currentEntry))
726 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
727 " of previous DocEntry failed.");
730 if ( !AddEntry(binEntry))
732 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
733 " promoted BinEntry failed.");
739 SetEntryByNumber(binArea, lgth, group, elem);
746 * \brief Modifies the value of a given Header Entry (Dicom Element)
747 * when it exists. Create it when unexistant.
748 * @param Group Group number of the Entry
749 * @param Elem Element number of the Entry
750 * \return pointer to the modified/created SeqEntry (NULL when creation
753 gdcmSeqEntry* gdcmDocument::ReplaceOrCreateByNumber(
758 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
761 a = NewSeqEntryByNumber(group, elem);
767 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
774 * \brief Set a new value if the invoked element exists
775 * Seems to be useless !!!
776 * @param value new element value
777 * @param group group number of the Entry
778 * @param elem element number of the Entry
781 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
782 uint16_t group, uint16_t elem )
784 SetEntryByNumber(value, group, elem);
789 //-----------------------------------------------------------------------------
793 * \brief Checks if a given Dicom Element exists within the H table
794 * @param group Group number of the searched Dicom Element
795 * @param element Element number of the searched Dicom Element
796 * @return true is found
798 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
800 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
801 return TagHT.count(key);
805 * \brief Searches within Header Entries (Dicom Elements) parsed with
806 * the public and private dictionaries
807 * for the element value of a given tag.
808 * \warning Don't use any longer : use GetPubEntryByName
809 * @param tagName name of the searched element.
810 * @return Corresponding element value when it exists,
811 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
813 std::string gdcmDocument::GetEntryByName(TagName const& tagName)
815 gdcmDictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
821 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
825 * \brief Searches within Header Entries (Dicom Elements) parsed with
826 * the public and private dictionaries
827 * for the element value representation of a given tag.
829 * Obtaining the VR (Value Representation) might be needed by caller
830 * to convert the string typed content to caller's native type
831 * (think of C++ vs Python). The VR is actually of a higher level
832 * of semantics than just the native C++ type.
833 * @param tagName name of the searched element.
834 * @return Corresponding element value representation when it exists,
835 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
837 std::string gdcmDocument::GetEntryVRByName(TagName const& tagName)
839 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
840 if( dictEntry == NULL)
845 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
846 dictEntry->GetElement());
847 return elem->GetVR();
851 * \brief Searches within Header Entries (Dicom Elements) parsed with
852 * the public and private dictionaries
853 * for the element value representation of a given tag.
854 * @param group Group number of the searched tag.
855 * @param element Element number of the searched tag.
856 * @return Corresponding element value representation when it exists,
857 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
859 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
861 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
862 /// \todo use map methods, instead of multimap JPR
863 if ( !TagHT.count(key))
868 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
872 * \brief Searches within Header Entries (Dicom Elements) parsed with
873 * the public and private dictionaries
874 * for the element value representation of a given tag..
876 * Obtaining the VR (Value Representation) might be needed by caller
877 * to convert the string typed content to caller's native type
878 * (think of C++ vs Python). The VR is actually of a higher level
879 * of semantics than just the native C++ type.
880 * @param group Group number of the searched tag.
881 * @param element Element number of the searched tag.
882 * @return Corresponding element value representation when it exists,
883 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
885 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
887 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
892 return elem->GetVR();
896 * \brief Searches within Header Entries (Dicom Elements) parsed with
897 * the public and private dictionaries
898 * for the value length of a given tag..
899 * @param group Group number of the searched tag.
900 * @param element Element number of the searched tag.
901 * @return Corresponding element length; -2 if not found
903 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
905 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
908 return -2; //magic number
910 return elem->GetLength();
913 * \brief Sets the value (string) of the Header Entry (Dicom Element)
914 * @param content string value of the Dicom Element
915 * @param tagName name of the searched Dicom Element.
916 * @return true when found
918 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
920 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
926 return SetEntryByNumber(content,dictEntry->GetGroup(),
927 dictEntry->GetElement());
931 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
932 * through it's (group, element) and modifies it's content with
934 * @param content new value (string) to substitute with
935 * @param group group number of the Dicom Element to modify
936 * @param element element number of the Dicom Element to modify
938 bool gdcmDocument::SetEntryByNumber(std::string const& content,
945 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
948 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
949 " ValEntry (try promotion first).");
952 // Non even content must be padded with a space (020H)...
953 std::string finalContent = content;
954 if( finalContent.length() % 2 )
956 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
958 valEntry->SetValue(finalContent);
960 // Integers have a special treatement for their length:
962 l = finalContent.length();
963 if ( l != 0) // To avoid to be cheated by 'zero length' integers
965 gdcmVRKey vr = valEntry->GetVR();
966 if( vr == "US" || vr == "SS" )
968 c = CountSubstring(content, "\\") + 1; // for multivaluated items
971 else if( vr == "UL" || vr == "SL" )
973 c = CountSubstring(content, "\\") + 1; // for multivaluated items
977 valEntry->SetLength(l);
982 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
983 * through it's (group, element) and modifies it's content with
985 * @param content new value (void* -> uint8_t*) to substitute with
986 * @param lgth new value length
987 * @param group group number of the Dicom Element to modify
988 * @param element element number of the Dicom Element to modify
990 bool gdcmDocument::SetEntryByNumber(uint8_t*content,
995 (void)lgth; //not used
996 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
997 if ( !TagHT.count(key))
1002 /* Hope Binary field length is *never* wrong
1003 if(lgth%2) // Non even length are padded with a space (020H).
1006 //content = content + '\0'; // fing a trick to enlarge a binary field?
1009 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
1010 a->SetBinArea(content);
1012 a->SetValue(GDCM_BINLOADED);
1018 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
1019 * in the PubDocEntrySet of this instance
1020 * through it's (group, element) and modifies it's length with
1022 * \warning Use with extreme caution.
1023 * @param l new length to substitute with
1024 * @param group group number of the Entry to modify
1025 * @param element element number of the Entry to modify
1026 * @return true on success, false otherwise.
1028 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
1032 /// \todo use map methods, instead of multimap JPR
1033 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1034 if ( !TagHT.count(key) )
1040 l++; // length must be even
1042 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1048 * \brief Gets (from Header) the offset of a 'non string' element value
1049 * (LoadElementValues has already be executed)
1050 * @param group group number of the Entry
1051 * @param elem element number of the Entry
1052 * @return File Offset of the Element Value
1054 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1056 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1059 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
1062 return entry->GetOffset();
1066 * \brief Gets (from Header) a 'non string' element value
1067 * (LoadElementValues has already be executed)
1068 * @param group group number of the Entry
1069 * @param elem element number of the Entry
1070 * @return Pointer to the 'non string' area
1072 void* gdcmDocument::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1074 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1077 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1080 return ((gdcmBinEntry *)entry)->GetBinArea();
1084 * \brief Loads (from disk) the element content
1085 * when a string is not suitable
1086 * @param group group number of the Entry
1087 * @param elem element number of the Entry
1089 void* gdcmDocument::LoadEntryBinArea(uint16_t group, uint16_t elem)
1091 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1096 size_t o =(size_t)docElement->GetOffset();
1097 fseek(Fp, o, SEEK_SET);
1098 size_t l = docElement->GetLength();
1099 uint8_t* a = new uint8_t[l];
1102 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1105 size_t l2 = fread(a, 1, l , Fp);
1111 /// \todo Drop any already existing void area! JPR
1112 if( !SetEntryBinAreaByNumber( a, group, elem ) );
1114 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea setting failed.");
1119 * \brief Loads (from disk) the element content
1120 * when a string is not suitable
1121 * @param element Entry whose binArea is going to be loaded
1123 void* gdcmDocument::LoadEntryBinArea(gdcmBinEntry* element)
1125 size_t o =(size_t)element->GetOffset();
1126 fseek(Fp, o, SEEK_SET);
1127 size_t l = element->GetLength();
1128 uint8_t* a = new uint8_t[l];
1131 dbg.Verbose(0, "gdcmDocument::LoadEntryBinArea cannot allocate a");
1134 element->SetBinArea((uint8_t*)a);
1135 /// \todo check the result
1136 size_t l2 = fread(a, 1, l , Fp);
1147 * \brief Sets a 'non string' value to a given Dicom Element
1148 * @param area area containing the 'non string' value
1149 * @param group Group number of the searched Dicom Element
1150 * @param element Element number of the searched Dicom Element
1153 bool gdcmDocument::SetEntryBinAreaByNumber(uint8_t* area,
1157 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1158 if ( !currentEntry )
1162 if ( gdcmBinEntry* binEntry = dynamic_cast<gdcmBinEntry*>(currentEntry) )
1164 binEntry->SetBinArea( area );
1171 * \brief Update the entries with the shadow dictionary.
1172 * Only non even entries are analyzed
1174 void gdcmDocument::UpdateShaEntries()
1176 //gdcmDictEntry *entry;
1179 /// \todo TODO : still any use to explore recursively the whole structure?
1181 for(ListTag::iterator it=listEntries.begin();
1182 it!=listEntries.end();
1185 // Odd group => from public dictionary
1186 if((*it)->GetGroup()%2==0)
1189 // Peer group => search the corresponding dict entry
1191 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1195 if((*it)->IsImplicitVR())
1200 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1202 // Set the new entry and the new value
1203 (*it)->SetDictEntry(entry);
1204 CheckDocEntryVR(*it,vr);
1206 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1211 // Remove precedent value transformation
1212 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1219 * \brief Searches within the Header Entries for a Dicom Element of
1221 * @param tagName name of the searched Dicom Element.
1222 * @return Corresponding Dicom Element when it exists, and NULL
1225 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1227 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1233 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1237 * \brief retrieves a Dicom Element (the first one) using (group, element)
1238 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1239 * if you think it's NOT UNIQUE, check the count number
1240 * and use iterators to retrieve ALL the Dicoms Elements within
1241 * a given couple (group, element)
1242 * @param group Group number of the searched Dicom Element
1243 * @param element Element number of the searched Dicom Element
1246 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1249 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1250 if ( !TagHT.count(key))
1254 return TagHT.find(key)->second;
1258 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1259 * returns a result when the corresponding entry is of type
1261 * @return When present, the corresponding ValEntry.
1263 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1266 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1267 if ( !currentEntry )
1271 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1275 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1281 * \brief Loads the element while preserving the current
1282 * underlying file position indicator as opposed to
1283 * to LoadDocEntry that modifies it.
1284 * @param entry Header Entry whose value shall be loaded.
1287 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1289 long PositionOnEntry = ftell(Fp);
1290 LoadDocEntry(entry);
1291 fseek(Fp, PositionOnEntry, SEEK_SET);
1295 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1297 * @return The properly swaped 32 bits integer.
1299 uint32_t gdcmDocument::SwapLong(uint32_t a)
1306 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1307 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1311 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1315 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1318 //std::cout << "swapCode= " << SwapCode << std::endl;
1319 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1326 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1328 * @return The properly unswaped 32 bits integer.
1330 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1336 * \brief Swaps the bytes so they agree with the processor order
1337 * @return The properly swaped 16 bits integer.
1339 uint16_t gdcmDocument::SwapShort(uint16_t a)
1341 if ( SwapCode == 4321 || SwapCode == 2143 )
1343 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1349 * \brief Unswaps the bytes so they agree with the processor order
1350 * @return The properly unswaped 16 bits integer.
1352 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1354 return SwapShort(a);
1357 //-----------------------------------------------------------------------------
1361 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1362 * @return length of the parsed set.
1365 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1370 gdcmDocEntry *newDocEntry = 0;
1371 unsigned long l = 0;
1375 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1379 newDocEntry = ReadNextDocEntry( );
1385 gdcmVRKey vr = newDocEntry->GetVR();
1389 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1391 /////////////////////// ValEntry
1392 gdcmValEntry* newValEntry =
1393 new gdcmValEntry( newDocEntry->GetDictEntry() );
1394 newValEntry->Copy( newDocEntry );
1396 // When "set" is a gdcmDocument, then we are at the top of the
1397 // hierarchy and the Key is simply of the form ( group, elem )...
1398 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1401 newValEntry->SetKey( newValEntry->GetKey() );
1403 // ...but when "set" is a gdcmSQItem, we are inserting this new
1404 // valEntry in a sequence item. Hence the key has the
1405 // generalized form (refer to \ref gdcmBaseTagKey):
1406 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1408 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1409 + newValEntry->GetKey() );
1412 set->AddEntry( newValEntry );
1413 LoadDocEntry( newValEntry );
1414 if (newValEntry->IsItemDelimitor())
1418 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1425 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1427 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1428 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1429 "nor BinEntry. Probably unknown VR.");
1432 //////////////////// BinEntry or UNKOWN VR:
1433 gdcmBinEntry* newBinEntry =
1434 new gdcmBinEntry( newDocEntry->GetDictEntry() );
1435 newBinEntry->Copy( newDocEntry );
1437 // When "this" is a gdcmDocument the Key is simply of the
1438 // form ( group, elem )...
1439 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1442 newBinEntry->SetKey( newBinEntry->GetKey() );
1444 // but when "this" is a SQItem, we are inserting this new
1445 // valEntry in a sequence item, and the kay has the
1446 // generalized form (refer to \ref gdcmBaseTagKey):
1447 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1449 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1450 + newBinEntry->GetKey() );
1453 set->AddEntry( newBinEntry );
1454 LoadDocEntry( newBinEntry );
1457 if (newDocEntry->GetGroup() == 0x7fe0 &&
1458 newDocEntry->GetElement() == 0x0010 )
1460 if ( newDocEntry->GetReadLength()==0xffffffff )
1462 // Broken US.3405.1.dcm
1463 Parse7FE0(); // to skip the pixels
1464 // (multipart JPEG/RLE are trouble makers)
1468 SkipToNextDocEntry(newDocEntry);
1469 l = newDocEntry->GetFullLength();
1474 // to be sure we are at the beginning
1475 SkipToNextDocEntry(newDocEntry);
1476 l = newDocEntry->GetFullLength();
1482 l = newDocEntry->GetReadLength();
1483 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1485 if ( l == 0xffffffff )
1494 // no other way to create it ...
1495 gdcmSeqEntry* newSeqEntry =
1496 new gdcmSeqEntry( newDocEntry->GetDictEntry() );
1497 newSeqEntry->Copy( newDocEntry );
1498 newSeqEntry->SetDelimitorMode( delim_mode );
1500 // At the top of the hierarchy, stands a gdcmDocument. When "set"
1501 // is a gdcmDocument, then we are building the first depth level.
1502 // Hence the gdcmSeqEntry we are building simply has a depth
1504 if (gdcmDocument* dummy = dynamic_cast< gdcmDocument* > ( set ) )
1507 newSeqEntry->SetDepthLevel( 1 );
1508 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1510 // But when "set" is allready a SQItem, we are building a nested
1511 // sequence, and hence the depth level of the new gdcmSeqEntry
1512 // we are building, is one level deeper:
1513 if (gdcmSQItem* parentSQItem = dynamic_cast< gdcmSQItem* > ( set ) )
1515 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1516 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1517 + newSeqEntry->GetKey() );
1521 { // Don't try to parse zero-length sequences
1522 (void)ParseSQ( newSeqEntry,
1523 newDocEntry->GetOffset(),
1526 set->AddEntry( newSeqEntry );
1527 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1534 return l; // Probably useless
1538 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1539 * @return parsed length for this level
1541 long gdcmDocument::ParseSQ( gdcmSeqEntry* seqEntry,
1542 long offset, long l_max, bool delim_mode)
1544 int SQItemNumber = 0;
1549 gdcmDocEntry* newDocEntry = ReadNextDocEntry();
1552 // FIXME Should warn user
1557 if ( newDocEntry->IsSequenceDelimitor() )
1559 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1563 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1568 gdcmSQItem *itemSQ = new gdcmSQItem( seqEntry->GetDepthLevel() );
1569 std::ostringstream newBase;
1570 newBase << seqEntry->GetKey()
1574 itemSQ->SetBaseTagKey( newBase.str() );
1575 unsigned int l = newDocEntry->GetReadLength();
1577 if ( l == 0xffffffff )
1586 (void)ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1588 seqEntry->AddEntry( itemSQ, SQItemNumber );
1590 if ( !delim_mode && ( ftell(Fp) - offset ) >= l_max )
1596 int lgth = ftell(Fp) - offset;
1601 * \brief Loads the element content if its length doesn't exceed
1602 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1603 * @param entry Header Entry (Dicom Element) to be dealt with
1605 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1608 uint16_t group = entry->GetGroup();
1609 std::string vr = entry->GetVR();
1610 uint32_t length = entry->GetLength();
1612 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1614 // A SeQuence "contains" a set of Elements.
1615 // (fffe e000) tells us an Element is beginning
1616 // (fffe e00d) tells us an Element just ended
1617 // (fffe e0dd) tells us the current SeQuence just ended
1618 if( group == 0xfffe )
1620 // NO more value field for SQ !
1624 // When the length is zero things are easy:
1627 ((gdcmValEntry *)entry)->SetValue("");
1631 // The elements whose length is bigger than the specified upper bound
1632 // are not loaded. Instead we leave a short notice of the offset of
1633 // the element content and it's length.
1635 std::ostringstream s;
1636 if (length > MaxSizeLoadEntry)
1638 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1640 //s << "gdcm::NotLoaded (BinEntry)";
1641 s << GDCM_NOTLOADED;
1642 s << " Address:" << (long)entry->GetOffset();
1643 s << " Length:" << entry->GetLength();
1644 s << " x(" << std::hex << entry->GetLength() << ")";
1645 binEntryPtr->SetValue(s.str());
1647 // Be carefull : a BinEntry IS_A ValEntry ...
1648 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1650 // s << "gdcm::NotLoaded. (ValEntry)";
1651 s << GDCM_NOTLOADED;
1652 s << " Address:" << (long)entry->GetOffset();
1653 s << " Length:" << entry->GetLength();
1654 s << " x(" << std::hex << entry->GetLength() << ")";
1655 valEntryPtr->SetValue(s.str());
1660 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1661 << "nor a ValEntry ?! Should never print that !" << std::endl;
1664 // to be sure we are at the end of the value ...
1665 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1669 // When we find a BinEntry not very much can be done :
1670 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1672 s << GDCM_BINLOADED;
1673 binEntryPtr->SetValue(s.str());
1674 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1678 /// \todo Any compacter code suggested (?)
1679 if ( IsDocEntryAnInteger(entry) )
1683 // When short integer(s) are expected, read and convert the following
1684 // n *two characters properly i.e. consider them as short integers as
1685 // opposed to strings.
1686 // Elements with Value Multiplicity > 1
1687 // contain a set of integers (not a single one)
1688 if (vr == "US" || vr == "SS")
1691 NewInt = ReadInt16();
1695 for (int i=1; i < nbInt; i++)
1698 NewInt = ReadInt16();
1703 // See above comment on multiple integers (mutatis mutandis).
1704 else if (vr == "UL" || vr == "SL")
1707 NewInt = ReadInt32();
1711 for (int i=1; i < nbInt; i++)
1714 NewInt = ReadInt32();
1719 #ifdef GDCM_NO_ANSI_STRING_STREAM
1720 s << std::ends; // to avoid oddities on Solaris
1721 #endif //GDCM_NO_ANSI_STRING_STREAM
1723 ((gdcmValEntry *)entry)->SetValue(s.str());
1727 // We need an additional byte for storing \0 that is not on disk
1728 //std::string newValue(length,0);
1729 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1730 //rah !! I can't believe it could work, normally this is a const char* !!!
1731 char *str = new char[length+1];
1732 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1734 std::string newValue = str;
1736 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1738 if ( item_read != 1 )
1740 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1741 "unread element value");
1742 valEntry->SetValue(GDCM_UNREAD);
1748 // Because of correspondance with the VR dic
1749 valEntry->SetValue(newValue);
1753 valEntry->SetValue(newValue);
1758 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1759 "Should have a ValEntry, here !");
1765 * \brief Find the value Length of the passed Header Entry
1766 * @param entry Header Entry whose length of the value shall be loaded.
1768 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1769 throw ( gdcmFormatError )
1771 uint16_t element = entry->GetElement();
1772 std::string vr = entry->GetVR();
1775 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1777 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1779 // The following reserved two bytes (see PS 3.5-2001, section
1780 // 7.1.2 Data element structure with explicit vr p27) must be
1781 // skipped before proceeding on reading the length on 4 bytes.
1782 fseek(Fp, 2L, SEEK_CUR);
1783 uint32_t length32 = ReadInt32();
1785 if ( vr == "OB" && length32 == 0xffffffff )
1790 lengthOB = FindDocEntryLengthOB();
1792 catch ( gdcmFormatUnexpected )
1794 // Computing the length failed (this happens with broken
1795 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1796 // chance to get the pixels by deciding the element goes
1797 // until the end of the file. Hence we artificially fix the
1798 // the length and proceed.
1799 long currentPosition = ftell(Fp);
1800 fseek(Fp,0L,SEEK_END);
1801 long lengthUntilEOF = ftell(Fp) - currentPosition;
1802 fseek(Fp, currentPosition, SEEK_SET);
1803 entry->SetLength(lengthUntilEOF);
1806 entry->SetLength(lengthOB);
1809 FixDocEntryFoundLength(entry, length32);
1813 // Length is encoded on 2 bytes.
1814 length16 = ReadInt16();
1816 // We can tell the current file is encoded in big endian (like
1817 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1818 // and it's value is the one of the encoding of a big endian file.
1819 // In order to deal with such big endian encoded files, we have
1820 // (at least) two strategies:
1821 // * when we load the "Transfer Syntax" tag with value of big endian
1822 // encoding, we raise the proper flags. Then we wait for the end
1823 // of the META group (0x0002) among which is "Transfer Syntax",
1824 // before switching the swap code to big endian. We have to postpone
1825 // the switching of the swap code since the META group is fully encoded
1826 // in little endian, and big endian coding only starts at the next
1827 // group. The corresponding code can be hard to analyse and adds
1828 // many additional unnecessary tests for regular tags.
1829 // * the second strategy consists in waiting for trouble, that shall
1830 // appear when we find the first group with big endian encoding. This
1831 // is easy to detect since the length of a "Group Length" tag (the
1832 // ones with zero as element number) has to be of 4 (0x0004). When we
1833 // encounter 1024 (0x0400) chances are the encoding changed and we
1834 // found a group with big endian encoding.
1835 // We shall use this second strategy. In order to make sure that we
1836 // can interpret the presence of an apparently big endian encoded
1837 // length of a "Group Length" without committing a big mistake, we
1838 // add an additional check: we look in the already parsed elements
1839 // for the presence of a "Transfer Syntax" whose value has to be "big
1840 // endian encoding". When this is the case, chances are we have got our
1841 // hands on a big endian encoded file: we switch the swap code to
1842 // big endian and proceed...
1843 if ( element == 0x0000 && length16 == 0x0400 )
1845 if ( !IsExplicitVRBigEndianTransferSyntax() )
1847 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1848 " not explicit VR." );
1852 SwitchSwapToBigEndian();
1853 // Restore the unproperly loaded values i.e. the group, the element
1854 // and the dictionary entry depending on them.
1855 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1856 uint16_t correctElem = SwapShort( entry->GetElement() );
1857 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1861 // This correct tag is not in the dictionary. Create a new one.
1862 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1864 // FIXME this can create a memory leaks on the old entry that be
1865 // left unreferenced.
1866 entry->SetDictEntry( newTag );
1869 // Heuristic: well, some files are really ill-formed.
1870 if ( length16 == 0xffff)
1872 // 0xffff means that we deal with 'Unknown Length' Sequence
1875 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1880 // Either implicit VR or a non DICOM conformal (see note below) explicit
1881 // VR that ommited the VR of (at least) this element. Farts happen.
1882 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1883 // on Data elements "Implicit and Explicit VR Data Elements shall
1884 // not coexist in a Data Set and Data Sets nested within it".]
1885 // Length is on 4 bytes.
1887 FixDocEntryFoundLength( entry, ReadInt32() );
1893 * \brief Find the Value Representation of the current Dicom Element.
1896 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1898 if ( Filetype != gdcmExplicitVR )
1905 long positionOnEntry = ftell(Fp);
1906 // Warning: we believe this is explicit VR (Value Representation) because
1907 // we used a heuristic that found "UL" in the first tag. Alas this
1908 // doesn't guarantee that all the tags will be in explicit VR. In some
1909 // cases (see e-film filtered files) one finds implicit VR tags mixed
1910 // within an explicit VR file. Hence we make sure the present tag
1911 // is in explicit VR and try to fix things if it happens not to be
1914 fread (vr, (size_t)2,(size_t)1, Fp);
1917 if( !CheckDocEntryVR(entry, vr) )
1919 fseek(Fp, positionOnEntry, SEEK_SET);
1920 // When this element is known in the dictionary we shall use, e.g. for
1921 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1922 // dictionary entry. Still we have to flag the element as implicit since
1923 // we know now our assumption on expliciteness is not furfilled.
1925 if ( entry->IsVRUnknown() )
1927 entry->SetVR("Implicit");
1929 entry->SetImplicitVR();
1934 * \brief Check the correspondance between the VR of the header entry
1935 * and the taken VR. If they are different, the header entry is
1936 * updated with the new VR.
1937 * @param entry Header Entry to check
1938 * @param vr Dicom Value Representation
1939 * @return false if the VR is incorrect of if the VR isn't referenced
1940 * otherwise, it returns true
1942 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1944 char msg[100]; // for sprintf
1945 bool realExplicit = true;
1947 // Assume we are reading a falsely explicit VR file i.e. we reached
1948 // a tag where we expect reading a VR but are in fact we read the
1949 // first to bytes of the length. Then we will interogate (through find)
1950 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1951 // both GCC and VC++ implementations of the STL map. Hence when the
1952 // expected VR read happens to be non-ascii characters we consider
1953 // we hit falsely explicit VR tag.
1955 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1957 realExplicit = false;
1960 // CLEANME searching the dicom_vr at each occurence is expensive.
1961 // PostPone this test in an optional integrity check at the end
1962 // of parsing or only in debug mode.
1963 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1965 realExplicit = false;
1968 if ( !realExplicit )
1970 // We thought this was explicit VR, but we end up with an
1971 // implicit VR tag. Let's backtrack.
1972 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1973 entry->GetGroup(), entry->GetElement());
1974 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1976 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1978 // Group length is UL !
1979 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1980 entry->GetGroup(), entry->GetElement(),
1981 "UL", "FIXME", "Group Length");
1982 entry->SetDictEntry( newEntry );
1987 if ( entry->IsVRUnknown() )
1989 // When not a dictionary entry, we can safely overwrite the VR.
1990 if( entry->GetElement() == 0x0000 )
1992 // Group length is UL !
2000 else if ( entry->GetVR() != vr )
2002 // The VR present in the file and the dictionary disagree. We assume
2003 // the file writer knew best and use the VR of the file. Since it would
2004 // be unwise to overwrite the VR of a dictionary (since it would
2005 // compromise it's next user), we need to clone the actual DictEntry
2006 // and change the VR for the read one.
2007 gdcmDictEntry* newEntry = NewVirtualDictEntry(
2008 entry->GetGroup(), entry->GetElement(),
2009 vr, "FIXME", entry->GetName());
2010 entry->SetDictEntry(newEntry);
2017 * \brief Get the transformed value of the header entry. The VR value
2018 * is used to define the transformation to operate on the value
2019 * \warning NOT end user intended method !
2020 * @param entry entry to tranform
2021 * @return Transformed entry value
2023 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
2025 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2027 std::string val = ((gdcmValEntry *)entry)->GetValue();
2028 std::string vr = entry->GetVR();
2029 uint32_t length = entry->GetLength();
2030 std::ostringstream s;
2033 // When short integer(s) are expected, read and convert the following
2034 // n * 2 bytes properly i.e. as a multivaluated strings
2035 // (each single value is separated fromthe next one by '\'
2036 // as usual for standard multivaluated filels
2037 // Elements with Value Multiplicity > 1
2038 // contain a set of short integers (not a single one)
2040 if( vr == "US" || vr == "SS" )
2045 for (int i=0; i < nbInt; i++)
2051 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2052 newInt16 = SwapShort( newInt16 );
2057 // When integer(s) are expected, read and convert the following
2058 // n * 4 bytes properly i.e. as a multivaluated strings
2059 // (each single value is separated fromthe next one by '\'
2060 // as usual for standard multivaluated filels
2061 // Elements with Value Multiplicity > 1
2062 // contain a set of integers (not a single one)
2063 else if( vr == "UL" || vr == "SL" )
2068 for (int i=0; i < nbInt; i++)
2074 newInt32 = ( val[4*i+0] & 0xFF )
2075 + (( val[4*i+1] & 0xFF ) << 8 )
2076 + (( val[4*i+2] & 0xFF ) << 16 )
2077 + (( val[4*i+3] & 0xFF ) << 24 );
2078 newInt32 = SwapLong( newInt32 );
2082 #ifdef GDCM_NO_ANSI_STRING_STREAM
2083 s << std::ends; // to avoid oddities on Solaris
2084 #endif //GDCM_NO_ANSI_STRING_STREAM
2088 return ((gdcmValEntry *)entry)->GetValue();
2092 * \brief Get the reverse transformed value of the header entry. The VR
2093 * value is used to define the reverse transformation to operate on
2095 * \warning NOT end user intended method !
2096 * @param entry Entry to reverse transform
2097 * @return Reverse transformed entry value
2099 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
2101 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2103 std::string vr = entry->GetVR();
2104 std::vector<std::string> tokens;
2105 std::ostringstream s;
2107 if ( vr == "US" || vr == "SS" )
2111 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2112 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2113 for (unsigned int i=0; i<tokens.size(); i++)
2115 newInt16 = atoi(tokens[i].c_str());
2116 s << ( newInt16 & 0xFF )
2117 << (( newInt16 >> 8 ) & 0xFF );
2121 if ( vr == "UL" || vr == "SL")
2125 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2126 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2127 for (unsigned int i=0; i<tokens.size();i++)
2129 newInt32 = atoi(tokens[i].c_str());
2130 s << (char)( newInt32 & 0xFF )
2131 << (char)(( newInt32 >> 8 ) & 0xFF )
2132 << (char)(( newInt32 >> 16 ) & 0xFF )
2133 << (char)(( newInt32 >> 24 ) & 0xFF );
2138 #ifdef GDCM_NO_ANSI_STRING_STREAM
2139 s << std::ends; // to avoid oddities on Solaris
2140 #endif //GDCM_NO_ANSI_STRING_STREAM
2144 return ((gdcmValEntry *)entry)->GetValue();
2148 * \brief Skip a given Header Entry
2149 * \warning NOT end user intended method !
2150 * @param entry entry to skip
2152 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2154 SkipBytes(entry->GetLength());
2158 * \brief Skips to the begining of the next Header Entry
2159 * \warning NOT end user intended method !
2160 * @param entry entry to skip
2162 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2164 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2165 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2169 * \brief When the length of an element value is obviously wrong (because
2170 * the parser went Jabberwocky) one can hope improving things by
2171 * applying some heuristics.
2172 * @param entry entry to check
2173 * @param foundLength fist assumption about length
2175 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2176 uint32_t foundLength)
2178 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2179 if ( foundLength == 0xffffffff)
2184 uint16_t gr = entry->GetGroup();
2185 uint16_t el = entry->GetElement();
2187 if ( foundLength % 2)
2189 std::ostringstream s;
2190 s << "Warning : Tag with uneven length "
2192 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2193 dbg.Verbose(0, s.str().c_str());
2196 //////// Fix for some naughty General Electric images.
2197 // Allthough not recent many such GE corrupted images are still present
2198 // on Creatis hard disks. Hence this fix shall remain when such images
2199 // are no longer in user (we are talking a few years, here)...
2200 // Note: XMedCom probably uses such a trick since it is able to read
2201 // those pesky GE images ...
2202 if ( foundLength == 13)
2204 // Only happens for this length !
2205 if ( entry->GetGroup() != 0x0008
2206 || ( entry->GetElement() != 0x0070
2207 && entry->GetElement() != 0x0080 ) )
2210 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2214 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2215 // Occurence of such images is quite low (unless one leaves close to a
2216 // 'Leonardo' source. Hence, one might consider commenting out the
2217 // following fix on efficiency reasons.
2218 else if ( entry->GetGroup() == 0x0009
2219 && ( entry->GetElement() == 0x1113
2220 || entry->GetElement() == 0x1114 ) )
2223 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2226 else if ( entry->GetVR() == "SQ" )
2228 foundLength = 0; // ReadLength is unchanged
2231 //////// We encountered a 'delimiter' element i.e. a tag of the form
2232 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2233 // taken into account.
2234 else if( entry->GetGroup() == 0xfffe )
2236 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2237 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2238 // causes extra troubles...
2239 if( entry->GetElement() != 0x0000 )
2245 entry->SetUsableLength(foundLength);
2249 * \brief Apply some heuristics to predict whether the considered
2250 * element value contains/represents an integer or not.
2251 * @param entry The element value on which to apply the predicate.
2252 * @return The result of the heuristical predicate.
2254 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2256 uint16_t element = entry->GetElement();
2257 uint16_t group = entry->GetGroup();
2258 std::string vr = entry->GetVR();
2259 uint32_t length = entry->GetLength();
2261 // When we have some semantics on the element we just read, and if we
2262 // a priori know we are dealing with an integer, then we shall be
2263 // able to swap it's element value properly.
2264 if ( element == 0 ) // This is the group length of the group
2272 // Allthough this should never happen, still some images have a
2273 // corrupted group length [e.g. have a glance at offset x(8336) of
2274 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2275 // Since for dicom compliant and well behaved headers, the present
2276 // test is useless (and might even look a bit paranoid), when we
2277 // encounter such an ill-formed image, we simply display a warning
2278 // message and proceed on parsing (while crossing fingers).
2279 std::ostringstream s;
2280 int filePosition = ftell(Fp);
2281 s << "Erroneous Group Length element length on : (" \
2282 << std::hex << group << " , " << element
2283 << ") -before- position x(" << filePosition << ")"
2284 << "lgt : " << length;
2285 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2289 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2298 * \brief Find the Length till the next sequence delimiter
2299 * \warning NOT end user intended method !
2303 uint32_t gdcmDocument::FindDocEntryLengthOB()
2304 throw( gdcmFormatUnexpected )
2306 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2307 long positionOnEntry = ftell(Fp);
2308 bool foundSequenceDelimiter = false;
2309 uint32_t totalLength = 0;
2311 while ( !foundSequenceDelimiter )
2317 group = ReadInt16();
2320 catch ( gdcmFormatError )
2322 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2323 " group or element not present.");
2326 // We have to decount the group and element we just read
2329 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2331 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2332 "tag nor a Sequence delimiter tag.");
2333 fseek(Fp, positionOnEntry, SEEK_SET);
2334 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2335 "Neither an Item tag nor a Sequence "
2339 if ( elem == 0xe0dd )
2341 foundSequenceDelimiter = true;
2344 uint32_t itemLength = ReadInt32();
2345 // We add 4 bytes since we just read the ItemLength with ReadInt32
2346 totalLength += itemLength + 4;
2347 SkipBytes(itemLength);
2349 if ( foundSequenceDelimiter )
2354 fseek(Fp, positionOnEntry, SEEK_SET);
2359 * \brief Reads a supposed to be 16 Bits integer
2360 * (swaps it depending on processor endianity)
2361 * @return read value
2363 uint16_t gdcmDocument::ReadInt16()
2364 throw( gdcmFormatError )
2367 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2368 if ( item_read != 1 )
2372 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2374 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2381 * \brief Reads a supposed to be 32 Bits integer
2382 * (swaps it depending on processor endianity)
2383 * @return read value
2385 uint32_t gdcmDocument::ReadInt32()
2386 throw( gdcmFormatError )
2389 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2390 if ( item_read != 1 )
2394 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2396 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2403 * \brief skips bytes inside the source file
2404 * \warning NOT end user intended method !
2407 void gdcmDocument::SkipBytes(uint32_t nBytes)
2409 //FIXME don't dump the returned value
2410 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2414 * \brief Loads all the needed Dictionaries
2415 * \warning NOT end user intended method !
2417 void gdcmDocument::Initialise()
2419 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2424 * \brief Discover what the swap code is (among little endian, big endian,
2425 * bad little endian, bad big endian).
2427 * @return false when we are absolutely sure
2428 * it's neither ACR-NEMA nor DICOM
2429 * true when we hope ours assuptions are OK
2431 bool gdcmDocument::CheckSwap()
2433 // The only guaranted way of finding the swap code is to find a
2434 // group tag since we know it's length has to be of four bytes i.e.
2435 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2436 // occurs when we can't find such group...
2438 uint32_t x = 4; // x : for ntohs
2439 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2443 char deb[HEADER_LENGTH_TO_READ];
2445 // First, compare HostByteOrder and NetworkByteOrder in order to
2446 // determine if we shall need to swap bytes (i.e. the Endian type).
2447 if ( x == ntohs(x) )
2456 // The easiest case is the one of a DICOM header, since it possesses a
2457 // file preamble where it suffice to look for the string "DICM".
2458 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2459 (void)lgrLue; //FIXME not used
2461 char *entCur = deb + 128;
2462 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2464 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2466 // Next, determine the value representation (VR). Let's skip to the
2467 // first element (0002, 0000) and check there if we find "UL"
2468 // - or "OB" if the 1st one is (0002,0001) -,
2469 // in which case we (almost) know it is explicit VR.
2470 // WARNING: if it happens to be implicit VR then what we will read
2471 // is the length of the group. If this ascii representation of this
2472 // length happens to be "UL" then we shall believe it is explicit VR.
2473 // FIXME: in order to fix the above warning, we could read the next
2474 // element value (or a couple of elements values) in order to make
2475 // sure we are not commiting a big mistake.
2476 // We need to skip :
2477 // * the 128 bytes of File Preamble (often padded with zeroes),
2478 // * the 4 bytes of "DICM" string,
2479 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2480 // i.e. a total of 136 bytes.
2484 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2485 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2486 // *Implicit* VR. -and it is !-
2488 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2489 memcmp(entCur, "OB", (size_t)2) == 0 ||
2490 memcmp(entCur, "UI", (size_t)2) == 0 ||
2491 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2492 // when Write DCM *adds*
2494 // Use gdcmDocument::dicom_vr to test all the possibilities
2495 // instead of just checking for UL, OB and UI !? group 0000
2497 Filetype = gdcmExplicitVR;
2498 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2499 "explicit Value Representation");
2503 Filetype = gdcmImplicitVR;
2504 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2505 "not an explicit Value Representation");
2511 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2512 "HostByteOrder != NetworkByteOrder");
2517 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2518 "HostByteOrder = NetworkByteOrder");
2521 // Position the file position indicator at first tag (i.e.
2522 // after the file preamble and the "DICM" string).
2524 fseek (Fp, 132L, SEEK_SET);
2528 // Alas, this is not a DicomV3 file and whatever happens there is no file
2529 // preamble. We can reset the file position indicator to where the data
2530 // is (i.e. the beginning of the file).
2531 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2534 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2535 // By clean we mean that the length of the first tag is written down.
2536 // If this is the case and since the length of the first group HAS to be
2537 // four (bytes), then determining the proper swap code is straightforward.
2540 // We assume the array of char we are considering contains the binary
2541 // representation of a 32 bits integer. Hence the following dirty
2543 s32 = *((uint32_t *)(entCur));
2564 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2565 // It is time for despaired wild guesses.
2566 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2567 // i.e. the 'group length' element is not present :
2569 // check the supposed to be 'group number'
2570 // 0x0002 or 0x0004 or 0x0008
2571 // to determine ' SwapCode' value .
2572 // Only 0 or 4321 will be possible
2573 // (no oportunity to check for the formerly well known
2574 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2575 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2576 // the file IS NOT ACR-NEMA nor DICOM V3
2577 // Find a trick to tell it the caller...
2579 s16 = *((uint16_t *)(deb));
2596 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2597 "ACR/NEMA unfound swap info (Really hopeless !)");
2598 Filetype = gdcmUnknown;
2601 // Then the only info we have is the net2host one.
2611 * \brief Restore the unproperly loaded values i.e. the group, the element
2612 * and the dictionary entry depending on them.
2614 void gdcmDocument::SwitchSwapToBigEndian()
2616 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2617 "Switching to BigEndian mode.");
2618 if ( SwapCode == 0 )
2622 else if ( SwapCode == 4321 )
2626 else if ( SwapCode == 3412 )
2630 else if ( SwapCode == 2143 )
2637 * \brief during parsing, Header Elements too long are not loaded in memory
2640 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2646 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2648 MaxSizeLoadEntry = 0xffffffff;
2651 MaxSizeLoadEntry = newSize;
2656 * \brief Header Elements too long will not be printed
2657 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2660 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2662 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2667 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2669 MaxSizePrintEntry = 0xffffffff;
2672 MaxSizePrintEntry = newSize;
2678 * \brief Read the next tag but WITHOUT loading it's value
2679 * (read the 'Group Number', the 'Element Number',
2680 * gets the Dict Entry
2681 * gets the VR, gets the length, gets the offset value)
2682 * @return On succes the newly created DocEntry, NULL on failure.
2684 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2691 group = ReadInt16();
2694 catch ( gdcmFormatError e )
2696 // We reached the EOF (or an error occured) therefore
2697 // header parsing has to be considered as finished.
2702 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2703 FindDocEntryVR(newEntry);
2707 FindDocEntryLength(newEntry);
2709 catch ( gdcmFormatError e )
2717 newEntry->SetOffset(ftell(Fp));
2724 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2725 * in the TagHt dictionary.
2726 * @param group The generated tag must belong to this group.
2727 * @return The element of tag with given group which is fee.
2729 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2731 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2733 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2734 if (TagHT.count(key) == 0)
2743 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2744 * is placed at the beginning of a tag check whether this
2745 * tag is (TestGroup, TestElement).
2746 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2747 * is modified to point after the tag.
2748 * On failure (i.e. when the tag wasn't the expected tag
2749 * (TestGroup, TestElement) the internal file pointer
2750 * \ref gdcmDocument::Fp is restored to it's original position.
2751 * @param testGroup The expected group of the tag.
2752 * @param testElement The expected Element of the tag.
2753 * @return True on success, false otherwise.
2755 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2757 long positionOnEntry = ftell(Fp);
2758 long currentPosition = ftell(Fp); // On debugging purposes
2760 //// Read the Item Tag group and element, and make
2761 // sure they are what we expected:
2762 uint16_t itemTagGroup = ReadInt16();
2763 uint16_t itemTagElement = ReadInt16();
2764 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2766 std::ostringstream s;
2767 s << " We should have found tag (";
2768 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2769 s << " but instead we encountered tag (";
2770 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2772 s << " at address: " << (unsigned)currentPosition << std::endl;
2773 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2774 dbg.Verbose(0, s.str().c_str());
2775 fseek(Fp, positionOnEntry, SEEK_SET);
2783 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2784 * is placed at the beginning of a tag (TestGroup, TestElement),
2785 * read the length associated to the Tag.
2786 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2787 * is modified to point after the tag and it's length.
2788 * On failure (i.e. when the tag wasn't the expected tag
2789 * (TestGroup, TestElement) the internal file pointer
2790 * \ref gdcmDocument::Fp is restored to it's original position.
2791 * @param testGroup The expected group of the tag.
2792 * @param testElement The expected Element of the tag.
2793 * @return On success returns the length associated to the tag. On failure
2796 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2798 long positionOnEntry = ftell(Fp);
2799 (void)positionOnEntry;
2801 if ( !ReadTag(testGroup, testElement) )
2806 //// Then read the associated Item Length
2807 long currentPosition = ftell(Fp);
2808 uint32_t itemLength = ReadInt32();
2810 std::ostringstream s;
2811 s << "Basic Item Length is: "
2812 << itemLength << std::endl;
2813 s << " at address: " << (unsigned)currentPosition << std::endl;
2814 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2820 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2821 * No other way so 'skip' the Data
2823 void gdcmDocument::Parse7FE0 ()
2825 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2828 // Should warn user FIXME
2832 if ( IsImplicitVRLittleEndianTransferSyntax()
2833 || IsExplicitVRLittleEndianTransferSyntax()
2834 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2835 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2840 // Encoded pixel data: for the time being we are only concerned with
2841 // Jpeg or RLE Pixel data encodings.
2842 // As stated in ps-3.3, 8.2:
2843 // "If sent in Encapsulated Format (i.e. other than the Narive Format) the
2844 // value representation OB is used".
2845 // Hence we expect an OB value representation. Concerning OB VR,
2846 // the section PS3.3, A.4.c (p58 and p59), states:
2847 // "For the Value Representations OB and OW, the encoding shall meet the
2848 // following specifications depending on the Data element tag:"
2850 // - the first item in the sequence of items before the encoded pixel
2851 // data stream shall be basic offset table item. The basic offset table
2852 // item value, however, is not required to be present"
2854 //// Read the Basic Offset Table Item Tag length...
2855 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2857 // When present, read the basic offset table itself.
2858 // Notes: - since the presence of this basic offset table is optional
2859 // we can't rely on it for the implementation, and we will simply
2860 // trash it's content (when present).
2861 // - still, when present, we could add some further checks on the
2862 // lengths, but not bother with such fuses for the time being.
2863 if ( itemLength != 0 )
2865 char* basicOffsetTableItemValue = new char[itemLength + 1];
2866 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2868 for (unsigned int i=0; i < itemLength; i += 4 )
2870 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2872 std::ostringstream s;
2873 s << " Read one length: ";
2874 s << std::hex << individualLength << std::endl;
2875 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2877 delete[] basicOffsetTableItemValue;
2880 if ( ! IsRLELossLessTransferSyntax() )
2884 //// We then skip (not reading them) all the fragments of images:
2885 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2887 SkipBytes(itemLength);
2892 // Encapsulated RLE Compressed Images (see PS-3.3, Annex G).
2893 // Loop on the frame[s] and store the parsed information in a
2894 // gdcmRLEFramesInfo.
2897 // Loop on the individual frame[s] and store the information
2898 // on the RLE fragments in a gdcmRLEFramesInfo.
2899 // Note: - when only a single frame is present, this is a
2901 // - when more than one frame are present, then we are in
2902 // the case of a multi-frame image.
2903 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2905 // Parse the RLE Header and store the corresponding RLE Segment
2906 // Offset Table information on fragments of this current Frame.
2907 // Note that the fragment pixels themselves are not loaded
2908 // (but just skipped).
2909 uint32_t nbRleSegments = ReadInt32();
2911 uint32_t rleSegmentOffsetTable[15];
2913 for( int k = 1; k <= 15; k++ )
2915 ftellRes = ftell(Fp);
2916 rleSegmentOffsetTable[k] = ReadInt32();
2919 // Deduce from both the RLE Header and the frameLength the
2920 // fragment length, and again store this infor in a
2921 // gdcmRLEFramesInfo.
2922 long rleSegmentLength[15];
2923 // skipping (not reading) RLE Segments
2924 if ( nbRleSegments > 1)
2926 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2928 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2929 - rleSegmentOffsetTable[k];
2930 ftellRes = ftell(Fp);
2931 SkipBytes(rleSegmentLength[k]);
2935 rleSegmentLength[nbRleSegments] = frameLength
2936 - rleSegmentOffsetTable[nbRleSegments];
2937 ftellRes = ftell(Fp);
2938 SkipBytes(rleSegmentLength[nbRleSegments]);
2940 // Store the collected info
2941 gdcmRLEFrame* newFrameInfo = new gdcmRLEFrame;
2942 newFrameInfo->NumberFragments = nbRleSegments;
2943 for( unsigned int k = 1; k <= nbRleSegments; k++ )
2945 newFrameInfo->Offset[k] = rleSegmentOffsetTable[k];
2946 newFrameInfo->Length[k] = rleSegmentLength[k];
2948 RLEInfo.Frames.push_back( newFrameInfo );
2951 // Make sure that at the end of the item we encounter a 'Sequence
2953 if ( !ReadTag(0xfffe, 0xe0dd) )
2955 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2956 dbg.Verbose(0, " at end of RLE item sequence");
2962 * \brief Walk recursively the given \ref gdcmDocEntrySet, and feed
2963 * the given hash table (\ref TagDocEntryHT) with all the
2964 * \ref gdcmDocEntry (Dicom entries) encountered.
2965 * This method does the job for \ref BuildFlatHashTable.
2966 * @param builtHT Where to collect all the \ref gdcmDocEntry encountered
2967 * when recursively walking the given set.
2968 * @param set The structure to be traversed (recursively).
2970 void gdcmDocument::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2971 gdcmDocEntrySet* set )
2973 if (gdcmElementSet* elementSet = dynamic_cast< gdcmElementSet* > ( set ) )
2975 TagDocEntryHT* currentHT = elementSet->GetTagHT();
2976 for( TagDocEntryHT::const_iterator i = currentHT->begin();
2977 i != currentHT->end();
2980 gdcmDocEntry* entry = i->second;
2981 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
2983 ListSQItem& items = seqEntry->GetSQItems();
2984 for( ListSQItem::const_iterator item = items.begin();
2985 item != items.end();
2988 BuildFlatHashTableRecurse( builtHT, *item );
2992 builtHT[entry->GetKey()] = entry;
2997 if (gdcmSQItem* SQItemSet = dynamic_cast< gdcmSQItem* > ( set ) )
2999 ListDocEntry& currentList = SQItemSet->GetDocEntries();
3000 for (ListDocEntry::iterator i = currentList.begin();
3001 i != currentList.end();
3004 gdcmDocEntry* entry = *i;
3005 if ( gdcmSeqEntry* seqEntry = dynamic_cast<gdcmSeqEntry*>(entry) )
3007 ListSQItem& items = seqEntry->GetSQItems();
3008 for( ListSQItem::const_iterator item = items.begin();
3009 item != items.end();
3012 BuildFlatHashTableRecurse( builtHT, *item );
3016 builtHT[entry->GetKey()] = entry;
3023 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3026 * The structure used by a gdcmDocument (through \ref gdcmElementSet),
3027 * in order to old the parsed entries of a Dicom header, is a recursive
3028 * one. This is due to the fact that the sequences (when present)
3029 * can be nested. Additionaly, the sequence items (represented in
3030 * gdcm as \ref gdcmSQItem) add an extra complexity to the data
3031 * structure. Hence, a gdcm user whishing to visit all the entries of
3032 * a Dicom header will need to dig in the gdcm internals (which
3033 * implies exposing all the internal data structures to the API).
3034 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3035 * recursively builds a temporary hash table, which holds all the
3036 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3038 * \warning Of course there is NO integrity constrain between the
3039 * returned \ref TagDocEntryHT and the \ref gdcmElementSet used
3040 * to build it. Hence if the underlying \ref gdcmElementSet is
3041 * altered, then it is the caller responsability to invoke
3042 * \ref BuildFlatHashTable again...
3043 * @return The flat std::map<> we juste build.
3045 TagDocEntryHT* gdcmDocument::BuildFlatHashTable()
3047 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3048 BuildFlatHashTableRecurse( *FlatHT, this );
3055 * \brief Compares two documents, according to \ref gdcmDicomDir rules
3056 * \warning Does NOT work with ACR-NEMA files
3057 * \todo Find a trick to solve the pb (use RET fields ?)
3059 * @return true if 'smaller'
3061 bool gdcmDocument::operator<(gdcmDocument &document)
3064 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3065 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3077 s1 = GetEntryByNumber(0x0010,0x0020);
3078 s2 = document.GetEntryByNumber(0x0010,0x0020);
3089 // Study Instance UID
3090 s1 = GetEntryByNumber(0x0020,0x000d);
3091 s2 = document.GetEntryByNumber(0x0020,0x000d);
3102 // Serie Instance UID
3103 s1 = GetEntryByNumber(0x0020,0x000e);
3104 s2 = document.GetEntryByNumber(0x0020,0x000e);
3120 //-----------------------------------------------------------------------------