1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/16 17:31:39 $
7 Version: $Revision: 1.131 $
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 // 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);
99 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
101 Fp->seekg( 0, std::ios_base::beg);
103 Fp->seekg(0, std::ios_base::end);
104 long lgt = Fp->tellg();
106 Fp->seekg( 0, std::ios_base::beg);
108 long beg = Fp->tellg();
111 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 Fp->seekg( 0, std::ios_base::beg);
115 // Load 'non string' values
117 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
118 if( PhotometricInterpretation == "PALETTE COLOR " )
120 LoadEntryBinArea(0x0028,0x1200); // gray LUT
121 /// FIXME FIXME FIXME
122 /// The tags refered by the three following lines used to be CORRECTLY
123 /// defined as having an US Value Representation in the public
124 /// dictionnary. BUT the semantics implied by the three following
125 /// lines state that the corresponding tag contents are in fact
126 /// the ones of a BinEntry.
127 /// In order to fix things "Quick and Dirty" the dictionnary was
128 /// altered on PURPOUS but now contains a WRONG value.
129 /// In order to fix things and restore the dictionary to its
130 /// correct value, one needs to decided of the semantics by deciding
131 /// wether the following tags are either:
132 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
133 /// also used as BinEntry, which requires the proper conversion,
134 /// - OW, and hence loaded as BinEntry, but afterwards also used
135 /// as ValEntry, which requires the proper conversion.
136 LoadEntryBinArea(0x0028,0x1201); // R LUT
137 LoadEntryBinArea(0x0028,0x1202); // G LUT
138 LoadEntryBinArea(0x0028,0x1203); // B LUT
140 // Segmented Red Palette Color LUT Data
141 LoadEntryBinArea(0x0028,0x1221);
142 // Segmented Green Palette Color LUT Data
143 LoadEntryBinArea(0x0028,0x1222);
144 // Segmented Blue Palette Color LUT Data
145 LoadEntryBinArea(0x0028,0x1223);
147 //FIXME later : how to use it?
148 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
152 // --------------------------------------------------------------
153 // Specific code to allow gdcm to read ACR-LibIDO formated images
154 // Note: ACR-LibIDO is an extension of the ACR standard that was
155 // used at CREATIS. For the time being (say a couple years)
156 // we keep this kludge to allow a smooth move to gdcm for
157 // CREATIS developpers (sorry folks).
159 // if recognition code tells us we deal with a LibIDO image
160 // we switch lineNumber and columnNumber
163 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
164 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
165 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
166 // with "little-endian strings"
168 Filetype = ACR_LIBIDO;
169 std::string rows = GetEntryByNumber(0x0028, 0x0010);
170 std::string columns = GetEntryByNumber(0x0028, 0x0011);
171 SetEntryByNumber(columns, 0x0028, 0x0010);
172 SetEntryByNumber(rows , 0x0028, 0x0011);
174 // ----------------- End of ACR-LibIDO kludge ------------------
176 PrintLevel = 1; // 'Medium' print level by default
180 * \brief This default constructor doesn't parse the file. You should
181 * then invoke \ref Document::SetFileName and then the parsing.
183 Document::Document() : ElementSet(-1)
187 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
190 Filetype = ExplicitVR;
191 PrintLevel = 1; // 'Medium' print level by default
195 * \brief Canonical destructor.
197 Document::~Document ()
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"
292 * \brief Accessor to the Transfer Syntax (when present) of the
293 * current document (it internally handles reading the
294 * value from disk when only parsing occured).
295 * @return The encountered Transfer Syntax of the current document.
297 TransferSyntaxType Document::GetTransferSyntax()
299 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
305 // The entry might be present but not loaded (parsing and loading
306 // happen at different stages): try loading and proceed with check...
307 LoadDocEntrySafe(entry);
308 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
310 std::string transfer = valEntry->GetValue();
311 // The actual transfer (as read from disk) might be padded. We
312 // first need to remove the potential padding. We can make the
313 // weak assumption that padding was not executed with digits...
314 if ( transfer.length() == 0 )
316 // for brain damaged headers
319 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
321 transfer.erase(transfer.length()-1, 1);
323 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
325 if ( TransferSyntaxStrings[i] == transfer )
327 return TransferSyntaxType(i);
334 bool Document::IsJPEGLossless()
336 TransferSyntaxType r = GetTransferSyntax();
337 return r == JPEGFullProgressionProcess10_12
338 || r == JPEGLosslessProcess14
339 || r == JPEGLosslessProcess14_1;
343 * \brief Determines if the Transfer Syntax was already encountered
344 * and if it corresponds to a JPEG2000 one
345 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
348 bool Document::IsJPEG2000()
350 TransferSyntaxType r = GetTransferSyntax();
351 return r == JPEG2000Lossless || r == JPEG2000;
355 * \brief Determines if the Transfer Syntax corresponds to any form
356 * of Jpeg encoded Pixel data.
357 * @return True when any form of JPEG found. False otherwise.
359 bool Document::IsJPEG()
361 TransferSyntaxType r = GetTransferSyntax();
362 return r == JPEGBaselineProcess1
363 || r == JPEGExtendedProcess2_4
364 || r == JPEGExtendedProcess3_5
365 || r == JPEGSpectralSelectionProcess6_8
371 * \brief Determines if the Transfer Syntax corresponds to encapsulated
372 * of encoded Pixel Data (as opposed to native).
373 * @return True when encapsulated. False when native.
375 bool Document::IsEncapsulate()
377 TransferSyntaxType r = GetTransferSyntax();
378 return IsJPEG() || r == RLELossless;
382 * \brief Predicate for dicom version 3 file.
383 * @return True when the file is a dicom version 3.
385 bool Document::IsDicomV3()
387 // Checking if Transfert Syntax exists is enough
388 // Anyway, it's to late check if the 'Preamble' was found ...
389 // And ... would it be a rich idea to check ?
390 // (some 'no Preamble' DICOM images exist !)
391 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
395 * \brief returns the File Type
396 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
397 * @return the FileType code
399 FileType Document::GetFileType()
405 * \brief Tries to open the file \ref Document::Filename and
406 * checks the preamble when existing.
407 * @return The FILE pointer on success.
409 std::ifstream* Document::OpenFile()
411 if (Filename.length() == 0) return 0;
415 "Document::OpenFile is already opened when opening: ",
419 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
424 "Document::OpenFile cannot open file: ",
430 Fp->read((char*)&zero, (size_t)2 );
432 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
434 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
435 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
436 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
437 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
443 Fp->seekg(126L, std::ios_base::cur);
445 Fp->read(dicm, (size_t)4);
446 if( memcmp(dicm, "DICM", 4) == 0 )
453 "Document::OpenFile not DICOM/ACR (missing preamble)",
460 * \brief closes the file
461 * @return TRUE if the close was successfull
463 bool Document::CloseFile()
472 return true; //FIXME how do we detect a non-close ifstream ?
476 * \brief Writes in a file all the Header Entries (Dicom Elements)
477 * @param fp file pointer on an already open file
478 * @param filetype Type of the File to be written
479 * (ACR-NEMA, ExplicitVR, ImplicitVR)
480 * \return Always true.
482 void Document::Write(std::ofstream* fp, FileType filetype)
484 /// \todo move the following lines (and a lot of others, to be written)
485 /// to a future function CheckAndCorrectHeader
486 /// (necessary if user wants to write a DICOM V3 file
487 /// starting from an ACR-NEMA (V2) Header
489 if (filetype == ImplicitVR)
492 Util::DicomString( TransferSyntaxStrings[ImplicitVRLittleEndian] );
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 /// in the following case we have to padd manually with a 0
500 SetEntryLengthByNumber(18, 0x0002, 0x0010);
503 if (filetype == ExplicitVR)
506 Util::DicomString( TransferSyntaxStrings[ExplicitVRLittleEndian] );
507 ReplaceOrCreateByNumber(ts, 0x0002, 0x0010); //LEAK
509 /// \todo Refer to standards on page 21, chapter 6.2
510 /// "Value representation": values with a VR of UI shall be
511 /// padded with a single trailing null
512 /// Dans le cas suivant on doit pader manuellement avec un 0
514 SetEntryLengthByNumber(20, 0x0002, 0x0010);
518 * \todo rewrite later, if really usefull
519 * - 'Group Length' element is optional in DICOM
520 * - but un-updated odd groups lengthes can causes pb
523 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
524 * UpdateGroupLength(false,filetype);
525 * if ( filetype == ACR)
526 * UpdateGroupLength(true,ACR);
529 ElementSet::Write(fp, filetype); // This one is recursive
534 * \brief Modifies the value of a given Header Entry (Dicom Element)
535 * when it exists. Create it with the given value when unexistant.
536 * @param value (string) Value to be set
537 * @param group Group number of the Entry
538 * @param elem Element number of the Entry
539 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
540 * \return pointer to the modified/created Header Entry (NULL when creation
543 ValEntry* Document::ReplaceOrCreateByNumber(
544 std::string const & value,
549 ValEntry* valEntry = 0;
550 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
554 // check if (group,element) DictEntry exists
555 // if it doesn't, create an entry in DictSet::VirtualEntry
558 // Find out if the tag we received is in the dictionaries:
559 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
560 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
563 currentEntry = NewDocEntryByNumber(group, elem, vr);
567 currentEntry = NewDocEntryByNumber(group, elem);
572 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
573 " NewDocEntryByNumber failed.");
577 valEntry = new ValEntry(currentEntry);
580 if ( !AddEntry(valEntry))
583 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
584 " failed allthough this is a creation.");
590 valEntry = dynamic_cast< ValEntry* >(currentEntry);
591 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
592 // then we change it to a ValEntry ?
593 // Shouldn't it be considered as an error ?
595 // We need to promote the DocEntry to a ValEntry:
596 valEntry = new ValEntry(currentEntry);
597 if (!RemoveEntry(currentEntry))
600 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
601 " of previous DocEntry failed.");
604 if ( !AddEntry(valEntry))
607 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
608 " promoted ValEntry failed.");
614 SetEntryByNumber(value, group, elem);
620 * \brief Modifies the value of a given Header Entry (Dicom Element)
621 * when it exists. Create it with the given value when unexistant.
622 * @param binArea (binary) value to be set
623 * @param Group Group number of the Entry
624 * @param Elem Element number of the Entry
625 * \return pointer to the modified/created Header Entry (NULL when creation
628 BinEntry* Document::ReplaceOrCreateByNumber(
635 BinEntry* binEntry = 0;
636 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
640 // check if (group,element) DictEntry exists
641 // if it doesn't, create an entry in DictSet::VirtualEntry
644 // Find out if the tag we received is in the dictionaries:
645 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
646 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
650 currentEntry = NewDocEntryByNumber(group, elem, vr);
654 currentEntry = NewDocEntryByNumber(group, elem);
658 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
659 " NewDocEntryByNumber failed.");
662 binEntry = new BinEntry(currentEntry);
663 if ( !AddEntry(binEntry))
665 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
666 " failed allthough this is a creation.");
671 binEntry = dynamic_cast< BinEntry* >(currentEntry);
672 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
673 // then we change it to a BinEntry ?
674 // Shouldn't it be considered as an error ?
676 // We need to promote the DocEntry to a BinEntry:
677 binEntry = new BinEntry(currentEntry);
678 if (!RemoveEntry(currentEntry))
680 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
681 " of previous DocEntry failed.");
684 if ( !AddEntry(binEntry))
686 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
687 " promoted BinEntry failed.");
693 SetEntryByNumber(binArea, lgth, group, elem);
700 * \brief Modifies the value of a given Header Entry (Dicom Element)
701 * when it exists. Create it when unexistant.
702 * @param Group Group number of the Entry
703 * @param Elem Element number of the Entry
704 * \return pointer to the modified/created SeqEntry (NULL when creation
707 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
710 DocEntry* a = GetDocEntryByNumber( group, elem);
713 a = NewSeqEntryByNumber(group, elem);
719 b = new SeqEntry(a, 1); // FIXME : 1 (Depth)
726 * \brief Set a new value if the invoked element exists
727 * Seems to be useless !!!
728 * @param value new element value
729 * @param group group number of the Entry
730 * @param elem element number of the Entry
733 bool Document::ReplaceIfExistByNumber(std::string const & value,
734 uint16_t group, uint16_t elem )
736 SetEntryByNumber(value, group, elem);
741 //-----------------------------------------------------------------------------
745 * \brief Checks if a given Dicom Element exists within the H table
746 * @param group Group number of the searched Dicom Element
747 * @param element Element number of the searched Dicom Element
748 * @return true is found
750 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
752 const std::string &key = DictEntry::TranslateToKey(group, element );
753 return TagHT.count(key) != 0;
757 * \brief Searches within Header Entries (Dicom Elements) parsed with
758 * the public and private dictionaries
759 * for the element value of a given tag.
760 * \warning Don't use any longer : use GetPubEntryByName
761 * @param tagName name of the searched element.
762 * @return Corresponding element value when it exists,
763 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
765 std::string Document::GetEntryByName(TagName const & tagName)
767 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
773 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
777 * \brief Searches within Header Entries (Dicom Elements) parsed with
778 * the public and private dictionaries
779 * for the element value representation of a given tag.
781 * Obtaining the VR (Value Representation) might be needed by caller
782 * to convert the string typed content to caller's native type
783 * (think of C++ vs Python). The VR is actually of a higher level
784 * of semantics than just the native C++ type.
785 * @param tagName name of the searched element.
786 * @return Corresponding element value representation when it exists,
787 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
789 std::string Document::GetEntryVRByName(TagName const& tagName)
791 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
792 if( dictEntry == NULL)
797 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
798 dictEntry->GetElement());
799 return elem->GetVR();
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.
806 * @param group Group number of the searched tag.
807 * @param element Element number of the searched tag.
808 * @return Corresponding element value representation when it exists,
809 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
811 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
813 TagKey key = DictEntry::TranslateToKey(group, element);
814 /// \todo use map methods, instead of multimap JPR
815 if ( !TagHT.count(key))
820 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
824 * \brief Searches within Header Entries (Dicom Elements) parsed with
825 * the public and private dictionaries
826 * for the element value representation of a given tag..
828 * Obtaining the VR (Value Representation) might be needed by caller
829 * to convert the string typed content to caller's native type
830 * (think of C++ vs Python). The VR is actually of a higher level
831 * of semantics than just the native C++ type.
832 * @param group Group number of the searched tag.
833 * @param element Element number of the searched tag.
834 * @return Corresponding element value representation when it exists,
835 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
837 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
839 DocEntry* elem = GetDocEntryByNumber(group, element);
844 return elem->GetVR();
848 * \brief Searches within Header Entries (Dicom Elements) parsed with
849 * the public and private dictionaries
850 * for the value length of a given tag..
851 * @param group Group number of the searched tag.
852 * @param element Element number of the searched tag.
853 * @return Corresponding element length; -2 if not found
855 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
857 DocEntry* elem = GetDocEntryByNumber(group, element);
860 return -2; //magic number
862 return elem->GetLength();
865 * \brief Sets the value (string) of the Header Entry (Dicom Element)
866 * @param content string value of the Dicom Element
867 * @param tagName name of the searched Dicom Element.
868 * @return true when found
870 bool Document::SetEntryByName( std::string const & content,
871 TagName const & tagName)
873 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
879 return SetEntryByNumber(content,dictEntry->GetGroup(),
880 dictEntry->GetElement());
884 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
885 * through it's (group, element) and modifies it's content with
887 * @param content new value (string) to substitute with
888 * @param group group number of the Dicom Element to modify
889 * @param element element number of the Dicom Element to modify
891 bool Document::SetEntryByNumber(std::string const& content,
892 uint16_t group, uint16_t element)
897 ValEntry* valEntry = GetValEntryByNumber(group, element);
900 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
901 " ValEntry (try promotion first).");
904 // Non even content must be padded with a space (020H)...
905 std::string finalContent = Util::DicomString( content.c_str() );
906 assert( !(finalContent.size() % 2) );
907 valEntry->SetValue(finalContent);
909 // Integers have a special treatement for their length:
911 l = finalContent.length();
912 if ( l != 0) // To avoid to be cheated by 'zero length' integers
914 VRKey vr = valEntry->GetVR();
915 if( vr == "US" || vr == "SS" )
917 // for multivaluated items
918 c = Util::CountSubstring(content, "\\") + 1;
921 else if( vr == "UL" || vr == "SL" )
923 // for multivaluated items
924 c = Util::CountSubstring(content, "\\") + 1;
928 valEntry->SetLength(l);
933 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
934 * through it's (group, element) and modifies it's content with
936 * @param content new value (void* -> uint8_t*) to substitute with
937 * @param lgth new value length
938 * @param group group number of the Dicom Element to modify
939 * @param element element number of the Dicom Element to modify
941 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
942 uint16_t group, uint16_t element)
944 (void)lgth; //not used
945 TagKey key = DictEntry::TranslateToKey(group, element);
946 if ( !TagHT.count(key))
951 /* Hope Binary field length is *never* wrong
952 if(lgth%2) // Non even length are padded with a space (020H).
955 //content = content + '\0'; // fing a trick to enlarge a binary field?
958 BinEntry* entry = (BinEntry *)TagHT[key];
959 entry->SetBinArea(content);
960 entry->SetLength(lgth);
961 entry->SetValue(GDCM_BINLOADED);
967 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
968 * in the PubDocEntrySet of this instance
969 * through it's (group, element) and modifies it's length with
971 * \warning Use with extreme caution.
972 * @param l new length to substitute with
973 * @param group group number of the Entry to modify
974 * @param element element number of the Entry to modify
975 * @return true on success, false otherwise.
977 bool Document::SetEntryLengthByNumber(uint32_t l,
978 uint16_t group, uint16_t element)
980 /// \todo use map methods, instead of multimap JPR
981 TagKey key = DictEntry::TranslateToKey(group, element);
982 if ( !TagHT.count(key) )
988 l++; // length must be even
990 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
996 * \brief Gets (from Header) the offset of 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 File Offset of the Element Value
1002 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1004 DocEntry* entry = GetDocEntryByNumber(group, elem);
1007 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1010 return entry->GetOffset();
1014 * \brief Gets (from Header) a 'non string' element value
1015 * (LoadElementValues has already be executed)
1016 * @param group group number of the Entry
1017 * @param elem element number of the Entry
1018 * @return Pointer to the 'non string' area
1020 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1022 DocEntry* entry = GetDocEntryByNumber(group, elem);
1025 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1028 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1030 return binEntry->GetBinArea();
1037 * \brief Loads (from disk) the element content
1038 * when a string is not suitable
1039 * @param group group number of the Entry
1040 * @param elem element number of the Entry
1042 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1044 // Search the corresponding DocEntry
1045 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1049 size_t o =(size_t)docElement->GetOffset();
1050 Fp->seekg( o, std::ios_base::beg);
1051 size_t l = docElement->GetLength();
1052 uint8_t* a = new uint8_t[l];
1055 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1060 Fp->read((char*)a, l);
1061 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1067 // Set the value to the DocEntry
1068 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1071 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1075 * \brief Loads (from disk) the element content
1076 * when a string is not suitable
1077 * @param element Entry whose binArea is going to be loaded
1079 void Document::LoadEntryBinArea(BinEntry* element)
1081 size_t o =(size_t)element->GetOffset();
1082 Fp->seekg(o, std::ios_base::beg);
1083 size_t l = element->GetLength();
1084 uint8_t* a = new uint8_t[l];
1087 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1091 /// \todo check the result
1092 Fp->read((char*)a, l);
1093 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1099 element->SetBinArea(a);
1103 * \brief Sets a 'non string' value to a given Dicom Element
1104 * @param area area containing the 'non string' value
1105 * @param group Group number of the searched Dicom Element
1106 * @param element Element number of the searched Dicom Element
1109 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1110 uint16_t group, uint16_t element)
1112 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1113 if ( !currentEntry )
1118 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1120 binEntry->SetBinArea( area );
1128 * \brief Update the entries with the shadow dictionary.
1129 * Only non even entries are analyzed
1131 void Document::UpdateShaEntries()
1136 /// \todo TODO : still any use to explore recursively the whole structure?
1138 for(ListTag::iterator it=listEntries.begin();
1139 it!=listEntries.end();
1142 // Odd group => from public dictionary
1143 if((*it)->GetGroup()%2==0)
1146 // Peer group => search the corresponding dict entry
1148 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1152 if((*it)->IsImplicitVR())
1157 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1159 // Set the new entry and the new value
1160 (*it)->SetDictEntry(entry);
1161 CheckDocEntryVR(*it,vr);
1163 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1168 // Remove precedent value transformation
1169 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1176 * \brief Searches within the Header Entries for a Dicom Element of
1178 * @param tagName name of the searched Dicom Element.
1179 * @return Corresponding Dicom Element when it exists, and NULL
1182 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1184 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1190 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1194 * \brief retrieves a Dicom Element (the first one) using (group, element)
1195 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1196 * if you think it's NOT UNIQUE, check the count number
1197 * and use iterators to retrieve ALL the Dicoms Elements within
1198 * a given couple (group, element)
1199 * @param group Group number of the searched Dicom Element
1200 * @param element Element number of the searched Dicom Element
1203 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1205 TagKey key = DictEntry::TranslateToKey(group, element);
1206 if ( !TagHT.count(key))
1210 return TagHT.find(key)->second;
1214 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1215 * returns a result when the corresponding entry is of type
1217 * @return When present, the corresponding ValEntry.
1219 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1221 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1222 if ( !currentEntry )
1226 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1230 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1236 * \brief Loads the element while preserving the current
1237 * underlying file position indicator as opposed to
1238 * to LoadDocEntry that modifies it.
1239 * @param entry Header Entry whose value shall be loaded.
1242 void Document::LoadDocEntrySafe(DocEntry * entry)
1244 long PositionOnEntry = Fp->tellg();
1245 LoadDocEntry(entry);
1246 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1250 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1252 * @return The properly swaped 32 bits integer.
1254 uint32_t Document::SwapLong(uint32_t a)
1261 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1262 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1266 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1270 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1273 //std::cout << "swapCode= " << SwapCode << std::endl;
1274 dbg.Error(" Document::SwapLong : unset swap code");
1281 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1283 * @return The properly unswaped 32 bits integer.
1285 uint32_t Document::UnswapLong(uint32_t a)
1291 * \brief Swaps the bytes so they agree with the processor order
1292 * @return The properly swaped 16 bits integer.
1294 uint16_t Document::SwapShort(uint16_t a)
1296 if ( SwapCode == 4321 || SwapCode == 2143 )
1298 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1304 * \brief Unswaps the bytes so they agree with the processor order
1305 * @return The properly unswaped 16 bits integer.
1307 uint16_t Document::UnswapShort(uint16_t a)
1309 return SwapShort(a);
1312 //-----------------------------------------------------------------------------
1316 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1317 * @return length of the parsed set.
1319 void Document::ParseDES(DocEntrySet *set, long offset,
1320 long l_max, bool delim_mode)
1322 DocEntry *newDocEntry = 0;
1326 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1330 newDocEntry = ReadNextDocEntry( );
1336 VRKey vr = newDocEntry->GetVR();
1340 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1342 /////////////////////// ValEntry
1343 ValEntry* newValEntry =
1344 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1345 newValEntry->Copy( newDocEntry );
1347 // When "set" is a Document, then we are at the top of the
1348 // hierarchy and the Key is simply of the form ( group, elem )...
1349 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1352 newValEntry->SetKey( newValEntry->GetKey() );
1354 // ...but when "set" is a SQItem, we are inserting this new
1355 // valEntry in a sequence item. Hence the key has the
1356 // generalized form (refer to \ref BaseTagKey):
1357 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1359 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1360 + newValEntry->GetKey() );
1363 LoadDocEntry( newValEntry );
1364 bool delimitor=newValEntry->IsItemDelimitor();
1365 if( !set->AddEntry( newValEntry ) )
1367 // If here expect big troubles
1368 delete newValEntry; //otherwise mem leak
1375 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1382 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1384 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1385 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1386 "nor BinEntry. Probably unknown VR.");
1389 //////////////////// BinEntry or UNKOWN VR:
1390 /* BinEntry* newBinEntry =
1391 new BinEntry( newDocEntry->GetDictEntry() ); //LEAK
1392 newBinEntry->Copy( newDocEntry );*/
1393 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1395 // When "this" is a Document the Key is simply of the
1396 // form ( group, elem )...
1397 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1400 newBinEntry->SetKey( newBinEntry->GetKey() );
1402 // but when "this" is a SQItem, we are inserting this new
1403 // valEntry in a sequence item, and the kay has the
1404 // generalized form (refer to \ref BaseTagKey):
1405 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1407 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1408 + newBinEntry->GetKey() );
1411 LoadDocEntry( newBinEntry );
1412 if( !set->AddEntry( newBinEntry ) )
1414 //Expect big troubles if here
1419 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1420 && ( newDocEntry->GetElement() == 0x0010 ) )
1422 TransferSyntaxType ts = GetTransferSyntax();
1423 if ( ts == RLELossless )
1425 long PositionOnEntry = Fp->tellg();
1426 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1428 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1430 else if ( IsJPEG() )
1432 long PositionOnEntry = Fp->tellg();
1433 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1434 ComputeJPEGFragmentInfo();
1435 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1439 // Just to make sure we are at the beginning of next entry.
1440 SkipToNextDocEntry(newDocEntry);
1445 unsigned long l = newDocEntry->GetReadLength();
1446 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1448 if ( l == 0xffffffff )
1457 // no other way to create it ...
1458 SeqEntry* newSeqEntry =
1459 new SeqEntry( newDocEntry->GetDictEntry() );
1460 newSeqEntry->Copy( newDocEntry );
1461 newSeqEntry->SetDelimitorMode( delim_mode );
1463 // At the top of the hierarchy, stands a Document. When "set"
1464 // is a Document, then we are building the first depth level.
1465 // Hence the SeqEntry we are building simply has a depth
1467 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1470 newSeqEntry->SetDepthLevel( 1 );
1471 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1473 // But when "set" is allready a SQItem, we are building a nested
1474 // sequence, and hence the depth level of the new SeqEntry
1475 // we are building, is one level deeper:
1476 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1478 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1479 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1480 + newSeqEntry->GetKey() );
1484 { // Don't try to parse zero-length sequences
1485 ParseSQ( newSeqEntry,
1486 newDocEntry->GetOffset(),
1489 set->AddEntry( newSeqEntry );
1490 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1500 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1501 * @return parsed length for this level
1503 void Document::ParseSQ( SeqEntry* seqEntry,
1504 long offset, long l_max, bool delim_mode)
1506 int SQItemNumber = 0;
1511 DocEntry* newDocEntry = ReadNextDocEntry();
1514 // FIXME Should warn user
1519 if ( newDocEntry->IsSequenceDelimitor() )
1521 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1525 if ( !delim_mode && (Fp->tellg()-offset) >= l_max)
1530 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1531 std::ostringstream newBase;
1532 newBase << seqEntry->GetKey()
1536 itemSQ->SetBaseTagKey( newBase.str() );
1537 unsigned int l = newDocEntry->GetReadLength();
1539 if ( l == 0xffffffff )
1548 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1550 seqEntry->AddEntry( itemSQ, SQItemNumber );
1552 if ( !delim_mode && ( Fp->tellg() - offset ) >= l_max )
1560 * \brief Loads the element content if its length doesn't exceed
1561 * the value specified with Document::SetMaxSizeLoadEntry()
1562 * @param entry Header Entry (Dicom Element) to be dealt with
1564 void Document::LoadDocEntry(DocEntry* entry)
1566 uint16_t group = entry->GetGroup();
1567 std::string vr = entry->GetVR();
1568 uint32_t length = entry->GetLength();
1570 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1572 // A SeQuence "contains" a set of Elements.
1573 // (fffe e000) tells us an Element is beginning
1574 // (fffe e00d) tells us an Element just ended
1575 // (fffe e0dd) tells us the current SeQuence just ended
1576 if( group == 0xfffe )
1578 // NO more value field for SQ !
1582 // When the length is zero things are easy:
1585 ((ValEntry *)entry)->SetValue("");
1589 // The elements whose length is bigger than the specified upper bound
1590 // are not loaded. Instead we leave a short notice of the offset of
1591 // the element content and it's length.
1593 std::ostringstream s;
1594 if (length > MaxSizeLoadEntry)
1596 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1598 //s << "gdcm::NotLoaded (BinEntry)";
1599 s << GDCM_NOTLOADED;
1600 s << " Address:" << (long)entry->GetOffset();
1601 s << " Length:" << entry->GetLength();
1602 s << " x(" << std::hex << entry->GetLength() << ")";
1603 binEntryPtr->SetValue(s.str());
1605 // Be carefull : a BinEntry IS_A ValEntry ...
1606 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1608 // s << "gdcm::NotLoaded. (ValEntry)";
1609 s << GDCM_NOTLOADED;
1610 s << " Address:" << (long)entry->GetOffset();
1611 s << " Length:" << entry->GetLength();
1612 s << " x(" << std::hex << entry->GetLength() << ")";
1613 valEntryPtr->SetValue(s.str());
1618 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1619 << "nor a ValEntry ?! Should never print that !" << std::endl;
1622 // to be sure we are at the end of the value ...
1623 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1624 std::ios_base::beg);
1628 // When we find a BinEntry not very much can be done :
1629 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1631 s << GDCM_BINLOADED;
1632 binEntryPtr->SetValue(s.str());
1633 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1637 /// \todo Any compacter code suggested (?)
1638 if ( IsDocEntryAnInteger(entry) )
1642 // When short integer(s) are expected, read and convert the following
1643 // n *two characters properly i.e. consider them as short integers as
1644 // opposed to strings.
1645 // Elements with Value Multiplicity > 1
1646 // contain a set of integers (not a single one)
1647 if (vr == "US" || vr == "SS")
1650 NewInt = ReadInt16();
1654 for (int i=1; i < nbInt; i++)
1657 NewInt = ReadInt16();
1662 // See above comment on multiple integers (mutatis mutandis).
1663 else if (vr == "UL" || vr == "SL")
1666 NewInt = ReadInt32();
1670 for (int i=1; i < nbInt; i++)
1673 NewInt = ReadInt32();
1678 #ifdef GDCM_NO_ANSI_STRING_STREAM
1679 s << std::ends; // to avoid oddities on Solaris
1680 #endif //GDCM_NO_ANSI_STRING_STREAM
1682 ((ValEntry *)entry)->SetValue(s.str());
1686 // FIXME: We need an additional byte for storing \0 that is not on disk
1687 char *str = new char[length+1];
1688 Fp->read(str, (size_t)length);
1689 str[length] = '\0'; //this is only useful when length is odd
1690 // Special DicomString call to properly handle \0 and even length
1691 std::string newValue;
1694 newValue = Util::DicomString(str, length+1);
1695 //dbg.Verbose(0, "Warning: bad length: ", length );
1696 dbg.Verbose(0, "For string :", newValue.c_str());
1697 // Since we change the length of string update it length
1698 entry->SetReadLength(length+1);
1702 newValue = Util::DicomString(str, length);
1706 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1708 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1710 dbg.Verbose(1, "Document::LoadDocEntry",
1711 "unread element value");
1712 valEntry->SetValue(GDCM_UNREAD);
1718 // Because of correspondance with the VR dic
1719 valEntry->SetValue(newValue);
1723 valEntry->SetValue(newValue);
1728 dbg.Error(true, "Document::LoadDocEntry"
1729 "Should have a ValEntry, here !");
1735 * \brief Find the value Length of the passed Header Entry
1736 * @param entry Header Entry whose length of the value shall be loaded.
1738 void Document::FindDocEntryLength( DocEntry *entry )
1739 throw ( FormatError )
1741 uint16_t element = entry->GetElement();
1742 std::string vr = entry->GetVR();
1745 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1747 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1749 // The following reserved two bytes (see PS 3.5-2003, section
1750 // "7.1.2 Data element structure with explicit vr", p 27) must be
1751 // skipped before proceeding on reading the length on 4 bytes.
1752 Fp->seekg( 2L, std::ios_base::cur);
1753 uint32_t length32 = ReadInt32();
1755 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1760 /// \todo rename that to FindDocEntryLengthOBOrOW since
1761 /// the above test is on both OB and OW...
1762 lengthOB = FindDocEntryLengthOB();
1764 catch ( FormatUnexpected )
1766 // Computing the length failed (this happens with broken
1767 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1768 // chance to get the pixels by deciding the element goes
1769 // until the end of the file. Hence we artificially fix the
1770 // the length and proceed.
1771 long currentPosition = Fp->tellg();
1772 Fp->seekg(0L,std::ios_base::end);
1773 long lengthUntilEOF = Fp->tellg() - currentPosition;
1774 Fp->seekg(currentPosition, std::ios_base::beg);
1775 entry->SetLength(lengthUntilEOF);
1778 entry->SetLength(lengthOB);
1781 FixDocEntryFoundLength(entry, length32);
1785 // Length is encoded on 2 bytes.
1786 length16 = ReadInt16();
1788 // We can tell the current file is encoded in big endian (like
1789 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1790 // and it's value is the one of the encoding of a big endian file.
1791 // In order to deal with such big endian encoded files, we have
1792 // (at least) two strategies:
1793 // * when we load the "Transfer Syntax" tag with value of big endian
1794 // encoding, we raise the proper flags. Then we wait for the end
1795 // of the META group (0x0002) among which is "Transfer Syntax",
1796 // before switching the swap code to big endian. We have to postpone
1797 // the switching of the swap code since the META group is fully encoded
1798 // in little endian, and big endian coding only starts at the next
1799 // group. The corresponding code can be hard to analyse and adds
1800 // many additional unnecessary tests for regular tags.
1801 // * the second strategy consists in waiting for trouble, that shall
1802 // appear when we find the first group with big endian encoding. This
1803 // is easy to detect since the length of a "Group Length" tag (the
1804 // ones with zero as element number) has to be of 4 (0x0004). When we
1805 // encounter 1024 (0x0400) chances are the encoding changed and we
1806 // found a group with big endian encoding.
1807 // We shall use this second strategy. In order to make sure that we
1808 // can interpret the presence of an apparently big endian encoded
1809 // length of a "Group Length" without committing a big mistake, we
1810 // add an additional check: we look in the already parsed elements
1811 // for the presence of a "Transfer Syntax" whose value has to be "big
1812 // endian encoding". When this is the case, chances are we have got our
1813 // hands on a big endian encoded file: we switch the swap code to
1814 // big endian and proceed...
1815 if ( element == 0x0000 && length16 == 0x0400 )
1817 TransferSyntaxType ts = GetTransferSyntax();
1818 if ( ts != ExplicitVRBigEndian )
1820 throw FormatError( "Document::FindDocEntryLength()",
1821 " not explicit VR." );
1825 SwitchSwapToBigEndian();
1826 // Restore the unproperly loaded values i.e. the group, the element
1827 // and the dictionary entry depending on them.
1828 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1829 uint16_t correctElem = SwapShort( entry->GetElement() );
1830 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1834 // This correct tag is not in the dictionary. Create a new one.
1835 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1837 // FIXME this can create a memory leaks on the old entry that be
1838 // left unreferenced.
1839 entry->SetDictEntry( newTag );
1842 // Heuristic: well, some files are really ill-formed.
1843 if ( length16 == 0xffff)
1845 // 0xffff means that we deal with 'Unknown Length' Sequence
1848 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1853 // Either implicit VR or a non DICOM conformal (see note below) explicit
1854 // VR that ommited the VR of (at least) this element. Farts happen.
1855 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1856 // on Data elements "Implicit and Explicit VR Data Elements shall
1857 // not coexist in a Data Set and Data Sets nested within it".]
1858 // Length is on 4 bytes.
1860 FixDocEntryFoundLength( entry, ReadInt32() );
1866 * \brief Find the Value Representation of the current Dicom Element.
1869 void Document::FindDocEntryVR( DocEntry *entry )
1871 if ( Filetype != ExplicitVR )
1878 long positionOnEntry = Fp->tellg();
1879 // Warning: we believe this is explicit VR (Value Representation) because
1880 // we used a heuristic that found "UL" in the first tag. Alas this
1881 // doesn't guarantee that all the tags will be in explicit VR. In some
1882 // cases (see e-film filtered files) one finds implicit VR tags mixed
1883 // within an explicit VR file. Hence we make sure the present tag
1884 // is in explicit VR and try to fix things if it happens not to be
1887 Fp->read (vr, (size_t)2);
1890 if( !CheckDocEntryVR(entry, vr) )
1892 Fp->seekg(positionOnEntry, std::ios_base::beg);
1893 // When this element is known in the dictionary we shall use, e.g. for
1894 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1895 // dictionary entry. Still we have to flag the element as implicit since
1896 // we know now our assumption on expliciteness is not furfilled.
1898 if ( entry->IsVRUnknown() )
1900 entry->SetVR("Implicit");
1902 entry->SetImplicitVR();
1907 * \brief Check the correspondance between the VR of the header entry
1908 * and the taken VR. If they are different, the header entry is
1909 * updated with the new VR.
1910 * @param entry Header Entry to check
1911 * @param vr Dicom Value Representation
1912 * @return false if the VR is incorrect of if the VR isn't referenced
1913 * otherwise, it returns true
1915 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1918 bool realExplicit = true;
1920 // Assume we are reading a falsely explicit VR file i.e. we reached
1921 // a tag where we expect reading a VR but are in fact we read the
1922 // first to bytes of the length. Then we will interogate (through find)
1923 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1924 // both GCC and VC++ implementations of the STL map. Hence when the
1925 // expected VR read happens to be non-ascii characters we consider
1926 // we hit falsely explicit VR tag.
1928 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1930 realExplicit = false;
1933 // CLEANME searching the dicom_vr at each occurence is expensive.
1934 // PostPone this test in an optional integrity check at the end
1935 // of parsing or only in debug mode.
1936 if ( realExplicit && !Global::GetVR()->Count(vr) )
1938 realExplicit = false;
1941 if ( !realExplicit )
1943 // We thought this was explicit VR, but we end up with an
1944 // implicit VR tag. Let's backtrack.
1945 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1946 entry->GetGroup(), entry->GetElement());
1947 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1949 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1951 // Group length is UL !
1952 DictEntry* newEntry = NewVirtualDictEntry(
1953 entry->GetGroup(), entry->GetElement(),
1954 "UL", "FIXME", "Group Length");
1955 entry->SetDictEntry( newEntry );
1960 if ( entry->IsVRUnknown() )
1962 // When not a dictionary entry, we can safely overwrite the VR.
1963 if( entry->GetElement() == 0x0000 )
1965 // Group length is UL !
1973 else if ( entry->GetVR() != vr )
1975 // The VR present in the file and the dictionary disagree. We assume
1976 // the file writer knew best and use the VR of the file. Since it would
1977 // be unwise to overwrite the VR of a dictionary (since it would
1978 // compromise it's next user), we need to clone the actual DictEntry
1979 // and change the VR for the read one.
1980 DictEntry* newEntry = NewVirtualDictEntry(
1981 entry->GetGroup(), entry->GetElement(),
1982 vr, "FIXME", entry->GetName());
1983 entry->SetDictEntry(newEntry);
1990 * \brief Get the transformed value of the header entry. The VR value
1991 * is used to define the transformation to operate on the value
1992 * \warning NOT end user intended method !
1993 * @param entry entry to tranform
1994 * @return Transformed entry value
1996 std::string Document::GetDocEntryValue(DocEntry *entry)
1998 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2000 std::string val = ((ValEntry *)entry)->GetValue();
2001 std::string vr = entry->GetVR();
2002 uint32_t length = entry->GetLength();
2003 std::ostringstream s;
2006 // When short integer(s) are expected, read and convert the following
2007 // n * 2 bytes properly i.e. as a multivaluated strings
2008 // (each single value is separated fromthe next one by '\'
2009 // as usual for standard multivaluated filels
2010 // Elements with Value Multiplicity > 1
2011 // contain a set of short integers (not a single one)
2013 if( vr == "US" || vr == "SS" )
2018 for (int i=0; i < nbInt; i++)
2024 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2025 newInt16 = SwapShort( newInt16 );
2030 // When integer(s) are expected, read and convert the following
2031 // n * 4 bytes properly i.e. as a multivaluated strings
2032 // (each single value is separated fromthe next one by '\'
2033 // as usual for standard multivaluated filels
2034 // Elements with Value Multiplicity > 1
2035 // contain a set of integers (not a single one)
2036 else if( vr == "UL" || vr == "SL" )
2041 for (int i=0; i < nbInt; i++)
2047 newInt32 = ( val[4*i+0] & 0xFF )
2048 + (( val[4*i+1] & 0xFF ) << 8 )
2049 + (( val[4*i+2] & 0xFF ) << 16 )
2050 + (( val[4*i+3] & 0xFF ) << 24 );
2051 newInt32 = SwapLong( newInt32 );
2055 #ifdef GDCM_NO_ANSI_STRING_STREAM
2056 s << std::ends; // to avoid oddities on Solaris
2057 #endif //GDCM_NO_ANSI_STRING_STREAM
2061 return ((ValEntry *)entry)->GetValue();
2065 * \brief Get the reverse transformed value of the header entry. The VR
2066 * value is used to define the reverse transformation to operate on
2068 * \warning NOT end user intended method !
2069 * @param entry Entry to reverse transform
2070 * @return Reverse transformed entry value
2072 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2074 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2076 std::string vr = entry->GetVR();
2077 std::vector<std::string> tokens;
2078 std::ostringstream s;
2080 if ( vr == "US" || vr == "SS" )
2084 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2085 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2086 for (unsigned int i=0; i<tokens.size(); i++)
2088 newInt16 = atoi(tokens[i].c_str());
2089 s << ( newInt16 & 0xFF )
2090 << (( newInt16 >> 8 ) & 0xFF );
2094 if ( vr == "UL" || vr == "SL")
2098 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2099 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2100 for (unsigned int i=0; i<tokens.size();i++)
2102 newInt32 = atoi(tokens[i].c_str());
2103 s << (char)( newInt32 & 0xFF )
2104 << (char)(( newInt32 >> 8 ) & 0xFF )
2105 << (char)(( newInt32 >> 16 ) & 0xFF )
2106 << (char)(( newInt32 >> 24 ) & 0xFF );
2111 #ifdef GDCM_NO_ANSI_STRING_STREAM
2112 s << std::ends; // to avoid oddities on Solaris
2113 #endif //GDCM_NO_ANSI_STRING_STREAM
2117 return ((ValEntry *)entry)->GetValue();
2121 * \brief Skip a given Header Entry
2122 * \warning NOT end user intended method !
2123 * @param entry entry to skip
2125 void Document::SkipDocEntry(DocEntry *entry)
2127 SkipBytes(entry->GetLength());
2131 * \brief Skips to the begining of the next Header Entry
2132 * \warning NOT end user intended method !
2133 * @param entry entry to skip
2135 void Document::SkipToNextDocEntry(DocEntry *entry)
2137 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2138 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2142 * \brief When the length of an element value is obviously wrong (because
2143 * the parser went Jabberwocky) one can hope improving things by
2144 * applying some heuristics.
2145 * @param entry entry to check
2146 * @param foundLength fist assumption about length
2148 void Document::FixDocEntryFoundLength(DocEntry *entry,
2149 uint32_t foundLength)
2151 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2152 if ( foundLength == 0xffffffff)
2157 uint16_t gr = entry->GetGroup();
2158 uint16_t el = entry->GetElement();
2160 if ( foundLength % 2)
2162 std::ostringstream s;
2163 s << "Warning : Tag with uneven length "
2165 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2166 dbg.Verbose(0, s.str().c_str());
2169 //////// Fix for some naughty General Electric images.
2170 // Allthough not recent many such GE corrupted images are still present
2171 // on Creatis hard disks. Hence this fix shall remain when such images
2172 // are no longer in user (we are talking a few years, here)...
2173 // Note: XMedCom probably uses such a trick since it is able to read
2174 // those pesky GE images ...
2175 if ( foundLength == 13)
2177 // Only happens for this length !
2178 if ( entry->GetGroup() != 0x0008
2179 || ( entry->GetElement() != 0x0070
2180 && entry->GetElement() != 0x0080 ) )
2183 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2187 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2188 // Occurence of such images is quite low (unless one leaves close to a
2189 // 'Leonardo' source. Hence, one might consider commenting out the
2190 // following fix on efficiency reasons.
2191 else if ( entry->GetGroup() == 0x0009
2192 && ( entry->GetElement() == 0x1113
2193 || entry->GetElement() == 0x1114 ) )
2196 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2199 else if ( entry->GetVR() == "SQ" )
2201 foundLength = 0; // ReadLength is unchanged
2204 //////// We encountered a 'delimiter' element i.e. a tag of the form
2205 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2206 // taken into account.
2207 else if( entry->GetGroup() == 0xfffe )
2209 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2210 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2211 // causes extra troubles...
2212 if( entry->GetElement() != 0x0000 )
2218 entry->SetUsableLength(foundLength);
2222 * \brief Apply some heuristics to predict whether the considered
2223 * element value contains/represents an integer or not.
2224 * @param entry The element value on which to apply the predicate.
2225 * @return The result of the heuristical predicate.
2227 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2229 uint16_t element = entry->GetElement();
2230 uint16_t group = entry->GetGroup();
2231 const std::string & vr = entry->GetVR();
2232 uint32_t length = entry->GetLength();
2234 // When we have some semantics on the element we just read, and if we
2235 // a priori know we are dealing with an integer, then we shall be
2236 // able to swap it's element value properly.
2237 if ( element == 0 ) // This is the group length of the group
2245 // Allthough this should never happen, still some images have a
2246 // corrupted group length [e.g. have a glance at offset x(8336) of
2247 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2248 // Since for dicom compliant and well behaved headers, the present
2249 // test is useless (and might even look a bit paranoid), when we
2250 // encounter such an ill-formed image, we simply display a warning
2251 // message and proceed on parsing (while crossing fingers).
2252 std::ostringstream s;
2253 long filePosition = Fp->tellg();
2254 s << "Erroneous Group Length element length on : (" \
2255 << std::hex << group << " , " << element
2256 << ") -before- position x(" << filePosition << ")"
2257 << "lgt : " << length;
2258 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2262 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2271 * \brief Find the Length till the next sequence delimiter
2272 * \warning NOT end user intended method !
2276 uint32_t Document::FindDocEntryLengthOB()
2277 throw( FormatUnexpected )
2279 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2280 long positionOnEntry = Fp->tellg();
2281 bool foundSequenceDelimiter = false;
2282 uint32_t totalLength = 0;
2284 while ( !foundSequenceDelimiter )
2290 group = ReadInt16();
2293 catch ( FormatError )
2295 throw FormatError("Document::FindDocEntryLengthOB()",
2296 " group or element not present.");
2299 // We have to decount the group and element we just read
2302 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2304 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2305 "tag nor a Sequence delimiter tag.");
2306 Fp->seekg(positionOnEntry, std::ios_base::beg);
2307 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2308 "Neither an Item tag nor a Sequence "
2312 if ( elem == 0xe0dd )
2314 foundSequenceDelimiter = true;
2317 uint32_t itemLength = ReadInt32();
2318 // We add 4 bytes since we just read the ItemLength with ReadInt32
2319 totalLength += itemLength + 4;
2320 SkipBytes(itemLength);
2322 if ( foundSequenceDelimiter )
2327 Fp->seekg( positionOnEntry, std::ios_base::beg);
2332 * \brief Reads a supposed to be 16 Bits integer
2333 * (swaps it depending on processor endianity)
2334 * @return read value
2336 uint16_t Document::ReadInt16()
2337 throw( FormatError )
2340 Fp->read ((char*)&g, (size_t)2);
2343 throw FormatError( "Document::ReadInt16()", " file error." );
2347 throw FormatError( "Document::ReadInt16()", "EOF." );
2354 * \brief Reads a supposed to be 32 Bits integer
2355 * (swaps it depending on processor endianity)
2356 * @return read value
2358 uint32_t Document::ReadInt32()
2359 throw( FormatError )
2362 Fp->read ((char*)&g, (size_t)4);
2365 throw FormatError( "Document::ReadInt32()", " file error." );
2369 throw FormatError( "Document::ReadInt32()", "EOF." );
2376 * \brief skips bytes inside the source file
2377 * \warning NOT end user intended method !
2380 void Document::SkipBytes(uint32_t nBytes)
2382 //FIXME don't dump the returned value
2383 Fp->seekg((long)nBytes, std::ios_base::cur);
2387 * \brief Loads all the needed Dictionaries
2388 * \warning NOT end user intended method !
2390 void Document::Initialise()
2392 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2394 RLEInfo = new RLEFramesInfo;
2395 JPEGInfo = new JPEGFragmentsInfo;
2399 * \brief Discover what the swap code is (among little endian, big endian,
2400 * bad little endian, bad big endian).
2402 * @return false when we are absolutely sure
2403 * it's neither ACR-NEMA nor DICOM
2404 * true when we hope ours assuptions are OK
2406 bool Document::CheckSwap()
2408 // The only guaranted way of finding the swap code is to find a
2409 // group tag since we know it's length has to be of four bytes i.e.
2410 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2411 // occurs when we can't find such group...
2413 uint32_t x = 4; // x : for ntohs
2414 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2418 char deb[256]; //HEADER_LENGTH_TO_READ];
2420 // First, compare HostByteOrder and NetworkByteOrder in order to
2421 // determine if we shall need to swap bytes (i.e. the Endian type).
2422 if ( x == ntohs(x) )
2431 // The easiest case is the one of a DICOM header, since it possesses a
2432 // file preamble where it suffice to look for the string "DICM".
2433 Fp->read(deb, HEADER_LENGTH_TO_READ);
2435 char *entCur = deb + 128;
2436 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2438 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2440 // Next, determine the value representation (VR). Let's skip to the
2441 // first element (0002, 0000) and check there if we find "UL"
2442 // - or "OB" if the 1st one is (0002,0001) -,
2443 // in which case we (almost) know it is explicit VR.
2444 // WARNING: if it happens to be implicit VR then what we will read
2445 // is the length of the group. If this ascii representation of this
2446 // length happens to be "UL" then we shall believe it is explicit VR.
2447 // FIXME: in order to fix the above warning, we could read the next
2448 // element value (or a couple of elements values) in order to make
2449 // sure we are not commiting a big mistake.
2450 // We need to skip :
2451 // * the 128 bytes of File Preamble (often padded with zeroes),
2452 // * the 4 bytes of "DICM" string,
2453 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2454 // i.e. a total of 136 bytes.
2458 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2459 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2460 // *Implicit* VR. -and it is !-
2462 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2463 memcmp(entCur, "OB", (size_t)2) == 0 ||
2464 memcmp(entCur, "UI", (size_t)2) == 0 ||
2465 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2466 // when Write DCM *adds*
2468 // Use Document::dicom_vr to test all the possibilities
2469 // instead of just checking for UL, OB and UI !? group 0000
2471 Filetype = ExplicitVR;
2472 dbg.Verbose(1, "Document::CheckSwap:",
2473 "explicit Value Representation");
2477 Filetype = ImplicitVR;
2478 dbg.Verbose(1, "Document::CheckSwap:",
2479 "not an explicit Value Representation");
2485 dbg.Verbose(1, "Document::CheckSwap:",
2486 "HostByteOrder != NetworkByteOrder");
2491 dbg.Verbose(1, "Document::CheckSwap:",
2492 "HostByteOrder = NetworkByteOrder");
2495 // Position the file position indicator at first tag (i.e.
2496 // after the file preamble and the "DICM" string).
2497 Fp->seekg(0, std::ios_base::beg);
2498 Fp->seekg ( 132L, std::ios_base::beg);
2502 // Alas, this is not a DicomV3 file and whatever happens there is no file
2503 // preamble. We can reset the file position indicator to where the data
2504 // is (i.e. the beginning of the file).
2505 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2506 Fp->seekg(0, std::ios_base::beg);
2508 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2509 // By clean we mean that the length of the first tag is written down.
2510 // If this is the case and since the length of the first group HAS to be
2511 // four (bytes), then determining the proper swap code is straightforward.
2514 // We assume the array of char we are considering contains the binary
2515 // representation of a 32 bits integer. Hence the following dirty
2517 s32 = *((uint32_t *)(entCur));
2538 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2539 // It is time for despaired wild guesses.
2540 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2541 // i.e. the 'group length' element is not present :
2543 // check the supposed-to-be 'group number'
2544 // in ( 0x0001 .. 0x0008 )
2545 // to determine ' SwapCode' value .
2546 // Only 0 or 4321 will be possible
2547 // (no oportunity to check for the formerly well known
2548 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2549 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2550 // the file IS NOT ACR-NEMA nor DICOM V3
2551 // Find a trick to tell it the caller...
2553 s16 = *((uint16_t *)(deb));
2580 dbg.Verbose(0, "Document::CheckSwap:",
2581 "ACR/NEMA unfound swap info (Really hopeless !)");
2585 // Then the only info we have is the net2host one.
2596 * \brief Restore the unproperly loaded values i.e. the group, the element
2597 * and the dictionary entry depending on them.
2599 void Document::SwitchSwapToBigEndian()
2601 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2602 "Switching to BigEndian mode.");
2603 if ( SwapCode == 0 )
2607 else if ( SwapCode == 4321 )
2611 else if ( SwapCode == 3412 )
2615 else if ( SwapCode == 2143 )
2622 * \brief during parsing, Header Elements too long are not loaded in memory
2625 void Document::SetMaxSizeLoadEntry(long newSize)
2631 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2633 MaxSizeLoadEntry = 0xffffffff;
2636 MaxSizeLoadEntry = newSize;
2641 * \brief Header Elements too long will not be printed
2642 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2645 void Document::SetMaxSizePrintEntry(long newSize)
2647 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2652 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2654 MaxSizePrintEntry = 0xffffffff;
2657 MaxSizePrintEntry = newSize;
2663 * \brief Handle broken private tag from Philips NTSCAN
2664 * where the endianess is being switch to BigEndian for no
2668 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2670 // Endian reversion. Some files contain groups of tags with reversed endianess.
2671 static int reversedEndian = 0;
2672 // try to fix endian switching in the middle of headers
2673 if ((group == 0xfeff) && (elem == 0x00e0))
2675 // start endian swap mark for group found
2677 SwitchSwapToBigEndian();
2682 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2684 // end of reversed endian group
2686 SwitchSwapToBigEndian();
2692 * \brief Read the next tag but WITHOUT loading it's value
2693 * (read the 'Group Number', the 'Element Number',
2694 * gets the Dict Entry
2695 * gets the VR, gets the length, gets the offset value)
2696 * @return On succes the newly created DocEntry, NULL on failure.
2698 DocEntry* Document::ReadNextDocEntry()
2705 group = ReadInt16();
2708 catch ( FormatError e )
2710 // We reached the EOF (or an error occured) therefore
2711 // header parsing has to be considered as finished.
2716 HandleBrokenEndian(group, elem);
2717 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2718 FindDocEntryVR(newEntry);
2722 FindDocEntryLength(newEntry);
2724 catch ( FormatError e )
2732 newEntry->SetOffset(Fp->tellg());
2739 * \brief Generate a free TagKey i.e. a TagKey that is not present
2740 * in the TagHt dictionary.
2741 * @param group The generated tag must belong to this group.
2742 * @return The element of tag with given group which is fee.
2744 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2746 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2748 TagKey key = DictEntry::TranslateToKey(group, elem);
2749 if (TagHT.count(key) == 0)
2758 * \brief Assuming the internal file pointer \ref Document::Fp
2759 * is placed at the beginning of a tag check whether this
2760 * tag is (TestGroup, TestElement).
2761 * \warning On success the internal file pointer \ref Document::Fp
2762 * is modified to point after the tag.
2763 * On failure (i.e. when the tag wasn't the expected tag
2764 * (TestGroup, TestElement) the internal file pointer
2765 * \ref Document::Fp is restored to it's original position.
2766 * @param testGroup The expected group of the tag.
2767 * @param testElement The expected Element of the tag.
2768 * @return True on success, false otherwise.
2770 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2772 long positionOnEntry = Fp->tellg();
2773 long currentPosition = Fp->tellg(); // On debugging purposes
2775 //// Read the Item Tag group and element, and make
2776 // sure they are what we expected:
2777 uint16_t itemTagGroup;
2778 uint16_t itemTagElement;
2781 itemTagGroup = ReadInt16();
2782 itemTagElement = ReadInt16();
2784 catch ( FormatError e )
2786 //std::cerr << e << std::endl;
2789 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2791 std::ostringstream s;
2792 s << " We should have found tag (";
2793 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2794 s << " but instead we encountered tag (";
2795 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2797 s << " at address: " << (unsigned)currentPosition << std::endl;
2798 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2799 dbg.Verbose(0, s.str().c_str());
2800 Fp->seekg(positionOnEntry, std::ios_base::beg);
2808 * \brief Assuming the internal file pointer \ref Document::Fp
2809 * is placed at the beginning of a tag (TestGroup, TestElement),
2810 * read the length associated to the Tag.
2811 * \warning On success the internal file pointer \ref Document::Fp
2812 * is modified to point after the tag and it's length.
2813 * On failure (i.e. when the tag wasn't the expected tag
2814 * (TestGroup, TestElement) the internal file pointer
2815 * \ref Document::Fp is restored to it's original position.
2816 * @param testGroup The expected group of the tag.
2817 * @param testElement The expected Element of the tag.
2818 * @return On success returns the length associated to the tag. On failure
2821 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2823 long positionOnEntry = Fp->tellg();
2824 (void)positionOnEntry;
2826 if ( !ReadTag(testGroup, testElement) )
2831 //// Then read the associated Item Length
2832 long currentPosition = Fp->tellg();
2833 uint32_t itemLength = ReadInt32();
2835 std::ostringstream s;
2836 s << "Basic Item Length is: "
2837 << itemLength << std::endl;
2838 s << " at address: " << (unsigned)currentPosition << std::endl;
2839 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2845 * \brief When parsing the Pixel Data of an encapsulated file, read
2846 * the basic offset table (when present, and BTW dump it).
2848 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2850 //// Read the Basic Offset Table Item Tag length...
2851 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2853 // When present, read the basic offset table itself.
2854 // Notes: - since the presence of this basic offset table is optional
2855 // we can't rely on it for the implementation, and we will simply
2856 // trash it's content (when present).
2857 // - still, when present, we could add some further checks on the
2858 // lengths, but we won't bother with such fuses for the time being.
2859 if ( itemLength != 0 )
2861 char* basicOffsetTableItemValue = new char[itemLength + 1];
2862 Fp->read(basicOffsetTableItemValue, itemLength);
2865 for (unsigned int i=0; i < itemLength; i += 4 )
2867 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2869 std::ostringstream s;
2870 s << " Read one length: ";
2871 s << std::hex << individualLength << std::endl;
2873 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2878 delete[] basicOffsetTableItemValue;
2883 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2884 * Compute the RLE extra information and store it in \ref RLEInfo
2885 * for later pixel retrieval usage.
2887 void Document::ComputeRLEInfo()
2889 TransferSyntaxType ts = GetTransferSyntax();
2890 if ( ts != RLELossless )
2895 // Encoded pixel data: for the time being we are only concerned with
2896 // Jpeg or RLE Pixel data encodings.
2897 // As stated in PS 3.5-2003, section 8.2 p44:
2898 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2899 // value representation OB is used".
2900 // Hence we expect an OB value representation. Concerning OB VR,
2901 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2902 // "For the Value Representations OB and OW, the encoding shall meet the
2903 // following specifications depending on the Data element tag:"
2905 // - the first item in the sequence of items before the encoded pixel
2906 // data stream shall be basic offset table item. The basic offset table
2907 // item value, however, is not required to be present"
2909 ReadAndSkipEncapsulatedBasicOffsetTable();
2911 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2912 // Loop on the individual frame[s] and store the information
2913 // on the RLE fragments in a RLEFramesInfo.
2914 // Note: - when only a single frame is present, this is a
2916 // - when more than one frame are present, then we are in
2917 // the case of a multi-frame image.
2919 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2921 // Parse the RLE Header and store the corresponding RLE Segment
2922 // Offset Table information on fragments of this current Frame.
2923 // Note that the fragment pixels themselves are not loaded
2924 // (but just skipped).
2925 long frameOffset = Fp->tellg();
2927 uint32_t nbRleSegments = ReadInt32();
2928 if ( nbRleSegments > 16 )
2930 // There should be at most 15 segments (refer to RLEFrame class)
2931 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2934 uint32_t rleSegmentOffsetTable[16];
2935 for( int k = 1; k <= 15; k++ )
2937 rleSegmentOffsetTable[k] = ReadInt32();
2940 // Deduce from both the RLE Header and the frameLength the
2941 // fragment length, and again store this info in a
2943 long rleSegmentLength[15];
2944 // skipping (not reading) RLE Segments
2945 if ( nbRleSegments > 1)
2947 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2949 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2950 - rleSegmentOffsetTable[k];
2951 SkipBytes(rleSegmentLength[k]);
2955 rleSegmentLength[nbRleSegments] = frameLength
2956 - rleSegmentOffsetTable[nbRleSegments];
2957 SkipBytes(rleSegmentLength[nbRleSegments]);
2959 // Store the collected info
2960 RLEFrame* newFrameInfo = new RLEFrame;
2961 newFrameInfo->NumberFragments = nbRleSegments;
2962 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2964 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2965 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2967 RLEInfo->Frames.push_back( newFrameInfo );
2970 // Make sure that at the end of the item we encounter a 'Sequence
2972 if ( !ReadTag(0xfffe, 0xe0dd) )
2974 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2975 dbg.Verbose(0, " item at end of RLE item sequence");
2980 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2981 * Compute the jpeg extra information (fragment[s] offset[s] and
2982 * length) and store it[them] in \ref JPEGInfo for later pixel
2985 void Document::ComputeJPEGFragmentInfo()
2987 // If you need to, look for comments of ComputeRLEInfo().
2993 ReadAndSkipEncapsulatedBasicOffsetTable();
2995 // Loop on the fragments[s] and store the parsed information in a
2997 long fragmentLength;
2998 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3000 long fragmentOffset = Fp->tellg();
3002 // Store the collected info
3003 JPEGFragment* newFragment = new JPEGFragment;
3004 newFragment->Offset = fragmentOffset;
3005 newFragment->Length = fragmentLength;
3006 JPEGInfo->Fragments.push_back( newFragment );
3008 SkipBytes( fragmentLength );
3011 // Make sure that at the end of the item we encounter a 'Sequence
3013 if ( !ReadTag(0xfffe, 0xe0dd) )
3015 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3016 dbg.Verbose(0, " item at end of JPEG item sequence");
3021 * \brief Walk recursively the given \ref DocEntrySet, and feed
3022 * the given hash table (\ref TagDocEntryHT) with all the
3023 * \ref DocEntry (Dicom entries) encountered.
3024 * This method does the job for \ref BuildFlatHashTable.
3025 * @param builtHT Where to collect all the \ref DocEntry encountered
3026 * when recursively walking the given set.
3027 * @param set The structure to be traversed (recursively).
3029 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3032 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3034 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3035 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3036 i != currentHT.end();
3039 DocEntry* entry = i->second;
3040 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3042 const ListSQItem& items = seqEntry->GetSQItems();
3043 for( ListSQItem::const_iterator item = items.begin();
3044 item != items.end();
3047 BuildFlatHashTableRecurse( builtHT, *item );
3051 builtHT[entry->GetKey()] = entry;
3056 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3058 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3059 for (ListDocEntry::const_iterator i = currentList.begin();
3060 i != currentList.end();
3063 DocEntry* entry = *i;
3064 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3066 const ListSQItem& items = seqEntry->GetSQItems();
3067 for( ListSQItem::const_iterator item = items.begin();
3068 item != items.end();
3071 BuildFlatHashTableRecurse( builtHT, *item );
3075 builtHT[entry->GetKey()] = entry;
3082 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3085 * The structure used by a Document (through \ref ElementSet),
3086 * in order to old the parsed entries of a Dicom header, is a recursive
3087 * one. This is due to the fact that the sequences (when present)
3088 * can be nested. Additionaly, the sequence items (represented in
3089 * gdcm as \ref SQItem) add an extra complexity to the data
3090 * structure. Hence, a gdcm user whishing to visit all the entries of
3091 * a Dicom header will need to dig in the gdcm internals (which
3092 * implies exposing all the internal data structures to the API).
3093 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3094 * recursively builds a temporary hash table, which holds all the
3095 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3097 * \warning Of course there is NO integrity constrain between the
3098 * returned \ref TagDocEntryHT and the \ref ElementSet used
3099 * to build it. Hence if the underlying \ref ElementSet is
3100 * altered, then it is the caller responsability to invoke
3101 * \ref BuildFlatHashTable again...
3102 * @return The flat std::map<> we juste build.
3104 TagDocEntryHT* Document::BuildFlatHashTable()
3106 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3107 BuildFlatHashTableRecurse( *FlatHT, this );
3114 * \brief Compares two documents, according to \ref DicomDir rules
3115 * \warning Does NOT work with ACR-NEMA files
3116 * \todo Find a trick to solve the pb (use RET fields ?)
3118 * @return true if 'smaller'
3120 bool Document::operator<(Document &document)
3123 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3124 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3136 s1 = GetEntryByNumber(0x0010,0x0020);
3137 s2 = document.GetEntryByNumber(0x0010,0x0020);
3148 // Study Instance UID
3149 s1 = GetEntryByNumber(0x0020,0x000d);
3150 s2 = document.GetEntryByNumber(0x0020,0x000d);
3161 // Serie Instance UID
3162 s1 = GetEntryByNumber(0x0020,0x000e);
3163 s2 = document.GetEntryByNumber(0x0020,0x000e);
3178 } // end namespace gdcm
3180 //-----------------------------------------------------------------------------