1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/25 16:35:16 $
7 Version: $Revision: 1.141 $
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 //-----------------------------------------------------------------------------
40 static const char *TransferSyntaxStrings[] = {
41 // Implicit VR Little Endian
43 // Implicit VR Little Endian DLX G.E?
45 // Explicit VR Little Endian
46 "1.2.840.10008.1.2.1",
47 // Deflated Explicit VR Little Endian
48 "1.2.840.10008.1.2.1.99",
49 // Explicit VR Big Endian
50 "1.2.840.10008.1.2.2",
51 // JPEG Baseline (Process 1)
52 "1.2.840.10008.1.2.4.50",
53 // JPEG Extended (Process 2 & 4)
54 "1.2.840.10008.1.2.4.51",
55 // JPEG Extended (Process 3 & 5)
56 "1.2.840.10008.1.2.4.52",
57 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
58 "1.2.840.10008.1.2.4.53",
59 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
60 "1.2.840.10008.1.2.4.55",
61 // JPEG Lossless, Non-Hierarchical (Process 14)
62 "1.2.840.10008.1.2.4.57",
63 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
64 "1.2.840.10008.1.2.4.70",
66 "1.2.840.10008.1.2.4.90",
68 "1.2.840.10008.1.2.4.91",
70 "1.2.840.10008.1.2.5",
72 "Unknown Transfer Syntax"
75 //-----------------------------------------------------------------------------
76 // Refer to Document::CheckSwap()
77 const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
79 // Refer to Document::SetMaxSizeLoadEntry()
80 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
81 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
83 //-----------------------------------------------------------------------------
84 // Constructor / Destructor
88 * @param filename file to be opened for parsing
90 Document::Document( std::string const & filename ) : ElementSet(-1)
92 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
102 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
104 Fp->seekg( 0, std::ios_base::beg);
106 Fp->seekg(0, std::ios_base::end);
107 long lgt = Fp->tellg();
109 Fp->seekg( 0, std::ios_base::beg);
111 long beg = Fp->tellg();
114 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
116 Fp->seekg( 0, std::ios_base::beg);
118 // Load 'non string' values
120 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
121 if( PhotometricInterpretation == "PALETTE COLOR " )
123 LoadEntryBinArea(0x0028,0x1200); // gray LUT
124 /// FIXME FIXME FIXME
125 /// The tags refered by the three following lines used to be CORRECTLY
126 /// defined as having an US Value Representation in the public
127 /// dictionnary. BUT the semantics implied by the three following
128 /// lines state that the corresponding tag contents are in fact
129 /// the ones of a BinEntry.
130 /// In order to fix things "Quick and Dirty" the dictionnary was
131 /// altered on PURPOUS but now contains a WRONG value.
132 /// In order to fix things and restore the dictionary to its
133 /// correct value, one needs to decided of the semantics by deciding
134 /// wether the following tags are either:
135 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
136 /// also used as BinEntry, which requires the proper conversion,
137 /// - OW, and hence loaded as BinEntry, but afterwards also used
138 /// as ValEntry, which requires the proper conversion.
139 LoadEntryBinArea(0x0028,0x1201); // R LUT
140 LoadEntryBinArea(0x0028,0x1202); // G LUT
141 LoadEntryBinArea(0x0028,0x1203); // B LUT
143 // Segmented Red Palette Color LUT Data
144 LoadEntryBinArea(0x0028,0x1221);
145 // Segmented Green Palette Color LUT Data
146 LoadEntryBinArea(0x0028,0x1222);
147 // Segmented Blue Palette Color LUT Data
148 LoadEntryBinArea(0x0028,0x1223);
150 //FIXME later : how to use it?
151 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
155 // --------------------------------------------------------------
156 // Specific code to allow gdcm to read ACR-LibIDO formated images
157 // Note: ACR-LibIDO is an extension of the ACR standard that was
158 // used at CREATIS. For the time being (say a couple years)
159 // we keep this kludge to allow a smooth move to gdcm for
160 // CREATIS developpers (sorry folks).
162 // if recognition code tells us we deal with a LibIDO image
163 // we switch lineNumber and columnNumber
166 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
167 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
168 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
169 // with "little-endian strings"
171 Filetype = ACR_LIBIDO;
172 std::string rows = GetEntryByNumber(0x0028, 0x0010);
173 std::string columns = GetEntryByNumber(0x0028, 0x0011);
174 SetEntryByNumber(columns, 0x0028, 0x0010);
175 SetEntryByNumber(rows , 0x0028, 0x0011);
177 // ----------------- End of ACR-LibIDO kludge ------------------
179 PrintLevel = 1; // 'Medium' print level by default
183 * \brief This default constructor doesn't parse the file. You should
184 * then invoke \ref Document::SetFileName and then the parsing.
186 Document::Document() : ElementSet(-1)
190 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
193 Filetype = ExplicitVR;
194 PrintLevel = 1; // 'Medium' print level by default
198 * \brief Canonical destructor.
200 Document::~Document ()
209 //-----------------------------------------------------------------------------
213 * \brief Prints The Dict Entries of THE public Dicom Dictionary
216 void Document::PrintPubDict(std::ostream & os)
218 RefPubDict->Print(os);
222 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
225 void Document::PrintShaDict(std::ostream & os)
227 RefShaDict->Print(os);
230 //-----------------------------------------------------------------------------
233 * \brief Get the public dictionary used
235 Dict* Document::GetPubDict()
241 * \brief Get the shadow dictionary used
243 Dict* Document::GetShaDict()
249 * \brief Set the shadow dictionary used
250 * \param dict dictionary to use in shadow
252 bool Document::SetShaDict(Dict *dict)
259 * \brief Set the shadow dictionary used
260 * \param dictName name of the dictionary to use in shadow
262 bool Document::SetShaDict(DictKey const & dictName)
264 RefShaDict = Global::GetDicts()->GetDict(dictName);
269 * \brief This predicate, based on hopefully reasonable heuristics,
270 * decides whether or not the current Document was properly parsed
271 * and contains the mandatory information for being considered as
272 * a well formed and usable Dicom/Acr File.
273 * @return true when Document is the one of a reasonable Dicom/Acr file,
276 bool Document::IsReadable()
278 if( Filetype == Unknown)
280 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
286 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
295 * \brief Accessor to the Transfer Syntax (when present) of the
296 * current document (it internally handles reading the
297 * value from disk when only parsing occured).
298 * @return The encountered Transfer Syntax of the current document.
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((unsigned char)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 if (Filename.length() == 0) return 0;
418 "Document::OpenFile is already opened when opening: ",
422 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
427 "Document::OpenFile cannot open file: ",
433 Fp->read((char*)&zero, (size_t)2 );
435 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
437 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
438 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
439 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
440 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
446 Fp->seekg(126L, std::ios_base::cur);
448 Fp->read(dicm, (size_t)4);
449 if( memcmp(dicm, "DICM", 4) == 0 )
456 "Document::OpenFile not DICOM/ACR (missing preamble)",
463 * \brief closes the file
464 * @return TRUE if the close was successfull
466 bool Document::CloseFile()
475 return true; //FIXME how do we detect a non-close ifstream ?
479 * \brief Writes in a file all the Header Entries (Dicom Elements)
480 * @param fp file pointer on an already open file
481 * @param filetype Type of the File to be written
482 * (ACR-NEMA, ExplicitVR, ImplicitVR)
483 * \return Always true.
485 void Document::WriteContent(std::ofstream* fp, FileType filetype)
487 /// \todo move the following lines (and a lot of others, to be written)
488 /// to a future function CheckAndCorrectHeader
489 /// (necessary if user wants to write a DICOM V3 file
490 /// starting from an ACR-NEMA (V2) Header
492 if ( filetype == ImplicitVR || filetype == ExplicitVR )
494 // writing Dicom File Preamble
495 char filePreamble[128];
496 memset(filePreamble, 0, 128);
497 fp->write(filePreamble, 128);
498 fp->write("DICM", 4);
502 * \todo rewrite later, if really usefull
503 * - 'Group Length' element is optional in DICOM
504 * - but un-updated odd groups lengthes can causes pb
507 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
508 * UpdateGroupLength(false,filetype);
509 * if ( filetype == ACR)
510 * UpdateGroupLength(true,ACR);
513 ElementSet::WriteContent(fp, filetype); // This one is recursive
517 * \brief Modifies the value of a given Header Entry (Dicom Element)
518 * when it exists. Create it with the given value when unexistant.
519 * @param value (string) Value to be set
520 * @param group Group number of the Entry
521 * @param elem Element number of the Entry
522 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
523 * \return pointer to the modified/created Header Entry (NULL when creation
526 ValEntry* Document::ReplaceOrCreateByNumber(
527 std::string const & value,
532 ValEntry* valEntry = 0;
533 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
537 // check if (group,element) DictEntry exists
538 // if it doesn't, create an entry in DictSet::VirtualEntry
541 // Find out if the tag we received is in the dictionaries:
542 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
543 DictEntry* dictEntry = pubDict->GetDictEntryByNumber(group, elem);
546 currentEntry = NewDocEntryByNumber(group, elem, vr);
550 currentEntry = NewDocEntryByNumber(group, elem);
555 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
556 " NewDocEntryByNumber failed.");
560 valEntry = new ValEntry(currentEntry);
563 if ( !AddEntry(valEntry))
566 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
567 " failed allthough this is a creation.");
573 valEntry = dynamic_cast< ValEntry* >(currentEntry);
574 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
575 // then we change it to a ValEntry ?
576 // Shouldn't it be considered as an error ?
578 // We need to promote the DocEntry to a ValEntry:
579 valEntry = new ValEntry(currentEntry);
580 if (!RemoveEntry(currentEntry))
583 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
584 " of previous DocEntry failed.");
587 if ( !AddEntry(valEntry))
590 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
591 " promoted ValEntry failed.");
597 SetEntryByNumber(value, group, elem);
603 * \brief Modifies the value of a given Header Entry (Dicom Element)
604 * when it exists. Create it with the given value when unexistant.
605 * A copy of the binArea is made to be kept in the Document.
606 * @param binArea (binary) value to be set
607 * @param Group Group number of the Entry
608 * @param Elem Element number of the Entry
609 * \return pointer to the modified/created Header Entry (NULL when creation
612 BinEntry* Document::ReplaceOrCreateByNumber(
619 BinEntry* binEntry = 0;
620 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
624 // check if (group,element) DictEntry exists
625 // if it doesn't, create an entry in DictSet::VirtualEntry
628 // Find out if the tag we received is in the dictionaries:
629 Dict *pubDict = Global::GetDicts()->GetDefaultPubDict();
630 DictEntry *dictEntry = pubDict->GetDictEntryByNumber(group, elem);
634 currentEntry = NewDocEntryByNumber(group, elem, vr);
638 currentEntry = NewDocEntryByNumber(group, elem);
642 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: call to"
643 " NewDocEntryByNumber failed.");
646 binEntry = new BinEntry(currentEntry);
647 if ( !AddEntry(binEntry))
649 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
650 " failed allthough this is a creation.");
655 binEntry = dynamic_cast< BinEntry* >(currentEntry);
656 if ( !binEntry ) // Euuuuh? It wasn't a BinEntry
657 // then we change it to a BinEntry ?
658 // Shouldn't it be considered as an error ?
660 // We need to promote the DocEntry to a BinEntry:
661 binEntry = new BinEntry(currentEntry);
662 if (!RemoveEntry(currentEntry))
664 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
665 " of previous DocEntry failed.");
668 if ( !AddEntry(binEntry))
670 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: adding"
671 " promoted BinEntry failed.");
678 if (lgth>0 && binArea)
680 tmpArea = new uint8_t[lgth];
681 memcpy(tmpArea,binArea,lgth);
687 if (!SetEntryByNumber(tmpArea, 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 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
743 return TransferSyntaxStrings[type];
746 //-----------------------------------------------------------------------------
750 * \brief Checks if a given Dicom Element exists within the H table
751 * @param group Group number of the searched Dicom Element
752 * @param element Element number of the searched Dicom Element
753 * @return true is found
755 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
757 const std::string &key = DictEntry::TranslateToKey(group, element );
758 return TagHT.count(key) != 0;
762 * \brief Searches within Header Entries (Dicom Elements) parsed with
763 * the public and private dictionaries
764 * for the element value of a given tag.
765 * \warning Don't use any longer : use GetPubEntryByName
766 * @param tagName name of the searched element.
767 * @return Corresponding element value when it exists,
768 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
770 std::string Document::GetEntryByName(TagName const & tagName)
772 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
778 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
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.
786 * Obtaining the VR (Value Representation) might be needed by caller
787 * to convert the string typed content to caller's native type
788 * (think of C++ vs Python). The VR is actually of a higher level
789 * of semantics than just the native C++ type.
790 * @param tagName name of the searched element.
791 * @return Corresponding element value representation when it exists,
792 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
794 std::string Document::GetEntryVRByName(TagName const& tagName)
796 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
797 if( dictEntry == NULL)
802 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
803 dictEntry->GetElement());
804 return elem->GetVR();
808 * \brief Searches within Header Entries (Dicom Elements) parsed with
809 * the public and private dictionaries
810 * for the element value representation of a given tag.
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::GetEntryByNumber(uint16_t group, uint16_t element)
818 TagKey key = DictEntry::TranslateToKey(group, element);
819 /// \todo use map methods, instead of multimap JPR
820 if ( !TagHT.count(key))
825 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
829 * \brief Searches within Header Entries (Dicom Elements) parsed with
830 * the public and private dictionaries
831 * for the element value representation of a given tag..
833 * Obtaining the VR (Value Representation) might be needed by caller
834 * to convert the string typed content to caller's native type
835 * (think of C++ vs Python). The VR is actually of a higher level
836 * of semantics than just the native C++ type.
837 * @param group Group number of the searched tag.
838 * @param element Element number of the searched tag.
839 * @return Corresponding element value representation when it exists,
840 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
842 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
844 DocEntry* elem = GetDocEntryByNumber(group, element);
849 return elem->GetVR();
853 * \brief Searches within Header Entries (Dicom Elements) parsed with
854 * the public and private dictionaries
855 * for the value length of a given tag..
856 * @param group Group number of the searched tag.
857 * @param element Element number of the searched tag.
858 * @return Corresponding element length; -2 if not found
860 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
862 DocEntry* elem = GetDocEntryByNumber(group, element);
865 return -2; //magic number
867 return elem->GetLength();
870 * \brief Sets the value (string) of the Header Entry (Dicom Element)
871 * @param content string value of the Dicom Element
872 * @param tagName name of the searched Dicom Element.
873 * @return true when found
875 bool Document::SetEntryByName( std::string const & content,
876 TagName const & tagName)
878 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
884 return SetEntryByNumber(content,dictEntry->GetGroup(),
885 dictEntry->GetElement());
889 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
890 * through it's (group, element) and modifies it's content with
892 * @param content new value (string) to substitute with
893 * @param group group number of the Dicom Element to modify
894 * @param element element number of the Dicom Element to modify
896 bool Document::SetEntryByNumber(std::string const& content,
897 uint16_t group, uint16_t element)
902 ValEntry* valEntry = GetValEntryByNumber(group, element);
905 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
906 " ValEntry (try promotion first).");
909 // Non even content must be padded with a space (020H)...
910 std::string finalContent = Util::DicomString( content.c_str() );
911 assert( !(finalContent.size() % 2) );
912 valEntry->SetValue(finalContent);
914 // Integers have a special treatement for their length:
916 l = finalContent.length();
917 if ( l != 0) // To avoid to be cheated by 'zero length' integers
919 VRKey vr = valEntry->GetVR();
920 if( vr == "US" || vr == "SS" )
922 // for multivaluated items
923 c = Util::CountSubstring(content, "\\") + 1;
926 else if( vr == "UL" || vr == "SL" )
928 // for multivaluated items
929 c = Util::CountSubstring(content, "\\") + 1;
933 valEntry->SetLength(l);
938 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
939 * through it's (group, element) and modifies it's content with
941 * @param content new value (void* -> uint8_t*) to substitute with
942 * @param lgth new value length
943 * @param group group number of the Dicom Element to modify
944 * @param element element number of the Dicom Element to modify
946 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
947 uint16_t group, uint16_t element)
949 (void)lgth; //not used
950 TagKey key = DictEntry::TranslateToKey(group, element);
951 if ( !TagHT.count(key))
956 /* Hope Binary field length is *never* wrong
957 if(lgth%2) // Non even length are padded with a space (020H).
960 //content = content + '\0'; // fing a trick to enlarge a binary field?
963 BinEntry* entry = (BinEntry *)TagHT[key];
964 entry->SetBinArea(content);
965 entry->SetLength(lgth);
966 entry->SetValue(GDCM_BINLOADED);
972 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
973 * in the PubDocEntrySet of this instance
974 * through it's (group, element) and modifies it's length with
976 * \warning Use with extreme caution.
977 * @param l new length to substitute with
978 * @param group group number of the Entry to modify
979 * @param element element number of the Entry to modify
980 * @return true on success, false otherwise.
982 bool Document::SetEntryLengthByNumber(uint32_t l,
983 uint16_t group, uint16_t element)
985 /// \todo use map methods, instead of multimap JPR
986 TagKey key = DictEntry::TranslateToKey(group, element);
987 if ( !TagHT.count(key) )
993 l++; // length must be even
995 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
1001 * \brief Gets (from Header) the offset of a 'non string' element value
1002 * (LoadElementValues has already be executed)
1003 * @param group group number of the Entry
1004 * @param elem element number of the Entry
1005 * @return File Offset of the Element Value
1007 size_t Document::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
1009 DocEntry* entry = GetDocEntryByNumber(group, elem);
1012 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry present.");
1015 return entry->GetOffset();
1019 * \brief Gets (from Header) a 'non string' element value
1020 * (LoadElementValues has already be executed)
1021 * @param group group number of the Entry
1022 * @param elem element number of the Entry
1023 * @return Pointer to the 'non string' area
1025 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
1027 DocEntry* entry = GetDocEntryByNumber(group, elem);
1030 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
1033 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
1035 return binEntry->GetBinArea();
1042 * \brief Loads (from disk) the element content
1043 * when a string is not suitable
1044 * @param group group number of the Entry
1045 * @param elem element number of the Entry
1047 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1049 // Search the corresponding DocEntry
1050 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1054 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1058 LoadEntryBinArea(binElement);
1059 /* size_t o =(size_t)docElement->GetOffset();
1060 Fp->seekg( o, std::ios_base::beg);
1061 size_t l = docElement->GetLength();
1062 uint8_t* a = new uint8_t[l];
1065 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1070 Fp->read((char*)a, l);
1071 if( Fp->fail() || Fp->eof() )//Fp->gcount() == 1
1077 // Set the value to the DocEntry
1078 if( !SetEntryBinAreaByNumber( a, group, elem ) )
1081 dbg.Verbose(0, "Document::LoadEntryBinArea setting failed.");
1086 * \brief Loads (from disk) the element content
1087 * when a string is not suitable
1088 * @param element Entry whose binArea is going to be loaded
1090 void Document::LoadEntryBinArea(BinEntry* element)
1092 if(element->GetBinArea())
1095 bool openFile = !Fp;
1099 size_t o =(size_t)element->GetOffset();
1100 Fp->seekg(o, std::ios_base::beg);
1102 size_t l = element->GetLength();
1103 uint8_t* a = new uint8_t[l];
1106 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1110 /// \todo check the result
1111 Fp->read((char*)a, l);
1112 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1118 element->SetBinArea(a);
1125 * \brief Sets a 'non string' value to a given Dicom Element
1126 * @param area area containing the 'non string' value
1127 * @param group Group number of the searched Dicom Element
1128 * @param element Element number of the searched Dicom Element
1131 bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1132 uint16_t group, uint16_t element)
1134 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1135 if ( !currentEntry )
1140 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1142 binEntry->SetBinArea( area );
1150 * \brief Update the entries with the shadow dictionary.
1151 * Only non even entries are analyzed
1153 void Document::UpdateShaEntries()
1158 /// \todo TODO : still any use to explore recursively the whole structure?
1160 for(ListTag::iterator it=listEntries.begin();
1161 it!=listEntries.end();
1164 // Odd group => from public dictionary
1165 if((*it)->GetGroup()%2==0)
1168 // Peer group => search the corresponding dict entry
1170 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1174 if((*it)->IsImplicitVR())
1179 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1181 // Set the new entry and the new value
1182 (*it)->SetDictEntry(entry);
1183 CheckDocEntryVR(*it,vr);
1185 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1190 // Remove precedent value transformation
1191 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1198 * \brief Searches within the Header Entries for a Dicom Element of
1200 * @param tagName name of the searched Dicom Element.
1201 * @return Corresponding Dicom Element when it exists, and NULL
1204 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1206 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1212 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1216 * \brief retrieves a Dicom Element (the first one) using (group, element)
1217 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1218 * if you think it's NOT UNIQUE, check the count number
1219 * and use iterators to retrieve ALL the Dicoms Elements within
1220 * a given couple (group, element)
1221 * @param group Group number of the searched Dicom Element
1222 * @param element Element number of the searched Dicom Element
1225 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1227 TagKey key = DictEntry::TranslateToKey(group, element);
1228 if ( !TagHT.count(key))
1232 return TagHT.find(key)->second;
1236 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1237 * returns a result when the corresponding entry is of type
1239 * @return When present, the corresponding ValEntry.
1241 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1243 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1244 if ( !currentEntry )
1248 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1252 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1258 * \brief Loads the element while preserving the current
1259 * underlying file position indicator as opposed to
1260 * to LoadDocEntry that modifies it.
1261 * @param entry Header Entry whose value shall be loaded.
1264 void Document::LoadDocEntrySafe(DocEntry * entry)
1268 long PositionOnEntry = Fp->tellg();
1269 LoadDocEntry(entry);
1270 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1275 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1277 * @return The properly swaped 32 bits integer.
1279 uint32_t Document::SwapLong(uint32_t a)
1286 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1287 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1291 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1295 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1298 //std::cout << "swapCode= " << SwapCode << std::endl;
1299 dbg.Error(" Document::SwapLong : unset swap code");
1306 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1308 * @return The properly unswaped 32 bits integer.
1310 uint32_t Document::UnswapLong(uint32_t a)
1316 * \brief Swaps the bytes so they agree with the processor order
1317 * @return The properly swaped 16 bits integer.
1319 uint16_t Document::SwapShort(uint16_t a)
1321 if ( SwapCode == 4321 || SwapCode == 2143 )
1323 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1329 * \brief Unswaps the bytes so they agree with the processor order
1330 * @return The properly unswaped 16 bits integer.
1332 uint16_t Document::UnswapShort(uint16_t a)
1334 return SwapShort(a);
1337 //-----------------------------------------------------------------------------
1341 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1342 * @return length of the parsed set.
1344 void Document::ParseDES(DocEntrySet *set, long offset,
1345 long l_max, bool delim_mode)
1347 DocEntry *newDocEntry = 0;
1351 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1355 newDocEntry = ReadNextDocEntry( );
1361 VRKey vr = newDocEntry->GetVR();
1365 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1367 /////////////////////// ValEntry
1368 ValEntry* newValEntry =
1369 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1370 newValEntry->Copy( newDocEntry );
1372 // When "set" is a Document, then we are at the top of the
1373 // hierarchy and the Key is simply of the form ( group, elem )...
1374 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1377 newValEntry->SetKey( newValEntry->GetKey() );
1379 // ...but when "set" is a SQItem, we are inserting this new
1380 // valEntry in a sequence item. Hence the key has the
1381 // generalized form (refer to \ref BaseTagKey):
1382 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1384 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1385 + newValEntry->GetKey() );
1388 LoadDocEntry( newValEntry );
1389 bool delimitor=newValEntry->IsItemDelimitor();
1390 if( !set->AddEntry( newValEntry ) )
1392 // If here expect big troubles
1393 delete newValEntry; //otherwise mem leak
1401 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1409 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1411 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1412 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1413 "nor BinEntry. Probably unknown VR.");
1416 //////////////////// BinEntry or UNKOWN VR:
1417 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1419 // When "this" is a Document the Key is simply of the
1420 // form ( group, elem )...
1421 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1424 newBinEntry->SetKey( newBinEntry->GetKey() );
1426 // but when "this" is a SQItem, we are inserting this new
1427 // valEntry in a sequence item, and the kay has the
1428 // generalized form (refer to \ref BaseTagKey):
1429 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1431 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1432 + newBinEntry->GetKey() );
1435 LoadDocEntry( newBinEntry );
1436 if( !set->AddEntry( newBinEntry ) )
1438 //Expect big troubles if here
1443 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1444 && ( newDocEntry->GetElement() == 0x0010 ) )
1446 TransferSyntaxType ts = GetTransferSyntax();
1447 if ( ts == RLELossless )
1449 long PositionOnEntry = Fp->tellg();
1450 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1452 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1454 else if ( IsJPEG() )
1456 long PositionOnEntry = Fp->tellg();
1457 Fp->seekg( newDocEntry->GetOffset(), std::ios_base::beg );
1458 ComputeJPEGFragmentInfo();
1459 Fp->seekg( PositionOnEntry, std::ios_base::beg );
1463 // Just to make sure we are at the beginning of next entry.
1464 SkipToNextDocEntry(newDocEntry);
1465 //delete newDocEntry;
1470 unsigned long l = newDocEntry->GetReadLength();
1471 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1473 if ( l == 0xffffffff )
1482 // no other way to create it ...
1483 SeqEntry* newSeqEntry =
1484 new SeqEntry( newDocEntry->GetDictEntry() );
1485 newSeqEntry->Copy( newDocEntry );
1486 newSeqEntry->SetDelimitorMode( delim_mode );
1488 // At the top of the hierarchy, stands a Document. When "set"
1489 // is a Document, then we are building the first depth level.
1490 // Hence the SeqEntry we are building simply has a depth
1492 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1495 newSeqEntry->SetDepthLevel( 1 );
1496 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1498 // But when "set" is allready a SQItem, we are building a nested
1499 // sequence, and hence the depth level of the new SeqEntry
1500 // we are building, is one level deeper:
1501 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1503 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1504 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1505 + newSeqEntry->GetKey() );
1509 { // Don't try to parse zero-length sequences
1510 ParseSQ( newSeqEntry,
1511 newDocEntry->GetOffset(),
1514 set->AddEntry( newSeqEntry );
1515 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1526 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1527 * @return parsed length for this level
1529 void Document::ParseSQ( SeqEntry* seqEntry,
1530 long offset, long l_max, bool delim_mode)
1532 int SQItemNumber = 0;
1537 DocEntry* newDocEntry = ReadNextDocEntry();
1540 // FIXME Should warn user
1545 if ( newDocEntry->IsSequenceDelimitor() )
1547 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1551 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1557 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1558 std::ostringstream newBase;
1559 newBase << seqEntry->GetKey()
1563 itemSQ->SetBaseTagKey( newBase.str() );
1564 unsigned int l = newDocEntry->GetReadLength();
1566 if ( l == 0xffffffff )
1575 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1578 seqEntry->AddEntry( itemSQ, SQItemNumber );
1580 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1588 * \brief Loads the element content if its length doesn't exceed
1589 * the value specified with Document::SetMaxSizeLoadEntry()
1590 * @param entry Header Entry (Dicom Element) to be dealt with
1592 void Document::LoadDocEntry(DocEntry* entry)
1594 uint16_t group = entry->GetGroup();
1595 std::string vr = entry->GetVR();
1596 uint32_t length = entry->GetLength();
1598 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1600 // A SeQuence "contains" a set of Elements.
1601 // (fffe e000) tells us an Element is beginning
1602 // (fffe e00d) tells us an Element just ended
1603 // (fffe e0dd) tells us the current SeQuence just ended
1604 if( group == 0xfffe )
1606 // NO more value field for SQ !
1610 // When the length is zero things are easy:
1613 ((ValEntry *)entry)->SetValue("");
1617 // The elements whose length is bigger than the specified upper bound
1618 // are not loaded. Instead we leave a short notice of the offset of
1619 // the element content and it's length.
1621 std::ostringstream s;
1622 if (length > MaxSizeLoadEntry)
1624 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1626 //s << "gdcm::NotLoaded (BinEntry)";
1627 s << GDCM_NOTLOADED;
1628 s << " Address:" << (long)entry->GetOffset();
1629 s << " Length:" << entry->GetLength();
1630 s << " x(" << std::hex << entry->GetLength() << ")";
1631 binEntryPtr->SetValue(s.str());
1633 // Be carefull : a BinEntry IS_A ValEntry ...
1634 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1636 // s << "gdcm::NotLoaded. (ValEntry)";
1637 s << GDCM_NOTLOADED;
1638 s << " Address:" << (long)entry->GetOffset();
1639 s << " Length:" << entry->GetLength();
1640 s << " x(" << std::hex << entry->GetLength() << ")";
1641 valEntryPtr->SetValue(s.str());
1646 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1647 << "nor a ValEntry ?! Should never print that !" << std::endl;
1650 // to be sure we are at the end of the value ...
1651 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1652 std::ios_base::beg);
1656 // When we find a BinEntry not very much can be done :
1657 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1659 s << GDCM_BINLOADED;
1660 binEntryPtr->SetValue(s.str());
1661 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1665 /// \todo Any compacter code suggested (?)
1666 if ( IsDocEntryAnInteger(entry) )
1670 // When short integer(s) are expected, read and convert the following
1671 // n *two characters properly i.e. consider them as short integers as
1672 // opposed to strings.
1673 // Elements with Value Multiplicity > 1
1674 // contain a set of integers (not a single one)
1675 if (vr == "US" || vr == "SS")
1678 NewInt = ReadInt16();
1682 for (int i=1; i < nbInt; i++)
1685 NewInt = ReadInt16();
1690 // See above comment on multiple integers (mutatis mutandis).
1691 else if (vr == "UL" || vr == "SL")
1694 NewInt = ReadInt32();
1698 for (int i=1; i < nbInt; i++)
1701 NewInt = ReadInt32();
1706 #ifdef GDCM_NO_ANSI_STRING_STREAM
1707 s << std::ends; // to avoid oddities on Solaris
1708 #endif //GDCM_NO_ANSI_STRING_STREAM
1710 ((ValEntry *)entry)->SetValue(s.str());
1714 // FIXME: We need an additional byte for storing \0 that is not on disk
1715 char *str = new char[length+1];
1716 Fp->read(str, (size_t)length);
1717 str[length] = '\0'; //this is only useful when length is odd
1718 // Special DicomString call to properly handle \0 and even length
1719 std::string newValue;
1722 newValue = Util::DicomString(str, length+1);
1723 //dbg.Verbose(0, "Warning: bad length: ", length );
1724 dbg.Verbose(0, "For string :", newValue.c_str());
1725 // Since we change the length of string update it length
1726 entry->SetReadLength(length+1);
1730 newValue = Util::DicomString(str, length);
1734 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1736 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1738 dbg.Verbose(1, "Document::LoadDocEntry",
1739 "unread element value");
1740 valEntry->SetValue(GDCM_UNREAD);
1746 // Because of correspondance with the VR dic
1747 valEntry->SetValue(newValue);
1751 valEntry->SetValue(newValue);
1756 dbg.Error(true, "Document::LoadDocEntry"
1757 "Should have a ValEntry, here !");
1763 * \brief Find the value Length of the passed Header Entry
1764 * @param entry Header Entry whose length of the value shall be loaded.
1766 void Document::FindDocEntryLength( DocEntry *entry )
1767 throw ( FormatError )
1769 uint16_t element = entry->GetElement();
1770 std::string vr = entry->GetVR();
1773 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1775 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1777 // The following reserved two bytes (see PS 3.5-2003, section
1778 // "7.1.2 Data element structure with explicit vr", p 27) must be
1779 // skipped before proceeding on reading the length on 4 bytes.
1780 Fp->seekg( 2L, std::ios_base::cur);
1781 uint32_t length32 = ReadInt32();
1783 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1788 /// \todo rename that to FindDocEntryLengthOBOrOW since
1789 /// the above test is on both OB and OW...
1790 lengthOB = FindDocEntryLengthOB();
1792 catch ( FormatUnexpected )
1794 // Computing the length failed (this happens with broken
1795 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1796 // chance to get the pixels by deciding the element goes
1797 // until the end of the file. Hence we artificially fix the
1798 // the length and proceed.
1799 long currentPosition = Fp->tellg();
1800 Fp->seekg(0L,std::ios_base::end);
1801 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1802 Fp->seekg(currentPosition, std::ios_base::beg);
1803 entry->SetLength(lengthUntilEOF);
1806 entry->SetLength(lengthOB);
1809 FixDocEntryFoundLength(entry, length32);
1813 // Length is encoded on 2 bytes.
1814 length16 = ReadInt16();
1816 // We can tell the current file is encoded in big endian (like
1817 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1818 // and it's value is the one of the encoding of a big endian file.
1819 // In order to deal with such big endian encoded files, we have
1820 // (at least) two strategies:
1821 // * when we load the "Transfer Syntax" tag with value of big endian
1822 // encoding, we raise the proper flags. Then we wait for the end
1823 // of the META group (0x0002) among which is "Transfer Syntax",
1824 // before switching the swap code to big endian. We have to postpone
1825 // the switching of the swap code since the META group is fully encoded
1826 // in little endian, and big endian coding only starts at the next
1827 // group. The corresponding code can be hard to analyse and adds
1828 // many additional unnecessary tests for regular tags.
1829 // * the second strategy consists in waiting for trouble, that shall
1830 // appear when we find the first group with big endian encoding. This
1831 // is easy to detect since the length of a "Group Length" tag (the
1832 // ones with zero as element number) has to be of 4 (0x0004). When we
1833 // encounter 1024 (0x0400) chances are the encoding changed and we
1834 // found a group with big endian encoding.
1835 // We shall use this second strategy. In order to make sure that we
1836 // can interpret the presence of an apparently big endian encoded
1837 // length of a "Group Length" without committing a big mistake, we
1838 // add an additional check: we look in the already parsed elements
1839 // for the presence of a "Transfer Syntax" whose value has to be "big
1840 // endian encoding". When this is the case, chances are we have got our
1841 // hands on a big endian encoded file: we switch the swap code to
1842 // big endian and proceed...
1843 if ( element == 0x0000 && length16 == 0x0400 )
1845 TransferSyntaxType ts = GetTransferSyntax();
1846 if ( ts != ExplicitVRBigEndian )
1848 throw FormatError( "Document::FindDocEntryLength()",
1849 " not explicit VR." );
1853 SwitchSwapToBigEndian();
1854 // Restore the unproperly loaded values i.e. the group, the element
1855 // and the dictionary entry depending on them.
1856 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1857 uint16_t correctElem = SwapShort( entry->GetElement() );
1858 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1862 // This correct tag is not in the dictionary. Create a new one.
1863 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1865 // FIXME this can create a memory leaks on the old entry that be
1866 // left unreferenced.
1867 entry->SetDictEntry( newTag );
1870 // Heuristic: well, some files are really ill-formed.
1871 if ( length16 == 0xffff)
1873 // 0xffff means that we deal with 'Unknown Length' Sequence
1876 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1881 // Either implicit VR or a non DICOM conformal (see note below) explicit
1882 // VR that ommited the VR of (at least) this element. Farts happen.
1883 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1884 // on Data elements "Implicit and Explicit VR Data Elements shall
1885 // not coexist in a Data Set and Data Sets nested within it".]
1886 // Length is on 4 bytes.
1888 FixDocEntryFoundLength( entry, ReadInt32() );
1894 * \brief Find the Value Representation of the current Dicom Element.
1897 void Document::FindDocEntryVR( DocEntry *entry )
1899 if ( Filetype != ExplicitVR )
1906 long positionOnEntry = Fp->tellg();
1907 // Warning: we believe this is explicit VR (Value Representation) because
1908 // we used a heuristic that found "UL" in the first tag. Alas this
1909 // doesn't guarantee that all the tags will be in explicit VR. In some
1910 // cases (see e-film filtered files) one finds implicit VR tags mixed
1911 // within an explicit VR file. Hence we make sure the present tag
1912 // is in explicit VR and try to fix things if it happens not to be
1915 Fp->read (vr, (size_t)2);
1918 if( !CheckDocEntryVR(entry, vr) )
1920 Fp->seekg(positionOnEntry, std::ios_base::beg);
1921 // When this element is known in the dictionary we shall use, e.g. for
1922 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1923 // dictionary entry. Still we have to flag the element as implicit since
1924 // we know now our assumption on expliciteness is not furfilled.
1926 if ( entry->IsVRUnknown() )
1928 entry->SetVR("Implicit");
1930 entry->SetImplicitVR();
1935 * \brief Check the correspondance between the VR of the header entry
1936 * and the taken VR. If they are different, the header entry is
1937 * updated with the new VR.
1938 * @param entry Header Entry to check
1939 * @param vr Dicom Value Representation
1940 * @return false if the VR is incorrect of if the VR isn't referenced
1941 * otherwise, it returns true
1943 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1946 bool realExplicit = true;
1948 // Assume we are reading a falsely explicit VR file i.e. we reached
1949 // a tag where we expect reading a VR but are in fact we read the
1950 // first to bytes of the length. Then we will interogate (through find)
1951 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1952 // both GCC and VC++ implementations of the STL map. Hence when the
1953 // expected VR read happens to be non-ascii characters we consider
1954 // we hit falsely explicit VR tag.
1956 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1958 realExplicit = false;
1961 // CLEANME searching the dicom_vr at each occurence is expensive.
1962 // PostPone this test in an optional integrity check at the end
1963 // of parsing or only in debug mode.
1964 if ( realExplicit && !Global::GetVR()->Count(vr) )
1966 realExplicit = false;
1969 if ( !realExplicit )
1971 // We thought this was explicit VR, but we end up with an
1972 // implicit VR tag. Let's backtrack.
1973 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1974 entry->GetGroup(), entry->GetElement());
1975 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1977 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1979 // Group length is UL !
1980 DictEntry* newEntry = NewVirtualDictEntry(
1981 entry->GetGroup(), entry->GetElement(),
1982 "UL", "FIXME", "Group Length");
1983 entry->SetDictEntry( newEntry );
1988 if ( entry->IsVRUnknown() )
1990 // When not a dictionary entry, we can safely overwrite the VR.
1991 if( entry->GetElement() == 0x0000 )
1993 // Group length is UL !
2001 else if ( entry->GetVR() != vr )
2003 // The VR present in the file and the dictionary disagree. We assume
2004 // the file writer knew best and use the VR of the file. Since it would
2005 // be unwise to overwrite the VR of a dictionary (since it would
2006 // compromise it's next user), we need to clone the actual DictEntry
2007 // and change the VR for the read one.
2008 DictEntry* newEntry = NewVirtualDictEntry(
2009 entry->GetGroup(), entry->GetElement(),
2010 vr, "FIXME", entry->GetName());
2011 entry->SetDictEntry(newEntry);
2018 * \brief Get the transformed value of the header entry. The VR value
2019 * is used to define the transformation to operate on the value
2020 * \warning NOT end user intended method !
2021 * @param entry entry to tranform
2022 * @return Transformed entry value
2024 std::string Document::GetDocEntryValue(DocEntry *entry)
2026 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2028 std::string val = ((ValEntry *)entry)->GetValue();
2029 std::string vr = entry->GetVR();
2030 uint32_t length = entry->GetLength();
2031 std::ostringstream s;
2034 // When short integer(s) are expected, read and convert the following
2035 // n * 2 bytes properly i.e. as a multivaluated strings
2036 // (each single value is separated fromthe next one by '\'
2037 // as usual for standard multivaluated filels
2038 // Elements with Value Multiplicity > 1
2039 // contain a set of short integers (not a single one)
2041 if( vr == "US" || vr == "SS" )
2046 for (int i=0; i < nbInt; i++)
2052 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2053 newInt16 = SwapShort( newInt16 );
2058 // When integer(s) are expected, read and convert the following
2059 // n * 4 bytes properly i.e. as a multivaluated strings
2060 // (each single value is separated fromthe next one by '\'
2061 // as usual for standard multivaluated filels
2062 // Elements with Value Multiplicity > 1
2063 // contain a set of integers (not a single one)
2064 else if( vr == "UL" || vr == "SL" )
2069 for (int i=0; i < nbInt; i++)
2075 newInt32 = ( val[4*i+0] & 0xFF )
2076 + (( val[4*i+1] & 0xFF ) << 8 )
2077 + (( val[4*i+2] & 0xFF ) << 16 )
2078 + (( val[4*i+3] & 0xFF ) << 24 );
2079 newInt32 = SwapLong( newInt32 );
2083 #ifdef GDCM_NO_ANSI_STRING_STREAM
2084 s << std::ends; // to avoid oddities on Solaris
2085 #endif //GDCM_NO_ANSI_STRING_STREAM
2089 return ((ValEntry *)entry)->GetValue();
2093 * \brief Get the reverse transformed value of the header entry. The VR
2094 * value is used to define the reverse transformation to operate on
2096 * \warning NOT end user intended method !
2097 * @param entry Entry to reverse transform
2098 * @return Reverse transformed entry value
2100 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2102 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2104 std::string vr = entry->GetVR();
2105 std::vector<std::string> tokens;
2106 std::ostringstream s;
2108 if ( vr == "US" || vr == "SS" )
2112 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2113 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2114 for (unsigned int i=0; i<tokens.size(); i++)
2116 newInt16 = atoi(tokens[i].c_str());
2117 s << ( newInt16 & 0xFF )
2118 << (( newInt16 >> 8 ) & 0xFF );
2122 if ( vr == "UL" || vr == "SL")
2126 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2127 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2128 for (unsigned int i=0; i<tokens.size();i++)
2130 newInt32 = atoi(tokens[i].c_str());
2131 s << (char)( newInt32 & 0xFF )
2132 << (char)(( newInt32 >> 8 ) & 0xFF )
2133 << (char)(( newInt32 >> 16 ) & 0xFF )
2134 << (char)(( newInt32 >> 24 ) & 0xFF );
2139 #ifdef GDCM_NO_ANSI_STRING_STREAM
2140 s << std::ends; // to avoid oddities on Solaris
2141 #endif //GDCM_NO_ANSI_STRING_STREAM
2145 return ((ValEntry *)entry)->GetValue();
2149 * \brief Skip a given Header Entry
2150 * \warning NOT end user intended method !
2151 * @param entry entry to skip
2153 void Document::SkipDocEntry(DocEntry *entry)
2155 SkipBytes(entry->GetLength());
2159 * \brief Skips to the begining of the next Header Entry
2160 * \warning NOT end user intended method !
2161 * @param entry entry to skip
2163 void Document::SkipToNextDocEntry(DocEntry *entry)
2165 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2166 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2170 * \brief When the length of an element value is obviously wrong (because
2171 * the parser went Jabberwocky) one can hope improving things by
2172 * applying some heuristics.
2173 * @param entry entry to check
2174 * @param foundLength fist assumption about length
2176 void Document::FixDocEntryFoundLength(DocEntry *entry,
2177 uint32_t foundLength)
2179 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2180 if ( foundLength == 0xffffffff)
2185 uint16_t gr = entry->GetGroup();
2186 uint16_t el = entry->GetElement();
2188 if ( foundLength % 2)
2190 std::ostringstream s;
2191 s << "Warning : Tag with uneven length "
2193 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2194 dbg.Verbose(0, s.str().c_str());
2197 //////// Fix for some naughty General Electric images.
2198 // Allthough not recent many such GE corrupted images are still present
2199 // on Creatis hard disks. Hence this fix shall remain when such images
2200 // are no longer in user (we are talking a few years, here)...
2201 // Note: XMedCom probably uses such a trick since it is able to read
2202 // those pesky GE images ...
2203 if ( foundLength == 13)
2205 // Only happens for this length !
2206 if ( entry->GetGroup() != 0x0008
2207 || ( entry->GetElement() != 0x0070
2208 && entry->GetElement() != 0x0080 ) )
2211 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2215 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2216 // Occurence of such images is quite low (unless one leaves close to a
2217 // 'Leonardo' source. Hence, one might consider commenting out the
2218 // following fix on efficiency reasons.
2219 else if ( entry->GetGroup() == 0x0009
2220 && ( entry->GetElement() == 0x1113
2221 || entry->GetElement() == 0x1114 ) )
2224 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2227 else if ( entry->GetVR() == "SQ" )
2229 foundLength = 0; // ReadLength is unchanged
2232 //////// We encountered a 'delimiter' element i.e. a tag of the form
2233 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2234 // taken into account.
2235 else if( entry->GetGroup() == 0xfffe )
2237 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2238 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2239 // causes extra troubles...
2240 if( entry->GetElement() != 0x0000 )
2246 entry->SetUsableLength(foundLength);
2250 * \brief Apply some heuristics to predict whether the considered
2251 * element value contains/represents an integer or not.
2252 * @param entry The element value on which to apply the predicate.
2253 * @return The result of the heuristical predicate.
2255 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2257 uint16_t element = entry->GetElement();
2258 uint16_t group = entry->GetGroup();
2259 const std::string & vr = entry->GetVR();
2260 uint32_t length = entry->GetLength();
2262 // When we have some semantics on the element we just read, and if we
2263 // a priori know we are dealing with an integer, then we shall be
2264 // able to swap it's element value properly.
2265 if ( element == 0 ) // This is the group length of the group
2273 // Allthough this should never happen, still some images have a
2274 // corrupted group length [e.g. have a glance at offset x(8336) of
2275 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2276 // Since for dicom compliant and well behaved headers, the present
2277 // test is useless (and might even look a bit paranoid), when we
2278 // encounter such an ill-formed image, we simply display a warning
2279 // message and proceed on parsing (while crossing fingers).
2280 std::ostringstream s;
2281 long filePosition = Fp->tellg();
2282 s << "Erroneous Group Length element length on : (" \
2283 << std::hex << group << " , " << element
2284 << ") -before- position x(" << filePosition << ")"
2285 << "lgt : " << length;
2286 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2290 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2299 * \brief Find the Length till the next sequence delimiter
2300 * \warning NOT end user intended method !
2304 uint32_t Document::FindDocEntryLengthOB()
2305 throw( FormatUnexpected )
2307 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2308 long positionOnEntry = Fp->tellg();
2309 bool foundSequenceDelimiter = false;
2310 uint32_t totalLength = 0;
2312 while ( !foundSequenceDelimiter )
2318 group = ReadInt16();
2321 catch ( FormatError )
2323 throw FormatError("Document::FindDocEntryLengthOB()",
2324 " group or element not present.");
2327 // We have to decount the group and element we just read
2330 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2332 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2333 "tag nor a Sequence delimiter tag.");
2334 Fp->seekg(positionOnEntry, std::ios_base::beg);
2335 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2336 "Neither an Item tag nor a Sequence "
2340 if ( elem == 0xe0dd )
2342 foundSequenceDelimiter = true;
2345 uint32_t itemLength = ReadInt32();
2346 // We add 4 bytes since we just read the ItemLength with ReadInt32
2347 totalLength += itemLength + 4;
2348 SkipBytes(itemLength);
2350 if ( foundSequenceDelimiter )
2355 Fp->seekg( positionOnEntry, std::ios_base::beg);
2360 * \brief Reads a supposed to be 16 Bits integer
2361 * (swaps it depending on processor endianity)
2362 * @return read value
2364 uint16_t Document::ReadInt16()
2365 throw( FormatError )
2368 Fp->read ((char*)&g, (size_t)2);
2371 throw FormatError( "Document::ReadInt16()", " file error." );
2375 throw FormatError( "Document::ReadInt16()", "EOF." );
2382 * \brief Reads a supposed to be 32 Bits integer
2383 * (swaps it depending on processor endianity)
2384 * @return read value
2386 uint32_t Document::ReadInt32()
2387 throw( FormatError )
2390 Fp->read ((char*)&g, (size_t)4);
2393 throw FormatError( "Document::ReadInt32()", " file error." );
2397 throw FormatError( "Document::ReadInt32()", "EOF." );
2404 * \brief skips bytes inside the source file
2405 * \warning NOT end user intended method !
2408 void Document::SkipBytes(uint32_t nBytes)
2410 //FIXME don't dump the returned value
2411 Fp->seekg((long)nBytes, std::ios_base::cur);
2415 * \brief Loads all the needed Dictionaries
2416 * \warning NOT end user intended method !
2418 void Document::Initialise()
2420 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2422 RLEInfo = new RLEFramesInfo;
2423 JPEGInfo = new JPEGFragmentsInfo;
2427 * \brief Discover what the swap code is (among little endian, big endian,
2428 * bad little endian, bad big endian).
2430 * @return false when we are absolutely sure
2431 * it's neither ACR-NEMA nor DICOM
2432 * true when we hope ours assuptions are OK
2434 bool Document::CheckSwap()
2436 // The only guaranted way of finding the swap code is to find a
2437 // group tag since we know it's length has to be of four bytes i.e.
2438 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2439 // occurs when we can't find such group...
2441 uint32_t x = 4; // x : for ntohs
2442 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2446 char deb[256]; //HEADER_LENGTH_TO_READ];
2448 // First, compare HostByteOrder and NetworkByteOrder in order to
2449 // determine if we shall need to swap bytes (i.e. the Endian type).
2450 if ( x == ntohs(x) )
2459 // The easiest case is the one of a DICOM header, since it possesses a
2460 // file preamble where it suffice to look for the string "DICM".
2461 Fp->read(deb, HEADER_LENGTH_TO_READ);
2463 char *entCur = deb + 128;
2464 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2466 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2468 // Next, determine the value representation (VR). Let's skip to the
2469 // first element (0002, 0000) and check there if we find "UL"
2470 // - or "OB" if the 1st one is (0002,0001) -,
2471 // in which case we (almost) know it is explicit VR.
2472 // WARNING: if it happens to be implicit VR then what we will read
2473 // is the length of the group. If this ascii representation of this
2474 // length happens to be "UL" then we shall believe it is explicit VR.
2475 // FIXME: in order to fix the above warning, we could read the next
2476 // element value (or a couple of elements values) in order to make
2477 // sure we are not commiting a big mistake.
2478 // We need to skip :
2479 // * the 128 bytes of File Preamble (often padded with zeroes),
2480 // * the 4 bytes of "DICM" string,
2481 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2482 // i.e. a total of 136 bytes.
2486 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2487 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2488 // *Implicit* VR. -and it is !-
2490 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2491 memcmp(entCur, "OB", (size_t)2) == 0 ||
2492 memcmp(entCur, "UI", (size_t)2) == 0 ||
2493 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2494 // when Write DCM *adds*
2496 // Use Document::dicom_vr to test all the possibilities
2497 // instead of just checking for UL, OB and UI !? group 0000
2499 Filetype = ExplicitVR;
2500 dbg.Verbose(1, "Document::CheckSwap:",
2501 "explicit Value Representation");
2505 Filetype = ImplicitVR;
2506 dbg.Verbose(1, "Document::CheckSwap:",
2507 "not an explicit Value Representation");
2513 dbg.Verbose(1, "Document::CheckSwap:",
2514 "HostByteOrder != NetworkByteOrder");
2519 dbg.Verbose(1, "Document::CheckSwap:",
2520 "HostByteOrder = NetworkByteOrder");
2523 // Position the file position indicator at first tag (i.e.
2524 // after the file preamble and the "DICM" string).
2525 Fp->seekg(0, std::ios_base::beg);
2526 Fp->seekg ( 132L, std::ios_base::beg);
2530 // Alas, this is not a DicomV3 file and whatever happens there is no file
2531 // preamble. We can reset the file position indicator to where the data
2532 // is (i.e. the beginning of the file).
2533 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2534 Fp->seekg(0, std::ios_base::beg);
2536 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2537 // By clean we mean that the length of the first tag is written down.
2538 // If this is the case and since the length of the first group HAS to be
2539 // four (bytes), then determining the proper swap code is straightforward.
2542 // We assume the array of char we are considering contains the binary
2543 // representation of a 32 bits integer. Hence the following dirty
2545 s32 = *((uint32_t *)(entCur));
2566 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2567 // It is time for despaired wild guesses.
2568 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2569 // i.e. the 'group length' element is not present :
2571 // check the supposed-to-be 'group number'
2572 // in ( 0x0001 .. 0x0008 )
2573 // to determine ' SwapCode' value .
2574 // Only 0 or 4321 will be possible
2575 // (no oportunity to check for the formerly well known
2576 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2577 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2578 // the file IS NOT ACR-NEMA nor DICOM V3
2579 // Find a trick to tell it the caller...
2581 s16 = *((uint16_t *)(deb));
2608 dbg.Verbose(0, "Document::CheckSwap:",
2609 "ACR/NEMA unfound swap info (Really hopeless !)");
2613 // Then the only info we have is the net2host one.
2625 * \brief Restore the unproperly loaded values i.e. the group, the element
2626 * and the dictionary entry depending on them.
2628 void Document::SwitchSwapToBigEndian()
2630 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2631 "Switching to BigEndian mode.");
2632 if ( SwapCode == 0 )
2636 else if ( SwapCode == 4321 )
2640 else if ( SwapCode == 3412 )
2644 else if ( SwapCode == 2143 )
2651 * \brief during parsing, Header Elements too long are not loaded in memory
2654 void Document::SetMaxSizeLoadEntry(long newSize)
2660 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2662 MaxSizeLoadEntry = 0xffffffff;
2665 MaxSizeLoadEntry = newSize;
2670 * \brief Header Elements too long will not be printed
2671 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2674 void Document::SetMaxSizePrintEntry(long newSize)
2676 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2681 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2683 MaxSizePrintEntry = 0xffffffff;
2686 MaxSizePrintEntry = newSize;
2692 * \brief Handle broken private tag from Philips NTSCAN
2693 * where the endianess is being switch to BigEndian for no
2697 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2699 // Endian reversion. Some files contain groups of tags with reversed endianess.
2700 static int reversedEndian = 0;
2701 // try to fix endian switching in the middle of headers
2702 if ((group == 0xfeff) && (elem == 0x00e0))
2704 // start endian swap mark for group found
2706 SwitchSwapToBigEndian();
2711 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2713 // end of reversed endian group
2715 SwitchSwapToBigEndian();
2721 * \brief Read the next tag but WITHOUT loading it's value
2722 * (read the 'Group Number', the 'Element Number',
2723 * gets the Dict Entry
2724 * gets the VR, gets the length, gets the offset value)
2725 * @return On succes the newly created DocEntry, NULL on failure.
2727 DocEntry* Document::ReadNextDocEntry()
2734 group = ReadInt16();
2737 catch ( FormatError e )
2739 // We reached the EOF (or an error occured) therefore
2740 // header parsing has to be considered as finished.
2745 HandleBrokenEndian(group, elem);
2746 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2747 FindDocEntryVR(newEntry);
2751 FindDocEntryLength(newEntry);
2753 catch ( FormatError e )
2761 newEntry->SetOffset(Fp->tellg());
2768 * \brief Generate a free TagKey i.e. a TagKey that is not present
2769 * in the TagHt dictionary.
2770 * @param group The generated tag must belong to this group.
2771 * @return The element of tag with given group which is fee.
2773 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2775 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2777 TagKey key = DictEntry::TranslateToKey(group, elem);
2778 if (TagHT.count(key) == 0)
2787 * \brief Assuming the internal file pointer \ref Document::Fp
2788 * is placed at the beginning of a tag check whether this
2789 * tag is (TestGroup, TestElement).
2790 * \warning On success the internal file pointer \ref Document::Fp
2791 * is modified to point after the tag.
2792 * On failure (i.e. when the tag wasn't the expected tag
2793 * (TestGroup, TestElement) the internal file pointer
2794 * \ref Document::Fp is restored to it's original position.
2795 * @param testGroup The expected group of the tag.
2796 * @param testElement The expected Element of the tag.
2797 * @return True on success, false otherwise.
2799 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2801 long positionOnEntry = Fp->tellg();
2802 long currentPosition = Fp->tellg(); // On debugging purposes
2804 //// Read the Item Tag group and element, and make
2805 // sure they are what we expected:
2806 uint16_t itemTagGroup;
2807 uint16_t itemTagElement;
2810 itemTagGroup = ReadInt16();
2811 itemTagElement = ReadInt16();
2813 catch ( FormatError e )
2815 //std::cerr << e << std::endl;
2818 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2820 std::ostringstream s;
2821 s << " We should have found tag (";
2822 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2823 s << " but instead we encountered tag (";
2824 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2826 s << " at address: " << (unsigned)currentPosition << std::endl;
2827 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2828 dbg.Verbose(0, s.str().c_str());
2829 Fp->seekg(positionOnEntry, std::ios_base::beg);
2837 * \brief Assuming the internal file pointer \ref Document::Fp
2838 * is placed at the beginning of a tag (TestGroup, TestElement),
2839 * read the length associated to the Tag.
2840 * \warning On success the internal file pointer \ref Document::Fp
2841 * is modified to point after the tag and it's length.
2842 * On failure (i.e. when the tag wasn't the expected tag
2843 * (TestGroup, TestElement) the internal file pointer
2844 * \ref Document::Fp is restored to it's original position.
2845 * @param testGroup The expected group of the tag.
2846 * @param testElement The expected Element of the tag.
2847 * @return On success returns the length associated to the tag. On failure
2850 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2852 long positionOnEntry = Fp->tellg();
2853 (void)positionOnEntry;
2855 if ( !ReadTag(testGroup, testElement) )
2860 //// Then read the associated Item Length
2861 long currentPosition = Fp->tellg();
2862 uint32_t itemLength = ReadInt32();
2864 std::ostringstream s;
2865 s << "Basic Item Length is: "
2866 << itemLength << std::endl;
2867 s << " at address: " << (unsigned)currentPosition << std::endl;
2868 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2874 * \brief When parsing the Pixel Data of an encapsulated file, read
2875 * the basic offset table (when present, and BTW dump it).
2877 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2879 //// Read the Basic Offset Table Item Tag length...
2880 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2882 // When present, read the basic offset table itself.
2883 // Notes: - since the presence of this basic offset table is optional
2884 // we can't rely on it for the implementation, and we will simply
2885 // trash it's content (when present).
2886 // - still, when present, we could add some further checks on the
2887 // lengths, but we won't bother with such fuses for the time being.
2888 if ( itemLength != 0 )
2890 char* basicOffsetTableItemValue = new char[itemLength + 1];
2891 Fp->read(basicOffsetTableItemValue, itemLength);
2894 for (unsigned int i=0; i < itemLength; i += 4 )
2896 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2898 std::ostringstream s;
2899 s << " Read one length: ";
2900 s << std::hex << individualLength << std::endl;
2902 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2907 delete[] basicOffsetTableItemValue;
2912 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2913 * Compute the RLE extra information and store it in \ref RLEInfo
2914 * for later pixel retrieval usage.
2916 void Document::ComputeRLEInfo()
2918 TransferSyntaxType ts = GetTransferSyntax();
2919 if ( ts != RLELossless )
2924 // Encoded pixel data: for the time being we are only concerned with
2925 // Jpeg or RLE Pixel data encodings.
2926 // As stated in PS 3.5-2003, section 8.2 p44:
2927 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2928 // value representation OB is used".
2929 // Hence we expect an OB value representation. Concerning OB VR,
2930 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2931 // "For the Value Representations OB and OW, the encoding shall meet the
2932 // following specifications depending on the Data element tag:"
2934 // - the first item in the sequence of items before the encoded pixel
2935 // data stream shall be basic offset table item. The basic offset table
2936 // item value, however, is not required to be present"
2938 ReadAndSkipEncapsulatedBasicOffsetTable();
2940 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2941 // Loop on the individual frame[s] and store the information
2942 // on the RLE fragments in a RLEFramesInfo.
2943 // Note: - when only a single frame is present, this is a
2945 // - when more than one frame are present, then we are in
2946 // the case of a multi-frame image.
2948 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2950 // Parse the RLE Header and store the corresponding RLE Segment
2951 // Offset Table information on fragments of this current Frame.
2952 // Note that the fragment pixels themselves are not loaded
2953 // (but just skipped).
2954 long frameOffset = Fp->tellg();
2956 uint32_t nbRleSegments = ReadInt32();
2957 if ( nbRleSegments > 16 )
2959 // There should be at most 15 segments (refer to RLEFrame class)
2960 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2963 uint32_t rleSegmentOffsetTable[16];
2964 for( int k = 1; k <= 15; k++ )
2966 rleSegmentOffsetTable[k] = ReadInt32();
2969 // Deduce from both the RLE Header and the frameLength the
2970 // fragment length, and again store this info in a
2972 long rleSegmentLength[15];
2973 // skipping (not reading) RLE Segments
2974 if ( nbRleSegments > 1)
2976 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2978 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2979 - rleSegmentOffsetTable[k];
2980 SkipBytes(rleSegmentLength[k]);
2984 rleSegmentLength[nbRleSegments] = frameLength
2985 - rleSegmentOffsetTable[nbRleSegments];
2986 SkipBytes(rleSegmentLength[nbRleSegments]);
2988 // Store the collected info
2989 RLEFrame* newFrameInfo = new RLEFrame;
2990 newFrameInfo->NumberFragments = nbRleSegments;
2991 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2993 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2994 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2996 RLEInfo->Frames.push_back( newFrameInfo );
2999 // Make sure that at the end of the item we encounter a 'Sequence
3001 if ( !ReadTag(0xfffe, 0xe0dd) )
3003 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3004 dbg.Verbose(0, " item at end of RLE item sequence");
3009 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
3010 * Compute the jpeg extra information (fragment[s] offset[s] and
3011 * length) and store it[them] in \ref JPEGInfo for later pixel
3014 void Document::ComputeJPEGFragmentInfo()
3016 // If you need to, look for comments of ComputeRLEInfo().
3022 ReadAndSkipEncapsulatedBasicOffsetTable();
3024 // Loop on the fragments[s] and store the parsed information in a
3026 long fragmentLength;
3027 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3029 long fragmentOffset = Fp->tellg();
3031 // Store the collected info
3032 JPEGFragment* newFragment = new JPEGFragment;
3033 newFragment->Offset = fragmentOffset;
3034 newFragment->Length = fragmentLength;
3035 JPEGInfo->Fragments.push_back( newFragment );
3037 SkipBytes( fragmentLength );
3040 // Make sure that at the end of the item we encounter a 'Sequence
3042 if ( !ReadTag(0xfffe, 0xe0dd) )
3044 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3045 dbg.Verbose(0, " item at end of JPEG item sequence");
3050 * \brief Walk recursively the given \ref DocEntrySet, and feed
3051 * the given hash table (\ref TagDocEntryHT) with all the
3052 * \ref DocEntry (Dicom entries) encountered.
3053 * This method does the job for \ref BuildFlatHashTable.
3054 * @param builtHT Where to collect all the \ref DocEntry encountered
3055 * when recursively walking the given set.
3056 * @param set The structure to be traversed (recursively).
3058 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3061 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3063 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3064 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3065 i != currentHT.end();
3068 DocEntry* entry = i->second;
3069 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3071 const ListSQItem& items = seqEntry->GetSQItems();
3072 for( ListSQItem::const_iterator item = items.begin();
3073 item != items.end();
3076 BuildFlatHashTableRecurse( builtHT, *item );
3080 builtHT[entry->GetKey()] = entry;
3085 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3087 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3088 for (ListDocEntry::const_iterator i = currentList.begin();
3089 i != currentList.end();
3092 DocEntry* entry = *i;
3093 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3095 const ListSQItem& items = seqEntry->GetSQItems();
3096 for( ListSQItem::const_iterator item = items.begin();
3097 item != items.end();
3100 BuildFlatHashTableRecurse( builtHT, *item );
3104 builtHT[entry->GetKey()] = entry;
3111 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3114 * The structure used by a Document (through \ref ElementSet),
3115 * in order to hold the parsed entries of a Dicom header, is a recursive
3116 * one. This is due to the fact that the sequences (when present)
3117 * can be nested. Additionaly, the sequence items (represented in
3118 * gdcm as \ref SQItem) add an extra complexity to the data
3119 * structure. Hence, a gdcm user whishing to visit all the entries of
3120 * a Dicom header will need to dig in the gdcm internals (which
3121 * implies exposing all the internal data structures to the API).
3122 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3123 * recursively builds a temporary hash table, which holds all the
3124 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3126 * \warning Of course there is NO integrity constrain between the
3127 * returned \ref TagDocEntryHT and the \ref ElementSet used
3128 * to build it. Hence if the underlying \ref ElementSet is
3129 * altered, then it is the caller responsability to invoke
3130 * \ref BuildFlatHashTable again...
3131 * @return The flat std::map<> we juste build.
3133 TagDocEntryHT* Document::BuildFlatHashTable()
3135 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3136 BuildFlatHashTableRecurse( *FlatHT, this );
3143 * \brief Compares two documents, according to \ref DicomDir rules
3144 * \warning Does NOT work with ACR-NEMA files
3145 * \todo Find a trick to solve the pb (use RET fields ?)
3147 * @return true if 'smaller'
3149 bool Document::operator<(Document &document)
3152 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3153 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3165 s1 = GetEntryByNumber(0x0010,0x0020);
3166 s2 = document.GetEntryByNumber(0x0010,0x0020);
3177 // Study Instance UID
3178 s1 = GetEntryByNumber(0x0020,0x000d);
3179 s2 = document.GetEntryByNumber(0x0020,0x000d);
3190 // Serie Instance UID
3191 s1 = GetEntryByNumber(0x0020,0x000e);
3192 s2 = document.GetEntryByNumber(0x0020,0x000e);
3207 } // end namespace gdcm
3209 //-----------------------------------------------------------------------------