1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/24 16:39:18 $
7 Version: $Revision: 1.137 $
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"
31 #if defined(_MSC_VER) || defined(__BORLANDC__)
34 #include <netinet/in.h>
39 static const char *TransferSyntaxStrings[] = {
40 // Implicit VR Little Endian
42 // Implicit VR Little Endian DLX G.E?
44 // Explicit VR Little Endian
45 "1.2.840.10008.1.2.1",
46 // Deflated Explicit VR Little Endian
47 "1.2.840.10008.1.2.1.99",
48 // Explicit VR Big Endian
49 "1.2.840.10008.1.2.2",
50 // JPEG Baseline (Process 1)
51 "1.2.840.10008.1.2.4.50",
52 // JPEG Extended (Process 2 & 4)
53 "1.2.840.10008.1.2.4.51",
54 // JPEG Extended (Process 3 & 5)
55 "1.2.840.10008.1.2.4.52",
56 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
57 "1.2.840.10008.1.2.4.53",
58 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
59 "1.2.840.10008.1.2.4.55",
60 // JPEG Lossless, Non-Hierarchical (Process 14)
61 "1.2.840.10008.1.2.4.57",
62 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
63 "1.2.840.10008.1.2.4.70",
65 "1.2.840.10008.1.2.4.90",
67 "1.2.840.10008.1.2.4.91",
69 "1.2.840.10008.1.2.5",
71 "Unknown Transfer Syntax"
74 //-----------------------------------------------------------------------------
75 // Refer to Document::CheckSwap()
76 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
78 // Refer to Document::SetMaxSizeLoadEntry()
79 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
80 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
82 //-----------------------------------------------------------------------------
83 // Constructor / Destructor
87 * @param filename file to be opened for parsing
89 Document::Document( std::string const & filename ) : ElementSet(-1)
91 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
101 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
103 Fp->seekg( 0, std::ios_base::beg);
105 Fp->seekg(0, std::ios_base::end);
106 long lgt = Fp->tellg();
108 Fp->seekg( 0, std::ios_base::beg);
110 long beg = Fp->tellg();
113 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
115 Fp->seekg( 0, std::ios_base::beg);
117 // Load 'non string' values
119 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
120 if( PhotometricInterpretation == "PALETTE COLOR " )
122 LoadEntryBinArea(0x0028,0x1200); // gray LUT
123 /// FIXME FIXME FIXME
124 /// The tags refered by the three following lines used to be CORRECTLY
125 /// defined as having an US Value Representation in the public
126 /// dictionnary. BUT the semantics implied by the three following
127 /// lines state that the corresponding tag contents are in fact
128 /// the ones of a BinEntry.
129 /// In order to fix things "Quick and Dirty" the dictionnary was
130 /// altered on PURPOUS but now contains a WRONG value.
131 /// In order to fix things and restore the dictionary to its
132 /// correct value, one needs to decided of the semantics by deciding
133 /// wether the following tags are either:
134 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
135 /// also used as BinEntry, which requires the proper conversion,
136 /// - OW, and hence loaded as BinEntry, but afterwards also used
137 /// as ValEntry, which requires the proper conversion.
138 LoadEntryBinArea(0x0028,0x1201); // R LUT
139 LoadEntryBinArea(0x0028,0x1202); // G LUT
140 LoadEntryBinArea(0x0028,0x1203); // B LUT
142 // Segmented Red Palette Color LUT Data
143 LoadEntryBinArea(0x0028,0x1221);
144 // Segmented Green Palette Color LUT Data
145 LoadEntryBinArea(0x0028,0x1222);
146 // Segmented Blue Palette Color LUT Data
147 LoadEntryBinArea(0x0028,0x1223);
149 //FIXME later : how to use it?
150 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
154 // --------------------------------------------------------------
155 // Specific code to allow gdcm to read ACR-LibIDO formated images
156 // Note: ACR-LibIDO is an extension of the ACR standard that was
157 // used at CREATIS. For the time being (say a couple years)
158 // we keep this kludge to allow a smooth move to gdcm for
159 // CREATIS developpers (sorry folks).
161 // if recognition code tells us we deal with a LibIDO image
162 // we switch lineNumber and columnNumber
165 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
166 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
167 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
168 // with "little-endian strings"
170 Filetype = ACR_LIBIDO;
171 std::string rows = GetEntryByNumber(0x0028, 0x0010);
172 std::string columns = GetEntryByNumber(0x0028, 0x0011);
173 SetEntryByNumber(columns, 0x0028, 0x0010);
174 SetEntryByNumber(rows , 0x0028, 0x0011);
176 // ----------------- End of ACR-LibIDO kludge ------------------
178 PrintLevel = 1; // 'Medium' print level by default
182 * \brief This default constructor doesn't parse the file. You should
183 * then invoke \ref Document::SetFileName and then the parsing.
185 Document::Document() : ElementSet(-1)
189 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
192 Filetype = ExplicitVR;
193 PrintLevel = 1; // 'Medium' print level by default
197 * \brief Canonical destructor.
199 Document::~Document ()
208 //-----------------------------------------------------------------------------
212 * \brief Prints The Dict Entries of THE public Dicom Dictionary
215 void Document::PrintPubDict(std::ostream & os)
217 RefPubDict->Print(os);
221 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
224 void Document::PrintShaDict(std::ostream & os)
226 RefShaDict->Print(os);
229 //-----------------------------------------------------------------------------
232 * \brief Get the public dictionary used
234 Dict* Document::GetPubDict()
240 * \brief Get the shadow dictionary used
242 Dict* Document::GetShaDict()
248 * \brief Set the shadow dictionary used
249 * \param dict dictionary to use in shadow
251 bool Document::SetShaDict(Dict *dict)
258 * \brief Set the shadow dictionary used
259 * \param dictName name of the dictionary to use in shadow
261 bool Document::SetShaDict(DictKey const & dictName)
263 RefShaDict = Global::GetDicts()->GetDict(dictName);
268 * \brief This predicate, based on hopefully reasonable heuristics,
269 * decides whether or not the current Document was properly parsed
270 * and contains the mandatory information for being considered as
271 * a well formed and usable Dicom/Acr File.
272 * @return true when Document is the one of a reasonable Dicom/Acr file,
275 bool Document::IsReadable()
277 if( Filetype == Unknown)
279 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
285 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
294 * \brief Accessor to the Transfer Syntax (when present) of the
295 * current document (it internally handles reading the
296 * value from disk when only parsing occured).
297 * @return The encountered Transfer Syntax of the current document.
299 TransferSyntaxType Document::GetTransferSyntax()
301 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
307 // The entry might be present but not loaded (parsing and loading
308 // happen at different stages): try loading and proceed with check...
309 LoadDocEntrySafe(entry);
310 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
312 std::string transfer = valEntry->GetValue();
313 // The actual transfer (as read from disk) might be padded. We
314 // first need to remove the potential padding. We can make the
315 // weak assumption that padding was not executed with digits...
316 if ( transfer.length() == 0 )
318 // for brain damaged headers
321 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
323 transfer.erase(transfer.length()-1, 1);
325 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
327 if ( TransferSyntaxStrings[i] == transfer )
329 return TransferSyntaxType(i);
336 bool Document::IsJPEGLossless()
338 TransferSyntaxType r = GetTransferSyntax();
339 return r == JPEGFullProgressionProcess10_12
340 || r == JPEGLosslessProcess14
341 || r == JPEGLosslessProcess14_1;
345 * \brief Determines if the Transfer Syntax was already encountered
346 * and if it corresponds to a JPEG2000 one
347 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
350 bool Document::IsJPEG2000()
352 TransferSyntaxType r = GetTransferSyntax();
353 return r == JPEG2000Lossless || r == JPEG2000;
357 * \brief Determines if the Transfer Syntax corresponds to any form
358 * of Jpeg encoded Pixel data.
359 * @return True when any form of JPEG found. False otherwise.
361 bool Document::IsJPEG()
363 TransferSyntaxType r = GetTransferSyntax();
364 return r == JPEGBaselineProcess1
365 || r == JPEGExtendedProcess2_4
366 || r == JPEGExtendedProcess3_5
367 || r == JPEGSpectralSelectionProcess6_8
373 * \brief Determines if the Transfer Syntax corresponds to encapsulated
374 * of encoded Pixel Data (as opposed to native).
375 * @return True when encapsulated. False when native.
377 bool Document::IsEncapsulate()
379 TransferSyntaxType r = GetTransferSyntax();
380 return IsJPEG() || r == RLELossless;
384 * \brief Predicate for dicom version 3 file.
385 * @return True when the file is a dicom version 3.
387 bool Document::IsDicomV3()
389 // Checking if Transfert Syntax exists is enough
390 // Anyway, it's to late check if the 'Preamble' was found ...
391 // And ... would it be a rich idea to check ?
392 // (some 'no Preamble' DICOM images exist !)
393 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
397 * \brief returns the File Type
398 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
399 * @return the FileType code
401 FileType Document::GetFileType()
407 * \brief Tries to open the file \ref Document::Filename and
408 * checks the preamble when existing.
409 * @return The FILE pointer on success.
411 std::ifstream* Document::OpenFile()
413 if (Filename.length() == 0) return 0;
417 "Document::OpenFile is already opened when opening: ",
421 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
426 "Document::OpenFile cannot open file: ",
432 Fp->read((char*)&zero, (size_t)2 );
434 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
436 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
437 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
438 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
439 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
445 Fp->seekg(126L, std::ios_base::cur);
447 Fp->read(dicm, (size_t)4);
448 if( memcmp(dicm, "DICM", 4) == 0 )
455 "Document::OpenFile not DICOM/ACR (missing preamble)",
462 * \brief closes the file
463 * @return TRUE if the close was successfull
465 bool Document::CloseFile()
474 return true; //FIXME how do we detect a non-close ifstream ?
478 * \brief Writes in a file all the Header Entries (Dicom Elements)
479 * @param fp file pointer on an already open file
480 * @param filetype Type of the File to be written
481 * (ACR-NEMA, ExplicitVR, ImplicitVR)
482 * \return Always true.
484 void Document::Write(std::ofstream* fp, FileType filetype)
486 /// \todo move the following lines (and a lot of others, to be written)
487 /// to a future function CheckAndCorrectHeader
488 /// (necessary if user wants to write a DICOM V3 file
489 /// starting from an ACR-NEMA (V2) Header
491 if ( filetype == ImplicitVR || filetype == ExplicitVR )
493 // writing Dicom File Preamble
494 char filePreamble[128];
495 memset(filePreamble, 0, 128);
496 fp->write(filePreamble, 128);
497 fp->write("DICM", 4);
500 if (filetype == ImplicitVR)
503 Util::DicomString( TransferSyntaxStrings[ImplicitVRLittleEndian] );
504 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010);
506 /// \todo Refer to standards on page 21, chapter 6.2
507 /// "Value representation": values with a VR of UI shall be
508 /// padded with a single trailing null
509 /// in the following case we have to padd manually with a 0
511 SetEntryLengthByNumber(18, 0x0002, 0x0010);
514 if (filetype == ExplicitVR)
517 Util::DicomString( TransferSyntaxStrings[ExplicitVRLittleEndian] );
518 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010); //LEAK
520 /// \todo Refer to standards on page 21, chapter 6.2
521 /// "Value representation": values with a VR of UI shall be
522 /// padded with a single trailing null
523 /// Dans le cas suivant on doit pader manuellement avec un 0
525 SetEntryLengthByNumber(20, 0x0002, 0x0010);
529 * \todo rewrite later, if really usefull
530 * - 'Group Length' element is optional in DICOM
531 * - but un-updated odd groups lengthes can causes pb
534 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
535 * UpdateGroupLength(false,filetype);
536 * if ( filetype == ACR)
537 * UpdateGroupLength(true,ACR);
540 ElementSet::Write(fp, filetype); // This one is recursive
545 * \brief Modifies the value of a given Header Entry (Dicom Element)
546 * when it exists. Create it with the given value when unexistant.
547 * @param value (string) Value to be set
548 * @param group Group number of the Entry
549 * @param elem Element number of the Entry
550 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
551 * \return pointer to the modified/created Header Entry (NULL when creation
554 ValEntry* Document::ReplaceOrCreateByNumber(
555 std::string const & value,
560 ValEntry* valEntry = 0;
561 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
565 // check if (group,element) DictEntry exists
566 // if it doesn't, create an entry in DictSet::VirtualEntry
569 // Find out if the tag we received is in the dictionaries:
570 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
571 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
574 currentEntry = NewDocEntryByNumber(group, elem, vr);
578 currentEntry = NewDocEntryByNumber(group, elem);
583 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
584 " NewDocEntryByNumber failed.");
588 valEntry = new ValEntry(currentEntry);
591 if ( !AddEntry(valEntry))
594 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
595 " failed allthough this is a creation.");
601 valEntry = dynamic_cast< ValEntry* >(currentEntry);
602 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
603 // then we change it to a ValEntry ?
604 // Shouldn't it be considered as an error ?
606 // We need to promote the DocEntry to a ValEntry:
607 valEntry = new ValEntry(currentEntry);
608 if (!RemoveEntry(currentEntry))
611 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
612 " of previous DocEntry failed.");
615 if ( !AddEntry(valEntry))
618 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
619 " promoted ValEntry failed.");
625 SetEntryByNumber(value, group, elem);
631 * \brief Modifies the value of a given Header Entry (Dicom Element)
632 * when it exists. Create it with the given value when unexistant.
633 * A copy of the binArea is made to be kept in the Document.
634 * @param binArea (binary) value to be set
635 * @param Group Group number of the Entry
636 * @param Elem Element number of the Entry
637 * \return pointer to the modified/created Header Entry (NULL when creation
640 BinEntry* Document::ReplaceOrCreateByNumber(
647 BinEntry* binEntry = 0;
648 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
652 // check if (group,element) DictEntry exists
653 // if it doesn't, create an entry in DictSet::VirtualEntry
656 // Find out if the tag we received is in the dictionaries:
657 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
658 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
662 currentEntry = NewDocEntryByNumber(group, elem, vr);
666 currentEntry = NewDocEntryByNumber(group, elem);
670 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
671 " NewDocEntryByNumber failed.");
674 binEntry = new BinEntry(currentEntry);
675 if ( !AddEntry(binEntry))
677 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
678 " failed allthough this is a creation.");
683 binEntry = dynamic_cast< BinEntry* >(currentEntry);
684 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
685 // then we change it to a BinEntry ?
686 // Shouldn't it be considered as an error ?
688 // We need to promote the DocEntry to a BinEntry:
689 binEntry = new BinEntry(currentEntry);
690 if (!RemoveEntry(currentEntry))
692 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
693 " of previous DocEntry failed.");
696 if ( !AddEntry(binEntry))
698 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
699 " promoted BinEntry failed.");
706 if (lgth>0 && binArea)
708 tmpArea = new uint8_t[lgth];
709 memcpy(tmpArea,binArea,lgth);
715 if (!SetEntryByNumber(tmpArea, lgth, group, elem))
728 * \brief Modifies the value of a given Header Entry (Dicom Element)
729 * when it exists. Create it when unexistant.
730 * @param Group Group number of the Entry
731 * @param Elem Element number of the Entry
732 * \return pointer to the modified/created SeqEntry (NULL when creation
735 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
738 DocEntry* a = GetDocEntryByNumber( group, elem);
741 a = NewSeqEntryByNumber(group, elem);
747 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
754 * \brief Set a new value if the invoked element exists
755 * Seems to be useless !!!
756 * @param value new element value
757 * @param group group number of the Entry
758 * @param elem element number of the Entry
761 bool Document::ReplaceIfExistByNumber(std::string const & value,
762 uint16_t group, uint16_t elem )
764 SetEntryByNumber(value, group, elem);
769 //-----------------------------------------------------------------------------
773 * \brief Checks if a given Dicom Element exists within the H table
774 * @param group Group number of the searched Dicom Element
775 * @param element Element number of the searched Dicom Element
776 * @return true is found
778 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
780 const std::string &key = DictEntry::TranslateToKey(group, element );
781 return TagHT.count(key) != 0;
785 * \brief Searches within Header Entries (Dicom Elements) parsed with
786 * the public and private dictionaries
787 * for the element value of a given tag.
788 * \warning Don't use any longer : use GetPubEntryByName
789 * @param tagName name of the searched element.
790 * @return Corresponding element value when it exists,
791 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
793 std::string Document::GetEntryByName(TagName const & tagName)
795 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
801 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
805 * \brief Searches within Header Entries (Dicom Elements) parsed with
806 * the public and private dictionaries
807 * for the element value representation of a given tag.
809 * Obtaining the VR (Value Representation) might be needed by caller
810 * to convert the string typed content to caller's native type
811 * (think of C++ vs Python). The VR is actually of a higher level
812 * of semantics than just the native C++ type.
813 * @param tagName name of the searched element.
814 * @return Corresponding element value representation when it exists,
815 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
817 std::string Document::GetEntryVRByName(TagName const& tagName)
819 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
820 if( dictEntry == NULL)
825 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
826 dictEntry->GetElement());
827 return elem->GetVR();
831 * \brief Searches within Header Entries (Dicom Elements) parsed with
832 * the public and private dictionaries
833 * for the element value representation of a given tag.
834 * @param group Group number of the searched tag.
835 * @param element Element number of the searched tag.
836 * @return Corresponding element value representation when it exists,
837 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
839 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
841 TagKey key = DictEntry::TranslateToKey(group, element);
842 /// \todo use map methods, instead of multimap JPR
843 if ( !TagHT.count(key))
848 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
852 * \brief Searches within Header Entries (Dicom Elements) parsed with
853 * the public and private dictionaries
854 * for the element value representation of a given tag..
856 * Obtaining the VR (Value Representation) might be needed by caller
857 * to convert the string typed content to caller's native type
858 * (think of C++ vs Python). The VR is actually of a higher level
859 * of semantics than just the native C++ type.
860 * @param group Group number of the searched tag.
861 * @param element Element number of the searched tag.
862 * @return Corresponding element value representation when it exists,
863 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
865 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
867 DocEntry* elem = GetDocEntryByNumber(group, element);
872 return elem->GetVR();
876 * \brief Searches within Header Entries (Dicom Elements) parsed with
877 * the public and private dictionaries
878 * for the value length of a given tag..
879 * @param group Group number of the searched tag.
880 * @param element Element number of the searched tag.
881 * @return Corresponding element length; -2 if not found
883 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
885 DocEntry* elem = GetDocEntryByNumber(group, element);
888 return -2; //magic number
890 return elem->GetLength();
893 * \brief Sets the value (string) of the Header Entry (Dicom Element)
894 * @param content string value of the Dicom Element
895 * @param tagName name of the searched Dicom Element.
896 * @return true when found
898 bool Document::SetEntryByName( std::string const & content,
899 TagName const & tagName)
901 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
907 return SetEntryByNumber(content,dictEntry->GetGroup(),
908 dictEntry->GetElement());
912 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
913 * through it's (group, element) and modifies it's content with
915 * @param content new value (string) to substitute with
916 * @param group group number of the Dicom Element to modify
917 * @param element element number of the Dicom Element to modify
919 bool Document::SetEntryByNumber(std::string const& content,
920 uint16_t group, uint16_t element)
925 ValEntry* valEntry = GetValEntryByNumber(group, element);
928 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
929 " ValEntry (try promotion first).");
932 // Non even content must be padded with a space (020H)...
933 std::string finalContent = Util::DicomString( content.c_str() );
934 assert( !(finalContent.size() % 2) );
935 valEntry->SetValue(finalContent);
937 // Integers have a special treatement for their length:
939 l = finalContent.length();
940 if ( l != 0) // To avoid to be cheated by 'zero length' integers
942 VRKey vr = valEntry->GetVR();
943 if( vr == "US" || vr == "SS" )
945 // for multivaluated items
946 c = Util::CountSubstring(content, "\\") + 1;
949 else if( vr == "UL" || vr == "SL" )
951 // for multivaluated items
952 c = Util::CountSubstring(content, "\\") + 1;
956 valEntry->SetLength(l);
961 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
962 * through it's (group, element) and modifies it's content with
964 * @param content new value (void* -> uint8_t*) to substitute with
965 * @param lgth new value length
966 * @param group group number of the Dicom Element to modify
967 * @param element element number of the Dicom Element to modify
969 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
970 uint16_t group, uint16_t element)
972 (void)lgth; //not used
973 TagKey key = DictEntry::TranslateToKey(group, element);
974 if ( !TagHT.count(key))
979 /* Hope Binary field length is *never* wrong
980 if(lgth%2) // Non even length are padded with a space (020H).
983 //content = content + '\0'; // fing a trick to enlarge a binary field?
986 BinEntry* entry = (BinEntry *)TagHT[key];
987 entry->SetBinArea(content);
988 entry->SetLength(lgth);
989 entry->SetValue(GDCM_BINLOADED);
995 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
996 * in the PubDocEntrySet of this instance
997 * through it's (group, element) and modifies it's length with
999 * \warning Use with extreme caution.
1000 * @param l new length to substitute with
1001 * @param group group number of the Entry to modify
1002 * @param element element number of the Entry to modify
1003 * @return true on success, false otherwise.
1005 bool Document::SetEntryLengthByNumber(uint32_t l,
1006 uint16_t group, uint16_t element)
1008 /// \todo use map methods, instead of multimap JPR
1009 TagKey key = DictEntry::TranslateToKey(group, element);
1010 if ( !TagHT.count(key) )
1016 l++; // length must be even
1018 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1024 * \brief Gets (from Header) the offset of a 'non string' element value
1025 * (LoadElementValues has already be executed)
1026 * @param group group number of the Entry
1027 * @param elem element number of the Entry
1028 * @return File Offset of the Element Value
1030 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1032 DocEntry* entry = GetDocEntryByNumber(group, elem);
1035 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1038 return entry->GetOffset();
1042 * \brief Gets (from Header) a 'non string' element value
1043 * (LoadElementValues has already be executed)
1044 * @param group group number of the Entry
1045 * @param elem element number of the Entry
1046 * @return Pointer to the 'non string' area
1048 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1050 DocEntry* entry = GetDocEntryByNumber(group, elem);
1053 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1056 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1058 return binEntry->GetBinArea();
1065 * \brief Loads (from disk) the element content
1066 * when a string is not suitable
1067 * @param group group number of the Entry
1068 * @param elem element number of the Entry
1070 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1072 // Search the corresponding DocEntry
1073 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1077 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1081 LoadEntryBinArea(binElement);
1082 /* size_t o =(size_t)docElement->GetOffset();
1083 Fp->seekg( o, std::ios_base::beg);
1084 size_t l = docElement->GetLength();
1085 uint8_t* a = new uint8_t[l];
1088 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1093 Fp->read((char*)a, l);
1094 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1100 // Set the value to the DocEntry
1101 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1104 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1109 * \brief Loads (from disk) the element content
1110 * when a string is not suitable
1111 * @param element Entry whose binArea is going to be loaded
1113 void Document::LoadEntryBinArea(BinEntry* element)
1115 if(element->GetBinArea())
1118 bool openFile = !Fp;
1122 size_t o =(size_t)element->GetOffset();
1123 Fp->seekg(o, std::ios_base::beg);
1125 size_t l = element->GetLength();
1126 uint8_t* a = new uint8_t[l];
1129 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1133 /// \todo check the result
1134 Fp->read((char*)a, l);
1135 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1141 element->SetBinArea(a);
1148 * \brief Sets a 'non string' value to a given Dicom Element
1149 * @param area area containing the 'non string' value
1150 * @param group Group number of the searched Dicom Element
1151 * @param element Element number of the searched Dicom Element
1154 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1155 uint16_t group, uint16_t element)
1157 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1158 if ( !currentEntry )
1163 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1165 binEntry->SetBinArea( area );
1173 * \brief Update the entries with the shadow dictionary.
1174 * Only non even entries are analyzed
1176 void Document::UpdateShaEntries()
1181 /// \todo TODO : still any use to explore recursively the whole structure?
1183 for(ListTag::iterator it=listEntries.begin();
1184 it!=listEntries.end();
1187 // Odd group => from public dictionary
1188 if((*it)->GetGroup()%2==0)
1191 // Peer group => search the corresponding dict entry
1193 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1197 if((*it)->IsImplicitVR())
1202 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1204 // Set the new entry and the new value
1205 (*it)->SetDictEntry(entry);
1206 CheckDocEntryVR(*it,vr);
1208 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1213 // Remove precedent value transformation
1214 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1221 * \brief Searches within the Header Entries for a Dicom Element of
1223 * @param tagName name of the searched Dicom Element.
1224 * @return Corresponding Dicom Element when it exists, and NULL
1227 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1229 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1235 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1239 * \brief retrieves a Dicom Element (the first one) using (group, element)
1240 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1241 * if you think it's NOT UNIQUE, check the count number
1242 * and use iterators to retrieve ALL the Dicoms Elements within
1243 * a given couple (group, element)
1244 * @param group Group number of the searched Dicom Element
1245 * @param element Element number of the searched Dicom Element
1248 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1250 TagKey key = DictEntry::TranslateToKey(group, element);
1251 if ( !TagHT.count(key))
1255 return TagHT.find(key)->second;
1259 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1260 * returns a result when the corresponding entry is of type
1262 * @return When present, the corresponding ValEntry.
1264 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1266 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1267 if ( !currentEntry )
1271 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1275 dbg.Verbose(0, "Document::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 Document::LoadDocEntrySafe(DocEntry * entry)
1289 long PositionOnEntry = Fp->tellg();
1290 LoadDocEntry(entry);
1291 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1295 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1297 * @return The properly swaped 32 bits integer.
1299 uint32_t Document::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(" Document::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 Document::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 Document::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 Document::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.
1364 void Document::ParseDES(DocEntrySet *set, long offset,
1365 long l_max, bool delim_mode)
1367 DocEntry *newDocEntry = 0;
1371 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1375 newDocEntry = ReadNextDocEntry( );
1381 VRKey vr = newDocEntry->GetVR();
1385 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1387 /////////////////////// ValEntry
1388 ValEntry* newValEntry =
1389 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1390 newValEntry->Copy( newDocEntry );
1392 // When "set" is a Document, then we are at the top of the
1393 // hierarchy and the Key is simply of the form ( group, elem )...
1394 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1397 newValEntry->SetKey( newValEntry->GetKey() );
1399 // ...but when "set" is a SQItem, we are inserting this new
1400 // valEntry in a sequence item. Hence the key has the
1401 // generalized form (refer to \ref BaseTagKey):
1402 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1404 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1405 + newValEntry->GetKey() );
1408 LoadDocEntry( newValEntry );
1409 bool delimitor=newValEntry->IsItemDelimitor();
1410 if( !set->AddEntry( newValEntry ) )
1412 // If here expect big troubles
1413 delete newValEntry; //otherwise mem leak
1421 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1429 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1431 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1432 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1433 "nor BinEntry. Probably unknown VR.");
1436 //////////////////// BinEntry or UNKOWN VR:
1437 /* BinEntry* newBinEntry =
1438 new BinEntry( newDocEntry->GetDictEntry() ); //LEAK
1439 newBinEntry->Copy( newDocEntry );*/
1440 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1442 // When "this" is a Document the Key is simply of the
1443 // form ( group, elem )...
1444 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1447 newBinEntry->SetKey( newBinEntry->GetKey() );
1449 // but when "this" is a SQItem, we are inserting this new
1450 // valEntry in a sequence item, and the kay has the
1451 // generalized form (refer to \ref BaseTagKey):
1452 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1454 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1455 + newBinEntry->GetKey() );
1458 LoadDocEntry( newBinEntry );
1459 if( !set->AddEntry( newBinEntry ) )
1461 //Expect big troubles if here
1466 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1467 && ( newDocEntry->GetElement() == 0x0010 ) )
1469 TransferSyntaxType ts = GetTransferSyntax();
1470 if ( ts == RLELossless )
1472 long PositionOnEntry = Fp->tellg();
1473 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1475 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1477 else if ( IsJPEG() )
1479 long PositionOnEntry = Fp->tellg();
1480 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1481 ComputeJPEGFragmentInfo();
1482 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1486 // Just to make sure we are at the beginning of next entry.
1487 SkipToNextDocEntry(newDocEntry);
1488 //delete newDocEntry;
1493 unsigned long l = newDocEntry->GetReadLength();
1494 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1496 if ( l == 0xffffffff )
1505 // no other way to create it ...
1506 SeqEntry* newSeqEntry =
1507 new SeqEntry( newDocEntry->GetDictEntry() );
1508 newSeqEntry->Copy( newDocEntry );
1509 newSeqEntry->SetDelimitorMode( delim_mode );
1511 // At the top of the hierarchy, stands a Document. When "set"
1512 // is a Document, then we are building the first depth level.
1513 // Hence the SeqEntry we are building simply has a depth
1515 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1518 newSeqEntry->SetDepthLevel( 1 );
1519 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1521 // But when "set" is allready a SQItem, we are building a nested
1522 // sequence, and hence the depth level of the new SeqEntry
1523 // we are building, is one level deeper:
1524 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1526 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1527 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1528 + newSeqEntry->GetKey() );
1532 { // Don't try to parse zero-length sequences
1533 ParseSQ( newSeqEntry,
1534 newDocEntry->GetOffset(),
1537 set->AddEntry( newSeqEntry );
1538 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1549 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1550 * @return parsed length for this level
1552 void Document::ParseSQ( SeqEntry* seqEntry,
1553 long offset, long l_max, bool delim_mode)
1555 int SQItemNumber = 0;
1560 DocEntry* newDocEntry = ReadNextDocEntry();
1563 // FIXME Should warn user
1568 if ( newDocEntry->IsSequenceDelimitor() )
1570 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1574 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1580 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1581 std::ostringstream newBase;
1582 newBase << seqEntry->GetKey()
1586 itemSQ->SetBaseTagKey( newBase.str() );
1587 unsigned int l = newDocEntry->GetReadLength();
1589 if ( l == 0xffffffff )
1598 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1601 seqEntry->AddEntry( itemSQ, SQItemNumber );
1603 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1611 * \brief Loads the element content if its length doesn't exceed
1612 * the value specified with Document::SetMaxSizeLoadEntry()
1613 * @param entry Header Entry (Dicom Element) to be dealt with
1615 void Document::LoadDocEntry(DocEntry* entry)
1617 uint16_t group = entry->GetGroup();
1618 std::string vr = entry->GetVR();
1619 uint32_t length = entry->GetLength();
1621 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1623 // A SeQuence "contains" a set of Elements.
1624 // (fffe e000) tells us an Element is beginning
1625 // (fffe e00d) tells us an Element just ended
1626 // (fffe e0dd) tells us the current SeQuence just ended
1627 if( group == 0xfffe )
1629 // NO more value field for SQ !
1633 // When the length is zero things are easy:
1636 ((ValEntry *)entry)->SetValue("");
1640 // The elements whose length is bigger than the specified upper bound
1641 // are not loaded. Instead we leave a short notice of the offset of
1642 // the element content and it's length.
1644 std::ostringstream s;
1645 if (length > MaxSizeLoadEntry)
1647 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1649 //s << "gdcm::NotLoaded (BinEntry)";
1650 s << GDCM_NOTLOADED;
1651 s << " Address:" << (long)entry->GetOffset();
1652 s << " Length:" << entry->GetLength();
1653 s << " x(" << std::hex << entry->GetLength() << ")";
1654 binEntryPtr->SetValue(s.str());
1656 // Be carefull : a BinEntry IS_A ValEntry ...
1657 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1659 // s << "gdcm::NotLoaded. (ValEntry)";
1660 s << GDCM_NOTLOADED;
1661 s << " Address:" << (long)entry->GetOffset();
1662 s << " Length:" << entry->GetLength();
1663 s << " x(" << std::hex << entry->GetLength() << ")";
1664 valEntryPtr->SetValue(s.str());
1669 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1670 << "nor a ValEntry ?! Should never print that !" << std::endl;
1673 // to be sure we are at the end of the value ...
1674 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1675 std::ios_base::beg);
1679 // When we find a BinEntry not very much can be done :
1680 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1682 s << GDCM_BINLOADED;
1683 binEntryPtr->SetValue(s.str());
1684 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1688 /// \todo Any compacter code suggested (?)
1689 if ( IsDocEntryAnInteger(entry) )
1693 // When short integer(s) are expected, read and convert the following
1694 // n *two characters properly i.e. consider them as short integers as
1695 // opposed to strings.
1696 // Elements with Value Multiplicity > 1
1697 // contain a set of integers (not a single one)
1698 if (vr == "US" || vr == "SS")
1701 NewInt = ReadInt16();
1705 for (int i=1; i < nbInt; i++)
1708 NewInt = ReadInt16();
1713 // See above comment on multiple integers (mutatis mutandis).
1714 else if (vr == "UL" || vr == "SL")
1717 NewInt = ReadInt32();
1721 for (int i=1; i < nbInt; i++)
1724 NewInt = ReadInt32();
1729 #ifdef GDCM_NO_ANSI_STRING_STREAM
1730 s << std::ends; // to avoid oddities on Solaris
1731 #endif //GDCM_NO_ANSI_STRING_STREAM
1733 ((ValEntry *)entry)->SetValue(s.str());
1737 // FIXME: We need an additional byte for storing \0 that is not on disk
1738 char *str = new char[length+1];
1739 Fp->read(str, (size_t)length);
1740 str[length] = '\0'; //this is only useful when length is odd
1741 // Special DicomString call to properly handle \0 and even length
1742 std::string newValue;
1745 newValue = Util::DicomString(str, length+1);
1746 //dbg.Verbose(0, "Warning: bad length: ", length );
1747 dbg.Verbose(0, "For string :", newValue.c_str());
1748 // Since we change the length of string update it length
1749 entry->SetReadLength(length+1);
1753 newValue = Util::DicomString(str, length);
1757 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1759 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1761 dbg.Verbose(1, "Document::LoadDocEntry",
1762 "unread element value");
1763 valEntry->SetValue(GDCM_UNREAD);
1769 // Because of correspondance with the VR dic
1770 valEntry->SetValue(newValue);
1774 valEntry->SetValue(newValue);
1779 dbg.Error(true, "Document::LoadDocEntry"
1780 "Should have a ValEntry, here !");
1786 * \brief Find the value Length of the passed Header Entry
1787 * @param entry Header Entry whose length of the value shall be loaded.
1789 void Document::FindDocEntryLength( DocEntry *entry )
1790 throw ( FormatError )
1792 uint16_t element = entry->GetElement();
1793 std::string vr = entry->GetVR();
1796 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1798 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1800 // The following reserved two bytes (see PS 3.5-2003, section
1801 // "7.1.2 Data element structure with explicit vr", p 27) must be
1802 // skipped before proceeding on reading the length on 4 bytes.
1803 Fp->seekg( 2L, std::ios_base::cur);
1804 uint32_t length32 = ReadInt32();
1806 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1811 /// \todo rename that to FindDocEntryLengthOBOrOW since
1812 /// the above test is on both OB and OW...
1813 lengthOB = FindDocEntryLengthOB();
1815 catch ( FormatUnexpected )
1817 // Computing the length failed (this happens with broken
1818 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1819 // chance to get the pixels by deciding the element goes
1820 // until the end of the file. Hence we artificially fix the
1821 // the length and proceed.
1822 long currentPosition = Fp->tellg();
1823 Fp->seekg(0L,std::ios_base::end);
1824 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1825 Fp->seekg(currentPosition, std::ios_base::beg);
1826 entry->SetLength(lengthUntilEOF);
1829 entry->SetLength(lengthOB);
1832 FixDocEntryFoundLength(entry, length32);
1836 // Length is encoded on 2 bytes.
1837 length16 = ReadInt16();
1839 // We can tell the current file is encoded in big endian (like
1840 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1841 // and it's value is the one of the encoding of a big endian file.
1842 // In order to deal with such big endian encoded files, we have
1843 // (at least) two strategies:
1844 // * when we load the "Transfer Syntax" tag with value of big endian
1845 // encoding, we raise the proper flags. Then we wait for the end
1846 // of the META group (0x0002) among which is "Transfer Syntax",
1847 // before switching the swap code to big endian. We have to postpone
1848 // the switching of the swap code since the META group is fully encoded
1849 // in little endian, and big endian coding only starts at the next
1850 // group. The corresponding code can be hard to analyse and adds
1851 // many additional unnecessary tests for regular tags.
1852 // * the second strategy consists in waiting for trouble, that shall
1853 // appear when we find the first group with big endian encoding. This
1854 // is easy to detect since the length of a "Group Length" tag (the
1855 // ones with zero as element number) has to be of 4 (0x0004). When we
1856 // encounter 1024 (0x0400) chances are the encoding changed and we
1857 // found a group with big endian encoding.
1858 // We shall use this second strategy. In order to make sure that we
1859 // can interpret the presence of an apparently big endian encoded
1860 // length of a "Group Length" without committing a big mistake, we
1861 // add an additional check: we look in the already parsed elements
1862 // for the presence of a "Transfer Syntax" whose value has to be "big
1863 // endian encoding". When this is the case, chances are we have got our
1864 // hands on a big endian encoded file: we switch the swap code to
1865 // big endian and proceed...
1866 if ( element == 0x0000 && length16 == 0x0400 )
1868 TransferSyntaxType ts = GetTransferSyntax();
1869 if ( ts != ExplicitVRBigEndian )
1871 throw FormatError( "Document::FindDocEntryLength()",
1872 " not explicit VR." );
1876 SwitchSwapToBigEndian();
1877 // Restore the unproperly loaded values i.e. the group, the element
1878 // and the dictionary entry depending on them.
1879 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1880 uint16_t correctElem = SwapShort( entry->GetElement() );
1881 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1885 // This correct tag is not in the dictionary. Create a new one.
1886 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1888 // FIXME this can create a memory leaks on the old entry that be
1889 // left unreferenced.
1890 entry->SetDictEntry( newTag );
1893 // Heuristic: well, some files are really ill-formed.
1894 if ( length16 == 0xffff)
1896 // 0xffff means that we deal with 'Unknown Length' Sequence
1899 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1904 // Either implicit VR or a non DICOM conformal (see note below) explicit
1905 // VR that ommited the VR of (at least) this element. Farts happen.
1906 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1907 // on Data elements "Implicit and Explicit VR Data Elements shall
1908 // not coexist in a Data Set and Data Sets nested within it".]
1909 // Length is on 4 bytes.
1911 FixDocEntryFoundLength( entry, ReadInt32() );
1917 * \brief Find the Value Representation of the current Dicom Element.
1920 void Document::FindDocEntryVR( DocEntry *entry )
1922 if ( Filetype != ExplicitVR )
1929 long positionOnEntry = Fp->tellg();
1930 // Warning: we believe this is explicit VR (Value Representation) because
1931 // we used a heuristic that found "UL" in the first tag. Alas this
1932 // doesn't guarantee that all the tags will be in explicit VR. In some
1933 // cases (see e-film filtered files) one finds implicit VR tags mixed
1934 // within an explicit VR file. Hence we make sure the present tag
1935 // is in explicit VR and try to fix things if it happens not to be
1938 Fp->read (vr, (size_t)2);
1941 if( !CheckDocEntryVR(entry, vr) )
1943 Fp->seekg(positionOnEntry, std::ios_base::beg);
1944 // When this element is known in the dictionary we shall use, e.g. for
1945 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1946 // dictionary entry. Still we have to flag the element as implicit since
1947 // we know now our assumption on expliciteness is not furfilled.
1949 if ( entry->IsVRUnknown() )
1951 entry->SetVR("Implicit");
1953 entry->SetImplicitVR();
1958 * \brief Check the correspondance between the VR of the header entry
1959 * and the taken VR. If they are different, the header entry is
1960 * updated with the new VR.
1961 * @param entry Header Entry to check
1962 * @param vr Dicom Value Representation
1963 * @return false if the VR is incorrect of if the VR isn't referenced
1964 * otherwise, it returns true
1966 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1969 bool realExplicit = true;
1971 // Assume we are reading a falsely explicit VR file i.e. we reached
1972 // a tag where we expect reading a VR but are in fact we read the
1973 // first to bytes of the length. Then we will interogate (through find)
1974 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1975 // both GCC and VC++ implementations of the STL map. Hence when the
1976 // expected VR read happens to be non-ascii characters we consider
1977 // we hit falsely explicit VR tag.
1979 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1981 realExplicit = false;
1984 // CLEANME searching the dicom_vr at each occurence is expensive.
1985 // PostPone this test in an optional integrity check at the end
1986 // of parsing or only in debug mode.
1987 if ( realExplicit && !Global::GetVR()->Count(vr) )
1989 realExplicit = false;
1992 if ( !realExplicit )
1994 // We thought this was explicit VR, but we end up with an
1995 // implicit VR tag. Let's backtrack.
1996 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1997 entry->GetGroup(), entry->GetElement());
1998 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2000 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
2002 // Group length is UL !
2003 DictEntry* newEntry = NewVirtualDictEntry(
2004 entry->GetGroup(), entry->GetElement(),
2005 "UL", "FIXME", "Group Length");
2006 entry->SetDictEntry( newEntry );
2011 if ( entry->IsVRUnknown() )
2013 // When not a dictionary entry, we can safely overwrite the VR.
2014 if( entry->GetElement() == 0x0000 )
2016 // Group length is UL !
2024 else if ( entry->GetVR() != vr )
2026 // The VR present in the file and the dictionary disagree. We assume
2027 // the file writer knew best and use the VR of the file. Since it would
2028 // be unwise to overwrite the VR of a dictionary (since it would
2029 // compromise it's next user), we need to clone the actual DictEntry
2030 // and change the VR for the read one.
2031 DictEntry* newEntry = NewVirtualDictEntry(
2032 entry->GetGroup(), entry->GetElement(),
2033 vr, "FIXME", entry->GetName());
2034 entry->SetDictEntry(newEntry);
2041 * \brief Get the transformed value of the header entry. The VR value
2042 * is used to define the transformation to operate on the value
2043 * \warning NOT end user intended method !
2044 * @param entry entry to tranform
2045 * @return Transformed entry value
2047 std::string Document::GetDocEntryValue(DocEntry *entry)
2049 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2051 std::string val = ((ValEntry *)entry)->GetValue();
2052 std::string vr = entry->GetVR();
2053 uint32_t length = entry->GetLength();
2054 std::ostringstream s;
2057 // When short integer(s) are expected, read and convert the following
2058 // n * 2 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 short integers (not a single one)
2064 if( vr == "US" || vr == "SS" )
2069 for (int i=0; i < nbInt; i++)
2075 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2076 newInt16 = SwapShort( newInt16 );
2081 // When integer(s) are expected, read and convert the following
2082 // n * 4 bytes properly i.e. as a multivaluated strings
2083 // (each single value is separated fromthe next one by '\'
2084 // as usual for standard multivaluated filels
2085 // Elements with Value Multiplicity > 1
2086 // contain a set of integers (not a single one)
2087 else if( vr == "UL" || vr == "SL" )
2092 for (int i=0; i < nbInt; i++)
2098 newInt32 = ( val[4*i+0] & 0xFF )
2099 + (( val[4*i+1] & 0xFF ) << 8 )
2100 + (( val[4*i+2] & 0xFF ) << 16 )
2101 + (( val[4*i+3] & 0xFF ) << 24 );
2102 newInt32 = SwapLong( newInt32 );
2106 #ifdef GDCM_NO_ANSI_STRING_STREAM
2107 s << std::ends; // to avoid oddities on Solaris
2108 #endif //GDCM_NO_ANSI_STRING_STREAM
2112 return ((ValEntry *)entry)->GetValue();
2116 * \brief Get the reverse transformed value of the header entry. The VR
2117 * value is used to define the reverse transformation to operate on
2119 * \warning NOT end user intended method !
2120 * @param entry Entry to reverse transform
2121 * @return Reverse transformed entry value
2123 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2125 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2127 std::string vr = entry->GetVR();
2128 std::vector<std::string> tokens;
2129 std::ostringstream s;
2131 if ( vr == "US" || vr == "SS" )
2135 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2136 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2137 for (unsigned int i=0; i<tokens.size(); i++)
2139 newInt16 = atoi(tokens[i].c_str());
2140 s << ( newInt16 & 0xFF )
2141 << (( newInt16 >> 8 ) & 0xFF );
2145 if ( vr == "UL" || vr == "SL")
2149 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2150 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2151 for (unsigned int i=0; i<tokens.size();i++)
2153 newInt32 = atoi(tokens[i].c_str());
2154 s << (char)( newInt32 & 0xFF )
2155 << (char)(( newInt32 >> 8 ) & 0xFF )
2156 << (char)(( newInt32 >> 16 ) & 0xFF )
2157 << (char)(( newInt32 >> 24 ) & 0xFF );
2162 #ifdef GDCM_NO_ANSI_STRING_STREAM
2163 s << std::ends; // to avoid oddities on Solaris
2164 #endif //GDCM_NO_ANSI_STRING_STREAM
2168 return ((ValEntry *)entry)->GetValue();
2172 * \brief Skip a given Header Entry
2173 * \warning NOT end user intended method !
2174 * @param entry entry to skip
2176 void Document::SkipDocEntry(DocEntry *entry)
2178 SkipBytes(entry->GetLength());
2182 * \brief Skips to the begining of the next Header Entry
2183 * \warning NOT end user intended method !
2184 * @param entry entry to skip
2186 void Document::SkipToNextDocEntry(DocEntry *entry)
2188 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2189 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2193 * \brief When the length of an element value is obviously wrong (because
2194 * the parser went Jabberwocky) one can hope improving things by
2195 * applying some heuristics.
2196 * @param entry entry to check
2197 * @param foundLength fist assumption about length
2199 void Document::FixDocEntryFoundLength(DocEntry *entry,
2200 uint32_t foundLength)
2202 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2203 if ( foundLength == 0xffffffff)
2208 uint16_t gr = entry->GetGroup();
2209 uint16_t el = entry->GetElement();
2211 if ( foundLength % 2)
2213 std::ostringstream s;
2214 s << "Warning : Tag with uneven length "
2216 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2217 dbg.Verbose(0, s.str().c_str());
2220 //////// Fix for some naughty General Electric images.
2221 // Allthough not recent many such GE corrupted images are still present
2222 // on Creatis hard disks. Hence this fix shall remain when such images
2223 // are no longer in user (we are talking a few years, here)...
2224 // Note: XMedCom probably uses such a trick since it is able to read
2225 // those pesky GE images ...
2226 if ( foundLength == 13)
2228 // Only happens for this length !
2229 if ( entry->GetGroup() != 0x0008
2230 || ( entry->GetElement() != 0x0070
2231 && entry->GetElement() != 0x0080 ) )
2234 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2238 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2239 // Occurence of such images is quite low (unless one leaves close to a
2240 // 'Leonardo' source. Hence, one might consider commenting out the
2241 // following fix on efficiency reasons.
2242 else if ( entry->GetGroup() == 0x0009
2243 && ( entry->GetElement() == 0x1113
2244 || entry->GetElement() == 0x1114 ) )
2247 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2250 else if ( entry->GetVR() == "SQ" )
2252 foundLength = 0; // ReadLength is unchanged
2255 //////// We encountered a 'delimiter' element i.e. a tag of the form
2256 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2257 // taken into account.
2258 else if( entry->GetGroup() == 0xfffe )
2260 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2261 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2262 // causes extra troubles...
2263 if( entry->GetElement() != 0x0000 )
2269 entry->SetUsableLength(foundLength);
2273 * \brief Apply some heuristics to predict whether the considered
2274 * element value contains/represents an integer or not.
2275 * @param entry The element value on which to apply the predicate.
2276 * @return The result of the heuristical predicate.
2278 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2280 uint16_t element = entry->GetElement();
2281 uint16_t group = entry->GetGroup();
2282 const std::string & vr = entry->GetVR();
2283 uint32_t length = entry->GetLength();
2285 // When we have some semantics on the element we just read, and if we
2286 // a priori know we are dealing with an integer, then we shall be
2287 // able to swap it's element value properly.
2288 if ( element == 0 ) // This is the group length of the group
2296 // Allthough this should never happen, still some images have a
2297 // corrupted group length [e.g. have a glance at offset x(8336) of
2298 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2299 // Since for dicom compliant and well behaved headers, the present
2300 // test is useless (and might even look a bit paranoid), when we
2301 // encounter such an ill-formed image, we simply display a warning
2302 // message and proceed on parsing (while crossing fingers).
2303 std::ostringstream s;
2304 long filePosition = Fp->tellg();
2305 s << "Erroneous Group Length element length on : (" \
2306 << std::hex << group << " , " << element
2307 << ") -before- position x(" << filePosition << ")"
2308 << "lgt : " << length;
2309 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2313 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2322 * \brief Find the Length till the next sequence delimiter
2323 * \warning NOT end user intended method !
2327 uint32_t Document::FindDocEntryLengthOB()
2328 throw( FormatUnexpected )
2330 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2331 long positionOnEntry = Fp->tellg();
2332 bool foundSequenceDelimiter = false;
2333 uint32_t totalLength = 0;
2335 while ( !foundSequenceDelimiter )
2341 group = ReadInt16();
2344 catch ( FormatError )
2346 throw FormatError("Document::FindDocEntryLengthOB()",
2347 " group or element not present.");
2350 // We have to decount the group and element we just read
2353 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2355 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2356 "tag nor a Sequence delimiter tag.");
2357 Fp->seekg(positionOnEntry, std::ios_base::beg);
2358 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2359 "Neither an Item tag nor a Sequence "
2363 if ( elem == 0xe0dd )
2365 foundSequenceDelimiter = true;
2368 uint32_t itemLength = ReadInt32();
2369 // We add 4 bytes since we just read the ItemLength with ReadInt32
2370 totalLength += itemLength + 4;
2371 SkipBytes(itemLength);
2373 if ( foundSequenceDelimiter )
2378 Fp->seekg( positionOnEntry, std::ios_base::beg);
2383 * \brief Reads a supposed to be 16 Bits integer
2384 * (swaps it depending on processor endianity)
2385 * @return read value
2387 uint16_t Document::ReadInt16()
2388 throw( FormatError )
2391 Fp->read ((char*)&g, (size_t)2);
2394 throw FormatError( "Document::ReadInt16()", " file error." );
2398 throw FormatError( "Document::ReadInt16()", "EOF." );
2405 * \brief Reads a supposed to be 32 Bits integer
2406 * (swaps it depending on processor endianity)
2407 * @return read value
2409 uint32_t Document::ReadInt32()
2410 throw( FormatError )
2413 Fp->read ((char*)&g, (size_t)4);
2416 throw FormatError( "Document::ReadInt32()", " file error." );
2420 throw FormatError( "Document::ReadInt32()", "EOF." );
2427 * \brief skips bytes inside the source file
2428 * \warning NOT end user intended method !
2431 void Document::SkipBytes(uint32_t nBytes)
2433 //FIXME don't dump the returned value
2434 Fp->seekg((long)nBytes, std::ios_base::cur);
2438 * \brief Loads all the needed Dictionaries
2439 * \warning NOT end user intended method !
2441 void Document::Initialise()
2443 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2445 RLEInfo = new RLEFramesInfo;
2446 JPEGInfo = new JPEGFragmentsInfo;
2450 * \brief Discover what the swap code is (among little endian, big endian,
2451 * bad little endian, bad big endian).
2453 * @return false when we are absolutely sure
2454 * it's neither ACR-NEMA nor DICOM
2455 * true when we hope ours assuptions are OK
2457 bool Document::CheckSwap()
2459 // The only guaranted way of finding the swap code is to find a
2460 // group tag since we know it's length has to be of four bytes i.e.
2461 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2462 // occurs when we can't find such group...
2464 uint32_t x = 4; // x : for ntohs
2465 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2469 char deb[256]; //HEADER_LENGTH_TO_READ];
2471 // First, compare HostByteOrder and NetworkByteOrder in order to
2472 // determine if we shall need to swap bytes (i.e. the Endian type).
2473 if ( x == ntohs(x) )
2482 // The easiest case is the one of a DICOM header, since it possesses a
2483 // file preamble where it suffice to look for the string "DICM".
2484 Fp->read(deb, HEADER_LENGTH_TO_READ);
2486 char *entCur = deb + 128;
2487 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2489 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2491 // Next, determine the value representation (VR). Let's skip to the
2492 // first element (0002, 0000) and check there if we find "UL"
2493 // - or "OB" if the 1st one is (0002,0001) -,
2494 // in which case we (almost) know it is explicit VR.
2495 // WARNING: if it happens to be implicit VR then what we will read
2496 // is the length of the group. If this ascii representation of this
2497 // length happens to be "UL" then we shall believe it is explicit VR.
2498 // FIXME: in order to fix the above warning, we could read the next
2499 // element value (or a couple of elements values) in order to make
2500 // sure we are not commiting a big mistake.
2501 // We need to skip :
2502 // * the 128 bytes of File Preamble (often padded with zeroes),
2503 // * the 4 bytes of "DICM" string,
2504 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2505 // i.e. a total of 136 bytes.
2509 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2510 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2511 // *Implicit* VR. -and it is !-
2513 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2514 memcmp(entCur, "OB", (size_t)2) == 0 ||
2515 memcmp(entCur, "UI", (size_t)2) == 0 ||
2516 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2517 // when Write DCM *adds*
2519 // Use Document::dicom_vr to test all the possibilities
2520 // instead of just checking for UL, OB and UI !? group 0000
2522 Filetype = ExplicitVR;
2523 dbg.Verbose(1, "Document::CheckSwap:",
2524 "explicit Value Representation");
2528 Filetype = ImplicitVR;
2529 dbg.Verbose(1, "Document::CheckSwap:",
2530 "not an explicit Value Representation");
2536 dbg.Verbose(1, "Document::CheckSwap:",
2537 "HostByteOrder != NetworkByteOrder");
2542 dbg.Verbose(1, "Document::CheckSwap:",
2543 "HostByteOrder = NetworkByteOrder");
2546 // Position the file position indicator at first tag (i.e.
2547 // after the file preamble and the "DICM" string).
2548 Fp->seekg(0, std::ios_base::beg);
2549 Fp->seekg ( 132L, std::ios_base::beg);
2553 // Alas, this is not a DicomV3 file and whatever happens there is no file
2554 // preamble. We can reset the file position indicator to where the data
2555 // is (i.e. the beginning of the file).
2556 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2557 Fp->seekg(0, std::ios_base::beg);
2559 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2560 // By clean we mean that the length of the first tag is written down.
2561 // If this is the case and since the length of the first group HAS to be
2562 // four (bytes), then determining the proper swap code is straightforward.
2565 // We assume the array of char we are considering contains the binary
2566 // representation of a 32 bits integer. Hence the following dirty
2568 s32 = *((uint32_t *)(entCur));
2589 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2590 // It is time for despaired wild guesses.
2591 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2592 // i.e. the 'group length' element is not present :
2594 // check the supposed-to-be 'group number'
2595 // in ( 0x0001 .. 0x0008 )
2596 // to determine ' SwapCode' value .
2597 // Only 0 or 4321 will be possible
2598 // (no oportunity to check for the formerly well known
2599 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2600 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2601 // the file IS NOT ACR-NEMA nor DICOM V3
2602 // Find a trick to tell it the caller...
2604 s16 = *((uint16_t *)(deb));
2631 dbg.Verbose(0, "Document::CheckSwap:",
2632 "ACR/NEMA unfound swap info (Really hopeless !)");
2636 // Then the only info we have is the net2host one.
2648 * \brief Restore the unproperly loaded values i.e. the group, the element
2649 * and the dictionary entry depending on them.
2651 void Document::SwitchSwapToBigEndian()
2653 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2654 "Switching to BigEndian mode.");
2655 if ( SwapCode == 0 )
2659 else if ( SwapCode == 4321 )
2663 else if ( SwapCode == 3412 )
2667 else if ( SwapCode == 2143 )
2674 * \brief during parsing, Header Elements too long are not loaded in memory
2677 void Document::SetMaxSizeLoadEntry(long newSize)
2683 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2685 MaxSizeLoadEntry = 0xffffffff;
2688 MaxSizeLoadEntry = newSize;
2693 * \brief Header Elements too long will not be printed
2694 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2697 void Document::SetMaxSizePrintEntry(long newSize)
2699 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2704 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2706 MaxSizePrintEntry = 0xffffffff;
2709 MaxSizePrintEntry = newSize;
2715 * \brief Handle broken private tag from Philips NTSCAN
2716 * where the endianess is being switch to BigEndian for no
2720 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2722 // Endian reversion. Some files contain groups of tags with reversed endianess.
2723 static int reversedEndian = 0;
2724 // try to fix endian switching in the middle of headers
2725 if ((group == 0xfeff) && (elem == 0x00e0))
2727 // start endian swap mark for group found
2729 SwitchSwapToBigEndian();
2734 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2736 // end of reversed endian group
2738 SwitchSwapToBigEndian();
2744 * \brief Read the next tag but WITHOUT loading it's value
2745 * (read the 'Group Number', the 'Element Number',
2746 * gets the Dict Entry
2747 * gets the VR, gets the length, gets the offset value)
2748 * @return On succes the newly created DocEntry, NULL on failure.
2750 DocEntry* Document::ReadNextDocEntry()
2757 group = ReadInt16();
2760 catch ( FormatError e )
2762 // We reached the EOF (or an error occured) therefore
2763 // header parsing has to be considered as finished.
2768 HandleBrokenEndian(group, elem);
2769 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2770 FindDocEntryVR(newEntry);
2774 FindDocEntryLength(newEntry);
2776 catch ( FormatError e )
2784 newEntry->SetOffset(Fp->tellg());
2791 * \brief Generate a free TagKey i.e. a TagKey that is not present
2792 * in the TagHt dictionary.
2793 * @param group The generated tag must belong to this group.
2794 * @return The element of tag with given group which is fee.
2796 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2798 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2800 TagKey key = DictEntry::TranslateToKey(group, elem);
2801 if (TagHT.count(key) == 0)
2810 * \brief Assuming the internal file pointer \ref Document::Fp
2811 * is placed at the beginning of a tag check whether this
2812 * tag is (TestGroup, TestElement).
2813 * \warning On success the internal file pointer \ref Document::Fp
2814 * is modified to point after the tag.
2815 * On failure (i.e. when the tag wasn't the expected tag
2816 * (TestGroup, TestElement) the internal file pointer
2817 * \ref Document::Fp is restored to it's original position.
2818 * @param testGroup The expected group of the tag.
2819 * @param testElement The expected Element of the tag.
2820 * @return True on success, false otherwise.
2822 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2824 long positionOnEntry = Fp->tellg();
2825 long currentPosition = Fp->tellg(); // On debugging purposes
2827 //// Read the Item Tag group and element, and make
2828 // sure they are what we expected:
2829 uint16_t itemTagGroup;
2830 uint16_t itemTagElement;
2833 itemTagGroup = ReadInt16();
2834 itemTagElement = ReadInt16();
2836 catch ( FormatError e )
2838 //std::cerr << e << std::endl;
2841 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2843 std::ostringstream s;
2844 s << " We should have found tag (";
2845 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2846 s << " but instead we encountered tag (";
2847 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2849 s << " at address: " << (unsigned)currentPosition << std::endl;
2850 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2851 dbg.Verbose(0, s.str().c_str());
2852 Fp->seekg(positionOnEntry, std::ios_base::beg);
2860 * \brief Assuming the internal file pointer \ref Document::Fp
2861 * is placed at the beginning of a tag (TestGroup, TestElement),
2862 * read the length associated to the Tag.
2863 * \warning On success the internal file pointer \ref Document::Fp
2864 * is modified to point after the tag and it's length.
2865 * On failure (i.e. when the tag wasn't the expected tag
2866 * (TestGroup, TestElement) the internal file pointer
2867 * \ref Document::Fp is restored to it's original position.
2868 * @param testGroup The expected group of the tag.
2869 * @param testElement The expected Element of the tag.
2870 * @return On success returns the length associated to the tag. On failure
2873 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2875 long positionOnEntry = Fp->tellg();
2876 (void)positionOnEntry;
2878 if ( !ReadTag(testGroup, testElement) )
2883 //// Then read the associated Item Length
2884 long currentPosition = Fp->tellg();
2885 uint32_t itemLength = ReadInt32();
2887 std::ostringstream s;
2888 s << "Basic Item Length is: "
2889 << itemLength << std::endl;
2890 s << " at address: " << (unsigned)currentPosition << std::endl;
2891 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2897 * \brief When parsing the Pixel Data of an encapsulated file, read
2898 * the basic offset table (when present, and BTW dump it).
2900 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2902 //// Read the Basic Offset Table Item Tag length...
2903 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2905 // When present, read the basic offset table itself.
2906 // Notes: - since the presence of this basic offset table is optional
2907 // we can't rely on it for the implementation, and we will simply
2908 // trash it's content (when present).
2909 // - still, when present, we could add some further checks on the
2910 // lengths, but we won't bother with such fuses for the time being.
2911 if ( itemLength != 0 )
2913 char* basicOffsetTableItemValue = new char[itemLength + 1];
2914 Fp->read(basicOffsetTableItemValue, itemLength);
2917 for (unsigned int i=0; i < itemLength; i += 4 )
2919 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2921 std::ostringstream s;
2922 s << " Read one length: ";
2923 s << std::hex << individualLength << std::endl;
2925 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2930 delete[] basicOffsetTableItemValue;
2935 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2936 * Compute the RLE extra information and store it in \ref RLEInfo
2937 * for later pixel retrieval usage.
2939 void Document::ComputeRLEInfo()
2941 TransferSyntaxType ts = GetTransferSyntax();
2942 if ( ts != RLELossless )
2947 // Encoded pixel data: for the time being we are only concerned with
2948 // Jpeg or RLE Pixel data encodings.
2949 // As stated in PS 3.5-2003, section 8.2 p44:
2950 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2951 // value representation OB is used".
2952 // Hence we expect an OB value representation. Concerning OB VR,
2953 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2954 // "For the Value Representations OB and OW, the encoding shall meet the
2955 // following specifications depending on the Data element tag:"
2957 // - the first item in the sequence of items before the encoded pixel
2958 // data stream shall be basic offset table item. The basic offset table
2959 // item value, however, is not required to be present"
2961 ReadAndSkipEncapsulatedBasicOffsetTable();
2963 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2964 // Loop on the individual frame[s] and store the information
2965 // on the RLE fragments in a RLEFramesInfo.
2966 // Note: - when only a single frame is present, this is a
2968 // - when more than one frame are present, then we are in
2969 // the case of a multi-frame image.
2971 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2973 // Parse the RLE Header and store the corresponding RLE Segment
2974 // Offset Table information on fragments of this current Frame.
2975 // Note that the fragment pixels themselves are not loaded
2976 // (but just skipped).
2977 long frameOffset = Fp->tellg();
2979 uint32_t nbRleSegments = ReadInt32();
2980 if ( nbRleSegments > 16 )
2982 // There should be at most 15 segments (refer to RLEFrame class)
2983 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2986 uint32_t rleSegmentOffsetTable[16];
2987 for( int k = 1; k <= 15; k++ )
2989 rleSegmentOffsetTable[k] = ReadInt32();
2992 // Deduce from both the RLE Header and the frameLength the
2993 // fragment length, and again store this info in a
2995 long rleSegmentLength[15];
2996 // skipping (not reading) RLE Segments
2997 if ( nbRleSegments > 1)
2999 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
3001 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
3002 - rleSegmentOffsetTable[k];
3003 SkipBytes(rleSegmentLength[k]);
3007 rleSegmentLength[nbRleSegments] = frameLength
3008 - rleSegmentOffsetTable[nbRleSegments];
3009 SkipBytes(rleSegmentLength[nbRleSegments]);
3011 // Store the collected info
3012 RLEFrame* newFrameInfo = new RLEFrame;
3013 newFrameInfo->NumberFragments = nbRleSegments;
3014 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
3016 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
3017 newFrameInfo->Length[uk] = rleSegmentLength[uk];
3019 RLEInfo->Frames.push_back( newFrameInfo );
3022 // Make sure that at the end of the item we encounter a 'Sequence
3024 if ( !ReadTag(0xfffe, 0xe0dd) )
3026 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3027 dbg.Verbose(0, " item at end of RLE item sequence");
3032 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3033 * Compute the jpeg extra information (fragment[s] offset[s] and
3034 * length) and store it[them] in \ref JPEGInfo for later pixel
3037 void Document::ComputeJPEGFragmentInfo()
3039 // If you need to, look for comments of ComputeRLEInfo().
3045 ReadAndSkipEncapsulatedBasicOffsetTable();
3047 // Loop on the fragments[s] and store the parsed information in a
3049 long fragmentLength;
3050 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3052 long fragmentOffset = Fp->tellg();
3054 // Store the collected info
3055 JPEGFragment* newFragment = new JPEGFragment;
3056 newFragment->Offset = fragmentOffset;
3057 newFragment->Length = fragmentLength;
3058 JPEGInfo->Fragments.push_back( newFragment );
3060 SkipBytes( fragmentLength );
3063 // Make sure that at the end of the item we encounter a 'Sequence
3065 if ( !ReadTag(0xfffe, 0xe0dd) )
3067 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3068 dbg.Verbose(0, " item at end of JPEG item sequence");
3073 * \brief Walk recursively the given \ref DocEntrySet, and feed
3074 * the given hash table (\ref TagDocEntryHT) with all the
3075 * \ref DocEntry (Dicom entries) encountered.
3076 * This method does the job for \ref BuildFlatHashTable.
3077 * @param builtHT Where to collect all the \ref DocEntry encountered
3078 * when recursively walking the given set.
3079 * @param set The structure to be traversed (recursively).
3081 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3084 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3086 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3087 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3088 i != currentHT.end();
3091 DocEntry* entry = i->second;
3092 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3094 const ListSQItem& items = seqEntry->GetSQItems();
3095 for( ListSQItem::const_iterator item = items.begin();
3096 item != items.end();
3099 BuildFlatHashTableRecurse( builtHT, *item );
3103 builtHT[entry->GetKey()] = entry;
3108 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3110 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3111 for (ListDocEntry::const_iterator i = currentList.begin();
3112 i != currentList.end();
3115 DocEntry* entry = *i;
3116 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3118 const ListSQItem& items = seqEntry->GetSQItems();
3119 for( ListSQItem::const_iterator item = items.begin();
3120 item != items.end();
3123 BuildFlatHashTableRecurse( builtHT, *item );
3127 builtHT[entry->GetKey()] = entry;
3134 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3137 * The structure used by a Document (through \ref ElementSet),
3138 * in order to hold the parsed entries of a Dicom header, is a recursive
3139 * one. This is due to the fact that the sequences (when present)
3140 * can be nested. Additionaly, the sequence items (represented in
3141 * gdcm as \ref SQItem) add an extra complexity to the data
3142 * structure. Hence, a gdcm user whishing to visit all the entries of
3143 * a Dicom header will need to dig in the gdcm internals (which
3144 * implies exposing all the internal data structures to the API).
3145 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3146 * recursively builds a temporary hash table, which holds all the
3147 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3149 * \warning Of course there is NO integrity constrain between the
3150 * returned \ref TagDocEntryHT and the \ref ElementSet used
3151 * to build it. Hence if the underlying \ref ElementSet is
3152 * altered, then it is the caller responsability to invoke
3153 * \ref BuildFlatHashTable again...
3154 * @return The flat std::map<> we juste build.
3156 TagDocEntryHT* Document::BuildFlatHashTable()
3158 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3159 BuildFlatHashTableRecurse( *FlatHT, this );
3166 * \brief Compares two documents, according to \ref DicomDir rules
3167 * \warning Does NOT work with ACR-NEMA files
3168 * \todo Find a trick to solve the pb (use RET fields ?)
3170 * @return true if 'smaller'
3172 bool Document::operator<(Document &document)
3175 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3176 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3188 s1 = GetEntryByNumber(0x0010,0x0020);
3189 s2 = document.GetEntryByNumber(0x0010,0x0020);
3200 // Study Instance UID
3201 s1 = GetEntryByNumber(0x0020,0x000d);
3202 s2 = document.GetEntryByNumber(0x0020,0x000d);
3213 // Serie Instance UID
3214 s1 = GetEntryByNumber(0x0020,0x000e);
3215 s2 = document.GetEntryByNumber(0x0020,0x000e);
3230 } // end namespace gdcm
3232 //-----------------------------------------------------------------------------