1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2005/01/06 16:33:54 $
7 Version: $Revision: 1.159 $
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"
27 #include "gdcmException.h"
28 #include "gdcmDictSet.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
31 #include "gdcmDocEntrySet.h"
32 #include "gdcmSQItem.h"
38 #if defined(_MSC_VER) || defined(__BORLANDC__)
41 #include <netinet/in.h>
46 //-----------------------------------------------------------------------------
47 static const char *TransferSyntaxStrings[] = {
48 // Implicit VR Little Endian
50 // Implicit VR Big Endian DLX G.E?
52 // Explicit VR Little Endian
53 "1.2.840.10008.1.2.1",
54 // Deflated Explicit VR Little Endian
55 "1.2.840.10008.1.2.1.99",
56 // Explicit VR Big Endian
57 "1.2.840.10008.1.2.2",
58 // JPEG Baseline (Process 1)
59 "1.2.840.10008.1.2.4.50",
60 // JPEG Extended (Process 2 & 4)
61 "1.2.840.10008.1.2.4.51",
62 // JPEG Extended (Process 3 & 5)
63 "1.2.840.10008.1.2.4.52",
64 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
65 "1.2.840.10008.1.2.4.53",
66 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
67 "1.2.840.10008.1.2.4.55",
68 // JPEG Lossless, Non-Hierarchical (Process 14)
69 "1.2.840.10008.1.2.4.57",
70 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
71 "1.2.840.10008.1.2.4.70",
73 "1.2.840.10008.1.2.4.90",
75 "1.2.840.10008.1.2.4.91",
77 "1.2.840.10008.1.2.5",
79 "Unknown Transfer Syntax"
82 //-----------------------------------------------------------------------------
83 // Refer to Document::CheckSwap()
84 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
86 // Refer to Document::SetMaxSizeLoadEntry()
87 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
88 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
90 //-----------------------------------------------------------------------------
91 // Constructor / Destructor
95 * @param filename file to be opened for parsing
97 Document::Document( std::string const & filename ) : ElementSet(-1)
99 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
109 dbg.Verbose(0, "Document::Document: starting parsing of file: ",
111 Fp->seekg( 0, std::ios::beg);
113 Fp->seekg(0, std::ios::end);
114 long lgt = Fp->tellg();
116 Fp->seekg( 0, std::ios::beg);
118 long beg = Fp->tellg();
121 ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
123 Fp->seekg( 0, std::ios::beg);
125 // Load 'non string' values
127 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
128 if( PhotometricInterpretation == "PALETTE COLOR " )
130 LoadEntryBinArea(0x0028,0x1200); // gray LUT
131 /// FIXME FIXME FIXME
132 /// The tags refered by the three following lines used to be CORRECTLY
133 /// defined as having an US Value Representation in the public
134 /// dictionnary. BUT the semantics implied by the three following
135 /// lines state that the corresponding tag contents are in fact
136 /// the ones of a BinEntry.
137 /// In order to fix things "Quick and Dirty" the dictionnary was
138 /// altered on PURPOUS but now contains a WRONG value.
139 /// In order to fix things and restore the dictionary to its
140 /// correct value, one needs to decided of the semantics by deciding
141 /// wether the following tags are either:
142 /// - multivaluated US, and hence loaded as ValEntry, but afterwards
143 /// also used as BinEntry, which requires the proper conversion,
144 /// - OW, and hence loaded as BinEntry, but afterwards also used
145 /// as ValEntry, which requires the proper conversion.
146 LoadEntryBinArea(0x0028,0x1201); // R LUT
147 LoadEntryBinArea(0x0028,0x1202); // G LUT
148 LoadEntryBinArea(0x0028,0x1203); // B LUT
150 // Segmented Red Palette Color LUT Data
151 LoadEntryBinArea(0x0028,0x1221);
152 // Segmented Green Palette Color LUT Data
153 LoadEntryBinArea(0x0028,0x1222);
154 // Segmented Blue Palette Color LUT Data
155 LoadEntryBinArea(0x0028,0x1223);
157 //FIXME later : how to use it?
158 LoadEntryBinArea(0x0028,0x3006); //LUT Data (CTX dependent)
162 // --------------------------------------------------------------
163 // Specific code to allow gdcm to read ACR-LibIDO formated images
164 // Note: ACR-LibIDO is an extension of the ACR standard that was
165 // used at CREATIS. For the time being (say a couple years)
166 // we keep this kludge to allow a smooth move to gdcm for
167 // CREATIS developpers (sorry folks).
169 // if recognition code tells us we deal with a LibIDO image
170 // we switch lineNumber and columnNumber
173 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
174 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
175 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
176 // with "little-endian strings"
178 Filetype = ACR_LIBIDO;
179 std::string rows = GetEntryByNumber(0x0028, 0x0010);
180 std::string columns = GetEntryByNumber(0x0028, 0x0011);
181 SetEntryByNumber(columns, 0x0028, 0x0010);
182 SetEntryByNumber(rows , 0x0028, 0x0011);
184 // ----------------- End of ACR-LibIDO kludge ------------------
188 * \brief This default constructor doesn't parse the file. You should
189 * then invoke \ref Document::SetFileName and then the parsing.
191 Document::Document() : ElementSet(-1)
195 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
198 Filetype = ExplicitVR;
202 * \brief Canonical destructor.
204 Document::~Document ()
213 //-----------------------------------------------------------------------------
217 * \brief Prints The Dict Entries of THE public Dicom Dictionary
220 void Document::PrintPubDict(std::ostream & os)
222 RefPubDict->SetPrintLevel(PrintLevel);
223 RefPubDict->Print(os);
227 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
230 void Document::PrintShaDict(std::ostream & os)
232 RefShaDict->SetPrintLevel(PrintLevel);
233 RefShaDict->Print(os);
236 //-----------------------------------------------------------------------------
239 * \brief Get the public dictionary used
241 Dict* Document::GetPubDict()
247 * \brief Get the shadow dictionary used
249 Dict* Document::GetShaDict()
255 * \brief Set the shadow dictionary used
256 * \param dict dictionary to use in shadow
258 bool Document::SetShaDict(Dict *dict)
265 * \brief Set the shadow dictionary used
266 * \param dictName name of the dictionary to use in shadow
268 bool Document::SetShaDict(DictKey const & dictName)
270 RefShaDict = Global::GetDicts()->GetDict(dictName);
275 * \brief This predicate, based on hopefully reasonable heuristics,
276 * decides whether or not the current Document was properly parsed
277 * and contains the mandatory information for being considered as
278 * a well formed and usable Dicom/Acr File.
279 * @return true when Document is the one of a reasonable Dicom/Acr file,
282 bool Document::IsReadable()
284 if( Filetype == Unknown)
286 dbg.Verbose(0, "Document::IsReadable: wrong filetype");
292 dbg.Verbose(0, "Document::IsReadable: no tags in internal"
301 * \brief Accessor to the Transfer Syntax (when present) of the
302 * current document (it internally handles reading the
303 * value from disk when only parsing occured).
304 * @return The encountered Transfer Syntax of the current document.
306 TransferSyntaxType Document::GetTransferSyntax()
308 DocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
314 // The entry might be present but not loaded (parsing and loading
315 // happen at different stages): try loading and proceed with check...
316 LoadDocEntrySafe(entry);
317 if (ValEntry* valEntry = dynamic_cast< ValEntry* >(entry) )
319 std::string transfer = valEntry->GetValue();
320 // The actual transfer (as read from disk) might be padded. We
321 // first need to remove the potential padding. We can make the
322 // weak assumption that padding was not executed with digits...
323 if ( transfer.length() == 0 )
325 // for brain damaged headers
328 while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
330 transfer.erase(transfer.length()-1, 1);
332 for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
334 if ( TransferSyntaxStrings[i] == transfer )
336 return TransferSyntaxType(i);
343 bool Document::IsJPEGLossless()
345 TransferSyntaxType r = GetTransferSyntax();
346 return r == JPEGFullProgressionProcess10_12
347 || r == JPEGLosslessProcess14
348 || r == JPEGLosslessProcess14_1;
352 * \brief Determines if the Transfer Syntax was already encountered
353 * and if it corresponds to a JPEG2000 one
354 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
357 bool Document::IsJPEG2000()
359 TransferSyntaxType r = GetTransferSyntax();
360 return r == JPEG2000Lossless || r == JPEG2000;
364 * \brief Determines if the Transfer Syntax corresponds to any form
365 * of Jpeg encoded Pixel data.
366 * @return True when any form of JPEG found. False otherwise.
368 bool Document::IsJPEG()
370 TransferSyntaxType r = GetTransferSyntax();
371 return r == JPEGBaselineProcess1
372 || r == JPEGExtendedProcess2_4
373 || r == JPEGExtendedProcess3_5
374 || r == JPEGSpectralSelectionProcess6_8
380 * \brief Determines if the Transfer Syntax corresponds to encapsulated
381 * of encoded Pixel Data (as opposed to native).
382 * @return True when encapsulated. False when native.
384 bool Document::IsEncapsulate()
386 TransferSyntaxType r = GetTransferSyntax();
387 return IsJPEG() || r == RLELossless;
391 * \brief Predicate for dicom version 3 file.
392 * @return True when the file is a dicom version 3.
394 bool Document::IsDicomV3()
396 // Checking if Transfert Syntax exists is enough
397 // Anyway, it's to late check if the 'Preamble' was found ...
398 // And ... would it be a rich idea to check ?
399 // (some 'no Preamble' DICOM images exist !)
400 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
404 * \brief returns the File Type
405 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
406 * @return the FileType code
408 FileType Document::GetFileType()
414 * \brief Tries to open the file \ref Document::Filename and
415 * checks the preamble when existing.
416 * @return The FILE pointer on success.
418 std::ifstream* Document::OpenFile()
420 if (Filename.length() == 0)
428 "Document::OpenFile is already opened when opening: ",
432 Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
436 "Document::OpenFile cannot open file: ",
444 Fp->read((char*)&zero, (size_t)2);
451 //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
453 zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
454 zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
455 zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
456 zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
462 Fp->seekg(126L, std::ios::cur);
464 Fp->read(dicm, (size_t)4);
470 if( memcmp(dicm, "DICM", 4) == 0 )
477 "Document::OpenFile not DICOM/ACR (missing preamble)",
484 * \brief closes the file
485 * @return TRUE if the close was successfull
487 bool Document::CloseFile()
496 return true; //FIXME how do we detect a non-close ifstream ?
500 * \brief Writes in a file all the Header Entries (Dicom Elements)
501 * @param fp file pointer on an already open file
502 * @param filetype Type of the File to be written
503 * (ACR-NEMA, ExplicitVR, ImplicitVR)
504 * \return Always true.
506 void Document::WriteContent(std::ofstream* fp, FileType filetype)
508 /// \todo move the following lines (and a lot of others, to be written)
509 /// to a future function CheckAndCorrectHeader
510 /// (necessary if user wants to write a DICOM V3 file
511 /// starting from an ACR-NEMA (V2) Header
513 if ( filetype == ImplicitVR || filetype == ExplicitVR )
515 // writing Dicom File Preamble
516 char filePreamble[128];
517 memset(filePreamble, 0, 128);
518 fp->write(filePreamble, 128);
519 fp->write("DICM", 4);
523 * \todo rewrite later, if really usefull
524 * - 'Group Length' element is optional in DICOM
525 * - but un-updated odd groups lengthes can causes pb
528 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
529 * UpdateGroupLength(false,filetype);
530 * if ( filetype == ACR)
531 * UpdateGroupLength(true,ACR);
534 ElementSet::WriteContent(fp, filetype); // This one is recursive
538 * \brief Modifies the value of a given Doc Entry (Dicom Element)
539 * when it exists. Create it with the given value when unexistant.
540 * @param value (string) Value to be set
541 * @param group Group number of the Entry
542 * @param elem Element number of the Entry
543 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
544 * \return pointer to the modified/created Header Entry (NULL when creation
547 ValEntry* Document::ReplaceOrCreateByNumber(std::string const & value,
552 ValEntry* valEntry = 0;
553 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
557 valEntry = dynamic_cast< ValEntry* >(currentEntry);
561 if( valEntry->GetVR()!=vr )
564 // if currentEntry doesn't correspond to the requested valEntry
567 if (!RemoveEntry(currentEntry))
569 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
570 " of previous DocEntry failed.");
577 // Create a new valEntry if necessary
580 valEntry = NewValEntryByNumber(group, elem, vr);
582 if ( !AddEntry(valEntry))
584 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
585 " failed allthough this is a creation.");
592 // Set the binEntry value
593 SetEntry(value, valEntry);
598 * \brief Modifies the value of a given Header Entry (Dicom Element)
599 * when it exists. Create it with the given value when unexistant.
600 * A copy of the binArea is made to be kept in the Document.
601 * @param binArea (binary) value to be set
602 * @param Group Group number of the Entry
603 * @param Elem Element number of the Entry
604 * @param vr V(alue) R(epresentation) of the Entry -if private Entry-
605 * \return pointer to the modified/created Header Entry (NULL when creation
608 BinEntry* Document::ReplaceOrCreateByNumber(uint8_t* binArea,
614 BinEntry* binEntry = 0;
615 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
617 // Verify the currentEntry
620 binEntry = dynamic_cast< BinEntry* >(currentEntry);
624 if( binEntry->GetVR()!=vr )
627 // if currentEntry doesn't correspond to the requested valEntry
630 if (!RemoveEntry(currentEntry))
632 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
633 " of previous DocEntry failed.");
640 // Create a new binEntry if necessary
643 binEntry = NewBinEntryByNumber(group, elem, vr);
645 if ( !AddEntry(binEntry))
647 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
648 " failed allthough this is a creation.");
655 // Set the binEntry value
657 if (lgth>0 && binArea)
659 tmpArea = new uint8_t[lgth];
660 memcpy(tmpArea,binArea,lgth);
666 if (!SetEntry(tmpArea,lgth,binEntry))
678 * \brief Modifies the value of a given Header Entry (Dicom Element)
679 * when it exists. Create it when unexistant.
680 * @param Group Group number of the Entry
681 * @param Elem Element number of the Entry
682 * \return pointer to the modified/created SeqEntry (NULL when creation
685 SeqEntry* Document::ReplaceOrCreateByNumber( uint16_t group, uint16_t elem)
687 SeqEntry* seqEntry = 0;
688 DocEntry* currentEntry = GetDocEntryByNumber( group, elem);
690 // Verify the currentEntry
693 seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
697 if( seqEntry->GetVR()!="SQ" )
700 // if currentEntry doesn't correspond to the requested valEntry
703 if (!RemoveEntry(currentEntry))
705 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: removal"
706 " of previous DocEntry failed.");
713 // Create a new seqEntry if necessary
716 seqEntry = NewSeqEntryByNumber(group, elem);
718 if ( !AddEntry(seqEntry))
720 dbg.Verbose(0, "Document::ReplaceOrCreateByNumber: AddEntry"
721 " failed allthough this is a creation.");
732 * \brief Set a new value if the invoked element exists
733 * Seems to be useless !!!
734 * @param value new element value
735 * @param group group number of the Entry
736 * @param elem element number of the Entry
739 bool Document::ReplaceIfExistByNumber(std::string const & value,
740 uint16_t group, uint16_t elem )
742 SetEntryByNumber(value, group, elem);
747 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
749 return TransferSyntaxStrings[type];
752 //-----------------------------------------------------------------------------
756 * \brief Checks if a given Dicom Element exists within the H table
757 * @param group Group number of the searched Dicom Element
758 * @param element Element number of the searched Dicom Element
759 * @return true is found
761 bool Document::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
763 const std::string &key = DictEntry::TranslateToKey(group, element );
764 return TagHT.count(key) != 0;
768 * \brief Searches within Header Entries (Dicom Elements) parsed with
769 * the public and private dictionaries
770 * for the element value of a given tag.
771 * \warning Don't use any longer : use GetPubEntryByName
772 * @param tagName name of the searched element.
773 * @return Corresponding element value when it exists,
774 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
776 std::string Document::GetEntryByName(TagName const & tagName)
778 DictEntry* dictEntry = RefPubDict->GetDictEntryByName(tagName);
784 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
788 * \brief Searches within Header Entries (Dicom Elements) parsed with
789 * the public and private dictionaries
790 * for the element value representation of a given tag.
792 * Obtaining the VR (Value Representation) might be needed by caller
793 * to convert the string typed content to caller's native type
794 * (think of C++ vs Python). The VR is actually of a higher level
795 * of semantics than just the native C++ type.
796 * @param tagName name of the searched element.
797 * @return Corresponding element value representation when it exists,
798 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
800 std::string Document::GetEntryVRByName(TagName const& tagName)
802 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
803 if( dictEntry == NULL)
808 DocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
809 dictEntry->GetElement());
810 return elem->GetVR();
814 * \brief Searches within Header Entries (Dicom Elements) parsed with
815 * the public and private dictionaries
816 * for the element value representation of a given tag.
817 * @param group Group number of the searched tag.
818 * @param element Element number of the searched tag.
819 * @return Corresponding element value representation when it exists,
820 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
822 std::string Document::GetEntryByNumber(uint16_t group, uint16_t element)
824 TagKey key = DictEntry::TranslateToKey(group, element);
825 if ( !TagHT.count(key))
830 return ((ValEntry *)TagHT.find(key)->second)->GetValue();
834 * \brief Searches within Header Entries (Dicom Elements) parsed with
835 * the public and private dictionaries
836 * for the element value representation of a given tag..
838 * Obtaining the VR (Value Representation) might be needed by caller
839 * to convert the string typed content to caller's native type
840 * (think of C++ vs Python). The VR is actually of a higher level
841 * of semantics than just the native C++ type.
842 * @param group Group number of the searched tag.
843 * @param element Element number of the searched tag.
844 * @return Corresponding element value representation when it exists,
845 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
847 std::string Document::GetEntryVRByNumber(uint16_t group, uint16_t element)
849 DocEntry* elem = GetDocEntryByNumber(group, element);
854 return elem->GetVR();
858 * \brief Searches within Header Entries (Dicom Elements) parsed with
859 * the public and private dictionaries
860 * for the value length of a given tag..
861 * @param group Group number of the searched tag.
862 * @param element Element number of the searched tag.
863 * @return Corresponding element length; -2 if not found
865 int Document::GetEntryLengthByNumber(uint16_t group, uint16_t element)
867 DocEntry* elem = GetDocEntryByNumber(group, element);
870 return -2; //magic number
872 return elem->GetLength();
875 * \brief Sets the value (string) of the Header Entry (Dicom Element)
876 * @param content string value of the Dicom Element
877 * @param tagName name of the searched Dicom Element.
878 * @return true when found
880 bool Document::SetEntryByName( std::string const & content,
881 TagName const & tagName)
883 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
889 return SetEntryByNumber(content,dictEntry->GetGroup(),
890 dictEntry->GetElement());
894 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
895 * through it's (group, element) and modifies it's content with
897 * @param content new value (string) to substitute with
898 * @param group group number of the Dicom Element to modify
899 * @param element element number of the Dicom Element to modify
901 bool Document::SetEntryByNumber(std::string const& content,
902 uint16_t group, uint16_t element)
904 ValEntry* entry = GetValEntryByNumber(group, element);
907 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
908 " ValEntry (try promotion first).");
911 return SetEntry(content,entry);
915 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
916 * through it's (group, element) and modifies it's content with
918 * @param content new value (void* -> uint8_t*) to substitute with
919 * @param lgth new value length
920 * @param group group number of the Dicom Element to modify
921 * @param element element number of the Dicom Element to modify
923 bool Document::SetEntryByNumber(uint8_t*content, int lgth,
924 uint16_t group, uint16_t element)
926 BinEntry* entry = GetBinEntryByNumber(group, element);
929 dbg.Verbose(0, "Document::SetEntryByNumber: no corresponding",
930 " ValEntry (try promotion first).");
934 return SetEntry(content,lgth,entry);
938 * \brief Accesses an existing DocEntry (i.e. a Dicom Element)
939 * and modifies it's content with the given value.
940 * @param content new value (string) to substitute with
941 * @param entry Entry to be modified
943 bool Document::SetEntry(std::string const & content,ValEntry* entry)
947 entry->SetValue(content);
954 * \brief Accesses an existing BinEntry (i.e. a Dicom Element)
955 * and modifies it's content with the given value.
956 * @param content new value (void* -> uint8_t*) to substitute with
957 * @param entry Entry to be modified
958 * @param lgth new value length
960 bool Document::SetEntry(uint8_t* content, int lgth, BinEntry* entry)
964 // Hope Binary field length is *never* wrong
965 /*if(lgth%2) // Non even length are padded with a space (020H).
968 //content = content + '\0'; // fing a trick to enlarge a binary field?
971 entry->SetBinArea(content);
972 entry->SetLength(lgth);
973 entry->SetValue(GDCM_BINLOADED);
980 * \brief Gets (from Header) a 'non string' element value
981 * (LoadElementValues has already be executed)
982 * @param group group number of the Entry
983 * @param elem element number of the Entry
984 * @return Pointer to the 'non string' area
986 void* Document::GetEntryBinAreaByNumber(uint16_t group, uint16_t elem)
988 DocEntry* entry = GetDocEntryByNumber(group, elem);
991 dbg.Verbose(1, "Document::GetDocEntryByNumber: no entry");
994 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(entry) )
996 return binEntry->GetBinArea();
1003 * \brief Loads (from disk) the element content
1004 * when a string is not suitable
1005 * @param group group number of the Entry
1006 * @param elem element number of the Entry
1008 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
1010 // Search the corresponding DocEntry
1011 DocEntry *docElement = GetDocEntryByNumber(group, elem);
1015 BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
1019 LoadEntryBinArea(binElement);
1023 * \brief Loads (from disk) the element content
1024 * when a string is not suitable
1025 * @param element Entry whose binArea is going to be loaded
1027 void Document::LoadEntryBinArea(BinEntry* element)
1029 if(element->GetBinArea())
1032 bool openFile = !Fp;
1036 size_t o =(size_t)element->GetOffset();
1037 Fp->seekg(o, std::ios::beg);
1039 size_t l = element->GetLength();
1040 uint8_t* a = new uint8_t[l];
1043 dbg.Verbose(0, "Document::LoadEntryBinArea cannot allocate a");
1047 /// \todo check the result
1048 Fp->read((char*)a, l);
1049 if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
1055 element->SetBinArea(a);
1062 * \brief Sets a 'non string' value to a given Dicom Element
1063 * @param area area containing the 'non string' value
1064 * @param group Group number of the searched Dicom Element
1065 * @param element Element number of the searched Dicom Element
1068 /*bool Document::SetEntryBinAreaByNumber(uint8_t* area,
1069 uint16_t group, uint16_t element)
1071 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1072 if ( !currentEntry )
1077 if ( BinEntry* binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1079 binEntry->SetBinArea( area );
1087 * \brief Searches within the Header Entries for a Dicom Element of
1089 * @param tagName name of the searched Dicom Element.
1090 * @return Corresponding Dicom Element when it exists, and NULL
1093 DocEntry* Document::GetDocEntryByName(TagName const & tagName)
1095 DictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1101 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1105 * \brief retrieves a Dicom Element (the first one) using (group, element)
1106 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1107 * if you think it's NOT UNIQUE, check the count number
1108 * and use iterators to retrieve ALL the Dicoms Elements within
1109 * a given couple (group, element)
1110 * @param group Group number of the searched Dicom Element
1111 * @param element Element number of the searched Dicom Element
1114 DocEntry* Document::GetDocEntryByNumber(uint16_t group, uint16_t element)
1116 TagKey key = DictEntry::TranslateToKey(group, element);
1117 if ( !TagHT.count(key))
1121 return TagHT.find(key)->second;
1125 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1126 * returns a result when the corresponding entry is of type
1128 * @return When present, the corresponding ValEntry.
1130 ValEntry* Document::GetValEntryByNumber(uint16_t group, uint16_t element)
1132 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1133 if ( !currentEntry )
1137 if ( ValEntry* entry = dynamic_cast<ValEntry*>(currentEntry) )
1141 dbg.Verbose(0, "Document::GetValEntryByNumber: unfound ValEntry.");
1147 * \brief Same as \ref Document::GetDocEntryByNumber except it only
1148 * returns a result when the corresponding entry is of type
1150 * @return When present, the corresponding BinEntry.
1152 BinEntry* Document::GetBinEntryByNumber(uint16_t group, uint16_t element)
1154 DocEntry* currentEntry = GetDocEntryByNumber(group, element);
1155 if ( !currentEntry )
1159 if ( BinEntry* entry = dynamic_cast<BinEntry*>(currentEntry) )
1163 dbg.Verbose(0, "Document::GetBinEntryByNumber: unfound BinEntry.");
1169 * \brief Loads the element while preserving the current
1170 * underlying file position indicator as opposed to
1171 * to LoadDocEntry that modifies it.
1172 * @param entry Header Entry whose value shall be loaded.
1175 void Document::LoadDocEntrySafe(DocEntry * entry)
1179 long PositionOnEntry = Fp->tellg();
1180 LoadDocEntry(entry);
1181 Fp->seekg(PositionOnEntry, std::ios::beg);
1186 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1188 * @return The properly swaped 32 bits integer.
1190 uint32_t Document::SwapLong(uint32_t a)
1197 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1198 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1202 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1206 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1209 //std::cout << "swapCode= " << SwapCode << std::endl;
1210 dbg.Error(" Document::SwapLong : unset swap code");
1217 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1219 * @return The properly unswaped 32 bits integer.
1221 uint32_t Document::UnswapLong(uint32_t a)
1227 * \brief Swaps the bytes so they agree with the processor order
1228 * @return The properly swaped 16 bits integer.
1230 uint16_t Document::SwapShort(uint16_t a)
1232 if ( SwapCode == 4321 || SwapCode == 2143 )
1234 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1240 * \brief Unswaps the bytes so they agree with the processor order
1241 * @return The properly unswaped 16 bits integer.
1243 uint16_t Document::UnswapShort(uint16_t a)
1245 return SwapShort(a);
1248 //-----------------------------------------------------------------------------
1252 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1253 * @return length of the parsed set.
1255 void Document::ParseDES(DocEntrySet *set, long offset,
1256 long l_max, bool delim_mode)
1258 DocEntry *newDocEntry = 0;
1262 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1266 newDocEntry = ReadNextDocEntry( );
1272 VRKey vr = newDocEntry->GetVR();
1276 if ( Global::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1278 /////////////////////// ValEntry
1279 ValEntry* newValEntry =
1280 new ValEntry( newDocEntry->GetDictEntry() ); //LEAK
1281 newValEntry->Copy( newDocEntry );
1283 // When "set" is a Document, then we are at the top of the
1284 // hierarchy and the Key is simply of the form ( group, elem )...
1285 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1288 newValEntry->SetKey( newValEntry->GetKey() );
1290 // ...but when "set" is a SQItem, we are inserting this new
1291 // valEntry in a sequence item. Hence the key has the
1292 // generalized form (refer to \ref BaseTagKey):
1293 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1295 newValEntry->SetKey( parentSQItem->GetBaseTagKey()
1296 + newValEntry->GetKey() );
1299 LoadDocEntry( newValEntry );
1300 bool delimitor=newValEntry->IsItemDelimitor();
1301 if( !set->AddEntry( newValEntry ) )
1303 // If here expect big troubles
1304 delete newValEntry; //otherwise mem leak
1312 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1320 if ( ! Global::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1322 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1323 dbg.Verbose(0, "Document::ParseDES: neither Valentry, "
1324 "nor BinEntry. Probably unknown VR.");
1327 //////////////////// BinEntry or UNKOWN VR:
1328 BinEntry* newBinEntry = new BinEntry( newDocEntry ); //LEAK
1330 // When "this" is a Document the Key is simply of the
1331 // form ( group, elem )...
1332 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1335 newBinEntry->SetKey( newBinEntry->GetKey() );
1337 // but when "this" is a SQItem, we are inserting this new
1338 // valEntry in a sequence item, and the kay has the
1339 // generalized form (refer to \ref BaseTagKey):
1340 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1342 newBinEntry->SetKey( parentSQItem->GetBaseTagKey()
1343 + newBinEntry->GetKey() );
1346 LoadDocEntry( newBinEntry );
1347 if( !set->AddEntry( newBinEntry ) )
1349 //Expect big troubles if here
1354 if ( ( newDocEntry->GetGroup() == 0x7fe0 )
1355 && ( newDocEntry->GetElement() == 0x0010 ) )
1357 TransferSyntaxType ts = GetTransferSyntax();
1358 if ( ts == RLELossless )
1360 long PositionOnEntry = Fp->tellg();
1361 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1363 Fp->seekg( PositionOnEntry, std::ios::beg );
1365 else if ( IsJPEG() )
1367 long PositionOnEntry = Fp->tellg();
1368 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1369 ComputeJPEGFragmentInfo();
1370 Fp->seekg( PositionOnEntry, std::ios::beg );
1374 // Just to make sure we are at the beginning of next entry.
1375 SkipToNextDocEntry(newDocEntry);
1376 //delete newDocEntry;
1381 unsigned long l = newDocEntry->GetReadLength();
1382 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1384 if ( l == 0xffffffff )
1393 // no other way to create it ...
1394 SeqEntry* newSeqEntry =
1395 new SeqEntry( newDocEntry->GetDictEntry() );
1396 newSeqEntry->Copy( newDocEntry );
1397 newSeqEntry->SetDelimitorMode( delim_mode );
1399 // At the top of the hierarchy, stands a Document. When "set"
1400 // is a Document, then we are building the first depth level.
1401 // Hence the SeqEntry we are building simply has a depth
1403 if (Document* dummy = dynamic_cast< Document* > ( set ) )
1406 newSeqEntry->SetDepthLevel( 1 );
1407 newSeqEntry->SetKey( newSeqEntry->GetKey() );
1409 // But when "set" is allready a SQItem, we are building a nested
1410 // sequence, and hence the depth level of the new SeqEntry
1411 // we are building, is one level deeper:
1412 if (SQItem* parentSQItem = dynamic_cast< SQItem* > ( set ) )
1414 newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1415 newSeqEntry->SetKey( parentSQItem->GetBaseTagKey()
1416 + newSeqEntry->GetKey() );
1420 { // Don't try to parse zero-length sequences
1421 ParseSQ( newSeqEntry,
1422 newDocEntry->GetOffset(),
1425 set->AddEntry( newSeqEntry );
1426 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1437 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1438 * @return parsed length for this level
1440 void Document::ParseSQ( SeqEntry* seqEntry,
1441 long offset, long l_max, bool delim_mode)
1443 int SQItemNumber = 0;
1448 DocEntry* newDocEntry = ReadNextDocEntry();
1451 // FIXME Should warn user
1456 if ( newDocEntry->IsSequenceDelimitor() )
1458 seqEntry->SetSequenceDelimitationItem( newDocEntry );
1462 if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1468 SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1469 std::ostringstream newBase;
1470 newBase << seqEntry->GetKey()
1474 itemSQ->SetBaseTagKey( newBase.str() );
1475 unsigned int l = newDocEntry->GetReadLength();
1477 if ( l == 0xffffffff )
1486 ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1489 seqEntry->AddEntry( itemSQ, SQItemNumber );
1491 if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1499 * \brief Loads the element content if its length doesn't exceed
1500 * the value specified with Document::SetMaxSizeLoadEntry()
1501 * @param entry Header Entry (Dicom Element) to be dealt with
1503 void Document::LoadDocEntry(DocEntry* entry)
1505 uint16_t group = entry->GetGroup();
1506 std::string vr = entry->GetVR();
1507 uint32_t length = entry->GetLength();
1509 Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1511 // A SeQuence "contains" a set of Elements.
1512 // (fffe e000) tells us an Element is beginning
1513 // (fffe e00d) tells us an Element just ended
1514 // (fffe e0dd) tells us the current SeQuence just ended
1515 if( group == 0xfffe )
1517 // NO more value field for SQ !
1521 // When the length is zero things are easy:
1524 ((ValEntry *)entry)->SetValue("");
1528 // The elements whose length is bigger than the specified upper bound
1529 // are not loaded. Instead we leave a short notice of the offset of
1530 // the element content and it's length.
1532 std::ostringstream s;
1533 if (length > MaxSizeLoadEntry)
1535 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1537 //s << "gdcm::NotLoaded (BinEntry)";
1538 s << GDCM_NOTLOADED;
1539 s << " Address:" << (long)entry->GetOffset();
1540 s << " Length:" << entry->GetLength();
1541 s << " x(" << std::hex << entry->GetLength() << ")";
1542 binEntryPtr->SetValue(s.str());
1544 // Be carefull : a BinEntry IS_A ValEntry ...
1545 else if (ValEntry* valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1547 // s << "gdcm::NotLoaded. (ValEntry)";
1548 s << GDCM_NOTLOADED;
1549 s << " Address:" << (long)entry->GetOffset();
1550 s << " Length:" << entry->GetLength();
1551 s << " x(" << std::hex << entry->GetLength() << ")";
1552 valEntryPtr->SetValue(s.str());
1557 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1558 << "nor a ValEntry ?! Should never print that !" << std::endl;
1561 // to be sure we are at the end of the value ...
1562 Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1567 // When we find a BinEntry not very much can be done :
1568 if (BinEntry* binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1570 s << GDCM_BINLOADED;
1571 binEntryPtr->SetValue(s.str());
1572 LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1576 /// \todo Any compacter code suggested (?)
1577 if ( IsDocEntryAnInteger(entry) )
1581 // When short integer(s) are expected, read and convert the following
1582 // n *two characters properly i.e. consider them as short integers as
1583 // opposed to strings.
1584 // Elements with Value Multiplicity > 1
1585 // contain a set of integers (not a single one)
1586 if (vr == "US" || vr == "SS")
1589 NewInt = ReadInt16();
1593 for (int i=1; i < nbInt; i++)
1596 NewInt = ReadInt16();
1601 // See above comment on multiple integers (mutatis mutandis).
1602 else if (vr == "UL" || vr == "SL")
1605 NewInt = ReadInt32();
1609 for (int i=1; i < nbInt; i++)
1612 NewInt = ReadInt32();
1617 #ifdef GDCM_NO_ANSI_STRING_STREAM
1618 s << std::ends; // to avoid oddities on Solaris
1619 #endif //GDCM_NO_ANSI_STRING_STREAM
1621 ((ValEntry *)entry)->SetValue(s.str());
1625 // FIXME: We need an additional byte for storing \0 that is not on disk
1626 char *str = new char[length+1];
1627 Fp->read(str, (size_t)length);
1628 str[length] = '\0'; //this is only useful when length is odd
1629 // Special DicomString call to properly handle \0 and even length
1630 std::string newValue;
1633 newValue = Util::DicomString(str, length+1);
1634 //dbg.Verbose(0, "Warning: bad length: ", length );
1635 dbg.Verbose(0, "For string :", newValue.c_str());
1636 // Since we change the length of string update it length
1637 entry->SetReadLength(length+1);
1641 newValue = Util::DicomString(str, length);
1645 if ( ValEntry* valEntry = dynamic_cast<ValEntry* >(entry) )
1647 if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1649 dbg.Verbose(1, "Document::LoadDocEntry",
1650 "unread element value");
1651 valEntry->SetValue(GDCM_UNREAD);
1657 // Because of correspondance with the VR dic
1658 valEntry->SetValue(newValue);
1662 valEntry->SetValue(newValue);
1667 dbg.Error(true, "Document::LoadDocEntry"
1668 "Should have a ValEntry, here !");
1674 * \brief Find the value Length of the passed Header Entry
1675 * @param entry Header Entry whose length of the value shall be loaded.
1677 void Document::FindDocEntryLength( DocEntry *entry )
1678 throw ( FormatError )
1680 uint16_t element = entry->GetElement();
1681 std::string vr = entry->GetVR();
1684 if ( Filetype == ExplicitVR && !entry->IsImplicitVR() )
1686 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1688 // The following reserved two bytes (see PS 3.5-2003, section
1689 // "7.1.2 Data element structure with explicit vr", p 27) must be
1690 // skipped before proceeding on reading the length on 4 bytes.
1691 Fp->seekg( 2L, std::ios::cur);
1692 uint32_t length32 = ReadInt32();
1694 if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff )
1699 /// \todo rename that to FindDocEntryLengthOBOrOW since
1700 /// the above test is on both OB and OW...
1701 lengthOB = FindDocEntryLengthOB();
1703 catch ( FormatUnexpected )
1705 // Computing the length failed (this happens with broken
1706 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1707 // chance to get the pixels by deciding the element goes
1708 // until the end of the file. Hence we artificially fix the
1709 // the length and proceed.
1710 long currentPosition = Fp->tellg();
1711 Fp->seekg(0L,std::ios::end);
1712 long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1713 Fp->seekg(currentPosition, std::ios::beg);
1714 entry->SetLength(lengthUntilEOF);
1717 entry->SetLength(lengthOB);
1720 FixDocEntryFoundLength(entry, length32);
1724 // Length is encoded on 2 bytes.
1725 length16 = ReadInt16();
1727 // We can tell the current file is encoded in big endian (like
1728 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1729 // and it's value is the one of the encoding of a big endian file.
1730 // In order to deal with such big endian encoded files, we have
1731 // (at least) two strategies:
1732 // * when we load the "Transfer Syntax" tag with value of big endian
1733 // encoding, we raise the proper flags. Then we wait for the end
1734 // of the META group (0x0002) among which is "Transfer Syntax",
1735 // before switching the swap code to big endian. We have to postpone
1736 // the switching of the swap code since the META group is fully encoded
1737 // in little endian, and big endian coding only starts at the next
1738 // group. The corresponding code can be hard to analyse and adds
1739 // many additional unnecessary tests for regular tags.
1740 // * the second strategy consists in waiting for trouble, that shall
1741 // appear when we find the first group with big endian encoding. This
1742 // is easy to detect since the length of a "Group Length" tag (the
1743 // ones with zero as element number) has to be of 4 (0x0004). When we
1744 // encounter 1024 (0x0400) chances are the encoding changed and we
1745 // found a group with big endian encoding.
1746 // We shall use this second strategy. In order to make sure that we
1747 // can interpret the presence of an apparently big endian encoded
1748 // length of a "Group Length" without committing a big mistake, we
1749 // add an additional check: we look in the already parsed elements
1750 // for the presence of a "Transfer Syntax" whose value has to be "big
1751 // endian encoding". When this is the case, chances are we have got our
1752 // hands on a big endian encoded file: we switch the swap code to
1753 // big endian and proceed...
1754 if ( element == 0x0000 && length16 == 0x0400 )
1756 TransferSyntaxType ts = GetTransferSyntax();
1757 if ( ts != ExplicitVRBigEndian )
1759 throw FormatError( "Document::FindDocEntryLength()",
1760 " not explicit VR." );
1764 SwitchSwapToBigEndian();
1765 // Restore the unproperly loaded values i.e. the group, the element
1766 // and the dictionary entry depending on them.
1767 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1768 uint16_t correctElem = SwapShort( entry->GetElement() );
1769 DictEntry* newTag = GetDictEntryByNumber( correctGroup,
1773 // This correct tag is not in the dictionary. Create a new one.
1774 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1776 // FIXME this can create a memory leaks on the old entry that be
1777 // left unreferenced.
1778 entry->SetDictEntry( newTag );
1781 // Heuristic: well, some files are really ill-formed.
1782 if ( length16 == 0xffff)
1784 // 0xffff means that we deal with 'Unknown Length' Sequence
1787 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1792 // Either implicit VR or a non DICOM conformal (see note below) explicit
1793 // VR that ommited the VR of (at least) this element. Farts happen.
1794 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1795 // on Data elements "Implicit and Explicit VR Data Elements shall
1796 // not coexist in a Data Set and Data Sets nested within it".]
1797 // Length is on 4 bytes.
1799 FixDocEntryFoundLength( entry, ReadInt32() );
1805 * \brief Find the Value Representation of the current Dicom Element.
1806 * @return Value Representation of the current Entry
1808 std::string Document::FindDocEntryVR()
1810 if ( Filetype != ExplicitVR )
1811 return(GDCM_UNKNOWN);
1813 long positionOnEntry = Fp->tellg();
1814 // Warning: we believe this is explicit VR (Value Representation) because
1815 // we used a heuristic that found "UL" in the first tag. Alas this
1816 // doesn't guarantee that all the tags will be in explicit VR. In some
1817 // cases (see e-film filtered files) one finds implicit VR tags mixed
1818 // within an explicit VR file. Hence we make sure the present tag
1819 // is in explicit VR and try to fix things if it happens not to be
1823 Fp->read (vr, (size_t)2);
1826 if( !CheckDocEntryVR(vr) )
1828 Fp->seekg(positionOnEntry, std::ios::beg);
1829 return(GDCM_UNKNOWN);
1835 * \brief Check the correspondance between the VR of the header entry
1836 * and the taken VR. If they are different, the header entry is
1837 * updated with the new VR.
1838 * @param vr Dicom Value Representation
1839 * @return false if the VR is incorrect of if the VR isn't referenced
1840 * otherwise, it returns true
1842 bool Document::CheckDocEntryVR(VRKey vr)
1844 // CLEANME searching the dicom_vr at each occurence is expensive.
1845 // PostPone this test in an optional integrity check at the end
1846 // of parsing or only in debug mode.
1847 if ( !Global::GetVR()->IsValidVR(vr) )
1854 * \brief Get the transformed value of the header entry. The VR value
1855 * is used to define the transformation to operate on the value
1856 * \warning NOT end user intended method !
1857 * @param entry entry to tranform
1858 * @return Transformed entry value
1860 std::string Document::GetDocEntryValue(DocEntry *entry)
1862 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1864 std::string val = ((ValEntry *)entry)->GetValue();
1865 std::string vr = entry->GetVR();
1866 uint32_t length = entry->GetLength();
1867 std::ostringstream s;
1870 // When short integer(s) are expected, read and convert the following
1871 // n * 2 bytes properly i.e. as a multivaluated strings
1872 // (each single value is separated fromthe next one by '\'
1873 // as usual for standard multivaluated filels
1874 // Elements with Value Multiplicity > 1
1875 // contain a set of short integers (not a single one)
1877 if( vr == "US" || vr == "SS" )
1882 for (int i=0; i < nbInt; i++)
1888 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1889 newInt16 = SwapShort( newInt16 );
1894 // When integer(s) are expected, read and convert the following
1895 // n * 4 bytes properly i.e. as a multivaluated strings
1896 // (each single value is separated fromthe next one by '\'
1897 // as usual for standard multivaluated filels
1898 // Elements with Value Multiplicity > 1
1899 // contain a set of integers (not a single one)
1900 else if( vr == "UL" || vr == "SL" )
1905 for (int i=0; i < nbInt; i++)
1911 newInt32 = ( val[4*i+0] & 0xFF )
1912 + (( val[4*i+1] & 0xFF ) << 8 )
1913 + (( val[4*i+2] & 0xFF ) << 16 )
1914 + (( val[4*i+3] & 0xFF ) << 24 );
1915 newInt32 = SwapLong( newInt32 );
1919 #ifdef GDCM_NO_ANSI_STRING_STREAM
1920 s << std::ends; // to avoid oddities on Solaris
1921 #endif //GDCM_NO_ANSI_STRING_STREAM
1925 return ((ValEntry *)entry)->GetValue();
1929 * \brief Get the reverse transformed value of the header entry. The VR
1930 * value is used to define the reverse transformation to operate on
1932 * \warning NOT end user intended method !
1933 * @param entry Entry to reverse transform
1934 * @return Reverse transformed entry value
1936 std::string Document::GetDocEntryUnvalue(DocEntry* entry)
1938 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1940 std::string vr = entry->GetVR();
1941 std::vector<std::string> tokens;
1942 std::ostringstream s;
1944 if ( vr == "US" || vr == "SS" )
1948 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1949 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1950 for (unsigned int i=0; i<tokens.size(); i++)
1952 newInt16 = atoi(tokens[i].c_str());
1953 s << ( newInt16 & 0xFF )
1954 << (( newInt16 >> 8 ) & 0xFF );
1958 if ( vr == "UL" || vr == "SL")
1962 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1963 Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1964 for (unsigned int i=0; i<tokens.size();i++)
1966 newInt32 = atoi(tokens[i].c_str());
1967 s << (char)( newInt32 & 0xFF )
1968 << (char)(( newInt32 >> 8 ) & 0xFF )
1969 << (char)(( newInt32 >> 16 ) & 0xFF )
1970 << (char)(( newInt32 >> 24 ) & 0xFF );
1975 #ifdef GDCM_NO_ANSI_STRING_STREAM
1976 s << std::ends; // to avoid oddities on Solaris
1977 #endif //GDCM_NO_ANSI_STRING_STREAM
1981 return ((ValEntry *)entry)->GetValue();
1985 * \brief Skip a given Header Entry
1986 * \warning NOT end user intended method !
1987 * @param entry entry to skip
1989 void Document::SkipDocEntry(DocEntry *entry)
1991 SkipBytes(entry->GetLength());
1995 * \brief Skips to the begining of the next Header Entry
1996 * \warning NOT end user intended method !
1997 * @param entry entry to skip
1999 void Document::SkipToNextDocEntry(DocEntry *entry)
2001 Fp->seekg((long)(entry->GetOffset()), std::ios::beg);
2002 Fp->seekg( (long)(entry->GetReadLength()), std::ios::cur);
2006 * \brief When the length of an element value is obviously wrong (because
2007 * the parser went Jabberwocky) one can hope improving things by
2008 * applying some heuristics.
2009 * @param entry entry to check
2010 * @param foundLength fist assumption about length
2012 void Document::FixDocEntryFoundLength(DocEntry *entry,
2013 uint32_t foundLength)
2015 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2016 if ( foundLength == 0xffffffff)
2021 uint16_t gr = entry->GetGroup();
2022 uint16_t el = entry->GetElement();
2024 if ( foundLength % 2)
2026 std::ostringstream s;
2027 s << "Warning : Tag with uneven length "
2029 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2030 dbg.Verbose(0, s.str().c_str());
2033 //////// Fix for some naughty General Electric images.
2034 // Allthough not recent many such GE corrupted images are still present
2035 // on Creatis hard disks. Hence this fix shall remain when such images
2036 // are no longer in user (we are talking a few years, here)...
2037 // Note: XMedCom probably uses such a trick since it is able to read
2038 // those pesky GE images ...
2039 if ( foundLength == 13)
2041 // Only happens for this length !
2042 if ( entry->GetGroup() != 0x0008
2043 || ( entry->GetElement() != 0x0070
2044 && entry->GetElement() != 0x0080 ) )
2047 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2051 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2052 // Occurence of such images is quite low (unless one leaves close to a
2053 // 'Leonardo' source. Hence, one might consider commenting out the
2054 // following fix on efficiency reasons.
2055 else if ( entry->GetGroup() == 0x0009
2056 && ( entry->GetElement() == 0x1113
2057 || entry->GetElement() == 0x1114 ) )
2060 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2063 else if ( entry->GetVR() == "SQ" )
2065 foundLength = 0; // ReadLength is unchanged
2068 //////// We encountered a 'delimiter' element i.e. a tag of the form
2069 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2070 // taken into account.
2071 else if( entry->GetGroup() == 0xfffe )
2073 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2074 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2075 // causes extra troubles...
2076 if( entry->GetElement() != 0x0000 )
2082 entry->SetUsableLength(foundLength);
2086 * \brief Apply some heuristics to predict whether the considered
2087 * element value contains/represents an integer or not.
2088 * @param entry The element value on which to apply the predicate.
2089 * @return The result of the heuristical predicate.
2091 bool Document::IsDocEntryAnInteger(DocEntry *entry)
2093 uint16_t element = entry->GetElement();
2094 uint16_t group = entry->GetGroup();
2095 const std::string & vr = entry->GetVR();
2096 uint32_t length = entry->GetLength();
2098 // When we have some semantics on the element we just read, and if we
2099 // a priori know we are dealing with an integer, then we shall be
2100 // able to swap it's element value properly.
2101 if ( element == 0 ) // This is the group length of the group
2109 // Allthough this should never happen, still some images have a
2110 // corrupted group length [e.g. have a glance at offset x(8336) of
2111 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2112 // Since for dicom compliant and well behaved headers, the present
2113 // test is useless (and might even look a bit paranoid), when we
2114 // encounter such an ill-formed image, we simply display a warning
2115 // message and proceed on parsing (while crossing fingers).
2116 std::ostringstream s;
2117 long filePosition = Fp->tellg();
2118 s << "Erroneous Group Length element length on : (" \
2119 << std::hex << group << " , " << element
2120 << ") -before- position x(" << filePosition << ")"
2121 << "lgt : " << length;
2122 dbg.Verbose(0, "Document::IsDocEntryAnInteger", s.str().c_str() );
2126 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2134 * \brief Find the Length till the next sequence delimiter
2135 * \warning NOT end user intended method !
2139 uint32_t Document::FindDocEntryLengthOB()
2140 throw( FormatUnexpected )
2142 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2143 long positionOnEntry = Fp->tellg();
2144 bool foundSequenceDelimiter = false;
2145 uint32_t totalLength = 0;
2147 while ( !foundSequenceDelimiter )
2153 group = ReadInt16();
2156 catch ( FormatError )
2158 throw FormatError("Document::FindDocEntryLengthOB()",
2159 " group or element not present.");
2162 // We have to decount the group and element we just read
2165 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2167 dbg.Verbose(1, "Document::FindDocEntryLengthOB: neither an Item "
2168 "tag nor a Sequence delimiter tag.");
2169 Fp->seekg(positionOnEntry, std::ios::beg);
2170 throw FormatUnexpected("Document::FindDocEntryLengthOB()",
2171 "Neither an Item tag nor a Sequence "
2175 if ( elem == 0xe0dd )
2177 foundSequenceDelimiter = true;
2180 uint32_t itemLength = ReadInt32();
2181 // We add 4 bytes since we just read the ItemLength with ReadInt32
2182 totalLength += itemLength + 4;
2183 SkipBytes(itemLength);
2185 if ( foundSequenceDelimiter )
2190 Fp->seekg( positionOnEntry, std::ios::beg);
2195 * \brief Reads a supposed to be 16 Bits integer
2196 * (swaps it depending on processor endianity)
2197 * @return read value
2199 uint16_t Document::ReadInt16()
2200 throw( FormatError )
2203 Fp->read ((char*)&g, (size_t)2);
2206 throw FormatError( "Document::ReadInt16()", " file error." );
2210 throw FormatError( "Document::ReadInt16()", "EOF." );
2217 * \brief Reads a supposed to be 32 Bits integer
2218 * (swaps it depending on processor endianity)
2219 * @return read value
2221 uint32_t Document::ReadInt32()
2222 throw( FormatError )
2225 Fp->read ((char*)&g, (size_t)4);
2228 throw FormatError( "Document::ReadInt32()", " file error." );
2232 throw FormatError( "Document::ReadInt32()", "EOF." );
2239 * \brief skips bytes inside the source file
2240 * \warning NOT end user intended method !
2243 void Document::SkipBytes(uint32_t nBytes)
2245 //FIXME don't dump the returned value
2246 Fp->seekg((long)nBytes, std::ios::cur);
2250 * \brief Loads all the needed Dictionaries
2251 * \warning NOT end user intended method !
2253 void Document::Initialise()
2255 RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2257 RLEInfo = new RLEFramesInfo;
2258 JPEGInfo = new JPEGFragmentsInfo;
2263 * \brief Discover what the swap code is (among little endian, big endian,
2264 * bad little endian, bad big endian).
2266 * @return false when we are absolutely sure
2267 * it's neither ACR-NEMA nor DICOM
2268 * true when we hope ours assuptions are OK
2270 bool Document::CheckSwap()
2272 // The only guaranted way of finding the swap code is to find a
2273 // group tag since we know it's length has to be of four bytes i.e.
2274 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2275 // occurs when we can't find such group...
2277 uint32_t x = 4; // x : for ntohs
2278 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2284 // First, compare HostByteOrder and NetworkByteOrder in order to
2285 // determine if we shall need to swap bytes (i.e. the Endian type).
2286 if ( x == ntohs(x) )
2295 // The easiest case is the one of a DICOM header, since it possesses a
2296 // file preamble where it suffice to look for the string "DICM".
2299 char *entCur = deb + 128;
2300 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2302 dbg.Verbose(1, "Document::CheckSwap:", "looks like DICOM Version3");
2304 // Next, determine the value representation (VR). Let's skip to the
2305 // first element (0002, 0000) and check there if we find "UL"
2306 // - or "OB" if the 1st one is (0002,0001) -,
2307 // in which case we (almost) know it is explicit VR.
2308 // WARNING: if it happens to be implicit VR then what we will read
2309 // is the length of the group. If this ascii representation of this
2310 // length happens to be "UL" then we shall believe it is explicit VR.
2311 // FIXME: in order to fix the above warning, we could read the next
2312 // element value (or a couple of elements values) in order to make
2313 // sure we are not commiting a big mistake.
2314 // We need to skip :
2315 // * the 128 bytes of File Preamble (often padded with zeroes),
2316 // * the 4 bytes of "DICM" string,
2317 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2318 // i.e. a total of 136 bytes.
2322 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2323 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2324 // *Implicit* VR. -and it is !-
2326 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2327 memcmp(entCur, "OB", (size_t)2) == 0 ||
2328 memcmp(entCur, "UI", (size_t)2) == 0 ||
2329 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2330 // when Write DCM *adds*
2332 // Use Document::dicom_vr to test all the possibilities
2333 // instead of just checking for UL, OB and UI !? group 0000
2335 Filetype = ExplicitVR;
2336 dbg.Verbose(1, "Document::CheckSwap:",
2337 "explicit Value Representation");
2341 Filetype = ImplicitVR;
2342 dbg.Verbose(1, "Document::CheckSwap:",
2343 "not an explicit Value Representation");
2349 dbg.Verbose(1, "Document::CheckSwap:",
2350 "HostByteOrder != NetworkByteOrder");
2355 dbg.Verbose(1, "Document::CheckSwap:",
2356 "HostByteOrder = NetworkByteOrder");
2359 // Position the file position indicator at first tag (i.e.
2360 // after the file preamble and the "DICM" string).
2361 Fp->seekg(0, std::ios::beg);
2362 Fp->seekg ( 132L, std::ios::beg);
2366 // Alas, this is not a DicomV3 file and whatever happens there is no file
2367 // preamble. We can reset the file position indicator to where the data
2368 // is (i.e. the beginning of the file).
2369 dbg.Verbose(1, "Document::CheckSwap:", "not a DICOM Version3 file");
2370 Fp->seekg(0, std::ios::beg);
2372 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2373 // By clean we mean that the length of the first tag is written down.
2374 // If this is the case and since the length of the first group HAS to be
2375 // four (bytes), then determining the proper swap code is straightforward.
2378 // We assume the array of char we are considering contains the binary
2379 // representation of a 32 bits integer. Hence the following dirty
2381 s32 = *((uint32_t *)(entCur));
2402 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2403 // It is time for despaired wild guesses.
2404 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2405 // i.e. the 'group length' element is not present :
2407 // check the supposed-to-be 'group number'
2408 // in ( 0x0001 .. 0x0008 )
2409 // to determine ' SwapCode' value .
2410 // Only 0 or 4321 will be possible
2411 // (no oportunity to check for the formerly well known
2412 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2413 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-)
2414 // the file IS NOT ACR-NEMA nor DICOM V3
2415 // Find a trick to tell it the caller...
2417 s16 = *((uint16_t *)(deb));
2444 dbg.Verbose(0, "Document::CheckSwap:",
2445 "ACR/NEMA unfound swap info (Really hopeless !)");
2449 // Then the only info we have is the net2host one.
2461 * \brief Restore the unproperly loaded values i.e. the group, the element
2462 * and the dictionary entry depending on them.
2464 void Document::SwitchSwapToBigEndian()
2466 dbg.Verbose(1, "Document::SwitchSwapToBigEndian",
2467 "Switching to BigEndian mode.");
2468 if ( SwapCode == 0 )
2472 else if ( SwapCode == 4321 )
2476 else if ( SwapCode == 3412 )
2480 else if ( SwapCode == 2143 )
2487 * \brief during parsing, Header Elements too long are not loaded in memory
2490 void Document::SetMaxSizeLoadEntry(long newSize)
2496 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2498 MaxSizeLoadEntry = 0xffffffff;
2501 MaxSizeLoadEntry = newSize;
2506 * \brief Header Elements too long will not be printed
2507 * \todo See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE
2510 void Document::SetMaxSizePrintEntry(long newSize)
2512 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2517 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2519 MaxSizePrintEntry = 0xffffffff;
2522 MaxSizePrintEntry = newSize;
2528 * \brief Handle broken private tag from Philips NTSCAN
2529 * where the endianess is being switch to BigEndian for no
2533 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2535 // Endian reversion. Some files contain groups of tags with reversed endianess.
2536 static int reversedEndian = 0;
2537 // try to fix endian switching in the middle of headers
2538 if ((group == 0xfeff) && (elem == 0x00e0))
2540 // start endian swap mark for group found
2542 SwitchSwapToBigEndian();
2547 else if ((group == 0xfffe) && (elem == 0xe00d) && reversedEndian)
2549 // end of reversed endian group
2551 SwitchSwapToBigEndian();
2556 * \brief Read the next tag but WITHOUT loading it's value
2557 * (read the 'Group Number', the 'Element Number',
2558 * gets the Dict Entry
2559 * gets the VR, gets the length, gets the offset value)
2560 * @return On succes the newly created DocEntry, NULL on failure.
2562 DocEntry* Document::ReadNextDocEntry()
2569 group = ReadInt16();
2572 catch ( FormatError e )
2574 // We reached the EOF (or an error occured) therefore
2575 // header parsing has to be considered as finished.
2580 HandleBrokenEndian(group, elem);
2581 std::string vr=FindDocEntryVR();
2583 DocEntry *newEntry = NewDocEntryByNumber(group, elem, vr);
2584 if( vr == GDCM_UNKNOWN )
2586 if( Filetype == ExplicitVR )
2588 // We thought this was explicit VR, but we end up with an
2589 // implicit VR tag. Let's backtrack.
2591 msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n",
2592 newEntry->GetGroup(), newEntry->GetElement());
2593 dbg.Verbose(1, "Document::FindVR: ", msg.c_str());
2595 newEntry->SetImplicitVR();
2600 FindDocEntryLength(newEntry);
2602 catch ( FormatError e )
2610 newEntry->SetOffset(Fp->tellg());
2617 * \brief Generate a free TagKey i.e. a TagKey that is not present
2618 * in the TagHt dictionary.
2619 * @param group The generated tag must belong to this group.
2620 * @return The element of tag with given group which is fee.
2622 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group)
2624 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2626 TagKey key = DictEntry::TranslateToKey(group, elem);
2627 if (TagHT.count(key) == 0)
2636 * \brief Assuming the internal file pointer \ref Document::Fp
2637 * is placed at the beginning of a tag check whether this
2638 * tag is (TestGroup, TestElement).
2639 * \warning On success the internal file pointer \ref Document::Fp
2640 * is modified to point after the tag.
2641 * On failure (i.e. when the tag wasn't the expected tag
2642 * (TestGroup, TestElement) the internal file pointer
2643 * \ref Document::Fp is restored to it's original position.
2644 * @param testGroup The expected group of the tag.
2645 * @param testElement The expected Element of the tag.
2646 * @return True on success, false otherwise.
2648 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2650 long positionOnEntry = Fp->tellg();
2651 long currentPosition = Fp->tellg(); // On debugging purposes
2653 //// Read the Item Tag group and element, and make
2654 // sure they are what we expected:
2655 uint16_t itemTagGroup;
2656 uint16_t itemTagElement;
2659 itemTagGroup = ReadInt16();
2660 itemTagElement = ReadInt16();
2662 catch ( FormatError e )
2664 //std::cerr << e << std::endl;
2667 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2669 std::ostringstream s;
2670 s << " We should have found tag (";
2671 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2672 s << " but instead we encountered tag (";
2673 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2675 s << " at address: " << (unsigned)currentPosition << std::endl;
2676 dbg.Verbose(0, "Document::ReadItemTagLength: wrong Item Tag found:");
2677 dbg.Verbose(0, s.str().c_str());
2678 Fp->seekg(positionOnEntry, std::ios::beg);
2686 * \brief Assuming the internal file pointer \ref Document::Fp
2687 * is placed at the beginning of a tag (TestGroup, TestElement),
2688 * read the length associated to the Tag.
2689 * \warning On success the internal file pointer \ref Document::Fp
2690 * is modified to point after the tag and it's length.
2691 * On failure (i.e. when the tag wasn't the expected tag
2692 * (TestGroup, TestElement) the internal file pointer
2693 * \ref Document::Fp is restored to it's original position.
2694 * @param testGroup The expected group of the tag.
2695 * @param testElement The expected Element of the tag.
2696 * @return On success returns the length associated to the tag. On failure
2699 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2701 long positionOnEntry = Fp->tellg();
2702 (void)positionOnEntry;
2704 if ( !ReadTag(testGroup, testElement) )
2709 //// Then read the associated Item Length
2710 long currentPosition = Fp->tellg();
2711 uint32_t itemLength = ReadInt32();
2713 std::ostringstream s;
2714 s << "Basic Item Length is: "
2715 << itemLength << std::endl;
2716 s << " at address: " << (unsigned)currentPosition << std::endl;
2717 dbg.Verbose(0, "Document::ReadItemTagLength: ", s.str().c_str());
2723 * \brief When parsing the Pixel Data of an encapsulated file, read
2724 * the basic offset table (when present, and BTW dump it).
2726 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2728 //// Read the Basic Offset Table Item Tag length...
2729 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2731 // When present, read the basic offset table itself.
2732 // Notes: - since the presence of this basic offset table is optional
2733 // we can't rely on it for the implementation, and we will simply
2734 // trash it's content (when present).
2735 // - still, when present, we could add some further checks on the
2736 // lengths, but we won't bother with such fuses for the time being.
2737 if ( itemLength != 0 )
2739 char* basicOffsetTableItemValue = new char[itemLength + 1];
2740 Fp->read(basicOffsetTableItemValue, itemLength);
2743 for (unsigned int i=0; i < itemLength; i += 4 )
2745 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2747 std::ostringstream s;
2748 s << " Read one length: ";
2749 s << std::hex << individualLength << std::endl;
2751 "Document::ReadAndSkipEncapsulatedBasicOffsetTable: ",
2756 delete[] basicOffsetTableItemValue;
2761 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2762 * Compute the RLE extra information and store it in \ref RLEInfo
2763 * for later pixel retrieval usage.
2765 void Document::ComputeRLEInfo()
2767 TransferSyntaxType ts = GetTransferSyntax();
2768 if ( ts != RLELossless )
2773 // Encoded pixel data: for the time being we are only concerned with
2774 // Jpeg or RLE Pixel data encodings.
2775 // As stated in PS 3.5-2003, section 8.2 p44:
2776 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2777 // value representation OB is used".
2778 // Hence we expect an OB value representation. Concerning OB VR,
2779 // the section PS 3.5-2003, section A.4.c p 58-59, states:
2780 // "For the Value Representations OB and OW, the encoding shall meet the
2781 // following specifications depending on the Data element tag:"
2783 // - the first item in the sequence of items before the encoded pixel
2784 // data stream shall be basic offset table item. The basic offset table
2785 // item value, however, is not required to be present"
2787 ReadAndSkipEncapsulatedBasicOffsetTable();
2789 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2790 // Loop on the individual frame[s] and store the information
2791 // on the RLE fragments in a RLEFramesInfo.
2792 // Note: - when only a single frame is present, this is a
2794 // - when more than one frame are present, then we are in
2795 // the case of a multi-frame image.
2797 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2799 // Parse the RLE Header and store the corresponding RLE Segment
2800 // Offset Table information on fragments of this current Frame.
2801 // Note that the fragment pixels themselves are not loaded
2802 // (but just skipped).
2803 long frameOffset = Fp->tellg();
2805 uint32_t nbRleSegments = ReadInt32();
2806 if ( nbRleSegments > 16 )
2808 // There should be at most 15 segments (refer to RLEFrame class)
2809 dbg.Verbose(0, "Document::ComputeRLEInfo: too many segments.");
2812 uint32_t rleSegmentOffsetTable[16];
2813 for( int k = 1; k <= 15; k++ )
2815 rleSegmentOffsetTable[k] = ReadInt32();
2818 // Deduce from both the RLE Header and the frameLength the
2819 // fragment length, and again store this info in a
2821 long rleSegmentLength[15];
2822 // skipping (not reading) RLE Segments
2823 if ( nbRleSegments > 1)
2825 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2827 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2828 - rleSegmentOffsetTable[k];
2829 SkipBytes(rleSegmentLength[k]);
2833 rleSegmentLength[nbRleSegments] = frameLength
2834 - rleSegmentOffsetTable[nbRleSegments];
2835 SkipBytes(rleSegmentLength[nbRleSegments]);
2837 // Store the collected info
2838 RLEFrame* newFrameInfo = new RLEFrame;
2839 newFrameInfo->NumberFragments = nbRleSegments;
2840 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2842 newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2843 newFrameInfo->Length[uk] = rleSegmentLength[uk];
2845 RLEInfo->Frames.push_back( newFrameInfo );
2848 // Make sure that at the end of the item we encounter a 'Sequence
2850 if ( !ReadTag(0xfffe, 0xe0dd) )
2852 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2853 dbg.Verbose(0, " item at end of RLE item sequence");
2858 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2859 * Compute the jpeg extra information (fragment[s] offset[s] and
2860 * length) and store it[them] in \ref JPEGInfo for later pixel
2863 void Document::ComputeJPEGFragmentInfo()
2865 // If you need to, look for comments of ComputeRLEInfo().
2871 ReadAndSkipEncapsulatedBasicOffsetTable();
2873 // Loop on the fragments[s] and store the parsed information in a
2875 long fragmentLength;
2876 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2878 long fragmentOffset = Fp->tellg();
2880 // Store the collected info
2881 JPEGFragment* newFragment = new JPEGFragment;
2882 newFragment->Offset = fragmentOffset;
2883 newFragment->Length = fragmentLength;
2884 JPEGInfo->Fragments.push_back( newFragment );
2886 SkipBytes( fragmentLength );
2889 // Make sure that at the end of the item we encounter a 'Sequence
2891 if ( !ReadTag(0xfffe, 0xe0dd) )
2893 dbg.Verbose(0, "Document::ComputeRLEInfo: no sequence delimiter ");
2894 dbg.Verbose(0, " item at end of JPEG item sequence");
2899 * \brief Walk recursively the given \ref DocEntrySet, and feed
2900 * the given hash table (\ref TagDocEntryHT) with all the
2901 * \ref DocEntry (Dicom entries) encountered.
2902 * This method does the job for \ref BuildFlatHashTable.
2903 * @param builtHT Where to collect all the \ref DocEntry encountered
2904 * when recursively walking the given set.
2905 * @param set The structure to be traversed (recursively).
2907 void Document::BuildFlatHashTableRecurse( TagDocEntryHT& builtHT,
2910 if (ElementSet* elementSet = dynamic_cast< ElementSet* > ( set ) )
2912 TagDocEntryHT const & currentHT = elementSet->GetTagHT();
2913 for( TagDocEntryHT::const_iterator i = currentHT.begin();
2914 i != currentHT.end();
2917 DocEntry* entry = i->second;
2918 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
2920 const ListSQItem& items = seqEntry->GetSQItems();
2921 for( ListSQItem::const_iterator item = items.begin();
2922 item != items.end();
2925 BuildFlatHashTableRecurse( builtHT, *item );
2929 builtHT[entry->GetKey()] = entry;
2934 if (SQItem* SQItemSet = dynamic_cast< SQItem* > ( set ) )
2936 const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2937 for (ListDocEntry::const_iterator i = currentList.begin();
2938 i != currentList.end();
2941 DocEntry* entry = *i;
2942 if ( SeqEntry* seqEntry = dynamic_cast<SeqEntry*>(entry) )
2944 const ListSQItem& items = seqEntry->GetSQItems();
2945 for( ListSQItem::const_iterator item = items.begin();
2946 item != items.end();
2949 BuildFlatHashTableRecurse( builtHT, *item );
2953 builtHT[entry->GetKey()] = entry;
2960 * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2963 * The structure used by a Document (through \ref ElementSet),
2964 * in order to hold the parsed entries of a Dicom header, is a recursive
2965 * one. This is due to the fact that the sequences (when present)
2966 * can be nested. Additionaly, the sequence items (represented in
2967 * gdcm as \ref SQItem) add an extra complexity to the data
2968 * structure. Hence, a gdcm user whishing to visit all the entries of
2969 * a Dicom header will need to dig in the gdcm internals (which
2970 * implies exposing all the internal data structures to the API).
2971 * In order to avoid this burden to the user, \ref BuildFlatHashTable
2972 * recursively builds a temporary hash table, which holds all the
2973 * Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2975 * \warning Of course there is NO integrity constrain between the
2976 * returned \ref TagDocEntryHT and the \ref ElementSet used
2977 * to build it. Hence if the underlying \ref ElementSet is
2978 * altered, then it is the caller responsability to invoke
2979 * \ref BuildFlatHashTable again...
2980 * @return The flat std::map<> we juste build.
2982 TagDocEntryHT* Document::BuildFlatHashTable()
2984 TagDocEntryHT* FlatHT = new TagDocEntryHT;
2985 BuildFlatHashTableRecurse( *FlatHT, this );
2992 * \brief Compares two documents, according to \ref DicomDir rules
2993 * \warning Does NOT work with ACR-NEMA files
2994 * \todo Find a trick to solve the pb (use RET fields ?)
2996 * @return true if 'smaller'
2998 bool Document::operator<(Document &document)
3001 std::string s1 = GetEntryByNumber(0x0010,0x0010);
3002 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
3014 s1 = GetEntryByNumber(0x0010,0x0020);
3015 s2 = document.GetEntryByNumber(0x0010,0x0020);
3026 // Study Instance UID
3027 s1 = GetEntryByNumber(0x0020,0x000d);
3028 s2 = document.GetEntryByNumber(0x0020,0x000d);
3039 // Serie Instance UID
3040 s1 = GetEntryByNumber(0x0020,0x000e);
3041 s2 = document.GetEntryByNumber(0x0020,0x000e);
3058 * \brief Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
3059 * @param filetype Type of the File to be written
3061 int Document::ComputeGroup0002Length( FileType filetype )
3066 int groupLength = 0;
3067 bool found0002 = false;
3069 // for each zero-level Tag in the DCM Header
3073 entry = GetNextEntry();
3076 gr = entry->GetGroup();
3082 el = entry->GetElement();
3083 vr = entry->GetVR();
3085 if (filetype == ExplicitVR)
3087 if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") )
3089 groupLength += 4; // explicit VR AND OB, OW, SQ : 4 more bytes
3092 groupLength += 2 + 2 + 4 + entry->GetLength();
3094 else if (found0002 )
3097 entry = GetNextEntry();
3102 } // end namespace gdcm
3104 //-----------------------------------------------------------------------------