1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/11/26 10:55:04 $
7 Version: $Revision: 1.142 $
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);
1062 * \brief Loads (from disk) the element content
1063 * when a string is not suitable
1064 * @param element Entry whose binArea is going to be loaded
1066 void Document::LoadEntryBinArea(BinEntry* element)
1068 if(element->GetBinArea())
1071 bool openFile = !Fp;
1075 size_t o =(size_t)element->GetOffset();
1076 Fp->seekg(o, std::ios_base::beg);
1078 size_t l = element->GetLength();
1079 uint8_t* a = new uint8_t[l];
1082 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1086 /// \todo check the result
1087 Fp->read((char*)a, l);
1088 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1094 element->SetBinArea(a);
1101 * \brief Sets a 'non string' value to a given Dicom Element
1102 * @param area area containing the 'non string' value
1103 * @param group Group number of the searched Dicom Element
1104 * @param element Element number of the searched Dicom Element
1107 /*bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1108 uint16_t group, uint16_t element)
1110 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1111 if ( !currentEntry )
1116 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1118 binEntry->SetBinArea( area );
1126 * \brief Update the entries with the shadow dictionary.
1127 * Only non even entries are analyzed
1129 void Document::UpdateShaEntries()
1134 /// \todo TODO : still any use to explore recursively the whole structure?
1136 for(ListTag::iterator it=listEntries.begin();
1137 it!=listEntries.end();
1140 // Odd group => from public dictionary
1141 if((*it)->GetGroup()%2==0)
1144 // Peer group => search the corresponding dict entry
1146 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1150 if((*it)->IsImplicitVR())
1155 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1157 // Set the new entry and the new value
1158 (*it)->SetDictEntry(entry);
1159 CheckDocEntryVR(*it,vr);
1161 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1166 // Remove precedent value transformation
1167 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1174 * \brief Searches within the Header Entries for a Dicom Element of
1176 * @param tagName name of the searched Dicom Element.
1177 * @return Corresponding Dicom Element when it exists, and NULL
1180 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1182 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1188 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1192 * \brief retrieves a Dicom Element (the first one) using (group, element)
1193 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1194 * if you think it's NOT UNIQUE, check the count number
1195 * and use iterators to retrieve ALL the Dicoms Elements within
1196 * a given couple (group, element)
1197 * @param group Group number of the searched Dicom Element
1198 * @param element Element number of the searched Dicom Element
1201 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1203 TagKey key = DictEntry::TranslateToKey(group, element);
1204 if ( !TagHT.count(key))
1208 return TagHT.find(key)->second;
1212 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1213 * returns a result when the corresponding entry is of type
1215 * @return When present, the corresponding ValEntry.
1217 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1219 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1220 if ( !currentEntry )
1224 if ( ValEntry* valEntry = dynamic_cast<ValEntry*>(currentEntry) )
1228 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1234 * \brief Loads the element while preserving the current
1235 * underlying file position indicator as opposed to
1236 * to LoadDocEntry that modifies it.
1237 * @param entry Header Entry whose value shall be loaded.
1240 void Document::LoadDocEntrySafe(DocEntry * entry)
1244 long PositionOnEntry = Fp->tellg();
1245 LoadDocEntry(entry);
1246 Fp->seekg(PositionOnEntry, std::ios_base::beg);
1251 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1253 * @return The properly swaped 32 bits integer.
1255 uint32_t Document::SwapLong(uint32_t a)
1262 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1263 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1267 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1271 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1274 //std::cout << "swapCode= " << SwapCode << std::endl;
1275 dbg.Error(" Document::SwapLong : unset swap code");
1282 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1284 * @return The properly unswaped 32 bits integer.
1286 uint32_t Document::UnswapLong(uint32_t a)
1292 * \brief Swaps the bytes so they agree with the processor order
1293 * @return The properly swaped 16 bits integer.
1295 uint16_t Document::SwapShort(uint16_t a)
1297 if ( SwapCode == 4321 || SwapCode == 2143 )
1299 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1305 * \brief Unswaps the bytes so they agree with the processor order
1306 * @return The properly unswaped 16 bits integer.
1308 uint16_t Document::UnswapShort(uint16_t a)
1310 return SwapShort(a);
1313 //-----------------------------------------------------------------------------
1317 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1318 * @return length of the parsed set.
1320 void Document::ParseDES(DocEntrySet *set, long offset,
1321 long l_max, bool delim_mode)
1323 DocEntry *newDocEntry = 0;
1327 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1331 newDocEntry = ReadNextDocEntry( );
1337 VRKey vr = newDocEntry->GetVR();
1341 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1343 /////////////////////// ValEntry
1344 ValEntry* newValEntry =
1345 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1346 newValEntry->Copy( newDocEntry );
1348 // When "set" is a Document, then we are at the top of the
1349 // hierarchy and the Key is simply of the form ( group, elem )...
1350 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1353 newValEntry->SetKey( newValEntry->GetKey() );
1355 // ...but when "set" is a SQItem, we are inserting this new
1356 // valEntry in a sequence item. Hence the key has the
1357 // generalized form (refer to \ref BaseTagKey):
1358 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1360 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1361 + newValEntry->GetKey() );
1364 LoadDocEntry( newValEntry );
1365 bool delimitor=newValEntry->IsItemDelimitor();
1366 if( !set->AddEntry( newValEntry ) )
1368 // If here expect big troubles
1369 delete newValEntry; //otherwise mem leak
1377 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1385 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1387 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1388 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1389 "nor BinEntry. Probably unknown VR.");
1392 //////////////////// BinEntry or UNKOWN VR:
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);
1441 //delete newDocEntry;
1446 unsigned long l = newDocEntry->GetReadLength();
1447 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1449 if ( l == 0xffffffff )
1458 // no other way to create it ...
1459 SeqEntry* newSeqEntry =
1460 new SeqEntry( newDocEntry->GetDictEntry() );
1461 newSeqEntry->Copy( newDocEntry );
1462 newSeqEntry->SetDelimitorMode( delim_mode );
1464 // At the top of the hierarchy, stands a Document. When "set"
1465 // is a Document, then we are building the first depth level.
1466 // Hence the SeqEntry we are building simply has a depth
1468 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1471 newSeqEntry->SetDepthLevel( 1 );
1472 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1474 // But when "set" is allready a SQItem, we are building a nested
1475 // sequence, and hence the depth level of the new SeqEntry
1476 // we are building, is one level deeper:
1477 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1479 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1480 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1481 + newSeqEntry->GetKey() );
1485 { // Don't try to parse zero-length sequences
1486 ParseSQ( newSeqEntry,
1487 newDocEntry->GetOffset(),
1490 set->AddEntry( newSeqEntry );
1491 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1502 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1503 * @return parsed length for this level
1505 void Document::ParseSQ( SeqEntry* seqEntry,
1506 long offset, long l_max, bool delim_mode)
1508 int SQItemNumber = 0;
1513 DocEntry* newDocEntry = ReadNextDocEntry();
1516 // FIXME Should warn user
1521 if ( newDocEntry->IsSequenceDelimitor() )
1523 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1527 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1533 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1534 std::ostringstream newBase;
1535 newBase << seqEntry->GetKey()
1539 itemSQ->SetBaseTagKey( newBase.str() );
1540 unsigned int l = newDocEntry->GetReadLength();
1542 if ( l == 0xffffffff )
1551 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1554 seqEntry->AddEntry( itemSQ, SQItemNumber );
1556 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1564 * \brief Loads the element content if its length doesn't exceed
1565 * the value specified with Document::SetMaxSizeLoadEntry()
1566 * @param entry Header Entry (Dicom Element) to be dealt with
1568 void Document::LoadDocEntry(DocEntry* entry)
1570 uint16_t group = entry->GetGroup();
1571 std::string vr = entry->GetVR();
1572 uint32_t length = entry->GetLength();
1574 Fp->seekg((long)entry->GetOffset(), std::ios_base::beg);
1576 // A SeQuence "contains" a set of Elements.
1577 // (fffe e000) tells us an Element is beginning
1578 // (fffe e00d) tells us an Element just ended
1579 // (fffe e0dd) tells us the current SeQuence just ended
1580 if( group == 0xfffe )
1582 // NO more value field for SQ !
1586 // When the length is zero things are easy:
1589 ((ValEntry *)entry)->SetValue("");
1593 // The elements whose length is bigger than the specified upper bound
1594 // are not loaded. Instead we leave a short notice of the offset of
1595 // the element content and it's length.
1597 std::ostringstream s;
1598 if (length > MaxSizeLoadEntry)
1600 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1602 //s << "gdcm::NotLoaded (BinEntry)";
1603 s << GDCM_NOTLOADED;
1604 s << " Address:" << (long)entry->GetOffset();
1605 s << " Length:" << entry->GetLength();
1606 s << " x(" << std::hex << entry->GetLength() << ")";
1607 binEntryPtr->SetValue(s.str());
1609 // Be carefull : a BinEntry IS_A ValEntry ...
1610 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1612 // s << "gdcm::NotLoaded. (ValEntry)";
1613 s << GDCM_NOTLOADED;
1614 s << " Address:" << (long)entry->GetOffset();
1615 s << " Length:" << entry->GetLength();
1616 s << " x(" << std::hex << entry->GetLength() << ")";
1617 valEntryPtr->SetValue(s.str());
1622 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1623 << "nor a ValEntry ?! Should never print that !" << std::endl;
1626 // to be sure we are at the end of the value ...
1627 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1628 std::ios_base::beg);
1632 // When we find a BinEntry not very much can be done :
1633 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1635 s << GDCM_BINLOADED;
1636 binEntryPtr->SetValue(s.str());
1637 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1641 /// \todo Any compacter code suggested (?)
1642 if ( IsDocEntryAnInteger(entry) )
1646 // When short integer(s) are expected, read and convert the following
1647 // n *two characters properly i.e. consider them as short integers as
1648 // opposed to strings.
1649 // Elements with Value Multiplicity > 1
1650 // contain a set of integers (not a single one)
1651 if (vr == "US" || vr == "SS")
1654 NewInt = ReadInt16();
1658 for (int i=1; i < nbInt; i++)
1661 NewInt = ReadInt16();
1666 // See above comment on multiple integers (mutatis mutandis).
1667 else if (vr == "UL" || vr == "SL")
1670 NewInt = ReadInt32();
1674 for (int i=1; i < nbInt; i++)
1677 NewInt = ReadInt32();
1682 #ifdef GDCM_NO_ANSI_STRING_STREAM
1683 s << std::ends; // to avoid oddities on Solaris
1684 #endif //GDCM_NO_ANSI_STRING_STREAM
1686 ((ValEntry *)entry)->SetValue(s.str());
1690 // FIXME: We need an additional byte for storing \0 that is not on disk
1691 char *str = new char[length+1];
1692 Fp->read(str, (size_t)length);
1693 str[length] = '\0'; //this is only useful when length is odd
1694 // Special DicomString call to properly handle \0 and even length
1695 std::string newValue;
1698 newValue = Util::DicomString(str, length+1);
1699 //dbg.Verbose(0, "Warning: bad length: ", length );
1700 dbg.Verbose(0, "For string :", newValue.c_str());
1701 // Since we change the length of string update it length
1702 entry->SetReadLength(length+1);
1706 newValue = Util::DicomString(str, length);
1710 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1712 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1714 dbg.Verbose(1, "Document::LoadDocEntry",
1715 "unread element value");
1716 valEntry->SetValue(GDCM_UNREAD);
1722 // Because of correspondance with the VR dic
1723 valEntry->SetValue(newValue);
1727 valEntry->SetValue(newValue);
1732 dbg.Error(true, "Document::LoadDocEntry"
1733 "Should have a ValEntry, here !");
1739 * \brief Find the value Length of the passed Header Entry
1740 * @param entry Header Entry whose length of the value shall be loaded.
1742 void Document::FindDocEntryLength( DocEntry *entry )
1743 throw ( FormatError )
1745 uint16_t element = entry->GetElement();
1746 std::string vr = entry->GetVR();
1749 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1751 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1753 // The following reserved two bytes (see PS 3.5-2003, section
1754 // "7.1.2 Data element structure with explicit vr", p 27) must be
1755 // skipped before proceeding on reading the length on 4 bytes.
1756 Fp->seekg( 2L, std::ios_base::cur);
1757 uint32_t length32 = ReadInt32();
1759 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1764 /// \todo rename that to FindDocEntryLengthOBOrOW since
1765 /// the above test is on both OB and OW...
1766 lengthOB = FindDocEntryLengthOB();
1768 catch ( FormatUnexpected )
1770 // Computing the length failed (this happens with broken
1771 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1772 // chance to get the pixels by deciding the element goes
1773 // until the end of the file. Hence we artificially fix the
1774 // the length and proceed.
1775 long currentPosition = Fp->tellg();
1776 Fp->seekg(0L,std::ios_base::end);
1777 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1778 Fp->seekg(currentPosition, std::ios_base::beg);
1779 entry->SetLength(lengthUntilEOF);
1782 entry->SetLength(lengthOB);
1785 FixDocEntryFoundLength(entry, length32);
1789 // Length is encoded on 2 bytes.
1790 length16 = ReadInt16();
1792 // We can tell the current file is encoded in big endian (like
1793 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1794 // and it's value is the one of the encoding of a big endian file.
1795 // In order to deal with such big endian encoded files, we have
1796 // (at least) two strategies:
1797 // * when we load the "Transfer Syntax" tag with value of big endian
1798 // encoding, we raise the proper flags. Then we wait for the end
1799 // of the META group (0x0002) among which is "Transfer Syntax",
1800 // before switching the swap code to big endian. We have to postpone
1801 // the switching of the swap code since the META group is fully encoded
1802 // in little endian, and big endian coding only starts at the next
1803 // group. The corresponding code can be hard to analyse and adds
1804 // many additional unnecessary tests for regular tags.
1805 // * the second strategy consists in waiting for trouble, that shall
1806 // appear when we find the first group with big endian encoding. This
1807 // is easy to detect since the length of a "Group Length" tag (the
1808 // ones with zero as element number) has to be of 4 (0x0004). When we
1809 // encounter 1024 (0x0400) chances are the encoding changed and we
1810 // found a group with big endian encoding.
1811 // We shall use this second strategy. In order to make sure that we
1812 // can interpret the presence of an apparently big endian encoded
1813 // length of a "Group Length" without committing a big mistake, we
1814 // add an additional check: we look in the already parsed elements
1815 // for the presence of a "Transfer Syntax" whose value has to be "big
1816 // endian encoding". When this is the case, chances are we have got our
1817 // hands on a big endian encoded file: we switch the swap code to
1818 // big endian and proceed...
1819 if ( element == 0x0000 && length16 == 0x0400 )
1821 TransferSyntaxType ts = GetTransferSyntax();
1822 if ( ts != ExplicitVRBigEndian )
1824 throw FormatError( "Document::FindDocEntryLength()",
1825 " not explicit VR." );
1829 SwitchSwapToBigEndian();
1830 // Restore the unproperly loaded values i.e. the group, the element
1831 // and the dictionary entry depending on them.
1832 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1833 uint16_t correctElem = SwapShort( entry->GetElement() );
1834 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1838 // This correct tag is not in the dictionary. Create a new one.
1839 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1841 // FIXME this can create a memory leaks on the old entry that be
1842 // left unreferenced.
1843 entry->SetDictEntry( newTag );
1846 // Heuristic: well, some files are really ill-formed.
1847 if ( length16 == 0xffff)
1849 // 0xffff means that we deal with 'Unknown Length' Sequence
1852 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1857 // Either implicit VR or a non DICOM conformal (see note below) explicit
1858 // VR that ommited the VR of (at least) this element. Farts happen.
1859 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1860 // on Data elements "Implicit and Explicit VR Data Elements shall
1861 // not coexist in a Data Set and Data Sets nested within it".]
1862 // Length is on 4 bytes.
1864 FixDocEntryFoundLength( entry, ReadInt32() );
1870 * \brief Find the Value Representation of the current Dicom Element.
1873 void Document::FindDocEntryVR( DocEntry *entry )
1875 if ( Filetype != ExplicitVR )
1882 long positionOnEntry = Fp->tellg();
1883 // Warning: we believe this is explicit VR (Value Representation) because
1884 // we used a heuristic that found "UL" in the first tag. Alas this
1885 // doesn't guarantee that all the tags will be in explicit VR. In some
1886 // cases (see e-film filtered files) one finds implicit VR tags mixed
1887 // within an explicit VR file. Hence we make sure the present tag
1888 // is in explicit VR and try to fix things if it happens not to be
1891 Fp->read (vr, (size_t)2);
1894 if( !CheckDocEntryVR(entry, vr) )
1896 Fp->seekg(positionOnEntry, std::ios_base::beg);
1897 // When this element is known in the dictionary we shall use, e.g. for
1898 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1899 // dictionary entry. Still we have to flag the element as implicit since
1900 // we know now our assumption on expliciteness is not furfilled.
1902 if ( entry->IsVRUnknown() )
1904 entry->SetVR("Implicit");
1906 entry->SetImplicitVR();
1911 * \brief Check the correspondance between the VR of the header entry
1912 * and the taken VR. If they are different, the header entry is
1913 * updated with the new VR.
1914 * @param entry Header Entry to check
1915 * @param vr Dicom Value Representation
1916 * @return false if the VR is incorrect of if the VR isn't referenced
1917 * otherwise, it returns true
1919 bool Document::CheckDocEntryVR(DocEntry *entry, VRKey vr)
1922 bool realExplicit = true;
1924 // Assume we are reading a falsely explicit VR file i.e. we reached
1925 // a tag where we expect reading a VR but are in fact we read the
1926 // first to bytes of the length. Then we will interogate (through find)
1927 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1928 // both GCC and VC++ implementations of the STL map. Hence when the
1929 // expected VR read happens to be non-ascii characters we consider
1930 // we hit falsely explicit VR tag.
1932 if ( !isalpha((unsigned char)vr[0]) && !isalpha((unsigned char)vr[1]) )
1934 realExplicit = false;
1937 // CLEANME searching the dicom_vr at each occurence is expensive.
1938 // PostPone this test in an optional integrity check at the end
1939 // of parsing or only in debug mode.
1940 if ( realExplicit && !Global::GetVR()->Count(vr) )
1942 realExplicit = false;
1945 if ( !realExplicit )
1947 // We thought this was explicit VR, but we end up with an
1948 // implicit VR tag. Let's backtrack.
1949 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
1950 entry->GetGroup(), entry->GetElement());
1951 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
1953 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1955 // Group length is UL !
1956 DictEntry* newEntry = NewVirtualDictEntry(
1957 entry->GetGroup(), entry->GetElement(),
1958 "UL", "FIXME", "Group Length");
1959 entry->SetDictEntry( newEntry );
1964 if ( entry->IsVRUnknown() )
1966 // When not a dictionary entry, we can safely overwrite the VR.
1967 if( entry->GetElement() == 0x0000 )
1969 // Group length is UL !
1977 else if ( entry->GetVR() != vr )
1979 // The VR present in the file and the dictionary disagree. We assume
1980 // the file writer knew best and use the VR of the file. Since it would
1981 // be unwise to overwrite the VR of a dictionary (since it would
1982 // compromise it's next user), we need to clone the actual DictEntry
1983 // and change the VR for the read one.
1984 DictEntry* newEntry = NewVirtualDictEntry(
1985 entry->GetGroup(), entry->GetElement(),
1986 vr, "FIXME", entry->GetName());
1987 entry->SetDictEntry(newEntry);
1994 * \brief Get the transformed value of the header entry. The VR value
1995 * is used to define the transformation to operate on the value
1996 * \warning NOT end user intended method !
1997 * @param entry entry to tranform
1998 * @return Transformed entry value
2000 std::string Document::GetDocEntryValue(DocEntry *entry)
2002 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2004 std::string val = ((ValEntry *)entry)->GetValue();
2005 std::string vr = entry->GetVR();
2006 uint32_t length = entry->GetLength();
2007 std::ostringstream s;
2010 // When short integer(s) are expected, read and convert the following
2011 // n * 2 bytes properly i.e. as a multivaluated strings
2012 // (each single value is separated fromthe next one by '\'
2013 // as usual for standard multivaluated filels
2014 // Elements with Value Multiplicity > 1
2015 // contain a set of short integers (not a single one)
2017 if( vr == "US" || vr == "SS" )
2022 for (int i=0; i < nbInt; i++)
2028 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
2029 newInt16 = SwapShort( newInt16 );
2034 // When integer(s) are expected, read and convert the following
2035 // n * 4 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 integers (not a single one)
2040 else if( vr == "UL" || vr == "SL" )
2045 for (int i=0; i < nbInt; i++)
2051 newInt32 = ( val[4*i+0] & 0xFF )
2052 + (( val[4*i+1] & 0xFF ) << 8 )
2053 + (( val[4*i+2] & 0xFF ) << 16 )
2054 + (( val[4*i+3] & 0xFF ) << 24 );
2055 newInt32 = SwapLong( newInt32 );
2059 #ifdef GDCM_NO_ANSI_STRING_STREAM
2060 s << std::ends; // to avoid oddities on Solaris
2061 #endif //GDCM_NO_ANSI_STRING_STREAM
2065 return ((ValEntry *)entry)->GetValue();
2069 * \brief Get the reverse transformed value of the header entry. The VR
2070 * value is used to define the reverse transformation to operate on
2072 * \warning NOT end user intended method !
2073 * @param entry Entry to reverse transform
2074 * @return Reverse transformed entry value
2076 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
2078 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
2080 std::string vr = entry->GetVR();
2081 std::vector<std::string> tokens;
2082 std::ostringstream s;
2084 if ( vr == "US" || vr == "SS" )
2088 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
2089 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2090 for (unsigned int i=0; i<tokens.size(); i++)
2092 newInt16 = atoi(tokens[i].c_str());
2093 s << ( newInt16 & 0xFF )
2094 << (( newInt16 >> 8 ) & 0xFF );
2098 if ( vr == "UL" || vr == "SL")
2102 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2103 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
2104 for (unsigned int i=0; i<tokens.size();i++)
2106 newInt32 = atoi(tokens[i].c_str());
2107 s << (char)( newInt32 & 0xFF )
2108 << (char)(( newInt32 >> 8 ) & 0xFF )
2109 << (char)(( newInt32 >> 16 ) & 0xFF )
2110 << (char)(( newInt32 >> 24 ) & 0xFF );
2115 #ifdef GDCM_NO_ANSI_STRING_STREAM
2116 s << std::ends; // to avoid oddities on Solaris
2117 #endif //GDCM_NO_ANSI_STRING_STREAM
2121 return ((ValEntry *)entry)->GetValue();
2125 * \brief Skip a given Header Entry
2126 * \warning NOT end user intended method !
2127 * @param entry entry to skip
2129 void Document::SkipDocEntry(DocEntry *entry)
2131 SkipBytes(entry->GetLength());
2135 * \brief Skips to the begining of the next Header Entry
2136 * \warning NOT end user intended method !
2137 * @param entry entry to skip
2139 void Document::SkipToNextDocEntry(DocEntry *entry)
2141 Fp->seekg((long)(entry->GetOffset()), std::ios_base::beg);
2142 Fp->seekg( (long)(entry->GetReadLength()), std::ios_base::cur);
2146 * \brief When the length of an element value is obviously wrong (because
2147 * the parser went Jabberwocky) one can hope improving things by
2148 * applying some heuristics.
2149 * @param entry entry to check
2150 * @param foundLength fist assumption about length
2152 void Document::FixDocEntryFoundLength(DocEntry *entry,
2153 uint32_t foundLength)
2155 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2156 if ( foundLength == 0xffffffff)
2161 uint16_t gr = entry->GetGroup();
2162 uint16_t el = entry->GetElement();
2164 if ( foundLength % 2)
2166 std::ostringstream s;
2167 s << "Warning : Tag with uneven length "
2169 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2170 dbg.Verbose(0, s.str().c_str());
2173 //////// Fix for some naughty General Electric images.
2174 // Allthough not recent many such GE corrupted images are still present
2175 // on Creatis hard disks. Hence this fix shall remain when such images
2176 // are no longer in user (we are talking a few years, here)...
2177 // Note: XMedCom probably uses such a trick since it is able to read
2178 // those pesky GE images ...
2179 if ( foundLength == 13)
2181 // Only happens for this length !
2182 if ( entry->GetGroup() != 0x0008
2183 || ( entry->GetElement() != 0x0070
2184 && entry->GetElement() != 0x0080 ) )
2187 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2191 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2192 // Occurence of such images is quite low (unless one leaves close to a
2193 // 'Leonardo' source. Hence, one might consider commenting out the
2194 // following fix on efficiency reasons.
2195 else if ( entry->GetGroup() == 0x0009
2196 && ( entry->GetElement() == 0x1113
2197 || entry->GetElement() == 0x1114 ) )
2200 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2203 else if ( entry->GetVR() == "SQ" )
2205 foundLength = 0; // ReadLength is unchanged
2208 //////// We encountered a 'delimiter' element i.e. a tag of the form
2209 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2210 // taken into account.
2211 else if( entry->GetGroup() == 0xfffe )
2213 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2214 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2215 // causes extra troubles...
2216 if( entry->GetElement() != 0x0000 )
2222 entry->SetUsableLength(foundLength);
2226 * \brief Apply some heuristics to predict whether the considered
2227 * element value contains/represents an integer or not.
2228 * @param entry The element value on which to apply the predicate.
2229 * @return The result of the heuristical predicate.
2231 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2233 uint16_t element = entry->GetElement();
2234 uint16_t group = entry->GetGroup();
2235 const std::string & vr = entry->GetVR();
2236 uint32_t length = entry->GetLength();
2238 // When we have some semantics on the element we just read, and if we
2239 // a priori know we are dealing with an integer, then we shall be
2240 // able to swap it's element value properly.
2241 if ( element == 0 ) // This is the group length of the group
2249 // Allthough this should never happen, still some images have a
2250 // corrupted group length [e.g. have a glance at offset x(8336) of
2251 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2252 // Since for dicom compliant and well behaved headers, the present
2253 // test is useless (and might even look a bit paranoid), when we
2254 // encounter such an ill-formed image, we simply display a warning
2255 // message and proceed on parsing (while crossing fingers).
2256 std::ostringstream s;
2257 long filePosition = Fp->tellg();
2258 s << "Erroneous Group Length element length on : (" \
2259 << std::hex << group << " , " << element
2260 << ") -before- position x(" << filePosition << ")"
2261 << "lgt : " << length;
2262 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2266 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2275 * \brief Find the Length till the next sequence delimiter
2276 * \warning NOT end user intended method !
2280 uint32_t Document::FindDocEntryLengthOB()
2281 throw( FormatUnexpected )
2283 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2284 long positionOnEntry = Fp->tellg();
2285 bool foundSequenceDelimiter = false;
2286 uint32_t totalLength = 0;
2288 while ( !foundSequenceDelimiter )
2294 group = ReadInt16();
2297 catch ( FormatError )
2299 throw FormatError("Document::FindDocEntryLengthOB()",
2300 " group or element not present.");
2303 // We have to decount the group and element we just read
2306 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2308 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2309 "tag nor a Sequence delimiter tag.");
2310 Fp->seekg(positionOnEntry, std::ios_base::beg);
2311 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2312 "Neither an Item tag nor a Sequence "
2316 if ( elem == 0xe0dd )
2318 foundSequenceDelimiter = true;
2321 uint32_t itemLength = ReadInt32();
2322 // We add 4 bytes since we just read the ItemLength with ReadInt32
2323 totalLength += itemLength + 4;
2324 SkipBytes(itemLength);
2326 if ( foundSequenceDelimiter )
2331 Fp->seekg( positionOnEntry, std::ios_base::beg);
2336 * \brief Reads a supposed to be 16 Bits integer
2337 * (swaps it depending on processor endianity)
2338 * @return read value
2340 uint16_t Document::ReadInt16()
2341 throw( FormatError )
2344 Fp->read ((char*)&g, (size_t)2);
2347 throw FormatError( "Document::ReadInt16()", " file error." );
2351 throw FormatError( "Document::ReadInt16()", "EOF." );
2358 * \brief Reads a supposed to be 32 Bits integer
2359 * (swaps it depending on processor endianity)
2360 * @return read value
2362 uint32_t Document::ReadInt32()
2363 throw( FormatError )
2366 Fp->read ((char*)&g, (size_t)4);
2369 throw FormatError( "Document::ReadInt32()", " file error." );
2373 throw FormatError( "Document::ReadInt32()", "EOF." );
2380 * \brief skips bytes inside the source file
2381 * \warning NOT end user intended method !
2384 void Document::SkipBytes(uint32_t nBytes)
2386 //FIXME don't dump the returned value
2387 Fp->seekg((long)nBytes, std::ios_base::cur);
2391 * \brief Loads all the needed Dictionaries
2392 * \warning NOT end user intended method !
2394 void Document::Initialise()
2396 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2398 RLEInfo = new RLEFramesInfo;
2399 JPEGInfo = new JPEGFragmentsInfo;
2403 * \brief Discover what the swap code is (among little endian, big endian,
2404 * bad little endian, bad big endian).
2406 * @return false when we are absolutely sure
2407 * it's neither ACR-NEMA nor DICOM
2408 * true when we hope ours assuptions are OK
2410 bool Document::CheckSwap()
2412 // The only guaranted way of finding the swap code is to find a
2413 // group tag since we know it's length has to be of four bytes i.e.
2414 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2415 // occurs when we can't find such group...
2417 uint32_t x = 4; // x : for ntohs
2418 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2422 char deb[256]; //HEADER_LENGTH_TO_READ];
2424 // First, compare HostByteOrder and NetworkByteOrder in order to
2425 // determine if we shall need to swap bytes (i.e. the Endian type).
2426 if ( x == ntohs(x) )
2435 // The easiest case is the one of a DICOM header, since it possesses a
2436 // file preamble where it suffice to look for the string "DICM".
2437 Fp->read(deb, HEADER_LENGTH_TO_READ);
2439 char *entCur = deb + 128;
2440 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2442 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2444 // Next, determine the value representation (VR). Let's skip to the
2445 // first element (0002, 0000) and check there if we find "UL"
2446 // - or "OB" if the 1st one is (0002,0001) -,
2447 // in which case we (almost) know it is explicit VR.
2448 // WARNING: if it happens to be implicit VR then what we will read
2449 // is the length of the group. If this ascii representation of this
2450 // length happens to be "UL" then we shall believe it is explicit VR.
2451 // FIXME: in order to fix the above warning, we could read the next
2452 // element value (or a couple of elements values) in order to make
2453 // sure we are not commiting a big mistake.
2454 // We need to skip :
2455 // * the 128 bytes of File Preamble (often padded with zeroes),
2456 // * the 4 bytes of "DICM" string,
2457 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2458 // i.e. a total of 136 bytes.
2462 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2463 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2464 // *Implicit* VR. -and it is !-
2466 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2467 memcmp(entCur, "OB", (size_t)2) == 0 ||
2468 memcmp(entCur, "UI", (size_t)2) == 0 ||
2469 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2470 // when Write DCM *adds*
2472 // Use Document::dicom_vr to test all the possibilities
2473 // instead of just checking for UL, OB and UI !? group 0000
2475 Filetype = ExplicitVR;
2476 dbg.Verbose(1, "Document::CheckSwap:",
2477 "explicit Value Representation");
2481 Filetype = ImplicitVR;
2482 dbg.Verbose(1, "Document::CheckSwap:",
2483 "not an explicit Value Representation");
2489 dbg.Verbose(1, "Document::CheckSwap:",
2490 "HostByteOrder != NetworkByteOrder");
2495 dbg.Verbose(1, "Document::CheckSwap:",
2496 "HostByteOrder = NetworkByteOrder");
2499 // Position the file position indicator at first tag (i.e.
2500 // after the file preamble and the "DICM" string).
2501 Fp->seekg(0, std::ios_base::beg);
2502 Fp->seekg ( 132L, std::ios_base::beg);
2506 // Alas, this is not a DicomV3 file and whatever happens there is no file
2507 // preamble. We can reset the file position indicator to where the data
2508 // is (i.e. the beginning of the file).
2509 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2510 Fp->seekg(0, std::ios_base::beg);
2512 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2513 // By clean we mean that the length of the first tag is written down.
2514 // If this is the case and since the length of the first group HAS to be
2515 // four (bytes), then determining the proper swap code is straightforward.
2518 // We assume the array of char we are considering contains the binary
2519 // representation of a 32 bits integer. Hence the following dirty
2521 s32 = *((uint32_t *)(entCur));
2542 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2543 // It is time for despaired wild guesses.
2544 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2545 // i.e. the 'group length' element is not present :
2547 // check the supposed-to-be 'group number'
2548 // in ( 0x0001 .. 0x0008 )
2549 // to determine ' SwapCode' value .
2550 // Only 0 or 4321 will be possible
2551 // (no oportunity to check for the formerly well known
2552 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2553 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2554 // the file IS NOT ACR-NEMA nor DICOM V3
2555 // Find a trick to tell it the caller...
2557 s16 = *((uint16_t *)(deb));
2584 dbg.Verbose(0, "Document::CheckSwap:",
2585 "ACR/NEMA unfound swap info (Really hopeless !)");
2589 // Then the only info we have is the net2host one.
2601 * \brief Restore the unproperly loaded values i.e. the group, the element
2602 * and the dictionary entry depending on them.
2604 void Document::SwitchSwapToBigEndian()
2606 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2607 "Switching to BigEndian mode.");
2608 if ( SwapCode == 0 )
2612 else if ( SwapCode == 4321 )
2616 else if ( SwapCode == 3412 )
2620 else if ( SwapCode == 2143 )
2627 * \brief during parsing, Header Elements too long are not loaded in memory
2630 void Document::SetMaxSizeLoadEntry(long newSize)
2636 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2638 MaxSizeLoadEntry = 0xffffffff;
2641 MaxSizeLoadEntry = newSize;
2646 * \brief Header Elements too long will not be printed
2647 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2650 void Document::SetMaxSizePrintEntry(long newSize)
2652 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2657 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2659 MaxSizePrintEntry = 0xffffffff;
2662 MaxSizePrintEntry = newSize;
2668 * \brief Handle broken private tag from Philips NTSCAN
2669 * where the endianess is being switch to BigEndian for no
2673 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2675 // Endian reversion. Some files contain groups of tags with reversed endianess.
2676 static int reversedEndian = 0;
2677 // try to fix endian switching in the middle of headers
2678 if ((group == 0xfeff) && (elem == 0x00e0))
2680 // start endian swap mark for group found
2682 SwitchSwapToBigEndian();
2687 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2689 // end of reversed endian group
2691 SwitchSwapToBigEndian();
2697 * \brief Read the next tag but WITHOUT loading it's value
2698 * (read the 'Group Number', the 'Element Number',
2699 * gets the Dict Entry
2700 * gets the VR, gets the length, gets the offset value)
2701 * @return On succes the newly created DocEntry, NULL on failure.
2703 DocEntry* Document::ReadNextDocEntry()
2710 group = ReadInt16();
2713 catch ( FormatError e )
2715 // We reached the EOF (or an error occured) therefore
2716 // header parsing has to be considered as finished.
2721 HandleBrokenEndian(group, elem);
2722 DocEntry *newEntry = NewDocEntryByNumber(group, elem);
2723 FindDocEntryVR(newEntry);
2727 FindDocEntryLength(newEntry);
2729 catch ( FormatError e )
2737 newEntry->SetOffset(Fp->tellg());
2744 * \brief Generate a free TagKey i.e. a TagKey that is not present
2745 * in the TagHt dictionary.
2746 * @param group The generated tag must belong to this group.
2747 * @return The element of tag with given group which is fee.
2749 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2751 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2753 TagKey key = DictEntry::TranslateToKey(group, elem);
2754 if (TagHT.count(key) == 0)
2763 * \brief Assuming the internal file pointer \ref Document::Fp
2764 * is placed at the beginning of a tag check whether this
2765 * tag is (TestGroup, TestElement).
2766 * \warning On success the internal file pointer \ref Document::Fp
2767 * is modified to point after the tag.
2768 * On failure (i.e. when the tag wasn't the expected tag
2769 * (TestGroup, TestElement) the internal file pointer
2770 * \ref Document::Fp is restored to it's original position.
2771 * @param testGroup The expected group of the tag.
2772 * @param testElement The expected Element of the tag.
2773 * @return True on success, false otherwise.
2775 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2777 long positionOnEntry = Fp->tellg();
2778 long currentPosition = Fp->tellg(); // On debugging purposes
2780 //// Read the Item Tag group and element, and make
2781 // sure they are what we expected:
2782 uint16_t itemTagGroup;
2783 uint16_t itemTagElement;
2786 itemTagGroup = ReadInt16();
2787 itemTagElement = ReadInt16();
2789 catch ( FormatError e )
2791 //std::cerr << e << std::endl;
2794 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2796 std::ostringstream s;
2797 s << " We should have found tag (";
2798 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2799 s << " but instead we encountered tag (";
2800 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2802 s << " at address: " << (unsigned)currentPosition << std::endl;
2803 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2804 dbg.Verbose(0, s.str().c_str());
2805 Fp->seekg(positionOnEntry, std::ios_base::beg);
2813 * \brief Assuming the internal file pointer \ref Document::Fp
2814 * is placed at the beginning of a tag (TestGroup, TestElement),
2815 * read the length associated to the Tag.
2816 * \warning On success the internal file pointer \ref Document::Fp
2817 * is modified to point after the tag and it's length.
2818 * On failure (i.e. when the tag wasn't the expected tag
2819 * (TestGroup, TestElement) the internal file pointer
2820 * \ref Document::Fp is restored to it's original position.
2821 * @param testGroup The expected group of the tag.
2822 * @param testElement The expected Element of the tag.
2823 * @return On success returns the length associated to the tag. On failure
2826 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2828 long positionOnEntry = Fp->tellg();
2829 (void)positionOnEntry;
2831 if ( !ReadTag(testGroup, testElement) )
2836 //// Then read the associated Item Length
2837 long currentPosition = Fp->tellg();
2838 uint32_t itemLength = ReadInt32();
2840 std::ostringstream s;
2841 s << "Basic Item Length is: "
2842 << itemLength << std::endl;
2843 s << " at address: " << (unsigned)currentPosition << std::endl;
2844 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2850 * \brief When parsing the Pixel Data of an encapsulated file, read
2851 * the basic offset table (when present, and BTW dump it).
2853 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2855 //// Read the Basic Offset Table Item Tag length...
2856 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2858 // When present, read the basic offset table itself.
2859 // Notes: - since the presence of this basic offset table is optional
2860 // we can't rely on it for the implementation, and we will simply
2861 // trash it's content (when present).
2862 // - still, when present, we could add some further checks on the
2863 // lengths, but we won't bother with such fuses for the time being.
2864 if ( itemLength != 0 )
2866 char* basicOffsetTableItemValue = new char[itemLength + 1];
2867 Fp->read(basicOffsetTableItemValue, itemLength);
2870 for (unsigned int i=0; i < itemLength; i += 4 )
2872 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2874 std::ostringstream s;
2875 s << " Read one length: ";
2876 s << std::hex << individualLength << std::endl;
2878 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2883 delete[] basicOffsetTableItemValue;
2888 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2889 * Compute the RLE extra information and store it in \ref RLEInfo
2890 * for later pixel retrieval usage.
2892 void Document::ComputeRLEInfo()
2894 TransferSyntaxType ts = GetTransferSyntax();
2895 if ( ts != RLELossless )
2900 // Encoded pixel data: for the time being we are only concerned with
2901 // Jpeg or RLE Pixel data encodings.
2902 // As stated in PS 3.5-2003, section 8.2 p44:
2903 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2904 // value representation OB is used".
2905 // Hence we expect an OB value representation. Concerning OB VR,
2906 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2907 // "For the Value Representations OB and OW, the encoding shall meet the
2908 // following specifications depending on the Data element tag:"
2910 // - the first item in the sequence of items before the encoded pixel
2911 // data stream shall be basic offset table item. The basic offset table
2912 // item value, however, is not required to be present"
2914 ReadAndSkipEncapsulatedBasicOffsetTable();
2916 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2917 // Loop on the individual frame[s] and store the information
2918 // on the RLE fragments in a RLEFramesInfo.
2919 // Note: - when only a single frame is present, this is a
2921 // - when more than one frame are present, then we are in
2922 // the case of a multi-frame image.
2924 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2926 // Parse the RLE Header and store the corresponding RLE Segment
2927 // Offset Table information on fragments of this current Frame.
2928 // Note that the fragment pixels themselves are not loaded
2929 // (but just skipped).
2930 long frameOffset = Fp->tellg();
2932 uint32_t nbRleSegments = ReadInt32();
2933 if ( nbRleSegments > 16 )
2935 // There should be at most 15 segments (refer to RLEFrame class)
2936 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2939 uint32_t rleSegmentOffsetTable[16];
2940 for( int k = 1; k <= 15; k++ )
2942 rleSegmentOffsetTable[k] = ReadInt32();
2945 // Deduce from both the RLE Header and the frameLength the
2946 // fragment length, and again store this info in a
2948 long rleSegmentLength[15];
2949 // skipping (not reading) RLE Segments
2950 if ( nbRleSegments > 1)
2952 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2954 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2955 - rleSegmentOffsetTable[k];
2956 SkipBytes(rleSegmentLength[k]);
2960 rleSegmentLength[nbRleSegments] = frameLength
2961 - rleSegmentOffsetTable[nbRleSegments];
2962 SkipBytes(rleSegmentLength[nbRleSegments]);
2964 // Store the collected info
2965 RLEFrame* newFrameInfo = new RLEFrame;
2966 newFrameInfo->NumberFragments = nbRleSegments;
2967 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2969 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2970 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2972 RLEInfo->Frames.push_back( newFrameInfo );
2975 // Make sure that at the end of the item we encounter a 'Sequence
2977 if ( !ReadTag(0xfffe, 0xe0dd) )
2979 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2980 dbg.Verbose(0, " item at end of RLE item sequence");
2985 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2986 * Compute the jpeg extra information (fragment[s] offset[s] and
2987 * length) and store it[them] in \ref JPEGInfo for later pixel
2990 void Document::ComputeJPEGFragmentInfo()
2992 // If you need to, look for comments of ComputeRLEInfo().
2998 ReadAndSkipEncapsulatedBasicOffsetTable();
3000 // Loop on the fragments[s] and store the parsed information in a
3002 long fragmentLength;
3003 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
3005 long fragmentOffset = Fp->tellg();
3007 // Store the collected info
3008 JPEGFragment* newFragment = new JPEGFragment;
3009 newFragment->Offset = fragmentOffset;
3010 newFragment->Length = fragmentLength;
3011 JPEGInfo->Fragments.push_back( newFragment );
3013 SkipBytes( fragmentLength );
3016 // Make sure that at the end of the item we encounter a 'Sequence
3018 if ( !ReadTag(0xfffe, 0xe0dd) )
3020 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
3021 dbg.Verbose(0, " item at end of JPEG item sequence");
3026 * \brief Walk recursively the given \ref DocEntrySet, and feed
3027 * the given hash table (\ref TagDocEntryHT) with all the
3028 * \ref DocEntry (Dicom entries) encountered.
3029 * This method does the job for \ref BuildFlatHashTable.
3030 * @param builtHT Where to collect all the \ref DocEntry encountered
3031 * when recursively walking the given set.
3032 * @param set The structure to be traversed (recursively).
3034 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
3037 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
3039 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
3040 for( TagDocEntryHT::const_iterator i = currentHT.begin();
3041 i != currentHT.end();
3044 DocEntry* entry = i->second;
3045 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
3047 const ListSQItem& items = seqEntry->GetSQItems();
3048 for( ListSQItem::const_iterator item = items.begin();
3049 item != items.end();
3052 BuildFlatHashTableRecurse( builtHT, *item );
3056 builtHT[entry->GetKey()] = entry;
3061 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
3063 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
3064 for (ListDocEntry::const_iterator i = currentList.begin();
3065 i != currentList.end();
3068 DocEntry* entry = *i;
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;
3087 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
3090 * The structure used by a Document (through \ref ElementSet),
3091 * in order to hold the parsed entries of a Dicom header, is a recursive
3092 * one. This is due to the fact that the sequences (when present)
3093 * can be nested. Additionaly, the sequence items (represented in
3094 * gdcm as \ref SQItem) add an extra complexity to the data
3095 * structure. Hence, a gdcm user whishing to visit all the entries of
3096 * a Dicom header will need to dig in the gdcm internals (which
3097 * implies exposing all the internal data structures to the API).
3098 * In order to avoid this burden to the user, \ref BuildFlatHashTable
3099 * recursively builds a temporary hash table, which holds all the
3100 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
3102 * \warning Of course there is NO integrity constrain between the
3103 * returned \ref TagDocEntryHT and the \ref ElementSet used
3104 * to build it. Hence if the underlying \ref ElementSet is
3105 * altered, then it is the caller responsability to invoke
3106 * \ref BuildFlatHashTable again...
3107 * @return The flat std::map<> we juste build.
3109 TagDocEntryHT* Document::BuildFlatHashTable()
3111 TagDocEntryHT* FlatHT = new TagDocEntryHT;
3112 BuildFlatHashTableRecurse( *FlatHT, this );
3119 * \brief Compares two documents, according to \ref DicomDir rules
3120 * \warning Does NOT work with ACR-NEMA files
3121 * \todo Find a trick to solve the pb (use RET fields ?)
3123 * @return true if 'smaller'
3125 bool Document::operator<(Document &document)
3128 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3129 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3141 s1 = GetEntryByNumber(0x0010,0x0020);
3142 s2 = document.GetEntryByNumber(0x0010,0x0020);
3153 // Study Instance UID
3154 s1 = GetEntryByNumber(0x0020,0x000d);
3155 s2 = document.GetEntryByNumber(0x0020,0x000d);
3166 // Serie Instance UID
3167 s1 = GetEntryByNumber(0x0020,0x000e);
3168 s2 = document.GetEntryByNumber(0x0020,0x000e);
3183 } // end namespace gdcm
3185 //-----------------------------------------------------------------------------