1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/12/06 11:37:38 $
7 Version: $Revision: 1.147 $
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"
27 #include "gdcmException.h"
28 #include "gdcmDictSet.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
31 #include "gdcmDocEntrySet.h"
32 #include "gdcmSQItem.h"
38 #if defined(_MSC_VER) || defined(__BORLANDC__)
41 #include <netinet/in.h>
46 //-----------------------------------------------------------------------------
47 static const char *TransferSyntaxStrings[] = {
48 // Implicit VR Little Endian
50 // Implicit VR Little Endian DLX G.E?
52 // Explicit VR Little Endian
53 "1.2.840.10008.1.2.1",
54 // Deflated Explicit VR Little Endian
55 "1.2.840.10008.1.2.1.99",
56 // Explicit VR Big Endian
57 "1.2.840.10008.1.2.2",
58 // JPEG Baseline (Process 1)
59 "1.2.840.10008.1.2.4.50",
60 // JPEG Extended (Process 2 & 4)
61 "1.2.840.10008.1.2.4.51",
62 // JPEG Extended (Process 3 & 5)
63 "1.2.840.10008.1.2.4.52",
64 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
65 "1.2.840.10008.1.2.4.53",
66 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
67 "1.2.840.10008.1.2.4.55",
68 // JPEG Lossless, Non-Hierarchical (Process 14)
69 "1.2.840.10008.1.2.4.57",
70 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
71 "1.2.840.10008.1.2.4.70",
73 "1.2.840.10008.1.2.4.90",
75 "1.2.840.10008.1.2.4.91",
77 "1.2.840.10008.1.2.5",
79 "Unknown Transfer Syntax"
82 //-----------------------------------------------------------------------------
83 // Refer to Document::CheckSwap()
84 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
86 // Refer to Document::SetMaxSizeLoadEntry()
87 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
88 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
90 //-----------------------------------------------------------------------------
91 // Constructor / Destructor
95 * @param filename file to be opened for parsing
97 Document::Document( std::string const & filename ) : ElementSet(-1)
99 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
109 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
111 Fp->seekg( 0, std::ios::beg);
113 Fp->seekg(0, std::ios::end);
114 long lgt = Fp->tellg();
116 Fp->seekg( 0, std::ios::beg);
118 long beg = Fp->tellg();
121 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
123 Fp->seekg( 0, std::ios::beg);
125 // Load 'non string' values
127 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
128 if( PhotometricInterpretation == "PALETTE COLOR " )
130 LoadEntryBinArea(0x0028,0x1200); // gray LUT
131 /// FIXME FIXME FIXME
132 /// The tags refered by the three following lines used to be CORRECTLY
133 /// defined as having an US Value Representation in the public
134 /// dictionnary. BUT the semantics implied by the three following
135 /// lines state that the corresponding tag contents are in fact
136 /// the ones of a BinEntry.
137 /// In order to fix things "Quick and Dirty" the dictionnary was
138 /// altered on PURPOUS but now contains a WRONG value.
139 /// In order to fix things and restore the dictionary to its
140 /// correct value, one needs to decided of the semantics by deciding
141 /// wether the following tags are either:
142 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
143 /// also used as BinEntry, which requires the proper conversion,
144 /// - OW, and hence loaded as BinEntry, but afterwards also used
145 /// as ValEntry, which requires the proper conversion.
146 LoadEntryBinArea(0x0028,0x1201); // R LUT
147 LoadEntryBinArea(0x0028,0x1202); // G LUT
148 LoadEntryBinArea(0x0028,0x1203); // B LUT
150 // Segmented Red Palette Color LUT Data
151 LoadEntryBinArea(0x0028,0x1221);
152 // Segmented Green Palette Color LUT Data
153 LoadEntryBinArea(0x0028,0x1222);
154 // Segmented Blue Palette Color LUT Data
155 LoadEntryBinArea(0x0028,0x1223);
157 //FIXME later : how to use it?
158 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
162 // --------------------------------------------------------------
163 // Specific code to allow gdcm to read ACR-LibIDO formated images
164 // Note: ACR-LibIDO is an extension of the ACR standard that was
165 // used at CREATIS. For the time being (say a couple years)
166 // we keep this kludge to allow a smooth move to gdcm for
167 // CREATIS developpers (sorry folks).
169 // if recognition code tells us we deal with a LibIDO image
170 // we switch lineNumber and columnNumber
173 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
174 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
175 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
176 // with "little-endian strings"
178 Filetype = ACR_LIBIDO;
179 std::string rows = GetEntryByNumber(0x0028, 0x0010);
180 std::string columns = GetEntryByNumber(0x0028, 0x0011);
181 SetEntryByNumber(columns, 0x0028, 0x0010);
182 SetEntryByNumber(rows , 0x0028, 0x0011);
184 // ----------------- End of ACR-LibIDO kludge ------------------
186 PrintLevel = 1; // 'Medium' print level by default
190 * \brief This default constructor doesn't parse the file. You should
191 * then invoke \ref Document::SetFileName and then the parsing.
193 Document::Document() : ElementSet(-1)
197 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
200 Filetype = ExplicitVR;
201 PrintLevel = 1; // 'Medium' print level by default
205 * \brief Canonical destructor.
207 Document::~Document ()
216 //-----------------------------------------------------------------------------
220 * \brief Prints The Dict Entries of THE public Dicom Dictionary
223 void Document::PrintPubDict(std::ostream & os)
225 RefPubDict->Print(os);
229 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
232 void Document::PrintShaDict(std::ostream & os)
234 RefShaDict->Print(os);
237 //-----------------------------------------------------------------------------
240 * \brief Get the public dictionary used
242 Dict* Document::GetPubDict()
248 * \brief Get the shadow dictionary used
250 Dict* Document::GetShaDict()
256 * \brief Set the shadow dictionary used
257 * \param dict dictionary to use in shadow
259 bool Document::SetShaDict(Dict *dict)
266 * \brief Set the shadow dictionary used
267 * \param dictName name of the dictionary to use in shadow
269 bool Document::SetShaDict(DictKey const & dictName)
271 RefShaDict = Global::GetDicts()->GetDict(dictName);
276 * \brief This predicate, based on hopefully reasonable heuristics,
277 * decides whether or not the current Document was properly parsed
278 * and contains the mandatory information for being considered as
279 * a well formed and usable Dicom/Acr File.
280 * @return true when Document is the one of a reasonable Dicom/Acr file,
283 bool Document::IsReadable()
285 if( Filetype == Unknown)
287 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
293 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
302 * \brief Accessor to the Transfer Syntax (when present) of the
303 * current document (it internally handles reading the
304 * value from disk when only parsing occured).
305 * @return The encountered Transfer Syntax of the current document.
307 TransferSyntaxType Document::GetTransferSyntax()
309 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
315 // The entry might be present but not loaded (parsing and loading
316 // happen at different stages): try loading and proceed with check...
317 LoadDocEntrySafe(entry);
318 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
320 std::string transfer = valEntry->GetValue();
321 // The actual transfer (as read from disk) might be padded. We
322 // first need to remove the potential padding. We can make the
323 // weak assumption that padding was not executed with digits...
324 if ( transfer.length() == 0 )
326 // for brain damaged headers
329 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
331 transfer.erase(transfer.length()-1, 1);
333 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
335 if ( TransferSyntaxStrings[i] == transfer )
337 return TransferSyntaxType(i);
344 bool Document::IsJPEGLossless()
346 TransferSyntaxType r = GetTransferSyntax();
347 return r == JPEGFullProgressionProcess10_12
348 || r == JPEGLosslessProcess14
349 || r == JPEGLosslessProcess14_1;
353 * \brief Determines if the Transfer Syntax was already encountered
354 * and if it corresponds to a JPEG2000 one
355 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
358 bool Document::IsJPEG2000()
360 TransferSyntaxType r = GetTransferSyntax();
361 return r == JPEG2000Lossless || r == JPEG2000;
365 * \brief Determines if the Transfer Syntax corresponds to any form
366 * of Jpeg encoded Pixel data.
367 * @return True when any form of JPEG found. False otherwise.
369 bool Document::IsJPEG()
371 TransferSyntaxType r = GetTransferSyntax();
372 return r == JPEGBaselineProcess1
373 || r == JPEGExtendedProcess2_4
374 || r == JPEGExtendedProcess3_5
375 || r == JPEGSpectralSelectionProcess6_8
381 * \brief Determines if the Transfer Syntax corresponds to encapsulated
382 * of encoded Pixel Data (as opposed to native).
383 * @return True when encapsulated. False when native.
385 bool Document::IsEncapsulate()
387 TransferSyntaxType r = GetTransferSyntax();
388 return IsJPEG() || r == RLELossless;
392 * \brief Predicate for dicom version 3 file.
393 * @return True when the file is a dicom version 3.
395 bool Document::IsDicomV3()
397 // Checking if Transfert Syntax exists is enough
398 // Anyway, it's to late check if the 'Preamble' was found ...
399 // And ... would it be a rich idea to check ?
400 // (some 'no Preamble' DICOM images exist !)
401 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
405 * \brief returns the File Type
406 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
407 * @return the FileType code
409 FileType Document::GetFileType()
415 * \brief Tries to open the file \ref Document::Filename and
416 * checks the preamble when existing.
417 * @return The FILE pointer on success.
419 std::ifstream* Document::OpenFile()
421 if (Filename.length() == 0)
429 "Document::OpenFile is already opened when opening: ",
433 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
437 "Document::OpenFile cannot open file: ",
445 Fp->read((char*)&zero, (size_t)2 );
447 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
449 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
450 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
451 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
452 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
458 Fp->seekg(126L, std::ios::cur);
460 Fp->read(dicm, (size_t)4);
461 if( memcmp(dicm, "DICM", 4) == 0 )
468 "Document::OpenFile not DICOM/ACR (missing preamble)",
475 * \brief closes the file
476 * @return TRUE if the close was successfull
478 bool Document::CloseFile()
487 return true; //FIXME how do we detect a non-close ifstream ?
491 * \brief Writes in a file all the Header Entries (Dicom Elements)
492 * @param fp file pointer on an already open file
493 * @param filetype Type of the File to be written
494 * (ACR-NEMA, ExplicitVR, ImplicitVR)
495 * \return Always true.
497 void Document::WriteContent(std::ofstream* fp, FileType filetype)
499 /// \todo move the following lines (and a lot of others, to be written)
500 /// to a future function CheckAndCorrectHeader
501 /// (necessary if user wants to write a DICOM V3 file
502 /// starting from an ACR-NEMA (V2) Header
504 if ( filetype == ImplicitVR || filetype == ExplicitVR )
506 // writing Dicom File Preamble
507 char filePreamble[128];
508 memset(filePreamble, 0, 128);
509 fp->write(filePreamble, 128);
510 fp->write("DICM", 4);
514 * \todo rewrite later, if really usefull
515 * - 'Group Length' element is optional in DICOM
516 * - but un-updated odd groups lengthes can causes pb
519 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
520 * UpdateGroupLength(false,filetype);
521 * if ( filetype == ACR)
522 * UpdateGroupLength(true,ACR);
525 ElementSet::WriteContent(fp, filetype); // This one is recursive
529 * \brief Modifies the value of a given Header Entry (Dicom Element)
530 * when it exists. Create it with the given value when unexistant.
531 * @param value (string) Value to be set
532 * @param group Group number of the Entry
533 * @param elem Element number of the Entry
534 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
535 * \return pointer to the modified/created Header Entry (NULL when creation
538 ValEntry* Document::ReplaceOrCreateByNumber(
539 std::string const & value,
544 ValEntry* valEntry = 0;
545 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
549 // check if (group,element) DictEntry exists
550 // if it doesn't, create an entry in DictSet::VirtualEntry
553 // Find out if the tag we received is in the dictionaries:
554 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
555 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
558 currentEntry = NewDocEntryByNumber(group, elem, vr);
562 currentEntry = NewDocEntryByNumber(group, elem);
567 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
568 " NewDocEntryByNumber failed.");
572 valEntry = new ValEntry(currentEntry);
575 if ( !AddEntry(valEntry))
578 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
579 " failed allthough this is a creation.");
585 valEntry = dynamic_cast< ValEntry* >(currentEntry);
586 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
587 // then we change it to a ValEntry ?
588 // Shouldn't it be considered as an error ?
590 // We need to promote the DocEntry to a ValEntry:
591 valEntry = new ValEntry(currentEntry);
592 if (!RemoveEntry(currentEntry))
595 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
596 " of previous DocEntry failed.");
599 if ( !AddEntry(valEntry))
602 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
603 " promoted ValEntry failed.");
609 SetEntryByNumber(value, group, elem);
615 * \brief Modifies the value of a given Header Entry (Dicom Element)
616 * when it exists. Create it with the given value when unexistant.
617 * A copy of the binArea is made to be kept in the Document.
618 * @param binArea (binary) value to be set
619 * @param Group Group number of the Entry
620 * @param Elem Element number of the Entry
621 * \return pointer to the modified/created Header Entry (NULL when creation
624 BinEntry* Document::ReplaceOrCreateByNumber(
631 BinEntry* binEntry = 0;
632 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
636 // check if (group,element) DictEntry exists
637 // if it doesn't, create an entry in DictSet::VirtualEntry
640 // Find out if the tag we received is in the dictionaries:
641 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
642 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
646 currentEntry = NewDocEntryByNumber(group, elem, vr);
650 currentEntry = NewDocEntryByNumber(group, elem);
654 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
655 " NewDocEntryByNumber failed.");
658 binEntry = new BinEntry(currentEntry);
659 if ( !AddEntry(binEntry))
661 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
662 " failed allthough this is a creation.");
668 binEntry = dynamic_cast< BinEntry* >(currentEntry);
669 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
670 // then we change it to a BinEntry ?
671 // Shouldn't it be considered as an error ?
673 // We need to promote the DocEntry to a BinEntry:
674 binEntry = new BinEntry(currentEntry);
675 if (!RemoveEntry(currentEntry))
677 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
678 " of previous DocEntry failed.");
681 if ( !AddEntry(binEntry))
683 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
684 " promoted BinEntry failed.");
691 if (lgth>0 && binArea)
693 tmpArea = new uint8_t[lgth];
694 memcpy(tmpArea,binArea,lgth);
700 if (!SetEntryByNumber(tmpArea, lgth, group, elem))
713 * \brief Modifies the value of a given Header Entry (Dicom Element)
714 * when it exists. Create it when unexistant.
715 * @param Group Group number of the Entry
716 * @param Elem Element number of the Entry
717 * \return pointer to the modified/created SeqEntry (NULL when creation
720 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
723 DocEntry* a = GetDocEntryByNumber( group, elem);
726 a = NewSeqEntryByNumber(group, elem);
732 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
739 * \brief Set a new value if the invoked element exists
740 * Seems to be useless !!!
741 * @param value new element value
742 * @param group group number of the Entry
743 * @param elem element number of the Entry
746 bool Document::ReplaceIfExistByNumber(std::string const & value,
747 uint16_t group, uint16_t elem )
749 SetEntryByNumber(value, group, elem);
754 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
756 return TransferSyntaxStrings[type];
759 //-----------------------------------------------------------------------------
763 * \brief Checks if a given Dicom Element exists within the H table
764 * @param group Group number of the searched Dicom Element
765 * @param element Element number of the searched Dicom Element
766 * @return true is found
768 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
770 const std::string &key = DictEntry::TranslateToKey(group, element );
771 return TagHT.count(key) != 0;
775 * \brief Searches within Header Entries (Dicom Elements) parsed with
776 * the public and private dictionaries
777 * for the element value of a given tag.
778 * \warning Don't use any longer : use GetPubEntryByName
779 * @param tagName name of the searched element.
780 * @return Corresponding element value when it exists,
781 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
783 std::string Document::GetEntryByName(TagName const & tagName)
785 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
791 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
795 * \brief Searches within Header Entries (Dicom Elements) parsed with
796 * the public and private dictionaries
797 * for the element value representation of a given tag.
799 * Obtaining the VR (Value Representation) might be needed by caller
800 * to convert the string typed content to caller's native type
801 * (think of C++ vs Python). The VR is actually of a higher level
802 * of semantics than just the native C++ type.
803 * @param tagName name of the searched element.
804 * @return Corresponding element value representation when it exists,
805 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
807 std::string Document::GetEntryVRByName(TagName const& tagName)
809 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
810 if( dictEntry == NULL)
815 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
816 dictEntry->GetElement());
817 return elem->GetVR();
821 * \brief Searches within Header Entries (Dicom Elements) parsed with
822 * the public and private dictionaries
823 * for the element value representation of a given tag.
824 * @param group Group number of the searched tag.
825 * @param element Element number of the searched tag.
826 * @return Corresponding element value representation when it exists,
827 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
829 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
831 TagKey key = DictEntry::TranslateToKey(group, element);
832 /// \todo use map methods, instead of multimap JPR
833 if ( !TagHT.count(key))
838 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
842 * \brief Searches within Header Entries (Dicom Elements) parsed with
843 * the public and private dictionaries
844 * for the element value representation of a given tag..
846 * Obtaining the VR (Value Representation) might be needed by caller
847 * to convert the string typed content to caller's native type
848 * (think of C++ vs Python). The VR is actually of a higher level
849 * of semantics than just the native C++ type.
850 * @param group Group number of the searched tag.
851 * @param element Element number of the searched tag.
852 * @return Corresponding element value representation when it exists,
853 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
855 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
857 DocEntry* elem = GetDocEntryByNumber(group, element);
862 return elem->GetVR();
866 * \brief Searches within Header Entries (Dicom Elements) parsed with
867 * the public and private dictionaries
868 * for the value length of a given tag..
869 * @param group Group number of the searched tag.
870 * @param element Element number of the searched tag.
871 * @return Corresponding element length; -2 if not found
873 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
875 DocEntry* elem = GetDocEntryByNumber(group, element);
878 return -2; //magic number
880 return elem->GetLength();
883 * \brief Sets the value (string) of the Header Entry (Dicom Element)
884 * @param content string value of the Dicom Element
885 * @param tagName name of the searched Dicom Element.
886 * @return true when found
888 bool Document::SetEntryByName( std::string const & content,
889 TagName const & tagName)
891 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
897 return SetEntryByNumber(content,dictEntry->GetGroup(),
898 dictEntry->GetElement());
902 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
903 * through it's (group, element) and modifies it's content with
905 * @param content new value (string) to substitute with
906 * @param group group number of the Dicom Element to modify
907 * @param element element number of the Dicom Element to modify
909 bool Document::SetEntryByNumber(std::string const& content,
910 uint16_t group, uint16_t element)
915 ValEntry* valEntry = GetValEntryByNumber(group, element);
918 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
919 " ValEntry (try promotion first).");
922 // Non even content must be padded with a space (020H)...
923 std::string finalContent = Util::DicomString( content.c_str() );
924 assert( !(finalContent.size() % 2) );
925 valEntry->SetValue(finalContent);
927 // Integers have a special treatement for their length:
928 l = finalContent.length();
929 if ( l != 0) // To avoid to be cheated by 'zero length' integers
931 VRKey vr = valEntry->GetVR();
932 if( vr == "US" || vr == "SS" )
934 // for multivaluated items
935 c = Util::CountSubstring(content, "\\") + 1;
938 else if( vr == "UL" || vr == "SL" )
940 // for multivaluated items
941 c = Util::CountSubstring(content, "\\") + 1;
945 valEntry->SetLength(l);
950 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
951 * through it's (group, element) and modifies it's content with
953 * @param content new value (void* -> uint8_t*) to substitute with
954 * @param lgth new value length
955 * @param group group number of the Dicom Element to modify
956 * @param element element number of the Dicom Element to modify
958 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
959 uint16_t group, uint16_t element)
961 (void)lgth; //not used
962 TagKey key = DictEntry::TranslateToKey(group, element);
963 if ( !TagHT.count(key))
968 /* Hope Binary field length is *never* wrong
969 if(lgth%2) // Non even length are padded with a space (020H).
972 //content = content + '\0'; // fing a trick to enlarge a binary field?
975 BinEntry* entry = (BinEntry *)TagHT[key];
976 entry->SetBinArea(content);
977 entry->SetLength(lgth);
978 entry->SetValue(GDCM_BINLOADED);
984 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
985 * in the PubDocEntrySet of this instance
986 * through it's (group, element) and modifies it's length with
988 * \warning Use with extreme caution.
989 * @param l new length to substitute with
990 * @param group group number of the Entry to modify
991 * @param element element number of the Entry to modify
992 * @return true on success, false otherwise.
994 /*bool Document::SetEntryLengthByNumber(uint32_t l,
995 uint16_t group, uint16_t element)
997 /// \todo use map methods, instead of multimap JPR
998 TagKey key = DictEntry::TranslateToKey(group, element);
999 if ( !TagHT.count(key) )
1005 l++; // length must be even
1007 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1013 * \brief Gets (from Header) the offset of a 'non string' element value
1014 * (LoadElementValues has already be executed)
1015 * @param group group number of the Entry
1016 * @param elem element number of the Entry
1017 * @return File Offset of the Element Value
1019 /*size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1021 DocEntry* entry = GetDocEntryByNumber(group, elem);
1024 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1027 return entry->GetOffset();
1031 * \brief Gets (from Header) a 'non string' element value
1032 * (LoadElementValues has already be executed)
1033 * @param group group number of the Entry
1034 * @param elem element number of the Entry
1035 * @return Pointer to the 'non string' area
1037 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1039 DocEntry* entry = GetDocEntryByNumber(group, elem);
1042 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1045 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1047 return binEntry->GetBinArea();
1054 * \brief Loads (from disk) the element content
1055 * when a string is not suitable
1056 * @param group group number of the Entry
1057 * @param elem element number of the Entry
1059 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1061 // Search the corresponding DocEntry
1062 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1066 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1070 LoadEntryBinArea(binElement);
1074 * \brief Loads (from disk) the element content
1075 * when a string is not suitable
1076 * @param element Entry whose binArea is going to be loaded
1078 void Document::LoadEntryBinArea(BinEntry* element)
1080 if(element->GetBinArea())
1083 bool openFile = !Fp;
1087 size_t o =(size_t)element->GetOffset();
1088 Fp->seekg(o, std::ios::beg);
1090 size_t l = element->GetLength();
1091 uint8_t* a = new uint8_t[l];
1094 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1098 /// \todo check the result
1099 Fp->read((char*)a, l);
1100 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1106 element->SetBinArea(a);
1113 * \brief Sets a 'non string' value to a given Dicom Element
1114 * @param area area containing the 'non string' value
1115 * @param group Group number of the searched Dicom Element
1116 * @param element Element number of the searched Dicom Element
1119 /*bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1120 uint16_t group, uint16_t element)
1122 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1123 if ( !currentEntry )
1128 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1130 binEntry->SetBinArea( area );
1138 * \brief Update the entries with the shadow dictionary.
1139 * Only non even entries are analyzed
1141 void Document::UpdateShaEntries()
1146 /// \todo TODO : still any use to explore recursively the whole structure?
1148 for(ListTag::iterator it=listEntries.begin();
1149 it!=listEntries.end();
1152 // Odd group => from public dictionary
1153 if((*it)->GetGroup()%2==0)
1156 // Peer group => search the corresponding dict entry
1158 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1162 if((*it)->IsImplicitVR())
1167 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1169 // Set the new entry and the new value
1170 (*it)->SetDictEntry(entry);
1171 CheckDocEntryVR(*it,vr);
1173 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1178 // Remove precedent value transformation
1179 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1186 * \brief Searches within the Header Entries for a Dicom Element of
1188 * @param tagName name of the searched Dicom Element.
1189 * @return Corresponding Dicom Element when it exists, and NULL
1192 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1194 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1200 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1204 * \brief retrieves a Dicom Element (the first one) using (group, element)
1205 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1206 * if you think it's NOT UNIQUE, check the count number
1207 * and use iterators to retrieve ALL the Dicoms Elements within
1208 * a given couple (group, element)
1209 * @param group Group number of the searched Dicom Element
1210 * @param element Element number of the searched Dicom Element
1213 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1215 TagKey key = DictEntry::TranslateToKey(group, element);
1216 if ( !TagHT.count(key))
1220 return TagHT.find(key)->second;
1224 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1225 * returns a result when the corresponding entry is of type
1227 * @return When present, the corresponding ValEntry.
1229 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1231 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1232 if ( !currentEntry )
1236 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1240 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1246 * \brief Loads the element while preserving the current
1247 * underlying file position indicator as opposed to
1248 * to LoadDocEntry that modifies it.
1249 * @param entry Header Entry whose value shall be loaded.
1252 void Document::LoadDocEntrySafe(DocEntry * entry)
1256 long PositionOnEntry = Fp->tellg();
1257 LoadDocEntry(entry);
1258 Fp->seekg(PositionOnEntry, std::ios::beg);
1263 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1265 * @return The properly swaped 32 bits integer.
1267 uint32_t Document::SwapLong(uint32_t a)
1274 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1275 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1279 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1283 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1286 //std::cout << "swapCode= " << SwapCode << std::endl;
1287 dbg.Error(" Document::SwapLong : unset swap code");
1294 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1296 * @return The properly unswaped 32 bits integer.
1298 uint32_t Document::UnswapLong(uint32_t a)
1304 * \brief Swaps the bytes so they agree with the processor order
1305 * @return The properly swaped 16 bits integer.
1307 uint16_t Document::SwapShort(uint16_t a)
1309 if ( SwapCode == 4321 || SwapCode == 2143 )
1311 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1317 * \brief Unswaps the bytes so they agree with the processor order
1318 * @return The properly unswaped 16 bits integer.
1320 uint16_t Document::UnswapShort(uint16_t a)
1322 return SwapShort(a);
1325 //-----------------------------------------------------------------------------
1329 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1330 * @return length of the parsed set.
1332 void Document::ParseDES(DocEntrySet *set, long offset,
1333 long l_max, bool delim_mode)
1335 DocEntry *newDocEntry = 0;
1339 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1343 newDocEntry = ReadNextDocEntry( );
1349 VRKey vr = newDocEntry->GetVR();
1353 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1355 /////////////////////// ValEntry
1356 ValEntry* newValEntry =
1357 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1358 newValEntry->Copy( newDocEntry );
1360 // When "set" is a Document, then we are at the top of the
1361 // hierarchy and the Key is simply of the form ( group, elem )...
1362 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1365 newValEntry->SetKey( newValEntry->GetKey() );
1367 // ...but when "set" is a SQItem, we are inserting this new
1368 // valEntry in a sequence item. Hence the key has the
1369 // generalized form (refer to \ref BaseTagKey):
1370 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1372 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1373 + newValEntry->GetKey() );
1376 LoadDocEntry( newValEntry );
1377 bool delimitor=newValEntry->IsItemDelimitor();
1378 if( !set->AddEntry( newValEntry ) )
1380 // If here expect big troubles
1381 delete newValEntry; //otherwise mem leak
1389 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1397 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1399 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1400 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1401 "nor BinEntry. Probably unknown VR.");
1404 //////////////////// BinEntry or UNKOWN VR:
1405 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1407 // When "this" is a Document the Key is simply of the
1408 // form ( group, elem )...
1409 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1412 newBinEntry->SetKey( newBinEntry->GetKey() );
1414 // but when "this" is a SQItem, we are inserting this new
1415 // valEntry in a sequence item, and the kay has the
1416 // generalized form (refer to \ref BaseTagKey):
1417 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1419 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1420 + newBinEntry->GetKey() );
1423 LoadDocEntry( newBinEntry );
1424 if( !set->AddEntry( newBinEntry ) )
1426 //Expect big troubles if here
1431 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1432 && ( newDocEntry->GetElement() == 0x0010 ) )
1434 TransferSyntaxType ts = GetTransferSyntax();
1435 if ( ts == RLELossless )
1437 long PositionOnEntry = Fp->tellg();
1438 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1440 Fp->seekg( PositionOnEntry, std::ios::beg );
1442 else if ( IsJPEG() )
1444 long PositionOnEntry = Fp->tellg();
1445 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1446 ComputeJPEGFragmentInfo();
1447 Fp->seekg( PositionOnEntry, std::ios::beg );
1451 // Just to make sure we are at the beginning of next entry.
1452 SkipToNextDocEntry(newDocEntry);
1453 //delete newDocEntry;
1458 unsigned long l = newDocEntry->GetReadLength();
1459 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1461 if ( l == 0xffffffff )
1470 // no other way to create it ...
1471 SeqEntry* newSeqEntry =
1472 new SeqEntry( newDocEntry->GetDictEntry() );
1473 newSeqEntry->Copy( newDocEntry );
1474 newSeqEntry->SetDelimitorMode( delim_mode );
1476 // At the top of the hierarchy, stands a Document. When "set"
1477 // is a Document, then we are building the first depth level.
1478 // Hence the SeqEntry we are building simply has a depth
1480 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1483 newSeqEntry->SetDepthLevel( 1 );
1484 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1486 // But when "set" is allready a SQItem, we are building a nested
1487 // sequence, and hence the depth level of the new SeqEntry
1488 // we are building, is one level deeper:
1489 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1491 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1492 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1493 + newSeqEntry->GetKey() );
1497 { // Don't try to parse zero-length sequences
1498 ParseSQ( newSeqEntry,
1499 newDocEntry->GetOffset(),
1502 set->AddEntry( newSeqEntry );
1503 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1514 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1515 * @return parsed length for this level
1517 void Document::ParseSQ( SeqEntry* seqEntry,
1518 long offset, long l_max, bool delim_mode)
1520 int SQItemNumber = 0;
1525 DocEntry* newDocEntry = ReadNextDocEntry();
1528 // FIXME Should warn user
1533 if ( newDocEntry->IsSequenceDelimitor() )
1535 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1539 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1545 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1546 std::ostringstream newBase;
1547 newBase << seqEntry->GetKey()
1551 itemSQ->SetBaseTagKey( newBase.str() );
1552 unsigned int l = newDocEntry->GetReadLength();
1554 if ( l == 0xffffffff )
1563 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1566 seqEntry->AddEntry( itemSQ, SQItemNumber );
1568 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1576 * \brief Loads the element content if its length doesn't exceed
1577 * the value specified with Document::SetMaxSizeLoadEntry()
1578 * @param entry Header Entry (Dicom Element) to be dealt with
1580 void Document::LoadDocEntry(DocEntry* entry)
1582 uint16_t group = entry->GetGroup();
1583 std::string vr = entry->GetVR();
1584 uint32_t length = entry->GetLength();
1586 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1588 // A SeQuence "contains" a set of Elements.
1589 // (fffe e000) tells us an Element is beginning
1590 // (fffe e00d) tells us an Element just ended
1591 // (fffe e0dd) tells us the current SeQuence just ended
1592 if( group == 0xfffe )
1594 // NO more value field for SQ !
1598 // When the length is zero things are easy:
1601 ((ValEntry *)entry)->SetValue("");
1605 // The elements whose length is bigger than the specified upper bound
1606 // are not loaded. Instead we leave a short notice of the offset of
1607 // the element content and it's length.
1609 std::ostringstream s;
1610 if (length > MaxSizeLoadEntry)
1612 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1614 //s << "gdcm::NotLoaded (BinEntry)";
1615 s << GDCM_NOTLOADED;
1616 s << " Address:" << (long)entry->GetOffset();
1617 s << " Length:" << entry->GetLength();
1618 s << " x(" << std::hex << entry->GetLength() << ")";
1619 binEntryPtr->SetValue(s.str());
1621 // Be carefull : a BinEntry IS_A ValEntry ...
1622 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1624 // s << "gdcm::NotLoaded. (ValEntry)";
1625 s << GDCM_NOTLOADED;
1626 s << " Address:" << (long)entry->GetOffset();
1627 s << " Length:" << entry->GetLength();
1628 s << " x(" << std::hex << entry->GetLength() << ")";
1629 valEntryPtr->SetValue(s.str());
1634 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1635 << "nor a ValEntry ?! Should never print that !" << std::endl;
1638 // to be sure we are at the end of the value ...
1639 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1644 // When we find a BinEntry not very much can be done :
1645 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1647 s << GDCM_BINLOADED;
1648 binEntryPtr->SetValue(s.str());
1649 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1653 /// \todo Any compacter code suggested (?)
1654 if ( IsDocEntryAnInteger(entry) )
1658 // When short integer(s) are expected, read and convert the following
1659 // n *two characters properly i.e. consider them as short integers as
1660 // opposed to strings.
1661 // Elements with Value Multiplicity > 1
1662 // contain a set of integers (not a single one)
1663 if (vr == "US" || vr == "SS")
1666 NewInt = ReadInt16();
1670 for (int i=1; i < nbInt; i++)
1673 NewInt = ReadInt16();
1678 // See above comment on multiple integers (mutatis mutandis).
1679 else if (vr == "UL" || vr == "SL")
1682 NewInt = ReadInt32();
1686 for (int i=1; i < nbInt; i++)
1689 NewInt = ReadInt32();
1694 #ifdef GDCM_NO_ANSI_STRING_STREAM
1695 s << std::ends; // to avoid oddities on Solaris
1696 #endif //GDCM_NO_ANSI_STRING_STREAM
1698 ((ValEntry *)entry)->SetValue(s.str());
1702 // FIXME: We need an additional byte for storing \0 that is not on disk
1703 char *str = new char[length+1];
1704 Fp->read(str, (size_t)length);
1705 str[length] = '\0'; //this is only useful when length is odd
1706 // Special DicomString call to properly handle \0 and even length
1707 std::string newValue;
1710 newValue = Util::DicomString(str, length+1);
1711 //dbg.Verbose(0, "Warning: bad length: ", length );
1712 dbg.Verbose(0, "For string :", newValue.c_str());
1713 // Since we change the length of string update it length
1714 entry->SetReadLength(length+1);
1718 newValue = Util::DicomString(str, length);
1722 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1724 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1726 dbg.Verbose(1, "Document::LoadDocEntry",
1727 "unread element value");
1728 valEntry->SetValue(GDCM_UNREAD);
1734 // Because of correspondance with the VR dic
1735 valEntry->SetValue(newValue);
1739 valEntry->SetValue(newValue);
1744 dbg.Error(true, "Document::LoadDocEntry"
1745 "Should have a ValEntry, here !");
1751 * \brief Find the value Length of the passed Header Entry
1752 * @param entry Header Entry whose length of the value shall be loaded.
1754 void Document::FindDocEntryLength( DocEntry *entry )
1755 throw ( FormatError )
1757 uint16_t element = entry->GetElement();
1758 std::string vr = entry->GetVR();
1761 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1763 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1765 // The following reserved two bytes (see PS 3.5-2003, section
1766 // "7.1.2 Data element structure with explicit vr", p 27) must be
1767 // skipped before proceeding on reading the length on 4 bytes.
1768 Fp->seekg( 2L, std::ios::cur);
1769 uint32_t length32 = ReadInt32();
1771 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1776 /// \todo rename that to FindDocEntryLengthOBOrOW since
1777 /// the above test is on both OB and OW...
1778 lengthOB = FindDocEntryLengthOB();
1780 catch ( FormatUnexpected )
1782 // Computing the length failed (this happens with broken
1783 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1784 // chance to get the pixels by deciding the element goes
1785 // until the end of the file. Hence we artificially fix the
1786 // the length and proceed.
1787 long currentPosition = Fp->tellg();
1788 Fp->seekg(0L,std::ios::end);
1789 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1790 Fp->seekg(currentPosition, std::ios::beg);
1791 entry->SetLength(lengthUntilEOF);
1794 entry->SetLength(lengthOB);
1797 FixDocEntryFoundLength(entry, length32);
1801 // Length is encoded on 2 bytes.
1802 length16 = ReadInt16();
1804 // We can tell the current file is encoded in big endian (like
1805 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1806 // and it's value is the one of the encoding of a big endian file.
1807 // In order to deal with such big endian encoded files, we have
1808 // (at least) two strategies:
1809 // * when we load the "Transfer Syntax" tag with value of big endian
1810 // encoding, we raise the proper flags. Then we wait for the end
1811 // of the META group (0x0002) among which is "Transfer Syntax",
1812 // before switching the swap code to big endian. We have to postpone
1813 // the switching of the swap code since the META group is fully encoded
1814 // in little endian, and big endian coding only starts at the next
1815 // group. The corresponding code can be hard to analyse and adds
1816 // many additional unnecessary tests for regular tags.
1817 // * the second strategy consists in waiting for trouble, that shall
1818 // appear when we find the first group with big endian encoding. This
1819 // is easy to detect since the length of a "Group Length" tag (the
1820 // ones with zero as element number) has to be of 4 (0x0004). When we
1821 // encounter 1024 (0x0400) chances are the encoding changed and we
1822 // found a group with big endian encoding.
1823 // We shall use this second strategy. In order to make sure that we
1824 // can interpret the presence of an apparently big endian encoded
1825 // length of a "Group Length" without committing a big mistake, we
1826 // add an additional check: we look in the already parsed elements
1827 // for the presence of a "Transfer Syntax" whose value has to be "big
1828 // endian encoding". When this is the case, chances are we have got our
1829 // hands on a big endian encoded file: we switch the swap code to
1830 // big endian and proceed...
1831 if ( element == 0x0000 && length16 == 0x0400 )
1833 TransferSyntaxType ts = GetTransferSyntax();
1834 if ( ts != ExplicitVRBigEndian )
1836 throw FormatError( "Document::FindDocEntryLength()",
1837 " not explicit VR." );
1841 SwitchSwapToBigEndian();
1842 // Restore the unproperly loaded values i.e. the group, the element
1843 // and the dictionary entry depending on them.
1844 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1845 uint16_t correctElem = SwapShort( entry->GetElement() );
1846 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1850 // This correct tag is not in the dictionary. Create a new one.
1851 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1853 // FIXME this can create a memory leaks on the old entry that be
1854 // left unreferenced.
1855 entry->SetDictEntry( newTag );
1858 // Heuristic: well, some files are really ill-formed.
1859 if ( length16 == 0xffff)
1861 // 0xffff means that we deal with 'Unknown Length' Sequence
1864 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1869 // Either implicit VR or a non DICOM conformal (see note below) explicit
1870 // VR that ommited the VR of (at least) this element. Farts happen.
1871 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1872 // on Data elements "Implicit and Explicit VR Data Elements shall
1873 // not coexist in a Data Set and Data Sets nested within it".]
1874 // Length is on 4 bytes.
1876 FixDocEntryFoundLength( entry, ReadInt32() );
1882 * \brief Find the Value Representation of the current Dicom Element.
1885 void Document::FindDocEntryVR( DocEntry *entry )
1887 if ( Filetype != ExplicitVR )
1894 long positionOnEntry = Fp->tellg();
1895 // Warning: we believe this is explicit VR (Value Representation) because
1896 // we used a heuristic that found "UL" in the first tag. Alas this
1897 // doesn't guarantee that all the tags will be in explicit VR. In some
1898 // cases (see e-film filtered files) one finds implicit VR tags mixed
1899 // within an explicit VR file. Hence we make sure the present tag
1900 // is in explicit VR and try to fix things if it happens not to be
1904 Fp->read (vr, (size_t)2);
1907 if( !CheckDocEntryVR(entry, vr) )
1909 Fp->seekg(positionOnEntry, std::ios::beg);
1910 // When this element is known in the dictionary we shall use, e.g. for
1911 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1912 // dictionary entry. Still we have to flag the element as implicit since
1913 // we know now our assumption on expliciteness is not furfilled.
1915 if ( entry->IsVRUnknown() )
1917 entry->SetVR("Implicit");
1919 entry->SetImplicitVR();
1924 * \brief Check the correspondance between the VR of the header entry
1925 * and the taken VR. If they are different, the header entry is
1926 * updated with the new VR.
1927 * @param entry Header Entry to check
1928 * @param vr Dicom Value Representation
1929 * @return false if the VR is incorrect of if the VR isn't referenced
1930 * otherwise, it returns true
1932 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1935 bool realExplicit = true;
1937 // Assume we are reading a falsely explicit VR file i.e. we reached
1938 // a tag where we expect reading a VR but are in fact we read the
1939 // first to bytes of the length. Then we will interogate (through find)
1940 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1941 // both GCC and VC++ implementations of the STL map. Hence when the
1942 // expected VR read happens to be non-ascii characters we consider
1943 // we hit falsely explicit VR tag.
1945 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1947 realExplicit = false;
1950 // CLEANME searching the dicom_vr at each occurence is expensive.
1951 // PostPone this test in an optional integrity check at the end
1952 // of parsing or only in debug mode.
1953 if ( realExplicit && !Global::GetVR()->Count(vr) )
1955 realExplicit = false;
1958 if ( !realExplicit )
1960 // We thought this was explicit VR, but we end up with an
1961 // implicit VR tag. Let's backtrack.
1962 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1963 entry->GetGroup(), entry->GetElement());
1964 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1966 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1968 // Group length is UL !
1969 DictEntry* newEntry = NewVirtualDictEntry(
1970 entry->GetGroup(), entry->GetElement(),
1971 "UL", "FIXME", "Group Length");
1972 entry->SetDictEntry( newEntry );
1977 if ( entry->IsVRUnknown() )
1979 // When not a dictionary entry, we can safely overwrite the VR.
1980 if( entry->GetElement() == 0x0000 )
1982 // Group length is UL !
1990 else if ( entry->GetVR() != vr )
1992 // The VR present in the file and the dictionary disagree. We assume
1993 // the file writer knew best and use the VR of the file. Since it would
1994 // be unwise to overwrite the VR of a dictionary (since it would
1995 // compromise it's next user), we need to clone the actual DictEntry
1996 // and change the VR for the read one.
1997 DictEntry* newEntry = NewVirtualDictEntry(
1998 entry->GetGroup(), entry->GetElement(),
1999 vr, "FIXME", entry->GetName());
2000 entry->SetDictEntry(newEntry);
2007 * \brief Get the transformed value of the header entry. The VR value
2008 * is used to define the transformation to operate on the value
2009 * \warning NOT end user intended method !
2010 * @param entry entry to tranform
2011 * @return Transformed entry value
2013 std::string Document::GetDocEntryValue(DocEntry *entry)
2015 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2017 std::string val = ((ValEntry *)entry)->GetValue();
2018 std::string vr = entry->GetVR();
2019 uint32_t length = entry->GetLength();
2020 std::ostringstream s;
2023 // When short integer(s) are expected, read and convert the following
2024 // n * 2 bytes properly i.e. as a multivaluated strings
2025 // (each single value is separated fromthe next one by '\'
2026 // as usual for standard multivaluated filels
2027 // Elements with Value Multiplicity > 1
2028 // contain a set of short integers (not a single one)
2030 if( vr == "US" || vr == "SS" )
2035 for (int i=0; i < nbInt; i++)
2041 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2042 newInt16 = SwapShort( newInt16 );
2047 // When integer(s) are expected, read and convert the following
2048 // n * 4 bytes properly i.e. as a multivaluated strings
2049 // (each single value is separated fromthe next one by '\'
2050 // as usual for standard multivaluated filels
2051 // Elements with Value Multiplicity > 1
2052 // contain a set of integers (not a single one)
2053 else if( vr == "UL" || vr == "SL" )
2058 for (int i=0; i < nbInt; i++)
2064 newInt32 = ( val[4*i+0] & 0xFF )
2065 + (( val[4*i+1] & 0xFF ) << 8 )
2066 + (( val[4*i+2] & 0xFF ) << 16 )
2067 + (( val[4*i+3] & 0xFF ) << 24 );
2068 newInt32 = SwapLong( newInt32 );
2072 #ifdef GDCM_NO_ANSI_STRING_STREAM
2073 s << std::ends; // to avoid oddities on Solaris
2074 #endif //GDCM_NO_ANSI_STRING_STREAM
2078 return ((ValEntry *)entry)->GetValue();
2082 * \brief Get the reverse transformed value of the header entry. The VR
2083 * value is used to define the reverse transformation to operate on
2085 * \warning NOT end user intended method !
2086 * @param entry Entry to reverse transform
2087 * @return Reverse transformed entry value
2089 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2091 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2093 std::string vr = entry->GetVR();
2094 std::vector<std::string> tokens;
2095 std::ostringstream s;
2097 if ( vr == "US" || vr == "SS" )
2101 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2102 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2103 for (unsigned int i=0; i<tokens.size(); i++)
2105 newInt16 = atoi(tokens[i].c_str());
2106 s << ( newInt16 & 0xFF )
2107 << (( newInt16 >> 8 ) & 0xFF );
2111 if ( vr == "UL" || vr == "SL")
2115 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2116 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2117 for (unsigned int i=0; i<tokens.size();i++)
2119 newInt32 = atoi(tokens[i].c_str());
2120 s << (char)( newInt32 & 0xFF )
2121 << (char)(( newInt32 >> 8 ) & 0xFF )
2122 << (char)(( newInt32 >> 16 ) & 0xFF )
2123 << (char)(( newInt32 >> 24 ) & 0xFF );
2128 #ifdef GDCM_NO_ANSI_STRING_STREAM
2129 s << std::ends; // to avoid oddities on Solaris
2130 #endif //GDCM_NO_ANSI_STRING_STREAM
2134 return ((ValEntry *)entry)->GetValue();
2138 * \brief Skip a given Header Entry
2139 * \warning NOT end user intended method !
2140 * @param entry entry to skip
2142 void Document::SkipDocEntry(DocEntry *entry)
2144 SkipBytes(entry->GetLength());
2148 * \brief Skips to the begining of the next Header Entry
2149 * \warning NOT end user intended method !
2150 * @param entry entry to skip
2152 void Document::SkipToNextDocEntry(DocEntry *entry)
2154 Fp->seekg((long)(entry->GetOffset()), std::ios::beg);
2155 Fp->seekg( (long)(entry->GetReadLength()), std::ios::cur);
2159 * \brief When the length of an element value is obviously wrong (because
2160 * the parser went Jabberwocky) one can hope improving things by
2161 * applying some heuristics.
2162 * @param entry entry to check
2163 * @param foundLength fist assumption about length
2165 void Document::FixDocEntryFoundLength(DocEntry *entry,
2166 uint32_t foundLength)
2168 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2169 if ( foundLength == 0xffffffff)
2174 uint16_t gr = entry->GetGroup();
2175 uint16_t el = entry->GetElement();
2177 if ( foundLength % 2)
2179 std::ostringstream s;
2180 s << "Warning : Tag with uneven length "
2182 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2183 dbg.Verbose(0, s.str().c_str());
2186 //////// Fix for some naughty General Electric images.
2187 // Allthough not recent many such GE corrupted images are still present
2188 // on Creatis hard disks. Hence this fix shall remain when such images
2189 // are no longer in user (we are talking a few years, here)...
2190 // Note: XMedCom probably uses such a trick since it is able to read
2191 // those pesky GE images ...
2192 if ( foundLength == 13)
2194 // Only happens for this length !
2195 if ( entry->GetGroup() != 0x0008
2196 || ( entry->GetElement() != 0x0070
2197 && entry->GetElement() != 0x0080 ) )
2200 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2204 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2205 // Occurence of such images is quite low (unless one leaves close to a
2206 // 'Leonardo' source. Hence, one might consider commenting out the
2207 // following fix on efficiency reasons.
2208 else if ( entry->GetGroup() == 0x0009
2209 && ( entry->GetElement() == 0x1113
2210 || entry->GetElement() == 0x1114 ) )
2213 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2216 else if ( entry->GetVR() == "SQ" )
2218 foundLength = 0; // ReadLength is unchanged
2221 //////// We encountered a 'delimiter' element i.e. a tag of the form
2222 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2223 // taken into account.
2224 else if( entry->GetGroup() == 0xfffe )
2226 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2227 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2228 // causes extra troubles...
2229 if( entry->GetElement() != 0x0000 )
2235 entry->SetUsableLength(foundLength);
2239 * \brief Apply some heuristics to predict whether the considered
2240 * element value contains/represents an integer or not.
2241 * @param entry The element value on which to apply the predicate.
2242 * @return The result of the heuristical predicate.
2244 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2246 uint16_t element = entry->GetElement();
2247 uint16_t group = entry->GetGroup();
2248 const std::string & vr = entry->GetVR();
2249 uint32_t length = entry->GetLength();
2251 // When we have some semantics on the element we just read, and if we
2252 // a priori know we are dealing with an integer, then we shall be
2253 // able to swap it's element value properly.
2254 if ( element == 0 ) // This is the group length of the group
2262 // Allthough this should never happen, still some images have a
2263 // corrupted group length [e.g. have a glance at offset x(8336) of
2264 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2265 // Since for dicom compliant and well behaved headers, the present
2266 // test is useless (and might even look a bit paranoid), when we
2267 // encounter such an ill-formed image, we simply display a warning
2268 // message and proceed on parsing (while crossing fingers).
2269 std::ostringstream s;
2270 long filePosition = Fp->tellg();
2271 s << "Erroneous Group Length element length on : (" \
2272 << std::hex << group << " , " << element
2273 << ") -before- position x(" << filePosition << ")"
2274 << "lgt : " << length;
2275 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2279 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2288 * \brief Find the Length till the next sequence delimiter
2289 * \warning NOT end user intended method !
2293 uint32_t Document::FindDocEntryLengthOB()
2294 throw( FormatUnexpected )
2296 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2297 long positionOnEntry = Fp->tellg();
2298 bool foundSequenceDelimiter = false;
2299 uint32_t totalLength = 0;
2301 while ( !foundSequenceDelimiter )
2307 group = ReadInt16();
2310 catch ( FormatError )
2312 throw FormatError("Document::FindDocEntryLengthOB()",
2313 " group or element not present.");
2316 // We have to decount the group and element we just read
2319 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2321 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2322 "tag nor a Sequence delimiter tag.");
2323 Fp->seekg(positionOnEntry, std::ios::beg);
2324 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2325 "Neither an Item tag nor a Sequence "
2329 if ( elem == 0xe0dd )
2331 foundSequenceDelimiter = true;
2334 uint32_t itemLength = ReadInt32();
2335 // We add 4 bytes since we just read the ItemLength with ReadInt32
2336 totalLength += itemLength + 4;
2337 SkipBytes(itemLength);
2339 if ( foundSequenceDelimiter )
2344 Fp->seekg( positionOnEntry, std::ios::beg);
2349 * \brief Reads a supposed to be 16 Bits integer
2350 * (swaps it depending on processor endianity)
2351 * @return read value
2353 uint16_t Document::ReadInt16()
2354 throw( FormatError )
2357 Fp->read ((char*)&g, (size_t)2);
2360 throw FormatError( "Document::ReadInt16()", " file error." );
2364 throw FormatError( "Document::ReadInt16()", "EOF." );
2371 * \brief Reads a supposed to be 32 Bits integer
2372 * (swaps it depending on processor endianity)
2373 * @return read value
2375 uint32_t Document::ReadInt32()
2376 throw( FormatError )
2379 Fp->read ((char*)&g, (size_t)4);
2382 throw FormatError( "Document::ReadInt32()", " file error." );
2386 throw FormatError( "Document::ReadInt32()", "EOF." );
2393 * \brief skips bytes inside the source file
2394 * \warning NOT end user intended method !
2397 void Document::SkipBytes(uint32_t nBytes)
2399 //FIXME don't dump the returned value
2400 Fp->seekg((long)nBytes, std::ios::cur);
2404 * \brief Loads all the needed Dictionaries
2405 * \warning NOT end user intended method !
2407 void Document::Initialise()
2409 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2411 RLEInfo = new RLEFramesInfo;
2412 JPEGInfo = new JPEGFragmentsInfo;
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 Document::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
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".
2453 char *entCur = deb + 128;
2454 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2456 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2458 // Next, determine the value representation (VR). Let's skip to the
2459 // first element (0002, 0000) and check there if we find "UL"
2460 // - or "OB" if the 1st one is (0002,0001) -,
2461 // in which case we (almost) know it is explicit VR.
2462 // WARNING: if it happens to be implicit VR then what we will read
2463 // is the length of the group. If this ascii representation of this
2464 // length happens to be "UL" then we shall believe it is explicit VR.
2465 // FIXME: in order to fix the above warning, we could read the next
2466 // element value (or a couple of elements values) in order to make
2467 // sure we are not commiting a big mistake.
2468 // We need to skip :
2469 // * the 128 bytes of File Preamble (often padded with zeroes),
2470 // * the 4 bytes of "DICM" string,
2471 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2472 // i.e. a total of 136 bytes.
2476 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2477 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2478 // *Implicit* VR. -and it is !-
2480 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2481 memcmp(entCur, "OB", (size_t)2) == 0 ||
2482 memcmp(entCur, "UI", (size_t)2) == 0 ||
2483 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2484 // when Write DCM *adds*
2486 // Use Document::dicom_vr to test all the possibilities
2487 // instead of just checking for UL, OB and UI !? group 0000
2489 Filetype = ExplicitVR;
2490 dbg.Verbose(1, "Document::CheckSwap:",
2491 "explicit Value Representation");
2495 Filetype = ImplicitVR;
2496 dbg.Verbose(1, "Document::CheckSwap:",
2497 "not an explicit Value Representation");
2503 dbg.Verbose(1, "Document::CheckSwap:",
2504 "HostByteOrder != NetworkByteOrder");
2509 dbg.Verbose(1, "Document::CheckSwap:",
2510 "HostByteOrder = NetworkByteOrder");
2513 // Position the file position indicator at first tag (i.e.
2514 // after the file preamble and the "DICM" string).
2515 Fp->seekg(0, std::ios::beg);
2516 Fp->seekg ( 132L, std::ios::beg);
2520 // Alas, this is not a DicomV3 file and whatever happens there is no file
2521 // preamble. We can reset the file position indicator to where the data
2522 // is (i.e. the beginning of the file).
2523 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2524 Fp->seekg(0, std::ios::beg);
2526 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2527 // By clean we mean that the length of the first tag is written down.
2528 // If this is the case and since the length of the first group HAS to be
2529 // four (bytes), then determining the proper swap code is straightforward.
2532 // We assume the array of char we are considering contains the binary
2533 // representation of a 32 bits integer. Hence the following dirty
2535 s32 = *((uint32_t *)(entCur));
2556 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2557 // It is time for despaired wild guesses.
2558 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2559 // i.e. the 'group length' element is not present :
2561 // check the supposed-to-be 'group number'
2562 // in ( 0x0001 .. 0x0008 )
2563 // to determine ' SwapCode' value .
2564 // Only 0 or 4321 will be possible
2565 // (no oportunity to check for the formerly well known
2566 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2567 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2568 // the file IS NOT ACR-NEMA nor DICOM V3
2569 // Find a trick to tell it the caller...
2571 s16 = *((uint16_t *)(deb));
2598 dbg.Verbose(0, "Document::CheckSwap:",
2599 "ACR/NEMA unfound swap info (Really hopeless !)");
2603 // Then the only info we have is the net2host one.
2615 * \brief Restore the unproperly loaded values i.e. the group, the element
2616 * and the dictionary entry depending on them.
2618 void Document::SwitchSwapToBigEndian()
2620 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2621 "Switching to BigEndian mode.");
2622 if ( SwapCode == 0 )
2626 else if ( SwapCode == 4321 )
2630 else if ( SwapCode == 3412 )
2634 else if ( SwapCode == 2143 )
2641 * \brief during parsing, Header Elements too long are not loaded in memory
2644 void Document::SetMaxSizeLoadEntry(long newSize)
2650 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2652 MaxSizeLoadEntry = 0xffffffff;
2655 MaxSizeLoadEntry = newSize;
2660 * \brief Header Elements too long will not be printed
2661 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2664 void Document::SetMaxSizePrintEntry(long newSize)
2666 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2671 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2673 MaxSizePrintEntry = 0xffffffff;
2676 MaxSizePrintEntry = newSize;
2682 * \brief Handle broken private tag from Philips NTSCAN
2683 * where the endianess is being switch to BigEndian for no
2687 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2689 // Endian reversion. Some files contain groups of tags with reversed endianess.
2690 static int reversedEndian = 0;
2691 // try to fix endian switching in the middle of headers
2692 if ((group == 0xfeff) && (elem == 0x00e0))
2694 // start endian swap mark for group found
2696 SwitchSwapToBigEndian();
2701 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2703 // end of reversed endian group
2705 SwitchSwapToBigEndian();
2711 * \brief Read the next tag but WITHOUT loading it's value
2712 * (read the 'Group Number', the 'Element Number',
2713 * gets the Dict Entry
2714 * gets the VR, gets the length, gets the offset value)
2715 * @return On succes the newly created DocEntry, NULL on failure.
2717 DocEntry* Document::ReadNextDocEntry()
2724 group = ReadInt16();
2727 catch ( FormatError e )
2729 // We reached the EOF (or an error occured) therefore
2730 // header parsing has to be considered as finished.
2735 HandleBrokenEndian(group, elem);
2736 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2737 FindDocEntryVR(newEntry);
2741 FindDocEntryLength(newEntry);
2743 catch ( FormatError e )
2751 newEntry->SetOffset(Fp->tellg());
2758 * \brief Generate a free TagKey i.e. a TagKey that is not present
2759 * in the TagHt dictionary.
2760 * @param group The generated tag must belong to this group.
2761 * @return The element of tag with given group which is fee.
2763 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2765 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2767 TagKey key = DictEntry::TranslateToKey(group, elem);
2768 if (TagHT.count(key) == 0)
2777 * \brief Assuming the internal file pointer \ref Document::Fp
2778 * is placed at the beginning of a tag check whether this
2779 * tag is (TestGroup, TestElement).
2780 * \warning On success the internal file pointer \ref Document::Fp
2781 * is modified to point after the tag.
2782 * On failure (i.e. when the tag wasn't the expected tag
2783 * (TestGroup, TestElement) the internal file pointer
2784 * \ref Document::Fp is restored to it's original position.
2785 * @param testGroup The expected group of the tag.
2786 * @param testElement The expected Element of the tag.
2787 * @return True on success, false otherwise.
2789 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2791 long positionOnEntry = Fp->tellg();
2792 long currentPosition = Fp->tellg(); // On debugging purposes
2794 //// Read the Item Tag group and element, and make
2795 // sure they are what we expected:
2796 uint16_t itemTagGroup;
2797 uint16_t itemTagElement;
2800 itemTagGroup = ReadInt16();
2801 itemTagElement = ReadInt16();
2803 catch ( FormatError e )
2805 //std::cerr << e << std::endl;
2808 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2810 std::ostringstream s;
2811 s << " We should have found tag (";
2812 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2813 s << " but instead we encountered tag (";
2814 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2816 s << " at address: " << (unsigned)currentPosition << std::endl;
2817 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2818 dbg.Verbose(0, s.str().c_str());
2819 Fp->seekg(positionOnEntry, std::ios::beg);
2827 * \brief Assuming the internal file pointer \ref Document::Fp
2828 * is placed at the beginning of a tag (TestGroup, TestElement),
2829 * read the length associated to the Tag.
2830 * \warning On success the internal file pointer \ref Document::Fp
2831 * is modified to point after the tag and it's length.
2832 * On failure (i.e. when the tag wasn't the expected tag
2833 * (TestGroup, TestElement) the internal file pointer
2834 * \ref Document::Fp is restored to it's original position.
2835 * @param testGroup The expected group of the tag.
2836 * @param testElement The expected Element of the tag.
2837 * @return On success returns the length associated to the tag. On failure
2840 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2842 long positionOnEntry = Fp->tellg();
2843 (void)positionOnEntry;
2845 if ( !ReadTag(testGroup, testElement) )
2850 //// Then read the associated Item Length
2851 long currentPosition = Fp->tellg();
2852 uint32_t itemLength = ReadInt32();
2854 std::ostringstream s;
2855 s << "Basic Item Length is: "
2856 << itemLength << std::endl;
2857 s << " at address: " << (unsigned)currentPosition << std::endl;
2858 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2864 * \brief When parsing the Pixel Data of an encapsulated file, read
2865 * the basic offset table (when present, and BTW dump it).
2867 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2869 //// Read the Basic Offset Table Item Tag length...
2870 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2872 // When present, read the basic offset table itself.
2873 // Notes: - since the presence of this basic offset table is optional
2874 // we can't rely on it for the implementation, and we will simply
2875 // trash it's content (when present).
2876 // - still, when present, we could add some further checks on the
2877 // lengths, but we won't bother with such fuses for the time being.
2878 if ( itemLength != 0 )
2880 char* basicOffsetTableItemValue = new char[itemLength + 1];
2881 Fp->read(basicOffsetTableItemValue, itemLength);
2884 for (unsigned int i=0; i < itemLength; i += 4 )
2886 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2888 std::ostringstream s;
2889 s << " Read one length: ";
2890 s << std::hex << individualLength << std::endl;
2892 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2897 delete[] basicOffsetTableItemValue;
2902 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2903 * Compute the RLE extra information and store it in \ref RLEInfo
2904 * for later pixel retrieval usage.
2906 void Document::ComputeRLEInfo()
2908 TransferSyntaxType ts = GetTransferSyntax();
2909 if ( ts != RLELossless )
2914 // Encoded pixel data: for the time being we are only concerned with
2915 // Jpeg or RLE Pixel data encodings.
2916 // As stated in PS 3.5-2003, section 8.2 p44:
2917 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2918 // value representation OB is used".
2919 // Hence we expect an OB value representation. Concerning OB VR,
2920 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2921 // "For the Value Representations OB and OW, the encoding shall meet the
2922 // following specifications depending on the Data element tag:"
2924 // - the first item in the sequence of items before the encoded pixel
2925 // data stream shall be basic offset table item. The basic offset table
2926 // item value, however, is not required to be present"
2928 ReadAndSkipEncapsulatedBasicOffsetTable();
2930 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2931 // Loop on the individual frame[s] and store the information
2932 // on the RLE fragments in a RLEFramesInfo.
2933 // Note: - when only a single frame is present, this is a
2935 // - when more than one frame are present, then we are in
2936 // the case of a multi-frame image.
2938 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2940 // Parse the RLE Header and store the corresponding RLE Segment
2941 // Offset Table information on fragments of this current Frame.
2942 // Note that the fragment pixels themselves are not loaded
2943 // (but just skipped).
2944 long frameOffset = Fp->tellg();
2946 uint32_t nbRleSegments = ReadInt32();
2947 if ( nbRleSegments > 16 )
2949 // There should be at most 15 segments (refer to RLEFrame class)
2950 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2953 uint32_t rleSegmentOffsetTable[16];
2954 for( int k = 1; k <= 15; k++ )
2956 rleSegmentOffsetTable[k] = ReadInt32();
2959 // Deduce from both the RLE Header and the frameLength the
2960 // fragment length, and again store this info in a
2962 long rleSegmentLength[15];
2963 // skipping (not reading) RLE Segments
2964 if ( nbRleSegments > 1)
2966 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2968 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2969 - rleSegmentOffsetTable[k];
2970 SkipBytes(rleSegmentLength[k]);
2974 rleSegmentLength[nbRleSegments] = frameLength
2975 - rleSegmentOffsetTable[nbRleSegments];
2976 SkipBytes(rleSegmentLength[nbRleSegments]);
2978 // Store the collected info
2979 RLEFrame* newFrameInfo = new RLEFrame;
2980 newFrameInfo->NumberFragments = nbRleSegments;
2981 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2983 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2984 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2986 RLEInfo->Frames.push_back( newFrameInfo );
2989 // Make sure that at the end of the item we encounter a 'Sequence
2991 if ( !ReadTag(0xfffe, 0xe0dd) )
2993 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2994 dbg.Verbose(0, " item at end of RLE item sequence");
2999 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3000 * Compute the jpeg extra information (fragment[s] offset[s] and
3001 * length) and store it[them] in \ref JPEGInfo for later pixel
3004 void Document::ComputeJPEGFragmentInfo()
3006 // If you need to, look for comments of ComputeRLEInfo().
3012 ReadAndSkipEncapsulatedBasicOffsetTable();
3014 // Loop on the fragments[s] and store the parsed information in a
3016 long fragmentLength;
3017 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3019 long fragmentOffset = Fp->tellg();
3021 // Store the collected info
3022 JPEGFragment* newFragment = new JPEGFragment;
3023 newFragment->Offset = fragmentOffset;
3024 newFragment->Length = fragmentLength;
3025 JPEGInfo->Fragments.push_back( newFragment );
3027 SkipBytes( fragmentLength );
3030 // Make sure that at the end of the item we encounter a 'Sequence
3032 if ( !ReadTag(0xfffe, 0xe0dd) )
3034 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3035 dbg.Verbose(0, " item at end of JPEG item sequence");
3040 * \brief Walk recursively the given \ref DocEntrySet, and feed
3041 * the given hash table (\ref TagDocEntryHT) with all the
3042 * \ref DocEntry (Dicom entries) encountered.
3043 * This method does the job for \ref BuildFlatHashTable.
3044 * @param builtHT Where to collect all the \ref DocEntry encountered
3045 * when recursively walking the given set.
3046 * @param set The structure to be traversed (recursively).
3048 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3051 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3053 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3054 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3055 i != currentHT.end();
3058 DocEntry* entry = i->second;
3059 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3061 const ListSQItem& items = seqEntry->GetSQItems();
3062 for( ListSQItem::const_iterator item = items.begin();
3063 item != items.end();
3066 BuildFlatHashTableRecurse( builtHT, *item );
3070 builtHT[entry->GetKey()] = entry;
3075 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3077 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3078 for (ListDocEntry::const_iterator i = currentList.begin();
3079 i != currentList.end();
3082 DocEntry* entry = *i;
3083 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3085 const ListSQItem& items = seqEntry->GetSQItems();
3086 for( ListSQItem::const_iterator item = items.begin();
3087 item != items.end();
3090 BuildFlatHashTableRecurse( builtHT, *item );
3094 builtHT[entry->GetKey()] = entry;
3101 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3104 * The structure used by a Document (through \ref ElementSet),
3105 * in order to hold the parsed entries of a Dicom header, is a recursive
3106 * one. This is due to the fact that the sequences (when present)
3107 * can be nested. Additionaly, the sequence items (represented in
3108 * gdcm as \ref SQItem) add an extra complexity to the data
3109 * structure. Hence, a gdcm user whishing to visit all the entries of
3110 * a Dicom header will need to dig in the gdcm internals (which
3111 * implies exposing all the internal data structures to the API).
3112 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3113 * recursively builds a temporary hash table, which holds all the
3114 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3116 * \warning Of course there is NO integrity constrain between the
3117 * returned \ref TagDocEntryHT and the \ref ElementSet used
3118 * to build it. Hence if the underlying \ref ElementSet is
3119 * altered, then it is the caller responsability to invoke
3120 * \ref BuildFlatHashTable again...
3121 * @return The flat std::map<> we juste build.
3123 TagDocEntryHT* Document::BuildFlatHashTable()
3125 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3126 BuildFlatHashTableRecurse( *FlatHT, this );
3133 * \brief Compares two documents, according to \ref DicomDir rules
3134 * \warning Does NOT work with ACR-NEMA files
3135 * \todo Find a trick to solve the pb (use RET fields ?)
3137 * @return true if 'smaller'
3139 bool Document::operator<(Document &document)
3142 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3143 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3155 s1 = GetEntryByNumber(0x0010,0x0020);
3156 s2 = document.GetEntryByNumber(0x0010,0x0020);
3167 // Study Instance UID
3168 s1 = GetEntryByNumber(0x0020,0x000d);
3169 s2 = document.GetEntryByNumber(0x0020,0x000d);
3180 // Serie Instance UID
3181 s1 = GetEntryByNumber(0x0020,0x000e);
3182 s2 = document.GetEntryByNumber(0x0020,0x000e);
3197 } // end namespace gdcm
3199 //-----------------------------------------------------------------------------