1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/04 18:14:34 $
7 Version: $Revision: 1.116 $
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"
34 #include <netinet/in.h>
39 static const char *TransferSyntaxStrings[] = {
40 // Implicit VR Little Endian
42 // Explicit VR Little Endian
43 "1.2.840.10008.1.2.1",
44 // Deflated Explicit VR Little Endian
45 "1.2.840.10008.1.2.1.99",
46 // Explicit VR Big Endian
47 "1.2.840.10008.1.2.2",
48 // JPEG Baseline (Process 1)
49 "1.2.840.10008.1.2.4.50",
50 // JPEG Extended (Process 2 & 4)
51 "1.2.840.10008.1.2.4.51",
52 // JPEG Extended (Process 3 & 5)
53 "1.2.840.10008.1.2.4.52",
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 "1.2.840.10008.1.2.4.53",
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 "1.2.840.10008.1.2.4.55",
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 "1.2.840.10008.1.2.4.57",
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
61 "1.2.840.10008.1.2.4.70",
63 "1.2.840.10008.1.2.4.90",
65 "1.2.840.10008.1.2.4.91",
67 "1.2.840.10008.1.2.5",
69 "Unknown Transfer Syntax"
72 //-----------------------------------------------------------------------------
73 // Refer to Document::CheckSwap()
74 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
76 // Refer to Document::SetMaxSizeLoadEntry()
77 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
78 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
80 //-----------------------------------------------------------------------------
81 // Constructor / Destructor
85 * @param filename file to be opened for parsing
87 Document::Document( std::string const & filename ) : ElementSet(-1)
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
100 Fp->seekg( 0, std::ios_base::beg);
102 Fp->seekg(0, std::ios_base::end);
103 long lgt = Fp->tellg();
105 Fp->seekg( 0, std::ios_base::beg);
107 long beg = Fp->tellg();
110 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
112 Fp->seekg( 0, std::ios_base::beg);
114 // Load 'non string' values
116 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
117 if( PhotometricInterpretation == "PALETTE COLOR " )
119 LoadEntryBinArea(0x0028,0x1200); // gray LUT
120 /// FIXME FIXME FIXME
121 /// The tags refered by the three following lines used to be CORRECTLY
122 /// defined as having an US Value Representation in the public
123 /// dictionnary. BUT the semantics implied by the three following
124 /// lines state that the corresponding tag contents are in fact
125 /// the ones of a BinEntry.
126 /// In order to fix things "Quick and Dirty" the dictionnary was
127 /// altered on PURPOUS but now contains a WRONG value.
128 /// In order to fix things and restore the dictionary to its
129 /// correct value, one needs to decided of the semantics by deciding
130 /// wether the following tags are either:
131 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
132 /// also used as BinEntry, which requires the proper conversion,
133 /// - OW, and hence loaded as BinEntry, but afterwards also used
134 /// as ValEntry, which requires the proper conversion.
135 LoadEntryBinArea(0x0028,0x1201); // R LUT
136 LoadEntryBinArea(0x0028,0x1202); // G LUT
137 LoadEntryBinArea(0x0028,0x1203); // B LUT
139 // Segmented Red Palette Color LUT Data
140 LoadEntryBinArea(0x0028,0x1221);
141 // Segmented Green Palette Color LUT Data
142 LoadEntryBinArea(0x0028,0x1222);
143 // Segmented Blue Palette Color LUT Data
144 LoadEntryBinArea(0x0028,0x1223);
146 //FIXME later : how to use it?
147 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
151 // --------------------------------------------------------------
152 // Specific code to allow gdcm to read ACR-LibIDO formated images
153 // Note: ACR-LibIDO is an extension of the ACR standard that was
154 // used at CREATIS. For the time being (say a couple years)
155 // we keep this kludge to allow a smooth move to gdcm for
156 // CREATIS developpers (sorry folks).
158 // if recognition code tells us we deal with a LibIDO image
159 // we switch lineNumber and columnNumber
162 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
163 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
164 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
165 // with "little-endian strings"
167 Filetype = ACR_LIBIDO;
168 std::string rows = GetEntryByNumber(0x0028, 0x0010);
169 std::string columns = GetEntryByNumber(0x0028, 0x0011);
170 SetEntryByNumber(columns, 0x0028, 0x0010);
171 SetEntryByNumber(rows , 0x0028, 0x0011);
173 // ----------------- End of ACR-LibIDO kludge ------------------
175 PrintLevel = 1; // 'Medium' print level by default
179 * \brief This default constructor doesn't parse the file. You should
180 * then invoke \ref Document::SetFileName and then the parsing.
182 Document::Document() : ElementSet(-1)
184 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
186 PrintLevel = 1; // 'Medium' print level by default
190 * \brief Canonical destructor.
192 Document::~Document ()
197 // Recursive clean up of sequences
198 for (TagDocEntryHT::const_iterator it = TagHT.begin();
199 it != TagHT.end(); ++it )
201 //delete it->second; //temp remove
206 //-----------------------------------------------------------------------------
210 * \brief Prints The Dict Entries of THE public Dicom Dictionary
213 void Document::PrintPubDict(std::ostream & os)
215 RefPubDict->Print(os);
219 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
222 void Document::PrintShaDict(std::ostream & os)
224 RefShaDict->Print(os);
227 //-----------------------------------------------------------------------------
230 * \brief Get the public dictionary used
232 Dict* Document::GetPubDict()
238 * \brief Get the shadow dictionary used
240 Dict* Document::GetShaDict()
246 * \brief Set the shadow dictionary used
247 * \param dict dictionary to use in shadow
249 bool Document::SetShaDict(Dict *dict)
256 * \brief Set the shadow dictionary used
257 * \param dictName name of the dictionary to use in shadow
259 bool Document::SetShaDict(DictKey const & dictName)
261 RefShaDict = Global::GetDicts()->GetDict(dictName);
266 * \brief This predicate, based on hopefully reasonable heuristics,
267 * decides whether or not the current Document was properly parsed
268 * and contains the mandatory information for being considered as
269 * a well formed and usable Dicom/Acr File.
270 * @return true when Document is the one of a reasonable Dicom/Acr file,
273 bool Document::IsReadable()
275 if( Filetype == Unknown)
277 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
283 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
293 * \brief Internal function that checks whether the Transfer Syntax given
294 * as argument is the one present in the current document.
295 * @param syntaxToCheck The transfert syntax we need to check against.
296 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
297 * the current document. False either when the document contains
298 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
300 TransferSyntaxType Document::GetTransferSyntax()
302 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
308 // The entry might be present but not loaded (parsing and loading
309 // happen at different stages): try loading and proceed with check...
310 LoadDocEntrySafe(entry);
311 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
313 std::string transfer = valEntry->GetValue();
314 // The actual transfer (as read from disk) might be padded. We
315 // first need to remove the potential padding. We can make the
316 // weak assumption that padding was not executed with digits...
317 if ( transfer.length() == 0 )
319 // for brain damaged headers
322 while ( !isdigit(transfer[transfer.length()-1]) )
324 transfer.erase(transfer.length()-1, 1);
326 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
328 if ( TransferSyntaxStrings[i] == transfer )
330 return TransferSyntaxType(i);
337 bool Document::IsJPEGLossless()
339 TransferSyntaxType r = GetTransferSyntax();
340 return r == JPEGFullProgressionProcess10_12
341 || r == JPEGLosslessProcess14
342 || r == JPEGLosslessProcess14_1;
346 * \brief Determines if the Transfer Syntax was already encountered
347 * and if it corresponds to a JPEG2000 one
348 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
351 bool Document::IsJPEG2000()
353 TransferSyntaxType r = GetTransferSyntax();
354 return r == JPEG2000Lossless || r == JPEG2000;
358 * \brief Determines if the Transfer Syntax corresponds to any form
359 * of Jpeg encoded Pixel data.
360 * @return True when any form of JPEG found. False otherwise.
362 bool Document::IsJPEG()
364 TransferSyntaxType r = GetTransferSyntax();
365 return r == JPEGBaselineProcess1
366 || r == JPEGExtendedProcess2_4
367 || r == JPEGExtendedProcess3_5
368 || r == JPEGSpectralSelectionProcess6_8
374 * \brief Determines if the Transfer Syntax corresponds to encapsulated
375 * of encoded Pixel Data (as opposed to native).
376 * @return True when encapsulated. False when native.
378 bool Document::IsEncapsulate()
380 TransferSyntaxType r = GetTransferSyntax();
381 return IsJPEG() || r == RLELossless;
385 * \brief Predicate for dicom version 3 file.
386 * @return True when the file is a dicom version 3.
388 bool Document::IsDicomV3()
390 // Checking if Transfert Syntax exists is enough
391 // Anyway, it's to late check if the 'Preamble' was found ...
392 // And ... would it be a rich idea to check ?
393 // (some 'no Preamble' DICOM images exist !)
394 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
398 * \brief returns the File Type
399 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
400 * @return the FileType code
402 FileType Document::GetFileType()
408 * \brief Tries to open the file \ref Document::Filename and
409 * checks the preamble when existing.
410 * @return The FILE pointer on success.
412 std::ifstream* Document::OpenFile()
414 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
419 "Document::OpenFile cannot open file: ",
425 Fp->read((char*)&zero, (size_t)2 );
427 //ACR -- or DICOM with no Preamble --
428 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
434 Fp->seekg(126L, std::ios_base::cur);
436 Fp->read(dicm, (size_t)4);
437 if( memcmp(dicm, "DICM", 4) == 0 )
444 "Document::OpenFile not DICOM/ACR (missing preamble)",
451 * \brief closes the file
452 * @return TRUE if the close was successfull
454 bool Document::CloseFile()
460 return true; //FIXME how do we detect a non-close ifstream ?
464 * \brief Writes in a file all the Header Entries (Dicom Elements)
465 * @param fp file pointer on an already open file
466 * @param filetype Type of the File to be written
467 * (ACR-NEMA, ExplicitVR, ImplicitVR)
468 * \return Always true.
470 void Document::Write(std::ofstream* fp, FileType filetype)
472 /// \todo move the following lines (and a lot of others, to be written)
473 /// to a future function CheckAndCorrectHeader
474 /// (necessary if user wants to write a DICOM V3 file
475 /// starting from an ACR-NEMA (V2) Header
477 if (filetype == ImplicitVR)
479 std::string ts = TransferSyntaxStrings[ImplicitVRLittleEndian];
480 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010);
482 /// \todo Refer to standards on page 21, chapter 6.2
483 /// "Value representation": values with a VR of UI shall be
484 /// padded with a single trailing null
485 /// in the following case we have to padd manually with a 0
487 SetEntryLengthByNumber(18, 0x0002, 0x0010);
490 if (filetype == ExplicitVR)
492 std::string ts = TransferSyntaxStrings[ExplicitVRLittleEndian];
493 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010);
495 /// \todo Refer to standards on page 21, chapter 6.2
496 /// "Value representation": values with a VR of UI shall be
497 /// padded with a single trailing null
498 /// Dans le cas suivant on doit pader manuellement avec un 0
500 SetEntryLengthByNumber(20, 0x0002, 0x0010);
504 * \todo rewrite later, if really usefull
505 * - 'Group Length' element is optional in DICOM
506 * - but un-updated odd groups lengthes can causes pb
509 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
510 * UpdateGroupLength(false,filetype);
511 * if ( filetype == ACR)
512 * UpdateGroupLength(true,ACR);
515 ElementSet::Write(fp, filetype); // This one is recursive
520 * \brief Modifies the value of a given Header Entry (Dicom Element)
521 * when it exists. Create it with the given value when unexistant.
522 * @param value (string) Value to be set
523 * @param group Group number of the Entry
524 * @param elem Element number of the Entry
525 * @param VR V(alue) R(epresentation) of the Entry -if private Entry-
526 * \return pointer to the modified/created Header Entry (NULL when creation
529 ValEntry* Document::ReplaceOrCreateByNumber(
530 std::string const & value,
535 ValEntry* valEntry = 0;
536 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
540 // check if (group,element) DictEntry exists
541 // if it doesn't, create an entry in DictSet::VirtualEntry
544 // Find out if the tag we received is in the dictionaries:
545 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
546 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
549 currentEntry = NewDocEntryByNumber(group, elem, vr);
553 currentEntry = NewDocEntryByNumber(group, elem);
558 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
559 " NewDocEntryByNumber failed.");
562 valEntry = new ValEntry(currentEntry);
563 if ( !AddEntry(valEntry))
565 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
566 " failed allthough this is a creation.");
571 valEntry = dynamic_cast< ValEntry* >(currentEntry);
572 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
573 // then we change it to a ValEntry ?
574 // Shouldn't it be considered as an error ?
576 // We need to promote the DocEntry to a ValEntry:
577 valEntry = new ValEntry(currentEntry);
578 if (!RemoveEntry(currentEntry))
580 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
581 " of previous DocEntry failed.");
584 if ( !AddEntry(valEntry))
586 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
587 " promoted ValEntry failed.");
593 SetEntryByNumber(value, group, elem);
599 * \brief Modifies the value of a given Header Entry (Dicom Element)
600 * when it exists. Create it with the given value when unexistant.
601 * @param binArea (binary) value to be set
602 * @param Group Group number of the Entry
603 * @param Elem Element number of the Entry
604 * \return pointer to the modified/created Header Entry (NULL when creation
607 BinEntry* Document::ReplaceOrCreateByNumber(
614 BinEntry* binEntry = 0;
615 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
619 // check if (group,element) DictEntry exists
620 // if it doesn't, create an entry in DictSet::VirtualEntry
623 // Find out if the tag we received is in the dictionaries:
624 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
625 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
629 currentEntry = NewDocEntryByNumber(group, elem, vr);
633 currentEntry = NewDocEntryByNumber(group, elem);
637 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
638 " NewDocEntryByNumber failed.");
641 binEntry = new BinEntry(currentEntry);
642 if ( !AddEntry(binEntry))
644 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
645 " failed allthough this is a creation.");
650 binEntry = dynamic_cast< BinEntry* >(currentEntry);
651 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
652 // then we change it to a BinEntry ?
653 // Shouldn't it be considered as an error ?
655 // We need to promote the DocEntry to a BinEntry:
656 binEntry = new BinEntry(currentEntry);
657 if (!RemoveEntry(currentEntry))
659 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
660 " of previous DocEntry failed.");
663 if ( !AddEntry(binEntry))
665 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
666 " promoted BinEntry failed.");
672 SetEntryByNumber(binArea, lgth, group, elem);
679 * \brief Modifies the value of a given Header Entry (Dicom Element)
680 * when it exists. Create it when unexistant.
681 * @param Group Group number of the Entry
682 * @param Elem Element number of the Entry
683 * \return pointer to the modified/created SeqEntry (NULL when creation
686 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
689 DocEntry* a = GetDocEntryByNumber( group, elem);
692 a = NewSeqEntryByNumber(group, elem);
698 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
705 * \brief Set a new value if the invoked element exists
706 * Seems to be useless !!!
707 * @param value new element value
708 * @param group group number of the Entry
709 * @param elem element number of the Entry
712 bool Document::ReplaceIfExistByNumber(std::string const & value,
713 uint16_t group, uint16_t elem )
715 SetEntryByNumber(value, group, elem);
720 //-----------------------------------------------------------------------------
724 * \brief Checks if a given Dicom Element exists within the H table
725 * @param group Group number of the searched Dicom Element
726 * @param element Element number of the searched Dicom Element
727 * @return true is found
729 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
731 const std::string &key = DictEntry::TranslateToKey(group, element );
732 return TagHT.count(key) != 0;
736 * \brief Searches within Header Entries (Dicom Elements) parsed with
737 * the public and private dictionaries
738 * for the element value of a given tag.
739 * \warning Don't use any longer : use GetPubEntryByName
740 * @param tagName name of the searched element.
741 * @return Corresponding element value when it exists,
742 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
744 std::string Document::GetEntryByName(TagName const & tagName)
746 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
752 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
756 * \brief Searches within Header Entries (Dicom Elements) parsed with
757 * the public and private dictionaries
758 * for the element value representation of a given tag.
760 * Obtaining the VR (Value Representation) might be needed by caller
761 * to convert the string typed content to caller's native type
762 * (think of C++ vs Python). The VR is actually of a higher level
763 * of semantics than just the native C++ type.
764 * @param tagName name of the searched element.
765 * @return Corresponding element value representation when it exists,
766 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
768 std::string Document::GetEntryVRByName(TagName const& tagName)
770 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
771 if( dictEntry == NULL)
776 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
777 dictEntry->GetElement());
778 return elem->GetVR();
782 * \brief Searches within Header Entries (Dicom Elements) parsed with
783 * the public and private dictionaries
784 * for the element value representation of a given tag.
785 * @param group Group number of the searched tag.
786 * @param element Element number of the searched tag.
787 * @return Corresponding element value representation when it exists,
788 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
790 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
792 TagKey key = DictEntry::TranslateToKey(group, element);
793 /// \todo use map methods, instead of multimap JPR
794 if ( !TagHT.count(key))
799 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
803 * \brief Searches within Header Entries (Dicom Elements) parsed with
804 * the public and private dictionaries
805 * for the element value representation of a given tag..
807 * Obtaining the VR (Value Representation) might be needed by caller
808 * to convert the string typed content to caller's native type
809 * (think of C++ vs Python). The VR is actually of a higher level
810 * of semantics than just the native C++ type.
811 * @param group Group number of the searched tag.
812 * @param element Element number of the searched tag.
813 * @return Corresponding element value representation when it exists,
814 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
816 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
818 DocEntry* elem = GetDocEntryByNumber(group, element);
823 return elem->GetVR();
827 * \brief Searches within Header Entries (Dicom Elements) parsed with
828 * the public and private dictionaries
829 * for the value length of a given tag..
830 * @param group Group number of the searched tag.
831 * @param element Element number of the searched tag.
832 * @return Corresponding element length; -2 if not found
834 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
836 DocEntry* elem = GetDocEntryByNumber(group, element);
839 return -2; //magic number
841 return elem->GetLength();
844 * \brief Sets the value (string) of the Header Entry (Dicom Element)
845 * @param content string value of the Dicom Element
846 * @param tagName name of the searched Dicom Element.
847 * @return true when found
849 bool Document::SetEntryByName(std::string const & content,
850 TagName const & tagName)
852 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
858 return SetEntryByNumber(content,dictEntry->GetGroup(),
859 dictEntry->GetElement());
863 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
864 * through it's (group, element) and modifies it's content with
866 * @param content new value (string) to substitute with
867 * @param group group number of the Dicom Element to modify
868 * @param element element number of the Dicom Element to modify
870 bool Document::SetEntryByNumber(std::string const& content,
871 uint16_t group, uint16_t element)
876 ValEntry* valEntry = GetValEntryByNumber(group, element);
879 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
880 " ValEntry (try promotion first).");
883 // Non even content must be padded with a space (020H)...
884 std::string finalContent = content;
885 if( finalContent.length() % 2 )
887 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
889 valEntry->SetValue(finalContent);
891 // Integers have a special treatement for their length:
893 l = finalContent.length();
894 if ( l != 0) // To avoid to be cheated by 'zero length' integers
896 VRKey vr = valEntry->GetVR();
897 if( vr == "US" || vr == "SS" )
899 // for multivaluated items
900 c = Util::CountSubstring(content, "\\") + 1;
903 else if( vr == "UL" || vr == "SL" )
905 // for multivaluated items
906 c = Util::CountSubstring(content, "\\") + 1;
910 valEntry->SetLength(l);
915 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
916 * through it's (group, element) and modifies it's content with
918 * @param content new value (void* -> uint8_t*) to substitute with
919 * @param lgth new value length
920 * @param group group number of the Dicom Element to modify
921 * @param element element number of the Dicom Element to modify
923 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
924 uint16_t group, uint16_t element)
926 (void)lgth; //not used
927 TagKey key = DictEntry::TranslateToKey(group, element);
928 if ( !TagHT.count(key))
933 /* Hope Binary field length is *never* wrong
934 if(lgth%2) // Non even length are padded with a space (020H).
937 //content = content + '\0'; // fing a trick to enlarge a binary field?
940 BinEntry* a = (BinEntry *)TagHT[key];
941 a->SetBinArea(content);
943 a->SetValue(GDCM_BINLOADED);
949 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
950 * in the PubDocEntrySet of this instance
951 * through it's (group, element) and modifies it's length with
953 * \warning Use with extreme caution.
954 * @param l new length to substitute with
955 * @param group group number of the Entry to modify
956 * @param element element number of the Entry to modify
957 * @return true on success, false otherwise.
959 bool Document::SetEntryLengthByNumber(uint32_t l,
960 uint16_t group, uint16_t element)
962 /// \todo use map methods, instead of multimap JPR
963 TagKey key = DictEntry::TranslateToKey(group, element);
964 if ( !TagHT.count(key) )
970 l++; // length must be even
972 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
978 * \brief Gets (from Header) the offset of a 'non string' element value
979 * (LoadElementValues has already be executed)
980 * @param group group number of the Entry
981 * @param elem element number of the Entry
982 * @return File Offset of the Element Value
984 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
986 DocEntry* entry = GetDocEntryByNumber(group, elem);
989 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
992 return entry->GetOffset();
996 * \brief Gets (from Header) a 'non string' element value
997 * (LoadElementValues has already be executed)
998 * @param group group number of the Entry
999 * @param elem element number of the Entry
1000 * @return Pointer to the 'non string' area
1002 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1004 DocEntry* entry = GetDocEntryByNumber(group, elem);
1007 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1010 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1012 return binEntry->GetBinArea();
1019 * \brief Loads (from disk) the element content
1020 * when a string is not suitable
1021 * @param group group number of the Entry
1022 * @param elem element number of the Entry
1024 void* Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1026 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1031 size_t o =(size_t)docElement->GetOffset();
1032 Fp->seekg( o, std::ios_base::beg);
1033 size_t l = docElement->GetLength();
1034 uint8_t* a = new uint8_t[l];
1037 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1040 Fp->read((char*)a, l);
1041 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1046 /// \todo Drop any already existing void area! JPR
1047 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1049 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1054 * \brief Loads (from disk) the element content
1055 * when a string is not suitable
1056 * @param element Entry whose binArea is going to be loaded
1058 void* Document::LoadEntryBinArea(BinEntry* element)
1060 size_t o =(size_t)element->GetOffset();
1061 Fp->seekg(o, std::ios_base::beg);
1062 size_t l = element->GetLength();
1063 uint8_t* a = new uint8_t[l];
1066 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1069 element->SetBinArea((uint8_t*)a);
1070 /// \todo check the result
1071 Fp->read((char*)a, l);
1072 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1082 * \brief Sets a 'non string' value to a given Dicom Element
1083 * @param area area containing the 'non string' value
1084 * @param group Group number of the searched Dicom Element
1085 * @param element Element number of the searched Dicom Element
1088 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1089 uint16_t group, uint16_t element)
1091 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1092 if ( !currentEntry )
1096 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1098 binEntry->SetBinArea( area );
1105 * \brief Update the entries with the shadow dictionary.
1106 * Only non even entries are analyzed
1108 void Document::UpdateShaEntries()
1113 /// \todo TODO : still any use to explore recursively the whole structure?
1115 for(ListTag::iterator it=listEntries.begin();
1116 it!=listEntries.end();
1119 // Odd group => from public dictionary
1120 if((*it)->GetGroup()%2==0)
1123 // Peer group => search the corresponding dict entry
1125 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1129 if((*it)->IsImplicitVR())
1134 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1136 // Set the new entry and the new value
1137 (*it)->SetDictEntry(entry);
1138 CheckDocEntryVR(*it,vr);
1140 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1145 // Remove precedent value transformation
1146 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1153 * \brief Searches within the Header Entries for a Dicom Element of
1155 * @param tagName name of the searched Dicom Element.
1156 * @return Corresponding Dicom Element when it exists, and NULL
1159 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1161 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1167 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1171 * \brief retrieves a Dicom Element (the first one) using (group, element)
1172 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1173 * if you think it's NOT UNIQUE, check the count number
1174 * and use iterators to retrieve ALL the Dicoms Elements within
1175 * a given couple (group, element)
1176 * @param group Group number of the searched Dicom Element
1177 * @param element Element number of the searched Dicom Element
1180 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1182 TagKey key = DictEntry::TranslateToKey(group, element);
1183 if ( !TagHT.count(key))
1187 return TagHT.find(key)->second;
1191 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1192 * returns a result when the corresponding entry is of type
1194 * @return When present, the corresponding ValEntry.
1196 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1198 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1199 if ( !currentEntry )
1203 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1207 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1213 * \brief Loads the element while preserving the current
1214 * underlying file position indicator as opposed to
1215 * to LoadDocEntry that modifies it.
1216 * @param entry Header Entry whose value shall be loaded.
1219 void Document::LoadDocEntrySafe(DocEntry * entry)
1221 long PositionOnEntry = Fp->tellg();
1222 LoadDocEntry(entry);
1223 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1227 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1229 * @return The properly swaped 32 bits integer.
1231 uint32_t Document::SwapLong(uint32_t a)
1238 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1239 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1243 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1247 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1250 //std::cout << "swapCode= " << SwapCode << std::endl;
1251 dbg.Error(" Document::SwapLong : unset swap code");
1258 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1260 * @return The properly unswaped 32 bits integer.
1262 uint32_t Document::UnswapLong(uint32_t a)
1268 * \brief Swaps the bytes so they agree with the processor order
1269 * @return The properly swaped 16 bits integer.
1271 uint16_t Document::SwapShort(uint16_t a)
1273 if ( SwapCode == 4321 || SwapCode == 2143 )
1275 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1281 * \brief Unswaps the bytes so they agree with the processor order
1282 * @return The properly unswaped 16 bits integer.
1284 uint16_t Document::UnswapShort(uint16_t a)
1286 return SwapShort(a);
1289 //-----------------------------------------------------------------------------
1293 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1294 * @return length of the parsed set.
1296 void Document::ParseDES(DocEntrySet *set, long offset,
1297 long l_max, bool delim_mode)
1299 DocEntry *newDocEntry = 0;
1303 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1307 newDocEntry = ReadNextDocEntry( );
1313 VRKey vr = newDocEntry->GetVR();
1317 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1319 /////////////////////// ValEntry
1320 ValEntry* newValEntry =
1321 new ValEntry( newDocEntry->GetDictEntry() );
1322 newValEntry->Copy( newDocEntry );
1324 // When "set" is a Document, then we are at the top of the
1325 // hierarchy and the Key is simply of the form ( group, elem )...
1326 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1329 newValEntry->SetKey( newValEntry->GetKey() );
1331 // ...but when "set" is a SQItem, we are inserting this new
1332 // valEntry in a sequence item. Hence the key has the
1333 // generalized form (refer to \ref BaseTagKey):
1334 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1336 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1337 + newValEntry->GetKey() );
1340 set->AddEntry( newValEntry );
1341 LoadDocEntry( newValEntry );
1342 if (newValEntry->IsItemDelimitor())
1346 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1353 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1355 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1356 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1357 "nor BinEntry. Probably unknown VR.");
1360 //////////////////// BinEntry or UNKOWN VR:
1361 BinEntry* newBinEntry =
1362 new BinEntry( newDocEntry->GetDictEntry() );
1363 newBinEntry->Copy( newDocEntry );
1365 // When "this" is a Document the Key is simply of the
1366 // form ( group, elem )...
1367 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1370 newBinEntry->SetKey( newBinEntry->GetKey() );
1372 // but when "this" is a SQItem, we are inserting this new
1373 // valEntry in a sequence item, and the kay has the
1374 // generalized form (refer to \ref BaseTagKey):
1375 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1377 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1378 + newBinEntry->GetKey() );
1381 set->AddEntry( newBinEntry );
1382 LoadDocEntry( newBinEntry );
1385 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1386 && ( newDocEntry->GetElement() == 0x0010 ) )
1388 TransferSyntaxType ts = GetTransferSyntax();
1389 if ( ts == RLELossless )
1391 long PositionOnEntry = Fp->tellg();
1392 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1394 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1396 else if ( IsJPEG() )
1398 long PositionOnEntry = Fp->tellg();
1399 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1400 ComputeJPEGFragmentInfo();
1401 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1405 // Just to make sure we are at the beginning of next entry.
1406 SkipToNextDocEntry(newDocEntry);
1411 unsigned long l = newDocEntry->GetReadLength();
1412 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1414 if ( l == 0xffffffff )
1423 // no other way to create it ...
1424 SeqEntry* newSeqEntry =
1425 new SeqEntry( newDocEntry->GetDictEntry() );
1426 newSeqEntry->Copy( newDocEntry );
1427 newSeqEntry->SetDelimitorMode( delim_mode );
1429 // At the top of the hierarchy, stands a Document. When "set"
1430 // is a Document, then we are building the first depth level.
1431 // Hence the SeqEntry we are building simply has a depth
1433 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1436 newSeqEntry->SetDepthLevel( 1 );
1437 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1439 // But when "set" is allready a SQItem, we are building a nested
1440 // sequence, and hence the depth level of the new SeqEntry
1441 // we are building, is one level deeper:
1442 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1444 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1445 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1446 + newSeqEntry->GetKey() );
1450 { // Don't try to parse zero-length sequences
1451 ParseSQ( newSeqEntry,
1452 newDocEntry->GetOffset(),
1455 set->AddEntry( newSeqEntry );
1456 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1466 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1467 * @return parsed length for this level
1469 void Document::ParseSQ( SeqEntry* seqEntry,
1470 long offset, long l_max, bool delim_mode)
1472 int SQItemNumber = 0;
1477 DocEntry* newDocEntry = ReadNextDocEntry();
1480 // FIXME Should warn user
1485 if ( newDocEntry->IsSequenceDelimitor() )
1487 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1491 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1496 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1497 std::ostringstream newBase;
1498 newBase << seqEntry->GetKey()
1502 itemSQ->SetBaseTagKey( newBase.str() );
1503 unsigned int l = newDocEntry->GetReadLength();
1505 if ( l == 0xffffffff )
1514 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1516 seqEntry->AddEntry( itemSQ, SQItemNumber );
1518 if ( !delim_mode && ( Fp->tellg() - offset ) >= l_max )
1526 * \brief Loads the element content if its length doesn't exceed
1527 * the value specified with Document::SetMaxSizeLoadEntry()
1528 * @param entry Header Entry (Dicom Element) to be dealt with
1530 void Document::LoadDocEntry(DocEntry* entry)
1532 uint16_t group = entry->GetGroup();
1533 std::string vr = entry->GetVR();
1534 uint32_t length = entry->GetLength();
1536 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1538 // A SeQuence "contains" a set of Elements.
1539 // (fffe e000) tells us an Element is beginning
1540 // (fffe e00d) tells us an Element just ended
1541 // (fffe e0dd) tells us the current SeQuence just ended
1542 if( group == 0xfffe )
1544 // NO more value field for SQ !
1548 // When the length is zero things are easy:
1551 ((ValEntry *)entry)->SetValue("");
1555 // The elements whose length is bigger than the specified upper bound
1556 // are not loaded. Instead we leave a short notice of the offset of
1557 // the element content and it's length.
1559 std::ostringstream s;
1560 if (length > MaxSizeLoadEntry)
1562 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1564 //s << "gdcm::NotLoaded (BinEntry)";
1565 s << GDCM_NOTLOADED;
1566 s << " Address:" << (long)entry->GetOffset();
1567 s << " Length:" << entry->GetLength();
1568 s << " x(" << std::hex << entry->GetLength() << ")";
1569 binEntryPtr->SetValue(s.str());
1571 // Be carefull : a BinEntry IS_A ValEntry ...
1572 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1574 // s << "gdcm::NotLoaded. (ValEntry)";
1575 s << GDCM_NOTLOADED;
1576 s << " Address:" << (long)entry->GetOffset();
1577 s << " Length:" << entry->GetLength();
1578 s << " x(" << std::hex << entry->GetLength() << ")";
1579 valEntryPtr->SetValue(s.str());
1584 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1585 << "nor a ValEntry ?! Should never print that !" << std::endl;
1588 // to be sure we are at the end of the value ...
1589 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),std::ios_base::beg);
1593 // When we find a BinEntry not very much can be done :
1594 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1596 s << GDCM_BINLOADED;
1597 binEntryPtr->SetValue(s.str());
1598 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1602 /// \todo Any compacter code suggested (?)
1603 if ( IsDocEntryAnInteger(entry) )
1607 // When short integer(s) are expected, read and convert the following
1608 // n *two characters properly i.e. consider them as short integers as
1609 // opposed to strings.
1610 // Elements with Value Multiplicity > 1
1611 // contain a set of integers (not a single one)
1612 if (vr == "US" || vr == "SS")
1615 NewInt = ReadInt16();
1619 for (int i=1; i < nbInt; i++)
1622 NewInt = ReadInt16();
1627 // See above comment on multiple integers (mutatis mutandis).
1628 else if (vr == "UL" || vr == "SL")
1631 NewInt = ReadInt32();
1635 for (int i=1; i < nbInt; i++)
1638 NewInt = ReadInt32();
1643 #ifdef GDCM_NO_ANSI_STRING_STREAM
1644 s << std::ends; // to avoid oddities on Solaris
1645 #endif //GDCM_NO_ANSI_STRING_STREAM
1647 ((ValEntry *)entry)->SetValue(s.str());
1651 // We need an additional byte for storing \0 that is not on disk
1652 char *str = new char[length+1];
1653 Fp->read(str, (size_t)length);
1655 std::string newValue = str;
1658 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1660 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1662 dbg.Verbose(1, "Document::LoadDocEntry",
1663 "unread element value");
1664 valEntry->SetValue(GDCM_UNREAD);
1670 // Because of correspondance with the VR dic
1671 valEntry->SetValue(newValue);
1675 valEntry->SetValue(newValue);
1680 dbg.Error(true, "Document::LoadDocEntry"
1681 "Should have a ValEntry, here !");
1687 * \brief Find the value Length of the passed Header Entry
1688 * @param entry Header Entry whose length of the value shall be loaded.
1690 void Document::FindDocEntryLength( DocEntry *entry )
1691 throw ( FormatError )
1693 uint16_t element = entry->GetElement();
1694 std::string vr = entry->GetVR();
1697 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1699 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1701 // The following reserved two bytes (see PS 3.5-2003, section
1702 // "7.1.2 Data element structure with explicit vr", p 27) must be
1703 // skipped before proceeding on reading the length on 4 bytes.
1704 Fp->seekg( 2L, std::ios_base::cur);
1705 uint32_t length32 = ReadInt32();
1707 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1712 /// \todo rename that to FindDocEntryLengthOBOrOW since
1713 /// the above test is on both OB and OW...
1714 lengthOB = FindDocEntryLengthOB();
1716 catch ( FormatUnexpected )
1718 // Computing the length failed (this happens with broken
1719 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1720 // chance to get the pixels by deciding the element goes
1721 // until the end of the file. Hence we artificially fix the
1722 // the length and proceed.
1723 long currentPosition = Fp->tellg();
1724 Fp->seekg(0L,std::ios_base::end);
1725 long lengthUntilEOF = Fp->tellg() - currentPosition;
1726 Fp->seekg(currentPosition, std::ios_base::beg);
1727 entry->SetLength(lengthUntilEOF);
1730 entry->SetLength(lengthOB);
1733 FixDocEntryFoundLength(entry, length32);
1737 // Length is encoded on 2 bytes.
1738 length16 = ReadInt16();
1740 // We can tell the current file is encoded in big endian (like
1741 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1742 // and it's value is the one of the encoding of a big endian file.
1743 // In order to deal with such big endian encoded files, we have
1744 // (at least) two strategies:
1745 // * when we load the "Transfer Syntax" tag with value of big endian
1746 // encoding, we raise the proper flags. Then we wait for the end
1747 // of the META group (0x0002) among which is "Transfer Syntax",
1748 // before switching the swap code to big endian. We have to postpone
1749 // the switching of the swap code since the META group is fully encoded
1750 // in little endian, and big endian coding only starts at the next
1751 // group. The corresponding code can be hard to analyse and adds
1752 // many additional unnecessary tests for regular tags.
1753 // * the second strategy consists in waiting for trouble, that shall
1754 // appear when we find the first group with big endian encoding. This
1755 // is easy to detect since the length of a "Group Length" tag (the
1756 // ones with zero as element number) has to be of 4 (0x0004). When we
1757 // encounter 1024 (0x0400) chances are the encoding changed and we
1758 // found a group with big endian encoding.
1759 // We shall use this second strategy. In order to make sure that we
1760 // can interpret the presence of an apparently big endian encoded
1761 // length of a "Group Length" without committing a big mistake, we
1762 // add an additional check: we look in the already parsed elements
1763 // for the presence of a "Transfer Syntax" whose value has to be "big
1764 // endian encoding". When this is the case, chances are we have got our
1765 // hands on a big endian encoded file: we switch the swap code to
1766 // big endian and proceed...
1767 if ( element == 0x0000 && length16 == 0x0400 )
1769 TransferSyntaxType ts = GetTransferSyntax();
1770 if ( ts != ExplicitVRBigEndian )
1772 throw FormatError( "Document::FindDocEntryLength()",
1773 " not explicit VR." );
1777 SwitchSwapToBigEndian();
1778 // Restore the unproperly loaded values i.e. the group, the element
1779 // and the dictionary entry depending on them.
1780 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1781 uint16_t correctElem = SwapShort( entry->GetElement() );
1782 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1786 // This correct tag is not in the dictionary. Create a new one.
1787 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1789 // FIXME this can create a memory leaks on the old entry that be
1790 // left unreferenced.
1791 entry->SetDictEntry( newTag );
1794 // Heuristic: well, some files are really ill-formed.
1795 if ( length16 == 0xffff)
1797 // 0xffff means that we deal with 'Unknown Length' Sequence
1800 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1805 // Either implicit VR or a non DICOM conformal (see note below) explicit
1806 // VR that ommited the VR of (at least) this element. Farts happen.
1807 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1808 // on Data elements "Implicit and Explicit VR Data Elements shall
1809 // not coexist in a Data Set and Data Sets nested within it".]
1810 // Length is on 4 bytes.
1812 FixDocEntryFoundLength( entry, ReadInt32() );
1818 * \brief Find the Value Representation of the current Dicom Element.
1821 void Document::FindDocEntryVR( DocEntry *entry )
1823 if ( Filetype != ExplicitVR )
1830 long positionOnEntry = Fp->tellg();
1831 // Warning: we believe this is explicit VR (Value Representation) because
1832 // we used a heuristic that found "UL" in the first tag. Alas this
1833 // doesn't guarantee that all the tags will be in explicit VR. In some
1834 // cases (see e-film filtered files) one finds implicit VR tags mixed
1835 // within an explicit VR file. Hence we make sure the present tag
1836 // is in explicit VR and try to fix things if it happens not to be
1839 Fp->read (vr, (size_t)2);
1842 if( !CheckDocEntryVR(entry, vr) )
1844 Fp->seekg(positionOnEntry, std::ios_base::beg);
1845 // When this element is known in the dictionary we shall use, e.g. for
1846 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1847 // dictionary entry. Still we have to flag the element as implicit since
1848 // we know now our assumption on expliciteness is not furfilled.
1850 if ( entry->IsVRUnknown() )
1852 entry->SetVR("Implicit");
1854 entry->SetImplicitVR();
1859 * \brief Check the correspondance between the VR of the header entry
1860 * and the taken VR. If they are different, the header entry is
1861 * updated with the new VR.
1862 * @param entry Header Entry to check
1863 * @param vr Dicom Value Representation
1864 * @return false if the VR is incorrect of if the VR isn't referenced
1865 * otherwise, it returns true
1867 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1870 bool realExplicit = true;
1872 // Assume we are reading a falsely explicit VR file i.e. we reached
1873 // a tag where we expect reading a VR but are in fact we read the
1874 // first to bytes of the length. Then we will interogate (through find)
1875 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1876 // both GCC and VC++ implementations of the STL map. Hence when the
1877 // expected VR read happens to be non-ascii characters we consider
1878 // we hit falsely explicit VR tag.
1880 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1882 realExplicit = false;
1885 // CLEANME searching the dicom_vr at each occurence is expensive.
1886 // PostPone this test in an optional integrity check at the end
1887 // of parsing or only in debug mode.
1888 if ( realExplicit && !Global::GetVR()->Count(vr) )
1890 realExplicit = false;
1893 if ( !realExplicit )
1895 // We thought this was explicit VR, but we end up with an
1896 // implicit VR tag. Let's backtrack.
1897 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1898 entry->GetGroup(), entry->GetElement());
1899 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1901 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1903 // Group length is UL !
1904 DictEntry* newEntry = NewVirtualDictEntry(
1905 entry->GetGroup(), entry->GetElement(),
1906 "UL", "FIXME", "Group Length");
1907 entry->SetDictEntry( newEntry );
1912 if ( entry->IsVRUnknown() )
1914 // When not a dictionary entry, we can safely overwrite the VR.
1915 if( entry->GetElement() == 0x0000 )
1917 // Group length is UL !
1925 else if ( entry->GetVR() != vr )
1927 // The VR present in the file and the dictionary disagree. We assume
1928 // the file writer knew best and use the VR of the file. Since it would
1929 // be unwise to overwrite the VR of a dictionary (since it would
1930 // compromise it's next user), we need to clone the actual DictEntry
1931 // and change the VR for the read one.
1932 DictEntry* newEntry = NewVirtualDictEntry(
1933 entry->GetGroup(), entry->GetElement(),
1934 vr, "FIXME", entry->GetName());
1935 entry->SetDictEntry(newEntry);
1942 * \brief Get the transformed value of the header entry. The VR value
1943 * is used to define the transformation to operate on the value
1944 * \warning NOT end user intended method !
1945 * @param entry entry to tranform
1946 * @return Transformed entry value
1948 std::string Document::GetDocEntryValue(DocEntry *entry)
1950 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1952 std::string val = ((ValEntry *)entry)->GetValue();
1953 std::string vr = entry->GetVR();
1954 uint32_t length = entry->GetLength();
1955 std::ostringstream s;
1958 // When short integer(s) are expected, read and convert the following
1959 // n * 2 bytes properly i.e. as a multivaluated strings
1960 // (each single value is separated fromthe next one by '\'
1961 // as usual for standard multivaluated filels
1962 // Elements with Value Multiplicity > 1
1963 // contain a set of short integers (not a single one)
1965 if( vr == "US" || vr == "SS" )
1970 for (int i=0; i < nbInt; i++)
1976 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1977 newInt16 = SwapShort( newInt16 );
1982 // When integer(s) are expected, read and convert the following
1983 // n * 4 bytes properly i.e. as a multivaluated strings
1984 // (each single value is separated fromthe next one by '\'
1985 // as usual for standard multivaluated filels
1986 // Elements with Value Multiplicity > 1
1987 // contain a set of integers (not a single one)
1988 else if( vr == "UL" || vr == "SL" )
1993 for (int i=0; i < nbInt; i++)
1999 newInt32 = ( val[4*i+0] & 0xFF )
2000 + (( val[4*i+1] & 0xFF ) << 8 )
2001 + (( val[4*i+2] & 0xFF ) << 16 )
2002 + (( val[4*i+3] & 0xFF ) << 24 );
2003 newInt32 = SwapLong( newInt32 );
2007 #ifdef GDCM_NO_ANSI_STRING_STREAM
2008 s << std::ends; // to avoid oddities on Solaris
2009 #endif //GDCM_NO_ANSI_STRING_STREAM
2013 return ((ValEntry *)entry)->GetValue();
2017 * \brief Get the reverse transformed value of the header entry. The VR
2018 * value is used to define the reverse transformation to operate on
2020 * \warning NOT end user intended method !
2021 * @param entry Entry to reverse transform
2022 * @return Reverse transformed entry value
2024 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2026 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2028 std::string vr = entry->GetVR();
2029 std::vector<std::string> tokens;
2030 std::ostringstream s;
2032 if ( vr == "US" || vr == "SS" )
2036 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2037 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2038 for (unsigned int i=0; i<tokens.size(); i++)
2040 newInt16 = atoi(tokens[i].c_str());
2041 s << ( newInt16 & 0xFF )
2042 << (( newInt16 >> 8 ) & 0xFF );
2046 if ( vr == "UL" || vr == "SL")
2050 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2051 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2052 for (unsigned int i=0; i<tokens.size();i++)
2054 newInt32 = atoi(tokens[i].c_str());
2055 s << (char)( newInt32 & 0xFF )
2056 << (char)(( newInt32 >> 8 ) & 0xFF )
2057 << (char)(( newInt32 >> 16 ) & 0xFF )
2058 << (char)(( newInt32 >> 24 ) & 0xFF );
2063 #ifdef GDCM_NO_ANSI_STRING_STREAM
2064 s << std::ends; // to avoid oddities on Solaris
2065 #endif //GDCM_NO_ANSI_STRING_STREAM
2069 return ((ValEntry *)entry)->GetValue();
2073 * \brief Skip a given Header Entry
2074 * \warning NOT end user intended method !
2075 * @param entry entry to skip
2077 void Document::SkipDocEntry(DocEntry *entry)
2079 SkipBytes(entry->GetLength());
2083 * \brief Skips to the begining of the next Header Entry
2084 * \warning NOT end user intended method !
2085 * @param entry entry to skip
2087 void Document::SkipToNextDocEntry(DocEntry *entry)
2089 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2090 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2094 * \brief When the length of an element value is obviously wrong (because
2095 * the parser went Jabberwocky) one can hope improving things by
2096 * applying some heuristics.
2097 * @param entry entry to check
2098 * @param foundLength fist assumption about length
2100 void Document::FixDocEntryFoundLength(DocEntry *entry,
2101 uint32_t foundLength)
2103 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2104 if ( foundLength == 0xffffffff)
2109 uint16_t gr = entry->GetGroup();
2110 uint16_t el = entry->GetElement();
2112 if ( foundLength % 2)
2114 std::ostringstream s;
2115 s << "Warning : Tag with uneven length "
2117 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2118 dbg.Verbose(0, s.str().c_str());
2121 //////// Fix for some naughty General Electric images.
2122 // Allthough not recent many such GE corrupted images are still present
2123 // on Creatis hard disks. Hence this fix shall remain when such images
2124 // are no longer in user (we are talking a few years, here)...
2125 // Note: XMedCom probably uses such a trick since it is able to read
2126 // those pesky GE images ...
2127 if ( foundLength == 13)
2129 // Only happens for this length !
2130 if ( entry->GetGroup() != 0x0008
2131 || ( entry->GetElement() != 0x0070
2132 && entry->GetElement() != 0x0080 ) )
2135 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2139 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2140 // Occurence of such images is quite low (unless one leaves close to a
2141 // 'Leonardo' source. Hence, one might consider commenting out the
2142 // following fix on efficiency reasons.
2143 else if ( entry->GetGroup() == 0x0009
2144 && ( entry->GetElement() == 0x1113
2145 || entry->GetElement() == 0x1114 ) )
2148 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2151 else if ( entry->GetVR() == "SQ" )
2153 foundLength = 0; // ReadLength is unchanged
2156 //////// We encountered a 'delimiter' element i.e. a tag of the form
2157 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2158 // taken into account.
2159 else if( entry->GetGroup() == 0xfffe )
2161 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2162 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2163 // causes extra troubles...
2164 if( entry->GetElement() != 0x0000 )
2170 entry->SetUsableLength(foundLength);
2174 * \brief Apply some heuristics to predict whether the considered
2175 * element value contains/represents an integer or not.
2176 * @param entry The element value on which to apply the predicate.
2177 * @return The result of the heuristical predicate.
2179 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2181 uint16_t element = entry->GetElement();
2182 uint16_t group = entry->GetGroup();
2183 std::string vr = entry->GetVR();
2184 uint32_t length = entry->GetLength();
2186 // When we have some semantics on the element we just read, and if we
2187 // a priori know we are dealing with an integer, then we shall be
2188 // able to swap it's element value properly.
2189 if ( element == 0 ) // This is the group length of the group
2197 // Allthough this should never happen, still some images have a
2198 // corrupted group length [e.g. have a glance at offset x(8336) of
2199 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2200 // Since for dicom compliant and well behaved headers, the present
2201 // test is useless (and might even look a bit paranoid), when we
2202 // encounter such an ill-formed image, we simply display a warning
2203 // message and proceed on parsing (while crossing fingers).
2204 std::ostringstream s;
2205 long filePosition = Fp->tellg();
2206 s << "Erroneous Group Length element length on : (" \
2207 << std::hex << group << " , " << element
2208 << ") -before- position x(" << filePosition << ")"
2209 << "lgt : " << length;
2210 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2214 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2223 * \brief Find the Length till the next sequence delimiter
2224 * \warning NOT end user intended method !
2228 uint32_t Document::FindDocEntryLengthOB()
2229 throw( FormatUnexpected )
2231 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2232 long positionOnEntry = Fp->tellg();
2233 bool foundSequenceDelimiter = false;
2234 uint32_t totalLength = 0;
2236 while ( !foundSequenceDelimiter )
2242 group = ReadInt16();
2245 catch ( FormatError )
2247 throw FormatError("Document::FindDocEntryLengthOB()",
2248 " group or element not present.");
2251 // We have to decount the group and element we just read
2254 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2256 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2257 "tag nor a Sequence delimiter tag.");
2258 Fp->seekg(positionOnEntry, std::ios_base::beg);
2259 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2260 "Neither an Item tag nor a Sequence "
2264 if ( elem == 0xe0dd )
2266 foundSequenceDelimiter = true;
2269 uint32_t itemLength = ReadInt32();
2270 // We add 4 bytes since we just read the ItemLength with ReadInt32
2271 totalLength += itemLength + 4;
2272 SkipBytes(itemLength);
2274 if ( foundSequenceDelimiter )
2279 Fp->seekg( positionOnEntry, std::ios_base::beg);
2284 * \brief Reads a supposed to be 16 Bits integer
2285 * (swaps it depending on processor endianity)
2286 * @return read value
2288 uint16_t Document::ReadInt16()
2289 throw( FormatError )
2292 Fp->read ((char*)&g, (size_t)2);
2295 throw FormatError( "Document::ReadInt16()", " file error." );
2299 throw FormatError( "Document::ReadInt16()", "EOF." );
2306 * \brief Reads a supposed to be 32 Bits integer
2307 * (swaps it depending on processor endianity)
2308 * @return read value
2310 uint32_t Document::ReadInt32()
2311 throw( FormatError )
2314 Fp->read ((char*)&g, (size_t)4);
2317 throw FormatError( "Document::ReadInt32()", " file error." );
2321 throw FormatError( "Document::ReadInt32()", "EOF." );
2328 * \brief skips bytes inside the source file
2329 * \warning NOT end user intended method !
2332 void Document::SkipBytes(uint32_t nBytes)
2334 //FIXME don't dump the returned value
2335 Fp->seekg((long)nBytes, std::ios_base::cur);
2339 * \brief Loads all the needed Dictionaries
2340 * \warning NOT end user intended method !
2342 void Document::Initialise()
2344 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2346 RLEInfo = new RLEFramesInfo;
2347 JPEGInfo = new JPEGFragmentsInfo;
2351 * \brief Discover what the swap code is (among little endian, big endian,
2352 * bad little endian, bad big endian).
2354 * @return false when we are absolutely sure
2355 * it's neither ACR-NEMA nor DICOM
2356 * true when we hope ours assuptions are OK
2358 bool Document::CheckSwap()
2360 // The only guaranted way of finding the swap code is to find a
2361 // group tag since we know it's length has to be of four bytes i.e.
2362 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2363 // occurs when we can't find such group...
2365 uint32_t x = 4; // x : for ntohs
2366 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2370 char deb[HEADER_LENGTH_TO_READ];
2372 // First, compare HostByteOrder and NetworkByteOrder in order to
2373 // determine if we shall need to swap bytes (i.e. the Endian type).
2374 if ( x == ntohs(x) )
2383 // The easiest case is the one of a DICOM header, since it possesses a
2384 // file preamble where it suffice to look for the string "DICM".
2385 Fp->read(deb, HEADER_LENGTH_TO_READ);
2387 char *entCur = deb + 128;
2388 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2390 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2392 // Next, determine the value representation (VR). Let's skip to the
2393 // first element (0002, 0000) and check there if we find "UL"
2394 // - or "OB" if the 1st one is (0002,0001) -,
2395 // in which case we (almost) know it is explicit VR.
2396 // WARNING: if it happens to be implicit VR then what we will read
2397 // is the length of the group. If this ascii representation of this
2398 // length happens to be "UL" then we shall believe it is explicit VR.
2399 // FIXME: in order to fix the above warning, we could read the next
2400 // element value (or a couple of elements values) in order to make
2401 // sure we are not commiting a big mistake.
2402 // We need to skip :
2403 // * the 128 bytes of File Preamble (often padded with zeroes),
2404 // * the 4 bytes of "DICM" string,
2405 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2406 // i.e. a total of 136 bytes.
2410 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2411 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2412 // *Implicit* VR. -and it is !-
2414 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2415 memcmp(entCur, "OB", (size_t)2) == 0 ||
2416 memcmp(entCur, "UI", (size_t)2) == 0 ||
2417 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2418 // when Write DCM *adds*
2420 // Use Document::dicom_vr to test all the possibilities
2421 // instead of just checking for UL, OB and UI !? group 0000
2423 Filetype = ExplicitVR;
2424 dbg.Verbose(1, "Document::CheckSwap:",
2425 "explicit Value Representation");
2429 Filetype = ImplicitVR;
2430 dbg.Verbose(1, "Document::CheckSwap:",
2431 "not an explicit Value Representation");
2437 dbg.Verbose(1, "Document::CheckSwap:",
2438 "HostByteOrder != NetworkByteOrder");
2443 dbg.Verbose(1, "Document::CheckSwap:",
2444 "HostByteOrder = NetworkByteOrder");
2447 // Position the file position indicator at first tag (i.e.
2448 // after the file preamble and the "DICM" string).
2449 Fp->seekg(0, std::ios_base::beg);
2450 Fp->seekg ( 132L, std::ios_base::beg);
2454 // Alas, this is not a DicomV3 file and whatever happens there is no file
2455 // preamble. We can reset the file position indicator to where the data
2456 // is (i.e. the beginning of the file).
2457 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2458 Fp->seekg(0, std::ios_base::beg);
2460 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2461 // By clean we mean that the length of the first tag is written down.
2462 // If this is the case and since the length of the first group HAS to be
2463 // four (bytes), then determining the proper swap code is straightforward.
2466 // We assume the array of char we are considering contains the binary
2467 // representation of a 32 bits integer. Hence the following dirty
2469 s32 = *((uint32_t *)(entCur));
2490 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2491 // It is time for despaired wild guesses.
2492 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2493 // i.e. the 'group length' element is not present :
2495 // check the supposed to be 'group number'
2496 // 0x0002 or 0x0004 or 0x0008
2497 // to determine ' SwapCode' value .
2498 // Only 0 or 4321 will be possible
2499 // (no oportunity to check for the formerly well known
2500 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2501 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2502 // the file IS NOT ACR-NEMA nor DICOM V3
2503 // Find a trick to tell it the caller...
2505 s16 = *((uint16_t *)(deb));
2522 dbg.Verbose(0, "Document::CheckSwap:",
2523 "ACR/NEMA unfound swap info (Really hopeless !)");
2527 // Then the only info we have is the net2host one.
2537 * \brief Restore the unproperly loaded values i.e. the group, the element
2538 * and the dictionary entry depending on them.
2540 void Document::SwitchSwapToBigEndian()
2542 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2543 "Switching to BigEndian mode.");
2544 if ( SwapCode == 0 )
2548 else if ( SwapCode == 4321 )
2552 else if ( SwapCode == 3412 )
2556 else if ( SwapCode == 2143 )
2563 * \brief during parsing, Header Elements too long are not loaded in memory
2566 void Document::SetMaxSizeLoadEntry(long newSize)
2572 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2574 MaxSizeLoadEntry = 0xffffffff;
2577 MaxSizeLoadEntry = newSize;
2582 * \brief Header Elements too long will not be printed
2583 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2586 void Document::SetMaxSizePrintEntry(long newSize)
2588 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2593 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2595 MaxSizePrintEntry = 0xffffffff;
2598 MaxSizePrintEntry = newSize;
2604 * \brief Read the next tag but WITHOUT loading it's value
2605 * (read the 'Group Number', the 'Element Number',
2606 * gets the Dict Entry
2607 * gets the VR, gets the length, gets the offset value)
2608 * @return On succes the newly created DocEntry, NULL on failure.
2610 DocEntry* Document::ReadNextDocEntry()
2617 group = ReadInt16();
2620 catch ( FormatError e )
2622 // We reached the EOF (or an error occured) therefore
2623 // header parsing has to be considered as finished.
2628 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2629 FindDocEntryVR(newEntry);
2633 FindDocEntryLength(newEntry);
2635 catch ( FormatError e )
2643 newEntry->SetOffset(Fp->tellg());
2650 * \brief Generate a free TagKey i.e. a TagKey that is not present
2651 * in the TagHt dictionary.
2652 * @param group The generated tag must belong to this group.
2653 * @return The element of tag with given group which is fee.
2655 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2657 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2659 TagKey key = DictEntry::TranslateToKey(group, elem);
2660 if (TagHT.count(key) == 0)
2669 * \brief Assuming the internal file pointer \ref Document::Fp
2670 * is placed at the beginning of a tag check whether this
2671 * tag is (TestGroup, TestElement).
2672 * \warning On success the internal file pointer \ref Document::Fp
2673 * is modified to point after the tag.
2674 * On failure (i.e. when the tag wasn't the expected tag
2675 * (TestGroup, TestElement) the internal file pointer
2676 * \ref Document::Fp is restored to it's original position.
2677 * @param testGroup The expected group of the tag.
2678 * @param testElement The expected Element of the tag.
2679 * @return True on success, false otherwise.
2681 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2683 long positionOnEntry = Fp->tellg();
2684 long currentPosition = Fp->tellg(); // On debugging purposes
2686 //// Read the Item Tag group and element, and make
2687 // sure they are what we expected:
2688 uint16_t itemTagGroup;
2689 uint16_t itemTagElement;
2692 itemTagGroup = ReadInt16();
2693 itemTagElement = ReadInt16();
2695 catch ( FormatError e )
2697 //std::cerr << e << std::endl;
2700 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2702 std::ostringstream s;
2703 s << " We should have found tag (";
2704 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2705 s << " but instead we encountered tag (";
2706 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2708 s << " at address: " << (unsigned)currentPosition << std::endl;
2709 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2710 dbg.Verbose(0, s.str().c_str());
2711 Fp->seekg(positionOnEntry, std::ios_base::beg);
2719 * \brief Assuming the internal file pointer \ref Document::Fp
2720 * is placed at the beginning of a tag (TestGroup, TestElement),
2721 * read the length associated to the Tag.
2722 * \warning On success the internal file pointer \ref Document::Fp
2723 * is modified to point after the tag and it's length.
2724 * On failure (i.e. when the tag wasn't the expected tag
2725 * (TestGroup, TestElement) the internal file pointer
2726 * \ref Document::Fp is restored to it's original position.
2727 * @param testGroup The expected group of the tag.
2728 * @param testElement The expected Element of the tag.
2729 * @return On success returns the length associated to the tag. On failure
2732 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2734 long positionOnEntry = Fp->tellg();
2735 (void)positionOnEntry;
2737 if ( !ReadTag(testGroup, testElement) )
2742 //// Then read the associated Item Length
2743 long currentPosition = Fp->tellg();
2744 uint32_t itemLength = ReadInt32();
2746 std::ostringstream s;
2747 s << "Basic Item Length is: "
2748 << itemLength << std::endl;
2749 s << " at address: " << (unsigned)currentPosition << std::endl;
2750 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2756 * \brief When parsing the Pixel Data of an encapsulated file, read
2757 * the basic offset table (when present, and BTW dump it).
2759 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2761 //// Read the Basic Offset Table Item Tag length...
2762 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2764 // When present, read the basic offset table itself.
2765 // Notes: - since the presence of this basic offset table is optional
2766 // we can't rely on it for the implementation, and we will simply
2767 // trash it's content (when present).
2768 // - still, when present, we could add some further checks on the
2769 // lengths, but we won't bother with such fuses for the time being.
2770 if ( itemLength != 0 )
2772 char* basicOffsetTableItemValue = new char[itemLength + 1];
2773 Fp->read(basicOffsetTableItemValue, itemLength);
2776 for (unsigned int i=0; i < itemLength; i += 4 )
2778 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2780 std::ostringstream s;
2781 s << " Read one length: ";
2782 s << std::hex << individualLength << std::endl;
2784 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2789 delete[] basicOffsetTableItemValue;
2794 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2795 * Compute the RLE extra information and store it in \ref RLEInfo
2796 * for later pixel retrieval usage.
2798 void Document::ComputeRLEInfo()
2800 TransferSyntaxType ts = GetTransferSyntax();
2801 if ( ts != RLELossless )
2806 // Encoded pixel data: for the time being we are only concerned with
2807 // Jpeg or RLE Pixel data encodings.
2808 // As stated in PS 3.5-2003, section 8.2 p44:
2809 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2810 // value representation OB is used".
2811 // Hence we expect an OB value representation. Concerning OB VR,
2812 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2813 // "For the Value Representations OB and OW, the encoding shall meet the
2814 // following specifications depending on the Data element tag:"
2816 // - the first item in the sequence of items before the encoded pixel
2817 // data stream shall be basic offset table item. The basic offset table
2818 // item value, however, is not required to be present"
2820 ReadAndSkipEncapsulatedBasicOffsetTable();
2822 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2823 // Loop on the individual frame[s] and store the information
2824 // on the RLE fragments in a RLEFramesInfo.
2825 // Note: - when only a single frame is present, this is a
2827 // - when more than one frame are present, then we are in
2828 // the case of a multi-frame image.
2830 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2832 // Parse the RLE Header and store the corresponding RLE Segment
2833 // Offset Table information on fragments of this current Frame.
2834 // Note that the fragment pixels themselves are not loaded
2835 // (but just skipped).
2836 long frameOffset = Fp->tellg();
2838 uint32_t nbRleSegments = ReadInt32();
2839 if ( nbRleSegments > 16 )
2841 // There should be at most 15 segments (refer to RLEFrame class)
2842 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2845 uint32_t rleSegmentOffsetTable[15];
2846 for( int k = 1; k <= 15; k++ )
2848 rleSegmentOffsetTable[k] = ReadInt32();
2851 // Deduce from both the RLE Header and the frameLength the
2852 // fragment length, and again store this info in a
2854 long rleSegmentLength[15];
2855 // skipping (not reading) RLE Segments
2856 if ( nbRleSegments > 1)
2858 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2860 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2861 - rleSegmentOffsetTable[k];
2862 SkipBytes(rleSegmentLength[k]);
2866 rleSegmentLength[nbRleSegments] = frameLength
2867 - rleSegmentOffsetTable[nbRleSegments];
2868 SkipBytes(rleSegmentLength[nbRleSegments]);
2870 // Store the collected info
2871 RLEFrame* newFrameInfo = new RLEFrame;
2872 newFrameInfo->NumberFragments = nbRleSegments;
2873 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2875 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2876 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2878 RLEInfo->Frames.push_back( newFrameInfo );
2881 // Make sure that at the end of the item we encounter a 'Sequence
2883 if ( !ReadTag(0xfffe, 0xe0dd) )
2885 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2886 dbg.Verbose(0, " item at end of RLE item sequence");
2891 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2892 * Compute the jpeg extra information (fragment[s] offset[s] and
2893 * length) and store it[them] in \ref JPEGInfo for later pixel
2896 void Document::ComputeJPEGFragmentInfo()
2898 // If you need to, look for comments of ComputeRLEInfo().
2904 ReadAndSkipEncapsulatedBasicOffsetTable();
2906 // Loop on the fragments[s] and store the parsed information in a
2908 long fragmentLength;
2909 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2911 long fragmentOffset = Fp->tellg();
2913 // Store the collected info
2914 JPEGFragment* newFragment = new JPEGFragment;
2915 newFragment->Offset = fragmentOffset;
2916 newFragment->Length = fragmentLength;
2917 JPEGInfo->Fragments.push_back( newFragment );
2919 SkipBytes( fragmentLength );
2922 // Make sure that at the end of the item we encounter a 'Sequence
2924 if ( !ReadTag(0xfffe, 0xe0dd) )
2926 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2927 dbg.Verbose(0, " item at end of JPEG item sequence");
2932 * \brief Walk recursively the given \ref DocEntrySet, and feed
2933 * the given hash table (\ref TagDocEntryHT) with all the
2934 * \ref DocEntry (Dicom entries) encountered.
2935 * This method does the job for \ref BuildFlatHashTable.
2936 * @param builtHT Where to collect all the \ref DocEntry encountered
2937 * when recursively walking the given set.
2938 * @param set The structure to be traversed (recursively).
2940 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2943 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
2945 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
2946 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2947 i != currentHT.end();
2950 DocEntry* entry = i->second;
2951 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
2953 const ListSQItem& items = seqEntry->GetSQItems();
2954 for( ListSQItem::const_iterator item = items.begin();
2955 item != items.end();
2958 BuildFlatHashTableRecurse( builtHT, *item );
2962 builtHT[entry->GetKey()] = entry;
2967 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
2969 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2970 for (ListDocEntry::const_iterator i = currentList.begin();
2971 i != currentList.end();
2974 DocEntry* entry = *i;
2975 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
2977 const ListSQItem& items = seqEntry->GetSQItems();
2978 for( ListSQItem::const_iterator item = items.begin();
2979 item != items.end();
2982 BuildFlatHashTableRecurse( builtHT, *item );
2986 builtHT[entry->GetKey()] = entry;
2993 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2996 * The structure used by a Document (through \ref ElementSet),
2997 * in order to old the parsed entries of a Dicom header, is a recursive
2998 * one. This is due to the fact that the sequences (when present)
2999 * can be nested. Additionaly, the sequence items (represented in
3000 * gdcm as \ref SQItem) add an extra complexity to the data
3001 * structure. Hence, a gdcm user whishing to visit all the entries of
3002 * a Dicom header will need to dig in the gdcm internals (which
3003 * implies exposing all the internal data structures to the API).
3004 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3005 * recursively builds a temporary hash table, which holds all the
3006 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3008 * \warning Of course there is NO integrity constrain between the
3009 * returned \ref TagDocEntryHT and the \ref ElementSet used
3010 * to build it. Hence if the underlying \ref ElementSet is
3011 * altered, then it is the caller responsability to invoke
3012 * \ref BuildFlatHashTable again...
3013 * @return The flat std::map<> we juste build.
3015 TagDocEntryHT* Document::BuildFlatHashTable()
3017 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3018 BuildFlatHashTableRecurse( *FlatHT, this );
3025 * \brief Compares two documents, according to \ref DicomDir rules
3026 * \warning Does NOT work with ACR-NEMA files
3027 * \todo Find a trick to solve the pb (use RET fields ?)
3029 * @return true if 'smaller'
3031 bool Document::operator<(Document &document)
3034 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3035 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3047 s1 = GetEntryByNumber(0x0010,0x0020);
3048 s2 = document.GetEntryByNumber(0x0010,0x0020);
3059 // Study Instance UID
3060 s1 = GetEntryByNumber(0x0020,0x000d);
3061 s2 = document.GetEntryByNumber(0x0020,0x000d);
3072 // Serie Instance UID
3073 s1 = GetEntryByNumber(0x0020,0x000e);
3074 s2 = document.GetEntryByNumber(0x0020,0x000e);
3089 } // end namespace gdcm
3091 //-----------------------------------------------------------------------------